Debian Codegraph @

vendor/rustix/src/maybe_polyfill/no_std/os/fd/owned.rs

raw
1 //! The following is derived from Rust's
2 //! library/std/src/os/fd/owned.rs at revision
3 //! 334a54cd83191f38ad8046ed94c45de735c86c65.
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 owns the file
22 /// descriptor. For the duration of that lifetime, it is guaranteed that nobody will close the file
23 /// descriptor.
24 ///
25 /// This uses `repr(transparent)` and has the representation of a host file
26 /// descriptor, so it can be used in FFI in places where a file descriptor is
27 /// passed as an argument, it is not captured or consumed, and it never has the
28 /// value `-1`.
29 ///
30 /// This type does not have a [`ToOwned`][crate::borrow::ToOwned]
31 /// implementation. Calling `.to_owned()` on a variable of this type will call
32 /// it on `&BorrowedFd` and use `Clone::clone()` like `ToOwned` does for all
33 /// types implementing `Clone`. The result will be descriptor borrowed under
34 /// the same lifetime.
35 ///
36 /// To obtain an [`OwnedFd`], you can use [`BorrowedFd::try_clone_to_owned`]
37 /// instead, but this is not supported on all platforms.
38 #[derive(Copy, Clone)]
39 #[repr(transparent)]
40 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_start(0))]
41 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
42 // 32-bit c_int. Below is -2, in two's complement, but that only works out
43 // because c_int is 32 bits.
44 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))]
45 #[cfg_attr(rustc_attrs, rustc_nonnull_optimization_guaranteed)]
46 #[cfg_attr(staged_api, stable(feature = "io_safety", since = "1.63.0"))]
47 pub struct BorrowedFd<'fd> {
48 fd: RawFd,
49 _phantom: PhantomData<&'fd OwnedFd>,
50 }
51
52 /// An owned file descriptor.
53 ///
54 /// This closes the file descriptor on drop. It is guaranteed that nobody else will close the file
55 /// descriptor.
56 ///
57 /// This uses `repr(transparent)` and has the representation of a host file
58 /// descriptor, so it can be used in FFI in places where a file descriptor is
59 /// passed as a consumed argument or returned as an owned value, and it never
60 /// has the value `-1`.
61 ///
62 /// You can use [`AsFd::as_fd`] to obtain a [`BorrowedFd`].
63 #[repr(transparent)]
64 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_start(0))]
65 // libstd/os/raw/mod.rs assures me that every libstd-supported platform has a
66 // 32-bit c_int. Below is -2, in two's complement, but that only works out
67 // because c_int is 32 bits.
68 #[cfg_attr(rustc_attrs, rustc_layout_scalar_valid_range_end(0xFF_FF_FF_FE))]
69 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
70 #[cfg_attr(rustc_attrs, rustc_nonnull_optimization_guaranteed)]
71 pub struct OwnedFd {
72 fd: RawFd,
73 }
74
75 impl BorrowedFd<'_> {
76 /// Returns a `BorrowedFd` holding the given raw file descriptor.
77 ///
78 /// # Safety
79 ///
80 /// The resource pointed to by `fd` must remain open for the duration of
81 /// the returned `BorrowedFd`, and it must not have the value `-1`.
82 #[inline]
83 #[cfg_attr(
84 staged_api,
85 rustc_const_stable(feature = "io_safety", since = "1.63.0")
86 )]
87 #[cfg_attr(staged_api, stable(feature = "io_safety", since = "1.63.0"))]
88 pub const unsafe fn borrow_raw(fd: RawFd) -> Self {
89 assert!(fd != u32::MAX as RawFd);
90 // 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)
91 #[allow(unused_unsafe)]
92 unsafe {
93 Self {
94 fd,
95 _phantom: PhantomData,
96 }
97 }
98 }
99 }
100
101 impl OwnedFd {
102 /// Creates a new `OwnedFd` instance that shares the same underlying file handle
103 /// as the existing `OwnedFd` instance.
104 #[cfg(not(target_arch = "wasm32"))]
105 pub fn try_clone(&self) -> crate::io::Result<Self> {
106 // We want to atomically duplicate this file descriptor and set the
107 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
108 // is a POSIX flag that was added to Linux in 2.6.24.
109 #[cfg(not(target_os = "espidf"))]
110 let fd = crate::io::fcntl_dupfd_cloexec(self, 0)?;
111
112 // For ESP-IDF, F_DUPFD is used instead, because the CLOEXEC semantics
113 // will never be supported, as this is a bare metal framework with
114 // no capabilities for multi-process execution. While F_DUPFD is also
115 // not supported yet, it might be (currently it returns ENOSYS).
116 #[cfg(target_os = "espidf")]
117 let fd = crate::io::fcntl_dupfd(self, 0)?;
118
119 Ok(fd.into())
120 }
121
122 /// Creates a new `OwnedFd` instance that shares the same underlying file handle
123 /// as the existing `OwnedFd` instance.
124 #[cfg(target_arch = "wasm32")]
125 pub fn try_clone(&self) -> crate::io::Result<Self> {
126 Err(crate::io::Errno::NOSYS)
127 }
128 }
129
130 impl BorrowedFd<'_> {
131 /// Creates a new `OwnedFd` instance that shares the same underlying file
132 /// description as the existing `BorrowedFd` instance.
133 #[cfg(not(any(target_arch = "wasm32", target_os = "hermit")))]
134 #[cfg_attr(staged_api, stable(feature = "io_safety", since = "1.63.0"))]
135 pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
136 // Avoid using file descriptors below 3 as they are used for stdio
137
138 // We want to atomically duplicate this file descriptor and set the
139 // CLOEXEC flag, and currently that's done via F_DUPFD_CLOEXEC. This
140 // is a POSIX flag that was added to Linux in 2.6.24.
141 #[cfg(not(target_os = "espidf"))]
142 let fd = crate::io::fcntl_dupfd_cloexec(self, 3)?;
143
144 // For ESP-IDF, F_DUPFD is used instead, because the CLOEXEC semantics
145 // will never be supported, as this is a bare metal framework with
146 // no capabilities for multi-process execution. While F_DUPFD is also
147 // not supported yet, it might be (currently it returns ENOSYS).
148 #[cfg(target_os = "espidf")]
149 let fd = crate::io::fcntl_dupfd(self, 3)?;
150
151 Ok(fd)
152 }
153
154 /// Creates a new `OwnedFd` instance that shares the same underlying file
155 /// description as the existing `BorrowedFd` instance.
156 #[cfg(any(target_arch = "wasm32", target_os = "hermit"))]
157 #[cfg_attr(staged_api, stable(feature = "io_safety", since = "1.63.0"))]
158 pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
159 Err(crate::io::Errno::NOSYS)
160 }
161 }
162
163 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
164 impl AsRawFd for BorrowedFd<'_> {
165 #[inline]
166 fn as_raw_fd(&self) -> RawFd {
167 self.fd
168 }
169 }
170
171 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
172 impl AsRawFd for OwnedFd {
173 #[inline]
174 fn as_raw_fd(&self) -> RawFd {
175 self.fd
176 }
177 }
178
179 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
180 impl IntoRawFd for OwnedFd {
181 #[inline]
182 fn into_raw_fd(self) -> RawFd {
183 let fd = self.fd;
184 forget(self);
185 fd
186 }
187 }
188
189 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
190 impl FromRawFd for OwnedFd {
191 /// Constructs a new instance of `Self` from the given raw file descriptor.
192 ///
193 /// # Safety
194 ///
195 /// The resource pointed to by `fd` must be open and suitable for assuming
196 /// [ownership][io-safety]. The resource must not require any cleanup other than `close`.
197 ///
198 /// [io-safety]: io#io-safety
199 #[inline]
200 unsafe fn from_raw_fd(fd: RawFd) -> Self {
201 assert_ne!(fd, u32::MAX as RawFd);
202 // 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)
203 #[allow(unused_unsafe)]
204 unsafe {
205 Self { fd }
206 }
207 }
208 }
209
210 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
211 impl Drop for OwnedFd {
212 #[inline]
213 fn drop(&mut self) {
214 unsafe {
215 // Errors are ignored when closing a file descriptor. The reason
216 // for this is that if an error occurs we don't actually know if
217 // the file descriptor was closed or not, and if we retried (for
218 // something like EINTR), we might close another valid file
219 // descriptor opened after we closed ours.
220 close(self.fd as _);
221 }
222 }
223 }
224
225 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
226 impl fmt::Debug for BorrowedFd<'_> {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 f.debug_struct("BorrowedFd").field("fd", &self.fd).finish()
229 }
230 }
231
232 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
233 impl fmt::Debug for OwnedFd {
234 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235 f.debug_struct("OwnedFd").field("fd", &self.fd).finish()
236 }
237 }
238
239 /// A trait to borrow the file descriptor from an underlying object.
240 ///
241 /// This is only available on unix platforms and must be imported in order to
242 /// call the method. Windows platforms have a corresponding `AsHandle` and
243 /// `AsSocket` set of traits.
244 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
245 pub trait AsFd {
246 /// Borrows the file descriptor.
247 ///
248 /// # Example
249 ///
250 /// ```no_run
251 /// # #![feature(io_safety)]
252 /// use std::fs::File;
253 /// # use std::io;
254 /// # #[cfg(target_os = "wasi")]
255 /// # use std::os::wasi::io::{AsFd, BorrowedFd};
256 /// # #[cfg(unix)]
257 /// # use std::os::unix::io::{AsFd, BorrowedFd};
258 ///
259 /// let mut f = File::open("foo.txt")?;
260 /// # #[cfg(any(unix, target_os = "wasi"))]
261 /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
262 /// # Ok::<(), io::Error>(())
263 /// ```
264 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
265 fn as_fd(&self) -> BorrowedFd<'_>;
266 }
267
268 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
269 impl<T: AsFd> AsFd for &T {
270 #[inline]
271 fn as_fd(&self) -> BorrowedFd<'_> {
272 T::as_fd(self)
273 }
274 }
275
276 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
277 impl<T: AsFd> AsFd for &mut T {
278 #[inline]
279 fn as_fd(&self) -> BorrowedFd<'_> {
280 T::as_fd(self)
281 }
282 }
283
284 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
285 impl AsFd for BorrowedFd<'_> {
286 #[inline]
287 fn as_fd(&self) -> BorrowedFd<'_> {
288 *self
289 }
290 }
291
292 #[cfg_attr(staged_api, unstable(feature = "io_safety", issue = "87074"))]
293 impl AsFd for OwnedFd {
294 #[inline]
295 fn as_fd(&self) -> BorrowedFd<'_> {
296 // SAFETY: `OwnedFd` and `BorrowedFd` have the same validity
297 // invariants, and the `BorrowedFd` is bounded by the lifetime
298 // of `&self`.
299 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
300 }
301 }