]> git.lizzy.rs Git - rust.git/blob - library/std/src/os/fd/owned.rs
Rollup merge of #105427 - GuillaumeGomez:dont-silently-ignore-rustdoc-errors, r=notriddle
[rust.git] / library / std / src / os / fd / owned.rs
1 //! Owned and borrowed Unix-like file descriptors.
2
3 #![stable(feature = "io_safety", since = "1.63.0")]
4 #![deny(unsafe_op_in_unsafe_fn)]
5
6 use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
7 use crate::fmt;
8 use crate::fs;
9 use crate::io;
10 use crate::marker::PhantomData;
11 use crate::mem::forget;
12 #[cfg(not(any(target_arch = "wasm32", target_env = "sgx")))]
13 use crate::sys::cvt;
14 use crate::sys_common::{AsInner, FromInner, IntoInner};
15
16 /// A borrowed file descriptor.
17 ///
18 /// This has a lifetime parameter to tie it to the lifetime of something that
19 /// owns the file descriptor.
20 ///
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
24 /// value `-1`.
25 ///
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)]
30 #[repr(transparent)]
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> {
39     fd: RawFd,
40     _phantom: PhantomData<&'fd OwnedFd>,
41 }
42
43 /// An owned file descriptor.
44 ///
45 /// This closes the file descriptor on drop.
46 ///
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`.
51 #[repr(transparent)]
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")]
59 pub struct OwnedFd {
60     fd: RawFd,
61 }
62
63 impl BorrowedFd<'_> {
64     /// Return a `BorrowedFd` holding the given raw file descriptor.
65     ///
66     /// # Safety
67     ///
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`.
70     #[inline]
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 } }
77     }
78 }
79
80 impl OwnedFd {
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()
86     }
87 }
88
89 impl BorrowedFd<'_> {
90     /// Creates a new `OwnedFd` instance that shares the same underlying file
91     /// description as the existing `BorrowedFd` instance.
92     #[cfg(not(target_arch = "wasm32"))]
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;
100
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;
107
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) })
111     }
112
113     /// Creates a new `OwnedFd` instance that shares the same underlying file
114     /// description as the existing `BorrowedFd` instance.
115     #[cfg(target_arch = "wasm32")]
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",
121         ))
122     }
123 }
124
125 #[stable(feature = "io_safety", since = "1.63.0")]
126 impl AsRawFd for BorrowedFd<'_> {
127     #[inline]
128     fn as_raw_fd(&self) -> RawFd {
129         self.fd
130     }
131 }
132
133 #[stable(feature = "io_safety", since = "1.63.0")]
134 impl AsRawFd for OwnedFd {
135     #[inline]
136     fn as_raw_fd(&self) -> RawFd {
137         self.fd
138     }
139 }
140
141 #[stable(feature = "io_safety", since = "1.63.0")]
142 impl IntoRawFd for OwnedFd {
143     #[inline]
144     fn into_raw_fd(self) -> RawFd {
145         let fd = self.fd;
146         forget(self);
147         fd
148     }
149 }
150
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.
154     ///
155     /// # Safety
156     ///
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`.
159     #[inline]
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 } }
164     }
165 }
166
167 #[stable(feature = "io_safety", since = "1.63.0")]
168 impl Drop for OwnedFd {
169     #[inline]
170     fn drop(&mut self) {
171         unsafe {
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             let _ = libc::close(self.fd);
178         }
179     }
180 }
181
182 #[stable(feature = "io_safety", since = "1.63.0")]
183 impl fmt::Debug for BorrowedFd<'_> {
184     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185         f.debug_struct("BorrowedFd").field("fd", &self.fd).finish()
186     }
187 }
188
189 #[stable(feature = "io_safety", since = "1.63.0")]
190 impl fmt::Debug for OwnedFd {
191     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192         f.debug_struct("OwnedFd").field("fd", &self.fd).finish()
193     }
194 }
195
196 macro_rules! impl_is_terminal {
197     ($($t:ty),*$(,)?) => {$(
198         #[unstable(feature = "sealed", issue = "none")]
199         impl crate::sealed::Sealed for $t {}
200
201         #[unstable(feature = "is_terminal", issue = "98070")]
202         impl crate::io::IsTerminal for $t {
203             #[inline]
204             fn is_terminal(&self) -> bool {
205                 crate::sys::io::is_terminal(self)
206             }
207         }
208     )*}
209 }
210
211 impl_is_terminal!(BorrowedFd<'_>, OwnedFd);
212
213 /// A trait to borrow the file descriptor from an underlying object.
214 ///
215 /// This is only available on unix platforms and must be imported in order to
216 /// call the method. Windows platforms have a corresponding `AsHandle` and
217 /// `AsSocket` set of traits.
218 #[stable(feature = "io_safety", since = "1.63.0")]
219 pub trait AsFd {
220     /// Borrows the file descriptor.
221     ///
222     /// # Example
223     ///
224     /// ```rust,no_run
225     /// use std::fs::File;
226     /// # use std::io;
227     /// # #[cfg(any(unix, target_os = "wasi"))]
228     /// # use std::os::fd::{AsFd, BorrowedFd};
229     ///
230     /// let mut f = File::open("foo.txt")?;
231     /// # #[cfg(any(unix, target_os = "wasi"))]
232     /// let borrowed_fd: BorrowedFd<'_> = f.as_fd();
233     /// # Ok::<(), io::Error>(())
234     /// ```
235     #[stable(feature = "io_safety", since = "1.63.0")]
236     fn as_fd(&self) -> BorrowedFd<'_>;
237 }
238
239 #[stable(feature = "io_safety", since = "1.63.0")]
240 impl<T: AsFd> AsFd for &T {
241     #[inline]
242     fn as_fd(&self) -> BorrowedFd<'_> {
243         T::as_fd(self)
244     }
245 }
246
247 #[stable(feature = "io_safety", since = "1.63.0")]
248 impl<T: AsFd> AsFd for &mut T {
249     #[inline]
250     fn as_fd(&self) -> BorrowedFd<'_> {
251         T::as_fd(self)
252     }
253 }
254
255 #[stable(feature = "io_safety", since = "1.63.0")]
256 impl AsFd for BorrowedFd<'_> {
257     #[inline]
258     fn as_fd(&self) -> BorrowedFd<'_> {
259         *self
260     }
261 }
262
263 #[stable(feature = "io_safety", since = "1.63.0")]
264 impl AsFd for OwnedFd {
265     #[inline]
266     fn as_fd(&self) -> BorrowedFd<'_> {
267         // Safety: `OwnedFd` and `BorrowedFd` have the same validity
268         // invariants, and the `BorrowdFd` is bounded by the lifetime
269         // of `&self`.
270         unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
271     }
272 }
273
274 #[stable(feature = "io_safety", since = "1.63.0")]
275 impl AsFd for fs::File {
276     #[inline]
277     fn as_fd(&self) -> BorrowedFd<'_> {
278         self.as_inner().as_fd()
279     }
280 }
281
282 #[stable(feature = "io_safety", since = "1.63.0")]
283 impl From<fs::File> for OwnedFd {
284     #[inline]
285     fn from(file: fs::File) -> OwnedFd {
286         file.into_inner().into_inner().into_inner()
287     }
288 }
289
290 #[stable(feature = "io_safety", since = "1.63.0")]
291 impl From<OwnedFd> for fs::File {
292     #[inline]
293     fn from(owned_fd: OwnedFd) -> Self {
294         Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned_fd)))
295     }
296 }
297
298 #[stable(feature = "io_safety", since = "1.63.0")]
299 impl AsFd for crate::net::TcpStream {
300     #[inline]
301     fn as_fd(&self) -> BorrowedFd<'_> {
302         self.as_inner().socket().as_fd()
303     }
304 }
305
306 #[stable(feature = "io_safety", since = "1.63.0")]
307 impl From<crate::net::TcpStream> for OwnedFd {
308     #[inline]
309     fn from(tcp_stream: crate::net::TcpStream) -> OwnedFd {
310         tcp_stream.into_inner().into_socket().into_inner().into_inner().into()
311     }
312 }
313
314 #[stable(feature = "io_safety", since = "1.63.0")]
315 impl From<OwnedFd> for crate::net::TcpStream {
316     #[inline]
317     fn from(owned_fd: OwnedFd) -> Self {
318         Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
319             owned_fd,
320         ))))
321     }
322 }
323
324 #[stable(feature = "io_safety", since = "1.63.0")]
325 impl AsFd for crate::net::TcpListener {
326     #[inline]
327     fn as_fd(&self) -> BorrowedFd<'_> {
328         self.as_inner().socket().as_fd()
329     }
330 }
331
332 #[stable(feature = "io_safety", since = "1.63.0")]
333 impl From<crate::net::TcpListener> for OwnedFd {
334     #[inline]
335     fn from(tcp_listener: crate::net::TcpListener) -> OwnedFd {
336         tcp_listener.into_inner().into_socket().into_inner().into_inner().into()
337     }
338 }
339
340 #[stable(feature = "io_safety", since = "1.63.0")]
341 impl From<OwnedFd> for crate::net::TcpListener {
342     #[inline]
343     fn from(owned_fd: OwnedFd) -> Self {
344         Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
345             owned_fd,
346         ))))
347     }
348 }
349
350 #[stable(feature = "io_safety", since = "1.63.0")]
351 impl AsFd for crate::net::UdpSocket {
352     #[inline]
353     fn as_fd(&self) -> BorrowedFd<'_> {
354         self.as_inner().socket().as_fd()
355     }
356 }
357
358 #[stable(feature = "io_safety", since = "1.63.0")]
359 impl From<crate::net::UdpSocket> for OwnedFd {
360     #[inline]
361     fn from(udp_socket: crate::net::UdpSocket) -> OwnedFd {
362         udp_socket.into_inner().into_socket().into_inner().into_inner().into()
363     }
364 }
365
366 #[stable(feature = "io_safety", since = "1.63.0")]
367 impl From<OwnedFd> for crate::net::UdpSocket {
368     #[inline]
369     fn from(owned_fd: OwnedFd) -> Self {
370         Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
371             owned_fd,
372         ))))
373     }
374 }
375
376 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
377 /// This impl allows implementing traits that require `AsFd` on Arc.
378 /// ```
379 /// # #[cfg(any(unix, target_os = "wasi"))] mod group_cfg {
380 /// # #[cfg(target_os = "wasi")]
381 /// # use std::os::wasi::io::AsFd;
382 /// # #[cfg(unix)]
383 /// # use std::os::unix::io::AsFd;
384 /// use std::net::UdpSocket;
385 /// use std::sync::Arc;
386 ///
387 /// trait MyTrait: AsFd {}
388 /// impl MyTrait for Arc<UdpSocket> {}
389 /// impl MyTrait for Box<UdpSocket> {}
390 /// # }
391 /// ```
392 impl<T: AsFd> AsFd for crate::sync::Arc<T> {
393     #[inline]
394     fn as_fd(&self) -> BorrowedFd<'_> {
395         (**self).as_fd()
396     }
397 }
398
399 #[stable(feature = "asfd_ptrs", since = "1.64.0")]
400 impl<T: AsFd> AsFd for Box<T> {
401     #[inline]
402     fn as_fd(&self) -> BorrowedFd<'_> {
403         (**self).as_fd()
404     }
405 }
406
407 #[stable(feature = "io_safety", since = "1.63.0")]
408 impl AsFd for io::Stdin {
409     #[inline]
410     fn as_fd(&self) -> BorrowedFd<'_> {
411         unsafe { BorrowedFd::borrow_raw(0) }
412     }
413 }
414
415 #[stable(feature = "io_safety", since = "1.63.0")]
416 impl<'a> AsFd for io::StdinLock<'a> {
417     #[inline]
418     fn as_fd(&self) -> BorrowedFd<'_> {
419         // SAFETY: user code should not close stdin out from under the standard library
420         unsafe { BorrowedFd::borrow_raw(0) }
421     }
422 }
423
424 #[stable(feature = "io_safety", since = "1.63.0")]
425 impl AsFd for io::Stdout {
426     #[inline]
427     fn as_fd(&self) -> BorrowedFd<'_> {
428         unsafe { BorrowedFd::borrow_raw(1) }
429     }
430 }
431
432 #[stable(feature = "io_safety", since = "1.63.0")]
433 impl<'a> AsFd for io::StdoutLock<'a> {
434     #[inline]
435     fn as_fd(&self) -> BorrowedFd<'_> {
436         // SAFETY: user code should not close stdout out from under the standard library
437         unsafe { BorrowedFd::borrow_raw(1) }
438     }
439 }
440
441 #[stable(feature = "io_safety", since = "1.63.0")]
442 impl AsFd for io::Stderr {
443     #[inline]
444     fn as_fd(&self) -> BorrowedFd<'_> {
445         unsafe { BorrowedFd::borrow_raw(2) }
446     }
447 }
448
449 #[stable(feature = "io_safety", since = "1.63.0")]
450 impl<'a> AsFd for io::StderrLock<'a> {
451     #[inline]
452     fn as_fd(&self) -> BorrowedFd<'_> {
453         // SAFETY: user code should not close stderr out from under the standard library
454         unsafe { BorrowedFd::borrow_raw(2) }
455     }
456 }