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};
9 use crate::marker::PhantomData;
10 use crate::mem::forget;
11 #[cfg(not(any(target_arch = "wasm32", target_env = "sgx")))]
13 use crate::sys_common::{AsInner, FromInner, IntoInner};
15 /// A borrowed file descriptor.
17 /// This has a lifetime parameter to tie it to the lifetime of something that
18 /// owns the file descriptor.
20 /// This uses `repr(transparent)` and has the representation of a host file
21 /// descriptor, so it can be used in FFI in places where a file descriptor is
22 /// passed as an argument, it is not captured or consumed, and it never has the
25 /// This type's `.to_owned()` implementation returns another `BorrowedFd`
26 /// rather than an `OwnedFd`. It just makes a trivial copy of the raw file
27 /// descriptor, which is then borrowed under the same lifetime.
28 #[derive(Copy, Clone)]
30 #[rustc_layout_scalar_valid_range_start(0)]
31 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
32 // 32-bit c_int. Below is -2, in two's complement, but that only works out
33 // because c_int is 32 bits.
34 #[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
35 #[rustc_nonnull_optimization_guaranteed]
36 #[stable(feature = "io_safety", since = "1.63.0")]
37 pub struct BorrowedFd<'fd> {
39 _phantom: PhantomData<&'fd OwnedFd>,
42 /// An owned file descriptor.
44 /// This closes the file descriptor on drop.
46 /// This uses `repr(transparent)` and has the representation of a host file
47 /// descriptor, so it can be used in FFI in places where a file descriptor is
48 /// passed as a consumed argument or returned as an owned value, and it never
49 /// has the value `-1`.
51 #[rustc_layout_scalar_valid_range_start(0)]
52 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
53 // 32-bit c_int. Below is -2, in two's complement, but that only works out
54 // because c_int is 32 bits.
55 #[rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE)]
56 #[rustc_nonnull_optimization_guaranteed]
57 #[stable(feature = "io_safety", since = "1.63.0")]
63 /// Return a `BorrowedFd` holding the given raw file descriptor.
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`.
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 unsafe { Self { fd, _phantom: PhantomData } }
80 /// Creates a new `OwnedFd` instance that shares the same underlying file
81 /// description as the existing `OwnedFd` instance.
82 #[stable(feature = "io_safety", since = "1.63.0")]
83 pub fn try_clone(&self) -> crate::io::Result<Self> {
84 self.as_fd().try_clone_to_owned()
89 /// Creates a new `OwnedFd` instance that shares the same underlying file
90 /// description as the existing `BorrowedFd` instance.
91 #[cfg(not(target_arch = "wasm32"))]
92 #[stable(feature = "io_safety", since = "1.63.0")]
93 pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
94 // We want to atomically duplicate this file descriptor and set the
95 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
96 // is a POSIX flag that was added to Linux in 2.6.24.
97 #[cfg(not(target_os = "espidf"))]
98 let cmd = libc::F_DUPFD_CLOEXEC;
100 // For ESP-IDF, F_DUPFD is used instead, because the CLOEXEC semantics
101 // will never be supported, as this is a bare metal framework with
102 // no capabilities for multi-process execution. While F_DUPFD is also
103 // not supported yet, it might be (currently it returns ENOSYS).
104 #[cfg(target_os = "espidf")]
105 let cmd = libc::F_DUPFD;
107 // Avoid using file descriptors below 3 as they are used for stdio
108 let fd = cvt(unsafe { libc::fcntl(self.as_raw_fd(), cmd, 3) })?;
109 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
112 /// Creates a new `OwnedFd` instance that shares the same underlying file
113 /// description as the existing `BorrowedFd` instance.
114 #[cfg(target_arch = "wasm32")]
115 #[stable(feature = "io_safety", since = "1.63.0")]
116 pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
117 Err(crate::io::const_io_error!(
118 crate::io::ErrorKind::Unsupported,
119 "operation not supported on WASI yet",
124 #[stable(feature = "io_safety", since = "1.63.0")]
125 impl AsRawFd for BorrowedFd<'_> {
127 fn as_raw_fd(&self) -> RawFd {
132 #[stable(feature = "io_safety", since = "1.63.0")]
133 impl AsRawFd for OwnedFd {
135 fn as_raw_fd(&self) -> RawFd {
140 #[stable(feature = "io_safety", since = "1.63.0")]
141 impl IntoRawFd for OwnedFd {
143 fn into_raw_fd(self) -> RawFd {
150 #[stable(feature = "io_safety", since = "1.63.0")]
151 impl FromRawFd for OwnedFd {
152 /// Constructs a new instance of `Self` from the given raw file descriptor.
156 /// The resource pointed to by `fd` must be open and suitable for assuming
157 /// ownership. The resource must not require any cleanup other than `close`.
159 unsafe fn from_raw_fd(fd: RawFd) -> Self {
160 assert_ne!(fd, u32::MAX as RawFd);
161 // 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)
162 unsafe { Self { fd } }
166 #[stable(feature = "io_safety", since = "1.63.0")]
167 impl Drop for OwnedFd {
171 // Note that errors are ignored when closing a file descriptor. The
172 // reason for this is that if an error occurs we don't actually know if
173 // the file descriptor was closed or not, and if we retried (for
174 // something like EINTR), we might close another valid file descriptor
175 // opened after we closed ours.
176 let _ = libc::close(self.fd);
181 #[stable(feature = "io_safety", since = "1.63.0")]
182 impl fmt::Debug for BorrowedFd<'_> {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 f.debug_struct("BorrowedFd").field("fd", &self.fd).finish()
188 #[stable(feature = "io_safety", since = "1.63.0")]
189 impl fmt::Debug for OwnedFd {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.debug_struct("OwnedFd").field("fd", &self.fd).finish()
195 /// A trait to borrow the file descriptor from an underlying object.
197 /// This is only available on unix platforms and must be imported in order to
198 /// call the method. Windows platforms have a corresponding `AsHandle` and
199 /// `AsSocket` set of traits.
200 #[stable(feature = "io_safety", since = "1.63.0")]
202 /// Borrows the file descriptor.
207 /// use std::fs::File;
209 /// # #[cfg(target_os = "wasi")]
210 /// # use std::os::wasi::io::{AsFd, BorrowedFd};
212 /// # use std::os::unix::io::{AsFd, BorrowedFd};
214 /// let mut f = File::open("foo.txt")?;
215 /// # #[cfg(any(unix, target_os = "wasi"))]
216 /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
217 /// # Ok::<(), io::Error>(())
219 #[stable(feature = "io_safety", since = "1.63.0")]
220 fn as_fd(&self) -> BorrowedFd<'_>;
223 #[stable(feature = "io_safety", since = "1.63.0")]
224 impl<T: AsFd> AsFd for &T {
226 fn as_fd(&self) -> BorrowedFd<'_> {
231 #[stable(feature = "io_safety", since = "1.63.0")]
232 impl<T: AsFd> AsFd for &mut T {
234 fn as_fd(&self) -> BorrowedFd<'_> {
239 #[stable(feature = "io_safety", since = "1.63.0")]
240 impl AsFd for BorrowedFd<'_> {
242 fn as_fd(&self) -> BorrowedFd<'_> {
247 #[stable(feature = "io_safety", since = "1.63.0")]
248 impl AsFd for OwnedFd {
250 fn as_fd(&self) -> BorrowedFd<'_> {
251 // Safety: `OwnedFd` and `BorrowedFd` have the same validity
252 // invariants, and the `BorrowdFd` is bounded by the lifetime
254 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
258 #[stable(feature = "io_safety", since = "1.63.0")]
259 impl AsFd for fs::File {
261 fn as_fd(&self) -> BorrowedFd<'_> {
262 self.as_inner().as_fd()
266 #[stable(feature = "io_safety", since = "1.63.0")]
267 impl From<fs::File> for OwnedFd {
269 fn from(file: fs::File) -> OwnedFd {
270 file.into_inner().into_inner().into_inner()
274 #[stable(feature = "io_safety", since = "1.63.0")]
275 impl From<OwnedFd> for fs::File {
277 fn from(owned_fd: OwnedFd) -> Self {
278 Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned_fd)))
282 #[stable(feature = "io_safety", since = "1.63.0")]
283 impl AsFd for crate::net::TcpStream {
285 fn as_fd(&self) -> BorrowedFd<'_> {
286 self.as_inner().socket().as_fd()
290 #[stable(feature = "io_safety", since = "1.63.0")]
291 impl From<crate::net::TcpStream> for OwnedFd {
293 fn from(tcp_stream: crate::net::TcpStream) -> OwnedFd {
294 tcp_stream.into_inner().into_socket().into_inner().into_inner().into()
298 #[stable(feature = "io_safety", since = "1.63.0")]
299 impl From<OwnedFd> for crate::net::TcpStream {
301 fn from(owned_fd: OwnedFd) -> Self {
302 Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
308 #[stable(feature = "io_safety", since = "1.63.0")]
309 impl AsFd for crate::net::TcpListener {
311 fn as_fd(&self) -> BorrowedFd<'_> {
312 self.as_inner().socket().as_fd()
316 #[stable(feature = "io_safety", since = "1.63.0")]
317 impl From<crate::net::TcpListener> for OwnedFd {
319 fn from(tcp_listener: crate::net::TcpListener) -> OwnedFd {
320 tcp_listener.into_inner().into_socket().into_inner().into_inner().into()
324 #[stable(feature = "io_safety", since = "1.63.0")]
325 impl From<OwnedFd> for crate::net::TcpListener {
327 fn from(owned_fd: OwnedFd) -> Self {
328 Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
334 #[stable(feature = "io_safety", since = "1.63.0")]
335 impl AsFd for crate::net::UdpSocket {
337 fn as_fd(&self) -> BorrowedFd<'_> {
338 self.as_inner().socket().as_fd()
342 #[stable(feature = "io_safety", since = "1.63.0")]
343 impl From<crate::net::UdpSocket> for OwnedFd {
345 fn from(udp_socket: crate::net::UdpSocket) -> OwnedFd {
346 udp_socket.into_inner().into_socket().into_inner().into_inner().into()
350 #[stable(feature = "io_safety", since = "1.63.0")]
351 impl From<OwnedFd> for crate::net::UdpSocket {
353 fn from(owned_fd: OwnedFd) -> Self {
354 Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
360 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
361 /// This impl allows implementing traits that require `AsFd` on Arc.
363 /// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
364 /// # #[cfg(target_os = "wasi")]
365 /// # use std::os::wasi::io::AsFd;
367 /// # use std::os::unix::io::AsFd;
368 /// use std::net::UdpSocket;
369 /// use std::sync::Arc;
371 /// trait MyTrait: AsFd {}
372 /// impl MyTrait for Arc<UdpSocket> {}
373 /// impl MyTrait for Box<UdpSocket> {}
376 impl<T: AsFd> AsFd for crate::sync::Arc<T> {
378 fn as_fd(&self) -> BorrowedFd<'_> {
383 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
384 impl<T: AsFd> AsFd for Box<T> {
386 fn as_fd(&self) -> BorrowedFd<'_> {