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