1 //! The following is derived from Rust's
2 //! library/std/src/os/fd/owned.rs at revision
3 //! fa68e73e9947be8ffc5b3b46d899e4953a44e7e9.
5 //! All code in this file is licensed MIT or Apache 2.0 at your option.
7 //! Owned and borrowed Unix-like file descriptors.
9 #![cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
10 #![deny(unsafe_op_in_unsafe_fn)]
11 #![allow(unsafe_code)]
13 use super::raw
::{AsRawFd, FromRawFd, IntoRawFd, RawFd}
;
16 use core
::marker
::PhantomData
;
17 use core
::mem
::forget
;
19 /// A borrowed file descriptor.
21 /// This has a lifetime parameter to tie it to the lifetime of something that
22 /// owns the file descriptor.
24 /// This uses `repr(transparent)` and has the representation of a host file
25 /// descriptor, so it can be used in FFI in places where a file descriptor is
26 /// passed as an argument, it is not captured or consumed, and it never has the
29 /// This type's `.to_owned()` implementation returns another `BorrowedFd`
30 /// rather than an `OwnedFd`. It just makes a trivial copy of the raw file
31 /// descriptor, which is then borrowed under the same lifetime.
32 #[derive(Copy, Clone)]
34 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_start(0))]
35 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
36 // 32-bit c_int. Below is -2, in two's complement, but that only works out
37 // because c_int is 32 bits.
38 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))]
39 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
40 #[cfg_attr(rustc_attrs, rustc_nonnull_optimization_guaranteed)]
41 pub struct BorrowedFd
<'fd
> {
43 _phantom
: PhantomData
<&'fd OwnedFd
>,
46 /// An owned file descriptor.
48 /// This closes the file descriptor on drop.
50 /// This uses `repr(transparent)` and has the representation of a host file
51 /// descriptor, so it can be used in FFI in places where a file descriptor is
52 /// passed as a consumed argument or returned as an owned value, and it never
53 /// has the value `-1`.
55 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_start(0))]
56 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
57 // 32-bit c_int. Below is -2, in two's complement, but that only works out
58 // because c_int is 32 bits.
59 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))]
60 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
61 #[cfg_attr(rustc_attrs, rustc_nonnull_optimization_guaranteed)]
67 /// Return a `BorrowedFd` holding the given raw file descriptor.
71 /// The resource pointed to by `fd` must remain open for the duration of
72 /// the returned `BorrowedFd`, and it must not have the value `-1`.
74 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
75 pub const unsafe fn borrow_raw(fd
: RawFd
) -> Self {
76 assert
!(fd
!= u32::MAX
as RawFd
);
77 // 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)
78 #[allow(unused_unsafe)]
82 _phantom
: PhantomData
,
89 /// Creates a new `OwnedFd` instance that shares the same underlying file handle
90 /// as the existing `OwnedFd` instance.
91 #[cfg(not(target_arch = "wasm32"))]
92 pub fn try_clone(&self) -> crate::io
::Result
<Self> {
93 // We want to atomically duplicate this file descriptor and set the
94 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
95 // is a POSIX flag that was added to Linux in 2.6.24.
96 #[cfg(not(target_os = "espidf"))]
97 let fd
= crate::io
::fcntl_dupfd_cloexec(self, 0)?
;
99 // For ESP-IDF, F_DUPFD is used instead, because the CLOEXEC semantics
100 // will never be supported, as this is a bare metal framework with
101 // no capabilities for multi-process execution. While F_DUPFD is also
102 // not supported yet, it might be (currently it returns ENOSYS).
103 #[cfg(target_os = "espidf")]
104 let fd
= crate::io
::fcntl_dupfd(self)?
;
109 #[cfg(target_arch = "wasm32")]
110 pub fn try_clone(&self) -> crate::io
::Result
<Self> {
111 Err(crate::io
::const_io_error
!(
112 crate::io
::ErrorKind
::Unsupported
,
113 "operation not supported on WASI yet",
118 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
119 impl AsRawFd
for BorrowedFd
<'_
> {
121 fn as_raw_fd(&self) -> RawFd
{
126 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
127 impl AsRawFd
for OwnedFd
{
129 fn as_raw_fd(&self) -> RawFd
{
134 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
135 impl IntoRawFd
for OwnedFd
{
137 fn into_raw_fd(self) -> RawFd
{
144 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
145 impl FromRawFd
for OwnedFd
{
146 /// Constructs a new instance of `Self` from the given raw file descriptor.
150 /// The resource pointed to by `fd` must be open and suitable for assuming
151 /// ownership. The resource must not require any cleanup other than `close`.
153 unsafe fn from_raw_fd(fd
: RawFd
) -> Self {
154 assert_ne
!(fd
, u32::MAX
as RawFd
);
155 // 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)
156 #[allow(unused_unsafe)]
163 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
164 impl Drop
for OwnedFd
{
168 // Errors are ignored when closing a file descriptor. The reason
169 // for this is that if an error occurs we don't actually know if
170 // the file descriptor was closed or not, and if we retried (for
171 // something like EINTR), we might close another valid file
172 // descriptor opened after we closed ours.
178 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
179 impl fmt
::Debug
for BorrowedFd
<'_
> {
180 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
181 f
.debug_struct("BorrowedFd").field("fd", &self.fd
).finish()
185 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
186 impl fmt
::Debug
for OwnedFd
{
187 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
188 f
.debug_struct("OwnedFd").field("fd", &self.fd
).finish()
192 /// A trait to borrow the file descriptor from an underlying object.
194 /// This is only available on unix platforms and must be imported in order to
195 /// call the method. Windows platforms have a corresponding `AsHandle` and
196 /// `AsSocket` set of traits.
197 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
199 /// Borrows the file descriptor.
204 /// # #![feature(io_safety)]
205 /// use std::fs::File;
207 /// # #[cfg(target_os = "wasi")]
208 /// # use std::os::wasi::io::{AsFd, BorrowedFd};
210 /// # use std::os::unix::io::{AsFd, BorrowedFd};
212 /// let mut f = File::open("foo.txt")?;
213 /// # #[cfg(any(unix, target_os = "wasi"))]
214 /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
215 /// # Ok::<(), io::Error>(())
217 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
218 fn as_fd(&self) -> BorrowedFd
<'_
>;
221 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
222 impl<T
: AsFd
> AsFd
for &T
{
224 fn as_fd(&self) -> BorrowedFd
<'_
> {
229 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
230 impl<T
: AsFd
> AsFd
for &mut T
{
232 fn as_fd(&self) -> BorrowedFd
<'_
> {
237 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
238 impl AsFd
for BorrowedFd
<'_
> {
240 fn as_fd(&self) -> BorrowedFd
<'_
> {
245 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
246 impl AsFd
for OwnedFd
{
248 fn as_fd(&self) -> BorrowedFd
<'_
> {
249 // SAFETY: `OwnedFd` and `BorrowedFd` have the same validity
250 // invariants, and the `BorrowedFd` is bounded by the lifetime
252 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }