Skip to main content

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