1#![stable(feature = "io_safety", since = "1.63.0")]
4#![deny(unsafe_op_in_unsafe_fn)]
5
6#[cfg(target_os = "motor")]
7use moto_rt::libc;
8
9use super::raw::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
10#[cfg(not(target_os = "trusty"))]
11use crate::fs;
12use crate::marker::PhantomData;
13use crate::mem::ManuallyDrop;
14#[cfg(not(any(
15    target_arch = "wasm32",
16    target_env = "sgx",
17    target_os = "hermit",
18    target_os = "trusty",
19    target_os = "motor"
20)))]
21use crate::sys::cvt;
22#[cfg(not(target_os = "trusty"))]
23use crate::sys_common::{AsInner, FromInner, IntoInner};
24use crate::{fmt, io};
25
26type ValidRawFd = core::num::niche_types::NotAllOnes<RawFd>;
27
28#[derive(Copy, Clone)]
48#[repr(transparent)]
49#[rustc_nonnull_optimization_guaranteed]
50#[stable(feature = "io_safety", since = "1.63.0")]
51pub struct BorrowedFd<'fd> {
52    fd: ValidRawFd,
53    _phantom: PhantomData<&'fd OwnedFd>,
54}
55
56#[repr(transparent)]
68#[rustc_nonnull_optimization_guaranteed]
69#[stable(feature = "io_safety", since = "1.63.0")]
70pub struct OwnedFd {
71    fd: ValidRawFd,
72}
73
74impl BorrowedFd<'_> {
75    #[inline]
82    #[track_caller]
83    #[rustc_const_stable(feature = "io_safety", since = "1.63.0")]
84    #[stable(feature = "io_safety", since = "1.63.0")]
85    pub const unsafe fn borrow_raw(fd: RawFd) -> Self {
86        Self { fd: ValidRawFd::new(fd).expect("fd != -1"), _phantom: PhantomData }
87    }
88}
89
90impl OwnedFd {
91    #[stable(feature = "io_safety", since = "1.63.0")]
94    pub fn try_clone(&self) -> crate::io::Result<Self> {
95        self.as_fd().try_clone_to_owned()
96    }
97}
98
99impl BorrowedFd<'_> {
100    #[cfg(not(any(
103        target_arch = "wasm32",
104        target_os = "hermit",
105        target_os = "trusty",
106        target_os = "motor"
107    )))]
108    #[stable(feature = "io_safety", since = "1.63.0")]
109    pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
110        #[cfg(not(any(target_os = "espidf", target_os = "vita")))]
114        let cmd = libc::F_DUPFD_CLOEXEC;
115
116        #[cfg(any(target_os = "espidf", target_os = "vita"))]
121        let cmd = libc::F_DUPFD;
122
123        let fd = cvt(unsafe { libc::fcntl(self.as_raw_fd(), cmd, 3) })?;
125        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
126    }
127
128    #[cfg(any(target_arch = "wasm32", target_os = "hermit", target_os = "trusty"))]
131    #[stable(feature = "io_safety", since = "1.63.0")]
132    pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
133        Err(crate::io::Error::UNSUPPORTED_PLATFORM)
134    }
135
136    #[cfg(target_os = "motor")]
139    #[stable(feature = "io_safety", since = "1.63.0")]
140    pub fn try_clone_to_owned(&self) -> crate::io::Result<OwnedFd> {
141        let fd = moto_rt::fs::duplicate(self.as_raw_fd()).map_err(crate::sys::map_motor_error)?;
142        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
143    }
144}
145
146#[stable(feature = "io_safety", since = "1.63.0")]
147impl AsRawFd for BorrowedFd<'_> {
148    #[inline]
149    fn as_raw_fd(&self) -> RawFd {
150        self.fd.as_inner()
151    }
152}
153
154#[stable(feature = "io_safety", since = "1.63.0")]
155impl AsRawFd for OwnedFd {
156    #[inline]
157    fn as_raw_fd(&self) -> RawFd {
158        self.fd.as_inner()
159    }
160}
161
162#[stable(feature = "io_safety", since = "1.63.0")]
163impl IntoRawFd for OwnedFd {
164    #[inline]
165    fn into_raw_fd(self) -> RawFd {
166        ManuallyDrop::new(self).fd.as_inner()
167    }
168}
169
170#[stable(feature = "io_safety", since = "1.63.0")]
171impl FromRawFd for OwnedFd {
172    #[inline]
181    #[track_caller]
182    unsafe fn from_raw_fd(fd: RawFd) -> Self {
183        Self { fd: ValidRawFd::new(fd).expect("fd != -1") }
184    }
185}
186
187#[stable(feature = "io_safety", since = "1.63.0")]
188impl Drop for OwnedFd {
189    #[inline]
190    fn drop(&mut self) {
191        unsafe {
192            #[cfg(not(target_os = "hermit"))]
204            {
205                #[cfg(unix)]
206                crate::sys::fs::debug_assert_fd_is_open(self.fd.as_inner());
207
208                let _ = libc::close(self.fd.as_inner());
209            }
210            #[cfg(target_os = "hermit")]
211            let _ = hermit_abi::close(self.fd.as_inner());
212        }
213    }
214}
215
216#[stable(feature = "io_safety", since = "1.63.0")]
217impl fmt::Debug for BorrowedFd<'_> {
218    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219        f.debug_struct("BorrowedFd").field("fd", &self.fd).finish()
220    }
221}
222
223#[stable(feature = "io_safety", since = "1.63.0")]
224impl fmt::Debug for OwnedFd {
225    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226        f.debug_struct("OwnedFd").field("fd", &self.fd).finish()
227    }
228}
229
230macro_rules! impl_is_terminal {
231    ($($t:ty),*$(,)?) => {$(
232        #[unstable(feature = "sealed", issue = "none")]
233        impl crate::sealed::Sealed for $t {}
234
235        #[stable(feature = "is_terminal", since = "1.70.0")]
236        impl crate::io::IsTerminal for $t {
237            #[inline]
238            fn is_terminal(&self) -> bool {
239                crate::sys::io::is_terminal(self)
240            }
241        }
242    )*}
243}
244
245impl_is_terminal!(BorrowedFd<'_>, OwnedFd);
246
247#[stable(feature = "io_safety", since = "1.63.0")]
253pub trait AsFd {
254    #[stable(feature = "io_safety", since = "1.63.0")]
270    fn as_fd(&self) -> BorrowedFd<'_>;
271}
272
273#[stable(feature = "io_safety", since = "1.63.0")]
274impl<T: AsFd + ?Sized> AsFd for &T {
275    #[inline]
276    fn as_fd(&self) -> BorrowedFd<'_> {
277        T::as_fd(self)
278    }
279}
280
281#[stable(feature = "io_safety", since = "1.63.0")]
282impl<T: AsFd + ?Sized> AsFd for &mut T {
283    #[inline]
284    fn as_fd(&self) -> BorrowedFd<'_> {
285        T::as_fd(self)
286    }
287}
288
289#[stable(feature = "io_safety", since = "1.63.0")]
290impl AsFd for BorrowedFd<'_> {
291    #[inline]
292    fn as_fd(&self) -> BorrowedFd<'_> {
293        *self
294    }
295}
296
297#[stable(feature = "io_safety", since = "1.63.0")]
298impl AsFd for OwnedFd {
299    #[inline]
300    fn as_fd(&self) -> BorrowedFd<'_> {
301        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
305    }
306}
307
308#[stable(feature = "io_safety", since = "1.63.0")]
309#[cfg(not(target_os = "trusty"))]
310impl AsFd for fs::File {
311    #[inline]
312    fn as_fd(&self) -> BorrowedFd<'_> {
313        self.as_inner().as_fd()
314    }
315}
316
317#[stable(feature = "io_safety", since = "1.63.0")]
318#[cfg(not(target_os = "trusty"))]
319impl From<fs::File> for OwnedFd {
320    #[inline]
322    fn from(file: fs::File) -> OwnedFd {
323        file.into_inner().into_inner().into_inner()
324    }
325}
326
327#[stable(feature = "io_safety", since = "1.63.0")]
328#[cfg(not(target_os = "trusty"))]
329impl From<OwnedFd> for fs::File {
330    #[inline]
333    fn from(owned_fd: OwnedFd) -> Self {
334        Self::from_inner(FromInner::from_inner(FromInner::from_inner(owned_fd)))
335    }
336}
337
338#[stable(feature = "io_safety", since = "1.63.0")]
339#[cfg(not(target_os = "trusty"))]
340impl AsFd for crate::net::TcpStream {
341    #[inline]
342    fn as_fd(&self) -> BorrowedFd<'_> {
343        self.as_inner().socket().as_fd()
344    }
345}
346
347#[stable(feature = "io_safety", since = "1.63.0")]
348#[cfg(not(target_os = "trusty"))]
349impl From<crate::net::TcpStream> for OwnedFd {
350    #[inline]
352    fn from(tcp_stream: crate::net::TcpStream) -> OwnedFd {
353        tcp_stream.into_inner().into_socket().into_inner().into_inner().into()
354    }
355}
356
357#[stable(feature = "io_safety", since = "1.63.0")]
358#[cfg(not(target_os = "trusty"))]
359impl From<OwnedFd> for crate::net::TcpStream {
360    #[inline]
361    fn from(owned_fd: OwnedFd) -> Self {
362        Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
363            owned_fd,
364        ))))
365    }
366}
367
368#[stable(feature = "io_safety", since = "1.63.0")]
369#[cfg(not(target_os = "trusty"))]
370impl AsFd for crate::net::TcpListener {
371    #[inline]
372    fn as_fd(&self) -> BorrowedFd<'_> {
373        self.as_inner().socket().as_fd()
374    }
375}
376
377#[stable(feature = "io_safety", since = "1.63.0")]
378#[cfg(not(target_os = "trusty"))]
379impl From<crate::net::TcpListener> for OwnedFd {
380    #[inline]
382    fn from(tcp_listener: crate::net::TcpListener) -> OwnedFd {
383        tcp_listener.into_inner().into_socket().into_inner().into_inner().into()
384    }
385}
386
387#[stable(feature = "io_safety", since = "1.63.0")]
388#[cfg(not(target_os = "trusty"))]
389impl From<OwnedFd> for crate::net::TcpListener {
390    #[inline]
391    fn from(owned_fd: OwnedFd) -> Self {
392        Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
393            owned_fd,
394        ))))
395    }
396}
397
398#[stable(feature = "io_safety", since = "1.63.0")]
399#[cfg(not(target_os = "trusty"))]
400impl AsFd for crate::net::UdpSocket {
401    #[inline]
402    fn as_fd(&self) -> BorrowedFd<'_> {
403        self.as_inner().socket().as_fd()
404    }
405}
406
407#[stable(feature = "io_safety", since = "1.63.0")]
408#[cfg(not(target_os = "trusty"))]
409impl From<crate::net::UdpSocket> for OwnedFd {
410    #[inline]
412    fn from(udp_socket: crate::net::UdpSocket) -> OwnedFd {
413        udp_socket.into_inner().into_socket().into_inner().into_inner().into()
414    }
415}
416
417#[stable(feature = "io_safety", since = "1.63.0")]
418#[cfg(not(target_os = "trusty"))]
419impl From<OwnedFd> for crate::net::UdpSocket {
420    #[inline]
421    fn from(owned_fd: OwnedFd) -> Self {
422        Self::from_inner(FromInner::from_inner(FromInner::from_inner(FromInner::from_inner(
423            owned_fd,
424        ))))
425    }
426}
427
428#[stable(feature = "asfd_ptrs", since = "1.64.0")]
429impl<T: AsFd + ?Sized> AsFd for crate::sync::Arc<T> {
445    #[inline]
446    fn as_fd(&self) -> BorrowedFd<'_> {
447        (**self).as_fd()
448    }
449}
450
451#[stable(feature = "asfd_rc", since = "1.69.0")]
452impl<T: AsFd + ?Sized> AsFd for crate::rc::Rc<T> {
453    #[inline]
454    fn as_fd(&self) -> BorrowedFd<'_> {
455        (**self).as_fd()
456    }
457}
458
459#[unstable(feature = "unique_rc_arc", issue = "112566")]
460impl<T: AsFd + ?Sized> AsFd for crate::rc::UniqueRc<T> {
461    #[inline]
462    fn as_fd(&self) -> BorrowedFd<'_> {
463        (**self).as_fd()
464    }
465}
466
467#[stable(feature = "asfd_ptrs", since = "1.64.0")]
468impl<T: AsFd + ?Sized> AsFd for Box<T> {
469    #[inline]
470    fn as_fd(&self) -> BorrowedFd<'_> {
471        (**self).as_fd()
472    }
473}
474
475#[stable(feature = "io_safety", since = "1.63.0")]
476impl AsFd for io::Stdin {
477    #[inline]
478    fn as_fd(&self) -> BorrowedFd<'_> {
479        unsafe { BorrowedFd::borrow_raw(0) }
480    }
481}
482
483#[stable(feature = "io_safety", since = "1.63.0")]
484impl<'a> AsFd for io::StdinLock<'a> {
485    #[inline]
486    fn as_fd(&self) -> BorrowedFd<'_> {
487        unsafe { BorrowedFd::borrow_raw(0) }
489    }
490}
491
492#[stable(feature = "io_safety", since = "1.63.0")]
493impl AsFd for io::Stdout {
494    #[inline]
495    fn as_fd(&self) -> BorrowedFd<'_> {
496        unsafe { BorrowedFd::borrow_raw(1) }
497    }
498}
499
500#[stable(feature = "io_safety", since = "1.63.0")]
501impl<'a> AsFd for io::StdoutLock<'a> {
502    #[inline]
503    fn as_fd(&self) -> BorrowedFd<'_> {
504        unsafe { BorrowedFd::borrow_raw(1) }
506    }
507}
508
509#[stable(feature = "io_safety", since = "1.63.0")]
510impl AsFd for io::Stderr {
511    #[inline]
512    fn as_fd(&self) -> BorrowedFd<'_> {
513        unsafe { BorrowedFd::borrow_raw(2) }
514    }
515}
516
517#[stable(feature = "io_safety", since = "1.63.0")]
518impl<'a> AsFd for io::StderrLock<'a> {
519    #[inline]
520    fn as_fd(&self) -> BorrowedFd<'_> {
521        unsafe { BorrowedFd::borrow_raw(2) }
523    }
524}
525
526#[stable(feature = "anonymous_pipe", since = "1.87.0")]
527#[cfg(not(target_os = "trusty"))]
528impl AsFd for io::PipeReader {
529    fn as_fd(&self) -> BorrowedFd<'_> {
530        self.0.as_fd()
531    }
532}
533
534#[stable(feature = "anonymous_pipe", since = "1.87.0")]
535#[cfg(not(target_os = "trusty"))]
536impl From<io::PipeReader> for OwnedFd {
537    fn from(pipe: io::PipeReader) -> Self {
538        pipe.0.into_inner()
539    }
540}
541
542#[stable(feature = "anonymous_pipe", since = "1.87.0")]
543#[cfg(not(target_os = "trusty"))]
544impl AsFd for io::PipeWriter {
545    fn as_fd(&self) -> BorrowedFd<'_> {
546        self.0.as_fd()
547    }
548}
549
550#[stable(feature = "anonymous_pipe", since = "1.87.0")]
551#[cfg(not(target_os = "trusty"))]
552impl From<io::PipeWriter> for OwnedFd {
553    fn from(pipe: io::PipeWriter) -> Self {
554        pipe.0.into_inner()
555    }
556}
557
558#[stable(feature = "anonymous_pipe", since = "1.87.0")]
559#[cfg(not(target_os = "trusty"))]
560impl From<OwnedFd> for io::PipeReader {
561    fn from(owned_fd: OwnedFd) -> Self {
562        Self(FromInner::from_inner(owned_fd))
563    }
564}
565
566#[stable(feature = "anonymous_pipe", since = "1.87.0")]
567#[cfg(not(target_os = "trusty"))]
568impl From<OwnedFd> for io::PipeWriter {
569    fn from(owned_fd: OwnedFd) -> Self {
570        Self(FromInner::from_inner(owned_fd))
571    }
572}