1 //! Owned and borrowed Unix-like file descriptors.
3 #![stable(feature = "io_safety", since = "1.63.0")]
4 #![deny(unsafe_op_in_unsafe_fn)]
6 use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
10 use crate::marker::PhantomData;
11 use crate::mem::forget;
12 #[cfg(not(any(target_arch = "wasm32", target_env = "sgx")))]
14 use crate::sys_common::{AsInner, FromInner, IntoInner};
16 /// A borrowed file descriptor.
18 /// This has a lifetime parameter to tie it to the lifetime of something that
19 /// owns the file descriptor.
21 /// This uses `repr(transparent)` and has the representation of a host file
22 /// descriptor, so it can be used in FFI in places where a file descriptor is
23 /// passed as an argument, it is not captured or consumed, and it never has the
26 /// This type's `.to_owned()` implementation returns another `BorrowedFd`
27 /// rather than an `OwnedFd`. It just makes a trivial copy of the raw file
28 /// descriptor, which is then borrowed under the same lifetime.
29 #[derive(Copy, Clone)]
31 #[rustc_layout_scalar_valid_range_start(0)]
32 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
33 // 32-bit c_int. Below is -2, in two's complement, but that only works out
34 // because c_int is 32 bits.
35 #[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
36 #[rustc_nonnull_optimization_guaranteed]
37 #[stable(feature = "io_safety", since = "1.63.0")]
38 pub struct BorrowedFd<'fd> {
40 _phantom: PhantomData<&'fd OwnedFd>,
43 /// An owned file descriptor.
45 /// This closes the file descriptor on drop.
47 /// This uses `repr(transparent)` and has the representation of a host file
48 /// descriptor, so it can be used in FFI in places where a file descriptor is
49 /// passed as a consumed argument or returned as an owned value, and it never
50 /// has the value `-1`.
52 #[rustc_layout_scalar_valid_range_start(0)]
53 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
54 // 32-bit c_int. Below is -2, in two's complement, but that only works out
55 // because c_int is 32 bits.
56 #[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
57 #[rustc_nonnull_optimization_guaranteed]
58 #[stable(feature = "io_safety", since = "1.63.0")]
64 /// Return a `BorrowedFd` holding the given raw file descriptor.
68 /// The resource pointed to by `fd` must remain open for the duration of
69 /// the returned `BorrowedFd`, and it must not have the value `-1`.
71 #[rustc_const_stable(feature = "io_safety", since = "1.63.0")]
72 #[stable(feature = "io_safety", since = "1.63.0")]
73 pub const unsafe fn borrow_raw(fd: RawFd) -> Self {
74 assert!(fd != u32::MAX as RawFd);
75 // 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)
76 unsafe { Self { fd, _phantom: PhantomData } }
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()
90 /// Creates a new `OwnedFd` instance that shares the same underlying file
91 /// description as the existing `BorrowedFd` instance.
92 #[cfg(not(target_arch = "wasm32"))]
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(target_os = "espidf"))]
99 let cmd = libc::F_DUPFD_CLOEXEC;
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(target_os = "espidf")]
106 let cmd = libc::F_DUPFD;
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) })
113 /// Creates a new `OwnedFd` instance that shares the same underlying file
114 /// description as the existing `BorrowedFd` instance.
115 #[cfg(target_arch = "wasm32")]
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::const_io_error!(
119 crate::io::ErrorKind::Unsupported,
120 "operation not supported on WASI yet",
125 #[stable(feature = "io_safety", since = "1.63.0")]
126 impl AsRawFd for BorrowedFd<'_> {
128 fn as_raw_fd(&self) -> RawFd {
133 #[stable(feature = "io_safety", since = "1.63.0")]
134 impl AsRawFd for OwnedFd {
136 fn as_raw_fd(&self) -> RawFd {
141 #[stable(feature = "io_safety", since = "1.63.0")]
142 impl IntoRawFd for OwnedFd {
144 fn into_raw_fd(self) -> RawFd {
151 #[stable(feature = "io_safety", since = "1.63.0")]
152 impl FromRawFd for OwnedFd {
153 /// Constructs a new instance of `Self` from the given raw file descriptor.
157 /// The resource pointed to by `fd` must be open and suitable for assuming
158 /// ownership. The resource must not require any cleanup other than `close`.
160 unsafe fn from_raw_fd(fd: RawFd) -> Self {
161 assert_ne!(fd, u32::MAX as RawFd);
162 // 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)
163 unsafe { Self { fd } }
167 #[stable(feature = "io_safety", since = "1.63.0")]
168 impl Drop for OwnedFd {
172 // Note that errors are ignored when closing a file descriptor. The
173 // reason for this is that if an error occurs we don't actually know if
174 // the file descriptor was closed or not, and if we retried (for
175 // something like EINTR), we might close another valid file descriptor
176 // opened after we closed ours.
177 let _ = libc::close(self.fd);
182 #[stable(feature = "io_safety", since = "1.63.0")]
183 impl fmt::Debug for BorrowedFd<'_> {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 f.debug_struct("BorrowedFd").field("fd", &self.fd).finish()
189 #[stable(feature = "io_safety", since = "1.63.0")]
190 impl fmt::Debug for OwnedFd {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 f.debug_struct("OwnedFd").field("fd", &self.fd).finish()
196 macro_rules! impl_is_terminal {
197 ($($t:ty),*$(,)?) => {$(
198 #[unstable(feature = "sealed", issue = "none")]
199 impl crate::sealed::Sealed for $t {}
201 #[unstable(feature = "is_terminal", issue = "98070")]
202 impl crate::io::IsTerminal for $t {
204 fn is_terminal(&self) -> bool {
205 crate::sys::io::is_terminal(self)
211 impl_is_terminal!(BorrowedFd<'_>, OwnedFd);
213 /// A trait to borrow the file descriptor from an underlying object.
215 /// This is only available on unix platforms and must be imported in order to
216 /// call the method. Windows platforms have a corresponding `AsHandle` and
217 /// `AsSocket` set of traits.
218 #[stable(feature = "io_safety", since = "1.63.0")]
220 /// Borrows the file descriptor.
225 /// use std::fs::File;
227 /// # #[cfg(any(unix, target_os = "wasi"))]
228 /// # use std::os::fd::{AsFd, BorrowedFd};
230 /// let mut f = File::open("foo.txt")?;
231 /// # #[cfg(any(unix, target_os = "wasi"))]
232 /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
233 /// # Ok::<(), io::Error>(())
235 #[stable(feature = "io_safety", since = "1.63.0")]
236 fn as_fd(&self) -> BorrowedFd<'_>;
239 #[stable(feature = "io_safety", since = "1.63.0")]
240 impl<T: AsFd> AsFd for &T {
242 fn as_fd(&self) -> BorrowedFd<'_> {
247 #[stable(feature = "io_safety", since = "1.63.0")]
248 impl<T: AsFd> AsFd for &mut T {
250 fn as_fd(&self) -> BorrowedFd<'_> {
255 #[stable(feature = "io_safety", since = "1.63.0")]
256 impl AsFd for BorrowedFd<'_> {
258 fn as_fd(&self) -> BorrowedFd<'_> {
263 #[stable(feature = "io_safety", since = "1.63.0")]
264 impl AsFd for OwnedFd {
266 fn as_fd(&self) -> BorrowedFd<'_> {
267 // Safety: `OwnedFd` and `BorrowedFd` have the same validity
268 // invariants, and the `BorrowdFd` is bounded by the lifetime
270 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
274 #[stable(feature = "io_safety", since = "1.63.0")]
275 impl AsFd for fs::File {
277 fn as_fd(&self) -> BorrowedFd<'_> {
278 self.as_inner().as_fd()
282 #[stable(feature = "io_safety", since = "1.63.0")]
283 impl From<fs::File> for OwnedFd {
285 fn from(file: fs::File) -> OwnedFd {
286 file.into_inner().into_inner().into_inner()
290 #[stable(feature = "io_safety", since = "1.63.0")]
291 impl From<OwnedFd> for fs::File {
293 fn from(owned_fd: OwnedFd) -> Self {
294 Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned_fd)))
298 #[stable(feature = "io_safety", since = "1.63.0")]
299 impl AsFd for crate::net::TcpStream {
301 fn as_fd(&self) -> BorrowedFd<'_> {
302 self.as_inner().socket().as_fd()
306 #[stable(feature = "io_safety", since = "1.63.0")]
307 impl From<crate::net::TcpStream> for OwnedFd {
309 fn from(tcp_stream: crate::net::TcpStream) -> OwnedFd {
310 tcp_stream.into_inner().into_socket().into_inner().into_inner().into()
314 #[stable(feature = "io_safety", since = "1.63.0")]
315 impl From<OwnedFd> for crate::net::TcpStream {
317 fn from(owned_fd: OwnedFd) -> Self {
318 Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
324 #[stable(feature = "io_safety", since = "1.63.0")]
325 impl AsFd for crate::net::TcpListener {
327 fn as_fd(&self) -> BorrowedFd<'_> {
328 self.as_inner().socket().as_fd()
332 #[stable(feature = "io_safety", since = "1.63.0")]
333 impl From<crate::net::TcpListener> for OwnedFd {
335 fn from(tcp_listener: crate::net::TcpListener) -> OwnedFd {
336 tcp_listener.into_inner().into_socket().into_inner().into_inner().into()
340 #[stable(feature = "io_safety", since = "1.63.0")]
341 impl From<OwnedFd> for crate::net::TcpListener {
343 fn from(owned_fd: OwnedFd) -> Self {
344 Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
350 #[stable(feature = "io_safety", since = "1.63.0")]
351 impl AsFd for crate::net::UdpSocket {
353 fn as_fd(&self) -> BorrowedFd<'_> {
354 self.as_inner().socket().as_fd()
358 #[stable(feature = "io_safety", since = "1.63.0")]
359 impl From<crate::net::UdpSocket> for OwnedFd {
361 fn from(udp_socket: crate::net::UdpSocket) -> OwnedFd {
362 udp_socket.into_inner().into_socket().into_inner().into_inner().into()
366 #[stable(feature = "io_safety", since = "1.63.0")]
367 impl From<OwnedFd> for crate::net::UdpSocket {
369 fn from(owned_fd: OwnedFd) -> Self {
370 Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
376 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
377 /// This impl allows implementing traits that require `AsFd` on Arc.
379 /// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
380 /// # #[cfg(target_os = "wasi")]
381 /// # use std::os::wasi::io::AsFd;
383 /// # use std::os::unix::io::AsFd;
384 /// use std::net::UdpSocket;
385 /// use std::sync::Arc;
387 /// trait MyTrait: AsFd {}
388 /// impl MyTrait for Arc<UdpSocket> {}
389 /// impl MyTrait for Box<UdpSocket> {}
392 impl<T: AsFd> AsFd for crate::sync::Arc<T> {
394 fn as_fd(&self) -> BorrowedFd<'_> {
399 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
400 impl<T: AsFd> AsFd for Box<T> {
402 fn as_fd(&self) -> BorrowedFd<'_> {
407 #[stable(feature = "io_safety", since = "1.63.0")]
408 impl AsFd for io::Stdin {
410 fn as_fd(&self) -> BorrowedFd<'_> {
411 unsafe { BorrowedFd::borrow_raw(0) }
415 #[stable(feature = "io_safety", since = "1.63.0")]
416 impl<'a> AsFd for io::StdinLock<'a> {
418 fn as_fd(&self) -> BorrowedFd<'_> {
419 // SAFETY: user code should not close stdin out from under the standard library
420 unsafe { BorrowedFd::borrow_raw(0) }
424 #[stable(feature = "io_safety", since = "1.63.0")]
425 impl AsFd for io::Stdout {
427 fn as_fd(&self) -> BorrowedFd<'_> {
428 unsafe { BorrowedFd::borrow_raw(1) }
432 #[stable(feature = "io_safety", since = "1.63.0")]
433 impl<'a> AsFd for io::StdoutLock<'a> {
435 fn as_fd(&self) -> BorrowedFd<'_> {
436 // SAFETY: user code should not close stdout out from under the standard library
437 unsafe { BorrowedFd::borrow_raw(1) }
441 #[stable(feature = "io_safety", since = "1.63.0")]
442 impl AsFd for io::Stderr {
444 fn as_fd(&self) -> BorrowedFd<'_> {
445 unsafe { BorrowedFd::borrow_raw(2) }
449 #[stable(feature = "io_safety", since = "1.63.0")]
450 impl<'a> AsFd for io::StderrLock<'a> {
452 fn as_fd(&self) -> BorrowedFd<'_> {
453 // SAFETY: user code should not close stderr out from under the standard library
454 unsafe { BorrowedFd::borrow_raw(2) }