std/os/fd/
owned.rs

1//! Owned and borrowed Unix-like file descriptors.
2
3#![stable(feature = "io_safety", since = "1.63.0")]
4#![deny(unsafe_op_in_unsafe_fn)]
5
6use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
7use crate::marker::PhantomData;
8use crate::mem::ManuallyDrop;
9#[cfg(not(any(target_arch = "wasm32", target_env = "sgx", target_os = "hermit")))]
10use crate::sys::cvt;
11use crate::sys_common::{AsInner, FromInner, IntoInner};
12use crate::{fmt, fs, io};
13
14type ValidRawFd = core::num::niche_types::NotAllOnes<RawFd>;
15
16/// A borrowed file descriptor.
17///
18/// This has a lifetime parameter to tie it to the lifetime of something that owns the file
19/// descriptor. For the duration of that lifetime, it is guaranteed that nobody will close the file
20/// descriptor.
21///
22/// This uses `repr(transparent)` and has the representation of a host file
23/// descriptor, so it can be used in FFI in places where a file descriptor is
24/// passed as an argument, it is not captured or consumed, and it never has the
25/// value `-1`.
26///
27/// This type does not have a [`ToOwned`][crate::borrow::ToOwned]
28/// implementation. Calling `.to_owned()` on a variable of this type will call
29/// it on `&BorrowedFd` and use `Clone::clone()` like `ToOwned` does for all
30/// types implementing `Clone`. The result will be descriptor borrowed under
31/// the same lifetime.
32///
33/// To obtain an [`OwnedFd`], you can use [`BorrowedFd::try_clone_to_owned`]
34/// instead, but this is not supported on all platforms.
35#[derive(Copy, Clone)]
36#[repr(transparent)]
37#[rustc_nonnull_optimization_guaranteed]
38#[stable(feature = "io_safety", since = "1.63.0")]
39pub struct BorrowedFd<'fd> {
40    fd: ValidRawFd,
41    _phantom: PhantomData<&'fd OwnedFd>,
42}
43
44/// An owned file descriptor.
45///
46/// This closes the file descriptor on drop. It is guaranteed that nobody else will close the file
47/// descriptor.
48///
49/// This uses `repr(transparent)` and has the representation of a host file
50/// descriptor, so it can be used in FFI in places where a file descriptor is
51/// passed as a consumed argument or returned as an owned value, and it never
52/// has the value `-1`.
53///
54/// You can use [`AsFd::as_fd`] to obtain a [`BorrowedFd`].
55#[repr(transparent)]
56#[rustc_nonnull_optimization_guaranteed]
57#[stable(feature = "io_safety", since = "1.63.0")]
58pub struct OwnedFd {
59    fd: ValidRawFd,
60}
61
62impl BorrowedFd<'_> {
63    /// Returns a `BorrowedFd` holding the given raw file descriptor.
64    ///
65    /// # Safety
66    ///
67    /// The resource pointed to by `fd` must remain open for the duration of
68    /// the returned `BorrowedFd`, and it must not have the value `-1`.
69    #[inline]
70    #[rustc_const_stable(feature = "io_safety", since = "1.63.0")]
71    #[stable(feature = "io_safety", since = "1.63.0")]
72    pub const unsafe fn borrow_raw(fd: RawFd) -> Self {
73        assert!(fd != u32::MAX as RawFd);
74        // SAFETY: we just asserted that the value is in the valid range and isn't `-1` (the only value bigger than `0xFF_FF_FF_FE` unsigned)
75        let fd = unsafe { ValidRawFd::new_unchecked(fd) };
76        Self { fd, _phantom: PhantomData }
77    }
78}
79
80impl OwnedFd {
81    /// Creates a new `OwnedFd` instance that shares the same underlying file
82    /// description as the existing `OwnedFd` instance.
83    #[stable(feature = "io_safety", since = "1.63.0")]
84    pub fn try_clone(&self) -> crate::io::Result<Self> {
85        self.as_fd().try_clone_to_owned()
86    }
87}
88
89impl BorrowedFd<'_> {
90    /// Creates a new `OwnedFd` instance that shares the same underlying file
91    /// description as the existing `BorrowedFd` instance.
92    #[cfg(not(any(target_arch = "wasm32", target_os = "hermit")))]
93    #[stable(feature = "io_safety", since = "1.63.0")]
94    pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
95        // We want to atomically duplicate this file descriptor and set the
96        // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
97        // is a POSIX flag that was added to Linux in 2.6.24.
98        #[cfg(not(any(target_os = "espidf", target_os = "vita")))]
99        let cmd = libc::F_DUPFD_CLOEXEC;
100
101        // For ESP-IDF, F_DUPFD is used instead, because the CLOEXEC semantics
102        // will never be supported, as this is a bare metal framework with
103        // no capabilities for multi-process execution. While F_DUPFD is also
104        // not supported yet, it might be (currently it returns ENOSYS).
105        #[cfg(any(target_os = "espidf", target_os = "vita"))]
106        let cmd = libc::F_DUPFD;
107
108        // Avoid using file descriptors below 3 as they are used for stdio
109        let fd = cvt(unsafe { libc::fcntl(self.as_raw_fd(), cmd, 3) })?;
110        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
111    }
112
113    /// Creates a new `OwnedFd` instance that shares the same underlying file
114    /// description as the existing `BorrowedFd` instance.
115    #[cfg(any(target_arch = "wasm32", target_os = "hermit"))]
116    #[stable(feature = "io_safety", since = "1.63.0")]
117    pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
118        Err(crate::io::Error::UNSUPPORTED_PLATFORM)
119    }
120}
121
122#[stable(feature = "io_safety", since = "1.63.0")]
123impl AsRawFd for BorrowedFd<'_> {
124    #[inline]
125    fn as_raw_fd(&self) -> RawFd {
126        self.fd.as_inner()
127    }
128}
129
130#[stable(feature = "io_safety", since = "1.63.0")]
131impl AsRawFd for OwnedFd {
132    #[inline]
133    fn as_raw_fd(&self) -> RawFd {
134        self.fd.as_inner()
135    }
136}
137
138#[stable(feature = "io_safety", since = "1.63.0")]
139impl IntoRawFd for OwnedFd {
140    #[inline]
141    fn into_raw_fd(self) -> RawFd {
142        ManuallyDrop::new(self).fd.as_inner()
143    }
144}
145
146#[stable(feature = "io_safety", since = "1.63.0")]
147impl FromRawFd for OwnedFd {
148    /// Constructs a new instance of `Self` from the given raw file descriptor.
149    ///
150    /// # Safety
151    ///
152    /// The resource pointed to by `fd` must be open and suitable for assuming
153    /// [ownership][io-safety]. The resource must not require any cleanup other than `close`.
154    ///
155    /// [io-safety]: io#io-safety
156    #[inline]
157    unsafe fn from_raw_fd(fd: RawFd) -> Self {
158        assert_ne!(fd, u32::MAX as RawFd);
159        // SAFETY: we just asserted that the value is in the valid range and isn't `-1` (the only value bigger than `0xFF_FF_FF_FE` unsigned)
160        let fd = unsafe { ValidRawFd::new_unchecked(fd) };
161        Self { fd }
162    }
163}
164
165#[stable(feature = "io_safety", since = "1.63.0")]
166impl Drop for OwnedFd {
167    #[inline]
168    fn drop(&mut self) {
169        unsafe {
170            // Note that errors are ignored when closing a file descriptor. According to POSIX 2024,
171            // we can and indeed should retry `close` on `EINTR`
172            // (https://pubs.opengroup.org/onlinepubs/9799919799.2024edition/functions/close.html),
173            // but it is not clear yet how well widely-used implementations are conforming with this
174            // mandate since older versions of POSIX left the state of the FD after an `EINTR`
175            // unspecified. Ignoring errors is "fine" because some of the major Unices (in
176            // particular, Linux) do make sure to always close the FD, even when `close()` is
177            // interrupted, and the scenario is rare to begin with. If we retried on a
178            // not-POSIX-compliant implementation, the consequences could be really bad since we may
179            // close the wrong FD. Helpful link to an epic discussion by POSIX workgroup that led to
180            // the latest POSIX wording: http://austingroupbugs.net/view.php?id=529
181            #[cfg(not(target_os = "hermit"))]
182            {
183                #[cfg(unix)]
184                crate::sys::fs::debug_assert_fd_is_open(self.fd.as_inner());
185
186                let _ = libc::close(self.fd.as_inner());
187            }
188            #[cfg(target_os = "hermit")]
189            let _ = hermit_abi::close(self.fd.as_inner());
190        }
191    }
192}
193
194#[stable(feature = "io_safety", since = "1.63.0")]
195impl fmt::Debug for BorrowedFd<'_> {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        f.debug_struct("BorrowedFd").field("fd", &self.fd).finish()
198    }
199}
200
201#[stable(feature = "io_safety", since = "1.63.0")]
202impl fmt::Debug for OwnedFd {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        f.debug_struct("OwnedFd").field("fd", &self.fd).finish()
205    }
206}
207
208macro_rules! impl_is_terminal {
209    ($($t:ty),*$(,)?) => {$(
210        #[unstable(feature = "sealed", issue = "none")]
211        impl crate::sealed::Sealed for $t {}
212
213        #[stable(feature = "is_terminal", since = "1.70.0")]
214        impl crate::io::IsTerminal for $t {
215            #[inline]
216            fn is_terminal(&self) -> bool {
217                crate::sys::io::is_terminal(self)
218            }
219        }
220    )*}
221}
222
223impl_is_terminal!(BorrowedFd<'_>, OwnedFd);
224
225/// A trait to borrow the file descriptor from an underlying object.
226///
227/// This is only available on unix platforms and must be imported in order to
228/// call the method. Windows platforms have a corresponding `AsHandle` and
229/// `AsSocket` set of traits.
230#[stable(feature = "io_safety", since = "1.63.0")]
231pub trait AsFd {
232    /// Borrows the file descriptor.
233    ///
234    /// # Example
235    ///
236    /// ```rust,no_run
237    /// use std::fs::File;
238    /// # use std::io;
239    /// # #[cfg(any(unix, target_os = "wasi"))]
240    /// # use std::os::fd::{AsFd, BorrowedFd};
241    ///
242    /// let mut f = File::open("foo.txt")?;
243    /// # #[cfg(any(unix, target_os = "wasi"))]
244    /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
245    /// # Ok::<(), io::Error>(())
246    /// ```
247    #[stable(feature = "io_safety", since = "1.63.0")]
248    fn as_fd(&self) -> BorrowedFd<'_>;
249}
250
251#[stable(feature = "io_safety", since = "1.63.0")]
252impl<T: AsFd + ?Sized> AsFd for &T {
253    #[inline]
254    fn as_fd(&self) -> BorrowedFd<'_> {
255        T::as_fd(self)
256    }
257}
258
259#[stable(feature = "io_safety", since = "1.63.0")]
260impl<T: AsFd + ?Sized> AsFd for &mut T {
261    #[inline]
262    fn as_fd(&self) -> BorrowedFd<'_> {
263        T::as_fd(self)
264    }
265}
266
267#[stable(feature = "io_safety", since = "1.63.0")]
268impl AsFd for BorrowedFd<'_> {
269    #[inline]
270    fn as_fd(&self) -> BorrowedFd<'_> {
271        *self
272    }
273}
274
275#[stable(feature = "io_safety", since = "1.63.0")]
276impl AsFd for OwnedFd {
277    #[inline]
278    fn as_fd(&self) -> BorrowedFd<'_> {
279        // Safety: `OwnedFd` and `BorrowedFd` have the same validity
280        // invariants, and the `BorrowedFd` is bounded by the lifetime
281        // of `&self`.
282        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
283    }
284}
285
286#[stable(feature = "io_safety", since = "1.63.0")]
287impl AsFd for fs::File {
288    #[inline]
289    fn as_fd(&self) -> BorrowedFd<'_> {
290        self.as_inner().as_fd()
291    }
292}
293
294#[stable(feature = "io_safety", since = "1.63.0")]
295impl From<fs::File> for OwnedFd {
296    /// Takes ownership of a [`File`](fs::File)'s underlying file descriptor.
297    #[inline]
298    fn from(file: fs::File) -> OwnedFd {
299        file.into_inner().into_inner().into_inner()
300    }
301}
302
303#[stable(feature = "io_safety", since = "1.63.0")]
304impl From<OwnedFd> for fs::File {
305    /// Returns a [`File`](fs::File) that takes ownership of the given
306    /// file descriptor.
307    #[inline]
308    fn from(owned_fd: OwnedFd) -> Self {
309        Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned_fd)))
310    }
311}
312
313#[stable(feature = "io_safety", since = "1.63.0")]
314impl AsFd for crate::net::TcpStream {
315    #[inline]
316    fn as_fd(&self) -> BorrowedFd<'_> {
317        self.as_inner().socket().as_fd()
318    }
319}
320
321#[stable(feature = "io_safety", since = "1.63.0")]
322impl From<crate::net::TcpStream> for OwnedFd {
323    /// Takes ownership of a [`TcpStream`](crate::net::TcpStream)'s socket file descriptor.
324    #[inline]
325    fn from(tcp_stream: crate::net::TcpStream) -> OwnedFd {
326        tcp_stream.into_inner().into_socket().into_inner().into_inner().into()
327    }
328}
329
330#[stable(feature = "io_safety", since = "1.63.0")]
331impl From<OwnedFd> for crate::net::TcpStream {
332    #[inline]
333    fn from(owned_fd: OwnedFd) -> Self {
334        Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
335            owned_fd,
336        ))))
337    }
338}
339
340#[stable(feature = "io_safety", since = "1.63.0")]
341impl AsFd for crate::net::TcpListener {
342    #[inline]
343    fn as_fd(&self) -> BorrowedFd<'_> {
344        self.as_inner().socket().as_fd()
345    }
346}
347
348#[stable(feature = "io_safety", since = "1.63.0")]
349impl From<crate::net::TcpListener> for OwnedFd {
350    /// Takes ownership of a [`TcpListener`](crate::net::TcpListener)'s socket file descriptor.
351    #[inline]
352    fn from(tcp_listener: crate::net::TcpListener) -> OwnedFd {
353        tcp_listener.into_inner().into_socket().into_inner().into_inner().into()
354    }
355}
356
357#[stable(feature = "io_safety", since = "1.63.0")]
358impl From<OwnedFd> for crate::net::TcpListener {
359    #[inline]
360    fn from(owned_fd: OwnedFd) -> Self {
361        Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
362            owned_fd,
363        ))))
364    }
365}
366
367#[stable(feature = "io_safety", since = "1.63.0")]
368impl AsFd for crate::net::UdpSocket {
369    #[inline]
370    fn as_fd(&self) -> BorrowedFd<'_> {
371        self.as_inner().socket().as_fd()
372    }
373}
374
375#[stable(feature = "io_safety", since = "1.63.0")]
376impl From<crate::net::UdpSocket> for OwnedFd {
377    /// Takes ownership of a [`UdpSocket`](crate::net::UdpSocket)'s file descriptor.
378    #[inline]
379    fn from(udp_socket: crate::net::UdpSocket) -> OwnedFd {
380        udp_socket.into_inner().into_socket().into_inner().into_inner().into()
381    }
382}
383
384#[stable(feature = "io_safety", since = "1.63.0")]
385impl From<OwnedFd> for crate::net::UdpSocket {
386    #[inline]
387    fn from(owned_fd: OwnedFd) -> Self {
388        Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
389            owned_fd,
390        ))))
391    }
392}
393
394#[stable(feature = "asfd_ptrs", since = "1.64.0")]
395/// This impl allows implementing traits that require `AsFd` on Arc.
396/// ```
397/// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
398/// # #[cfg(target_os = "wasi")]
399/// # use std::os::wasi::io::AsFd;
400/// # #[cfg(unix)]
401/// # use std::os::unix::io::AsFd;
402/// use std::net::UdpSocket;
403/// use std::sync::Arc;
404///
405/// trait MyTrait: AsFd {}
406/// impl MyTrait for Arc<UdpSocket> {}
407/// impl MyTrait for Box<UdpSocket> {}
408/// # }
409/// ```
410impl<T: AsFd + ?Sized> AsFd for crate::sync::Arc<T> {
411    #[inline]
412    fn as_fd(&self) -> BorrowedFd<'_> {
413        (**self).as_fd()
414    }
415}
416
417#[stable(feature = "asfd_rc", since = "1.69.0")]
418impl<T: AsFd + ?Sized> AsFd for crate::rc::Rc<T> {
419    #[inline]
420    fn as_fd(&self) -> BorrowedFd<'_> {
421        (**self).as_fd()
422    }
423}
424
425#[unstable(feature = "unique_rc_arc", issue = "112566")]
426impl<T: AsFd + ?Sized> AsFd for crate::rc::UniqueRc<T> {
427    #[inline]
428    fn as_fd(&self) -> BorrowedFd<'_> {
429        (**self).as_fd()
430    }
431}
432
433#[stable(feature = "asfd_ptrs", since = "1.64.0")]
434impl<T: AsFd + ?Sized> AsFd for Box<T> {
435    #[inline]
436    fn as_fd(&self) -> BorrowedFd<'_> {
437        (**self).as_fd()
438    }
439}
440
441#[stable(feature = "io_safety", since = "1.63.0")]
442impl AsFd for io::Stdin {
443    #[inline]
444    fn as_fd(&self) -> BorrowedFd<'_> {
445        unsafe { BorrowedFd::borrow_raw(0) }
446    }
447}
448
449#[stable(feature = "io_safety", since = "1.63.0")]
450impl<'a> AsFd for io::StdinLock<'a> {
451    #[inline]
452    fn as_fd(&self) -> BorrowedFd<'_> {
453        // SAFETY: user code should not close stdin out from under the standard library
454        unsafe { BorrowedFd::borrow_raw(0) }
455    }
456}
457
458#[stable(feature = "io_safety", since = "1.63.0")]
459impl AsFd for io::Stdout {
460    #[inline]
461    fn as_fd(&self) -> BorrowedFd<'_> {
462        unsafe { BorrowedFd::borrow_raw(1) }
463    }
464}
465
466#[stable(feature = "io_safety", since = "1.63.0")]
467impl<'a> AsFd for io::StdoutLock<'a> {
468    #[inline]
469    fn as_fd(&self) -> BorrowedFd<'_> {
470        // SAFETY: user code should not close stdout out from under the standard library
471        unsafe { BorrowedFd::borrow_raw(1) }
472    }
473}
474
475#[stable(feature = "io_safety", since = "1.63.0")]
476impl AsFd for io::Stderr {
477    #[inline]
478    fn as_fd(&self) -> BorrowedFd<'_> {
479        unsafe { BorrowedFd::borrow_raw(2) }
480    }
481}
482
483#[stable(feature = "io_safety", since = "1.63.0")]
484impl<'a> AsFd for io::StderrLock<'a> {
485    #[inline]
486    fn as_fd(&self) -> BorrowedFd<'_> {
487        // SAFETY: user code should not close stderr out from under the standard library
488        unsafe { BorrowedFd::borrow_raw(2) }
489    }
490}