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", target_os = "hermit")))]
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(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(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(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
::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 #[cfg(not(target_os = "hermit"))]
178 let _
= libc
::close(self.fd
);
179 #[cfg(target_os = "hermit")]
180 let _
= hermit_abi
::close(self.fd
);
185 #[stable(feature = "io_safety", since = "1.63.0")]
186 impl fmt
::Debug
for BorrowedFd
<'_
> {
187 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
188 f
.debug_struct("BorrowedFd").field("fd", &self.fd
).finish()
192 #[stable(feature = "io_safety", since = "1.63.0")]
193 impl fmt
::Debug
for OwnedFd
{
194 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
195 f
.debug_struct("OwnedFd").field("fd", &self.fd
).finish()
199 macro_rules
! impl_is_terminal
{
200 ($
($t
:ty
),*$
(,)?
) => {$
(
201 #[unstable(feature = "sealed", issue = "none")]
202 impl crate::sealed
::Sealed
for $t {}
204 #[unstable(feature = "is_terminal", issue = "98070")]
205 impl crate::io
::IsTerminal
for $t
{
207 fn is_terminal(&self) -> bool
{
208 crate::sys
::io
::is_terminal(self)
214 impl_is_terminal
!(BorrowedFd
<'_
>, OwnedFd
);
216 /// A trait to borrow the file descriptor from an underlying object.
218 /// This is only available on unix platforms and must be imported in order to
219 /// call the method. Windows platforms have a corresponding `AsHandle` and
220 /// `AsSocket` set of traits.
221 #[stable(feature = "io_safety", since = "1.63.0")]
223 /// Borrows the file descriptor.
228 /// use std::fs::File;
230 /// # #[cfg(any(unix, target_os = "wasi"))]
231 /// # use std::os::fd::{AsFd, BorrowedFd};
233 /// let mut f = File::open("foo.txt")?;
234 /// # #[cfg(any(unix, target_os = "wasi"))]
235 /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
236 /// # Ok::<(), io::Error>(())
238 #[stable(feature = "io_safety", since = "1.63.0")]
239 fn as_fd(&self) -> BorrowedFd
<'_
>;
242 #[stable(feature = "io_safety", since = "1.63.0")]
243 impl<T
: AsFd
> AsFd
for &T
{
245 fn as_fd(&self) -> BorrowedFd
<'_
> {
250 #[stable(feature = "io_safety", since = "1.63.0")]
251 impl<T
: AsFd
> AsFd
for &mut T
{
253 fn as_fd(&self) -> BorrowedFd
<'_
> {
258 #[stable(feature = "io_safety", since = "1.63.0")]
259 impl AsFd
for BorrowedFd
<'_
> {
261 fn as_fd(&self) -> BorrowedFd
<'_
> {
266 #[stable(feature = "io_safety", since = "1.63.0")]
267 impl AsFd
for OwnedFd
{
269 fn as_fd(&self) -> BorrowedFd
<'_
> {
270 // Safety: `OwnedFd` and `BorrowedFd` have the same validity
271 // invariants, and the `BorrowdFd` is bounded by the lifetime
273 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
277 #[stable(feature = "io_safety", since = "1.63.0")]
278 impl AsFd
for fs
::File
{
280 fn as_fd(&self) -> BorrowedFd
<'_
> {
281 self.as_inner().as_fd()
285 #[stable(feature = "io_safety", since = "1.63.0")]
286 impl From
<fs
::File
> for OwnedFd
{
288 fn from(file
: fs
::File
) -> OwnedFd
{
289 file
.into_inner().into_inner().into_inner()
293 #[stable(feature = "io_safety", since = "1.63.0")]
294 impl From
<OwnedFd
> for fs
::File
{
296 fn from(owned_fd
: OwnedFd
) -> Self {
297 Self::from_inner(FromInner
::from_inner(FromInner
::from_inner(owned_fd
)))
301 #[stable(feature = "io_safety", since = "1.63.0")]
302 impl AsFd
for crate::net
::TcpStream
{
304 fn as_fd(&self) -> BorrowedFd
<'_
> {
305 self.as_inner().socket().as_fd()
309 #[stable(feature = "io_safety", since = "1.63.0")]
310 impl From
<crate::net
::TcpStream
> for OwnedFd
{
312 fn from(tcp_stream
: crate::net
::TcpStream
) -> OwnedFd
{
313 tcp_stream
.into_inner().into_socket().into_inner().into_inner().into()
317 #[stable(feature = "io_safety", since = "1.63.0")]
318 impl From
<OwnedFd
> for crate::net
::TcpStream
{
320 fn from(owned_fd
: OwnedFd
) -> Self {
321 Self::from_inner(FromInner
::from_inner(FromInner
::from_inner(FromInner
::from_inner(
327 #[stable(feature = "io_safety", since = "1.63.0")]
328 impl AsFd
for crate::net
::TcpListener
{
330 fn as_fd(&self) -> BorrowedFd
<'_
> {
331 self.as_inner().socket().as_fd()
335 #[stable(feature = "io_safety", since = "1.63.0")]
336 impl From
<crate::net
::TcpListener
> for OwnedFd
{
338 fn from(tcp_listener
: crate::net
::TcpListener
) -> OwnedFd
{
339 tcp_listener
.into_inner().into_socket().into_inner().into_inner().into()
343 #[stable(feature = "io_safety", since = "1.63.0")]
344 impl From
<OwnedFd
> for crate::net
::TcpListener
{
346 fn from(owned_fd
: OwnedFd
) -> Self {
347 Self::from_inner(FromInner
::from_inner(FromInner
::from_inner(FromInner
::from_inner(
353 #[stable(feature = "io_safety", since = "1.63.0")]
354 impl AsFd
for crate::net
::UdpSocket
{
356 fn as_fd(&self) -> BorrowedFd
<'_
> {
357 self.as_inner().socket().as_fd()
361 #[stable(feature = "io_safety", since = "1.63.0")]
362 impl From
<crate::net
::UdpSocket
> for OwnedFd
{
364 fn from(udp_socket
: crate::net
::UdpSocket
) -> OwnedFd
{
365 udp_socket
.into_inner().into_socket().into_inner().into_inner().into()
369 #[stable(feature = "io_safety", since = "1.63.0")]
370 impl From
<OwnedFd
> for crate::net
::UdpSocket
{
372 fn from(owned_fd
: OwnedFd
) -> Self {
373 Self::from_inner(FromInner
::from_inner(FromInner
::from_inner(FromInner
::from_inner(
379 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
380 /// This impl allows implementing traits that require `AsFd` on Arc.
382 /// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
383 /// # #[cfg(target_os = "wasi")]
384 /// # use std::os::wasi::io::AsFd;
386 /// # use std::os::unix::io::AsFd;
387 /// use std::net::UdpSocket;
388 /// use std::sync::Arc;
390 /// trait MyTrait: AsFd {}
391 /// impl MyTrait for Arc<UdpSocket> {}
392 /// impl MyTrait for Box<UdpSocket> {}
395 impl<T
: AsFd
> AsFd
for crate::sync
::Arc
<T
> {
397 fn as_fd(&self) -> BorrowedFd
<'_
> {
402 #[stable(feature = "asfd_rc", since = "1.69.0")]
403 impl<T
: AsFd
> AsFd
for crate::rc
::Rc
<T
> {
405 fn as_fd(&self) -> BorrowedFd
<'_
> {
410 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
411 impl<T
: AsFd
> AsFd
for Box
<T
> {
413 fn as_fd(&self) -> BorrowedFd
<'_
> {
418 #[stable(feature = "io_safety", since = "1.63.0")]
419 impl AsFd
for io
::Stdin
{
421 fn as_fd(&self) -> BorrowedFd
<'_
> {
422 unsafe { BorrowedFd::borrow_raw(0) }
426 #[stable(feature = "io_safety", since = "1.63.0")]
427 impl<'a
> AsFd
for io
::StdinLock
<'a
> {
429 fn as_fd(&self) -> BorrowedFd
<'_
> {
430 // SAFETY: user code should not close stdin out from under the standard library
431 unsafe { BorrowedFd::borrow_raw(0) }
435 #[stable(feature = "io_safety", since = "1.63.0")]
436 impl AsFd
for io
::Stdout
{
438 fn as_fd(&self) -> BorrowedFd
<'_
> {
439 unsafe { BorrowedFd::borrow_raw(1) }
443 #[stable(feature = "io_safety", since = "1.63.0")]
444 impl<'a
> AsFd
for io
::StdoutLock
<'a
> {
446 fn as_fd(&self) -> BorrowedFd
<'_
> {
447 // SAFETY: user code should not close stdout out from under the standard library
448 unsafe { BorrowedFd::borrow_raw(1) }
452 #[stable(feature = "io_safety", since = "1.63.0")]
453 impl AsFd
for io
::Stderr
{
455 fn as_fd(&self) -> BorrowedFd
<'_
> {
456 unsafe { BorrowedFd::borrow_raw(2) }
460 #[stable(feature = "io_safety", since = "1.63.0")]
461 impl<'a
> AsFd
for io
::StderrLock
<'a
> {
463 fn as_fd(&self) -> BorrowedFd
<'_
> {
464 // SAFETY: user code should not close stderr out from under the standard library
465 unsafe { BorrowedFd::borrow_raw(2) }