]> git.proxmox.com Git - rustc.git/blob - vendor/rustix/src/maybe_polyfill/no_std/os/fd/owned.rs
New upstream version 1.72.1+dfsg1
[rustc.git] / vendor / rustix / src / maybe_polyfill / no_std / os / fd / owned.rs
1 //! The following is derived from Rust's
2 //! library/std/src/os/fd/owned.rs at revision
3 //! fa68e73e9947be8ffc5b3b46d899e4953a44e7e9.
4 //!
5 //! All code in this file is licensed MIT or Apache 2.0 at your option.
6 //!
7 //! Owned and borrowed Unix-like file descriptors.
8
9 #![cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
10 #![deny(unsafe_op_in_unsafe_fn)]
11 #![allow(unsafe_code)]
12
13 use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
14 use crate::io::close;
15 use core::fmt;
16 use core::marker::PhantomData;
17 use core::mem::forget;
18
19 /// A borrowed file descriptor.
20 ///
21 /// This has a lifetime parameter to tie it to the lifetime of something that
22 /// owns the file descriptor.
23 ///
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
27 /// value `-1`.
28 ///
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)]
33 #[repr(transparent)]
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> {
42 fd: RawFd,
43 _phantom: PhantomData<&'fd OwnedFd>,
44 }
45
46 /// An owned file descriptor.
47 ///
48 /// This closes the file descriptor on drop.
49 ///
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`.
54 #[repr(transparent)]
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)]
62 pub struct OwnedFd {
63 fd: RawFd,
64 }
65
66 impl BorrowedFd<'_> {
67 /// Return a `BorrowedFd` holding the given raw file descriptor.
68 ///
69 /// # Safety
70 ///
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`.
73 #[inline]
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)]
79 unsafe {
80 Self {
81 fd,
82 _phantom: PhantomData,
83 }
84 }
85 }
86 }
87
88 impl OwnedFd {
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)?;
98
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)?;
105
106 Ok(fd.into())
107 }
108
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",
114 ))
115 }
116 }
117
118 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
119 impl AsRawFd for BorrowedFd<'_> {
120 #[inline]
121 fn as_raw_fd(&self) -> RawFd {
122 self.fd
123 }
124 }
125
126 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
127 impl AsRawFd for OwnedFd {
128 #[inline]
129 fn as_raw_fd(&self) -> RawFd {
130 self.fd
131 }
132 }
133
134 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
135 impl IntoRawFd for OwnedFd {
136 #[inline]
137 fn into_raw_fd(self) -> RawFd {
138 let fd = self.fd;
139 forget(self);
140 fd
141 }
142 }
143
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.
147 ///
148 /// # Safety
149 ///
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`.
152 #[inline]
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)]
157 unsafe {
158 Self { fd }
159 }
160 }
161 }
162
163 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
164 impl Drop for OwnedFd {
165 #[inline]
166 fn drop(&mut self) {
167 unsafe {
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.
173 close(self.fd as _);
174 }
175 }
176 }
177
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()
182 }
183 }
184
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()
189 }
190 }
191
192 /// A trait to borrow the file descriptor from an underlying object.
193 ///
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"))]
198 pub trait AsFd {
199 /// Borrows the file descriptor.
200 ///
201 /// # Example
202 ///
203 /// ```no_run
204 /// # #![feature(io_safety)]
205 /// use std::fs::File;
206 /// # use std::io;
207 /// # #[cfg(target_os = "wasi")]
208 /// # use std::os::wasi::io::{AsFd, BorrowedFd};
209 /// # #[cfg(unix)]
210 /// # use std::os::unix::io::{AsFd, BorrowedFd};
211 ///
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>(())
216 /// ```
217 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
218 fn as_fd(&self) -> BorrowedFd<'_>;
219 }
220
221 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
222 impl<T: AsFd> AsFd for &T {
223 #[inline]
224 fn as_fd(&self) -> BorrowedFd<'_> {
225 T::as_fd(self)
226 }
227 }
228
229 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
230 impl<T: AsFd> AsFd for &mut T {
231 #[inline]
232 fn as_fd(&self) -> BorrowedFd<'_> {
233 T::as_fd(self)
234 }
235 }
236
237 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
238 impl AsFd for BorrowedFd<'_> {
239 #[inline]
240 fn as_fd(&self) -> BorrowedFd<'_> {
241 *self
242 }
243 }
244
245 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
246 impl AsFd for OwnedFd {
247 #[inline]
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
251 // of `&self`.
252 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
253 }
254 }