std/sys/fs/
unix.rs

1#![allow(nonstandard_style)]
2#![allow(unsafe_op_in_unsafe_fn)]
3// miri has some special hacks here that make things unused.
4#![cfg_attr(miri, allow(unused))]
5
6#[cfg(test)]
7mod tests;
8
9#[cfg(all(target_os = "linux", target_env = "gnu"))]
10use libc::c_char;
11#[cfg(any(
12    all(target_os = "linux", not(target_env = "musl")),
13    target_os = "android",
14    target_os = "fuchsia",
15    target_os = "hurd",
16    target_os = "illumos",
17))]
18use libc::dirfd;
19#[cfg(any(target_os = "fuchsia", target_os = "illumos"))]
20use libc::fstatat as fstatat64;
21#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
22use libc::fstatat64;
23#[cfg(any(
24    target_os = "android",
25    target_os = "solaris",
26    target_os = "fuchsia",
27    target_os = "redox",
28    target_os = "illumos",
29    target_os = "aix",
30    target_os = "nto",
31    target_os = "vita",
32    all(target_os = "linux", target_env = "musl"),
33))]
34use libc::readdir as readdir64;
35#[cfg(not(any(
36    target_os = "android",
37    target_os = "linux",
38    target_os = "solaris",
39    target_os = "illumos",
40    target_os = "l4re",
41    target_os = "fuchsia",
42    target_os = "redox",
43    target_os = "aix",
44    target_os = "nto",
45    target_os = "vita",
46    target_os = "hurd",
47)))]
48use libc::readdir_r as readdir64_r;
49#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
50use libc::readdir64;
51#[cfg(target_os = "l4re")]
52use libc::readdir64_r;
53use libc::{c_int, mode_t};
54#[cfg(target_os = "android")]
55use libc::{
56    dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
57    lstat as lstat64, off64_t, open as open64, stat as stat64,
58};
59#[cfg(not(any(
60    all(target_os = "linux", not(target_env = "musl")),
61    target_os = "l4re",
62    target_os = "android",
63    target_os = "hurd",
64)))]
65use libc::{
66    dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
67    lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
68};
69#[cfg(any(
70    all(target_os = "linux", not(target_env = "musl")),
71    target_os = "l4re",
72    target_os = "hurd"
73))]
74use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
75
76use crate::ffi::{CStr, OsStr, OsString};
77use crate::fmt::{self, Write as _};
78use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
79use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
80use crate::os::unix::prelude::*;
81use crate::path::{Path, PathBuf};
82use crate::sync::Arc;
83use crate::sys::common::small_c_string::run_path_with_cstr;
84use crate::sys::fd::FileDesc;
85pub use crate::sys::fs::common::exists;
86use crate::sys::time::SystemTime;
87#[cfg(all(target_os = "linux", target_env = "gnu"))]
88use crate::sys::weak::syscall;
89#[cfg(target_os = "android")]
90use crate::sys::weak::weak;
91use crate::sys::{cvt, cvt_r};
92use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
93use crate::{mem, ptr};
94
95pub struct File(FileDesc);
96
97// FIXME: This should be available on Linux with all `target_env`.
98// But currently only glibc exposes `statx` fn and structs.
99// We don't want to import unverified raw C structs here directly.
100// https://github.com/rust-lang/rust/pull/67774
101macro_rules! cfg_has_statx {
102    ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
103        cfg_if::cfg_if! {
104            if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
105                $($then_tt)*
106            } else {
107                $($else_tt)*
108            }
109        }
110    };
111    ($($block_inner:tt)*) => {
112        #[cfg(all(target_os = "linux", target_env = "gnu"))]
113        {
114            $($block_inner)*
115        }
116    };
117}
118
119cfg_has_statx! {{
120    #[derive(Clone)]
121    pub struct FileAttr {
122        stat: stat64,
123        statx_extra_fields: Option<StatxExtraFields>,
124    }
125
126    #[derive(Clone)]
127    struct StatxExtraFields {
128        // This is needed to check if btime is supported by the filesystem.
129        stx_mask: u32,
130        stx_btime: libc::statx_timestamp,
131        // With statx, we can overcome 32-bit `time_t` too.
132        #[cfg(target_pointer_width = "32")]
133        stx_atime: libc::statx_timestamp,
134        #[cfg(target_pointer_width = "32")]
135        stx_ctime: libc::statx_timestamp,
136        #[cfg(target_pointer_width = "32")]
137        stx_mtime: libc::statx_timestamp,
138
139    }
140
141    // We prefer `statx` on Linux if available, which contains file creation time,
142    // as well as 64-bit timestamps of all kinds.
143    // Default `stat64` contains no creation time and may have 32-bit `time_t`.
144    unsafe fn try_statx(
145        fd: c_int,
146        path: *const c_char,
147        flags: i32,
148        mask: u32,
149    ) -> Option<io::Result<FileAttr>> {
150        use crate::sync::atomic::{AtomicU8, Ordering};
151
152        // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`.
153        // We check for it on first failure and remember availability to avoid having to
154        // do it again.
155        #[repr(u8)]
156        enum STATX_STATE{ Unknown = 0, Present, Unavailable }
157        static STATX_SAVED_STATE: AtomicU8 = AtomicU8::new(STATX_STATE::Unknown as u8);
158
159        syscall!(
160            fn statx(
161                fd: c_int,
162                pathname: *const c_char,
163                flags: c_int,
164                mask: libc::c_uint,
165                statxbuf: *mut libc::statx,
166            ) -> c_int;
167        );
168
169        let statx_availability = STATX_SAVED_STATE.load(Ordering::Relaxed);
170        if statx_availability == STATX_STATE::Unavailable as u8 {
171            return None;
172        }
173
174        let mut buf: libc::statx = mem::zeroed();
175        if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
176            if STATX_SAVED_STATE.load(Ordering::Relaxed) == STATX_STATE::Present as u8 {
177                return Some(Err(err));
178            }
179
180            // We're not yet entirely sure whether `statx` is usable on this kernel
181            // or not. Syscalls can return errors from things other than the kernel
182            // per se, e.g. `EPERM` can be returned if seccomp is used to block the
183            // syscall, or `ENOSYS` might be returned from a faulty FUSE driver.
184            //
185            // Availability is checked by performing a call which expects `EFAULT`
186            // if the syscall is usable.
187            //
188            // See: https://github.com/rust-lang/rust/issues/65662
189            //
190            // FIXME what about transient conditions like `ENOMEM`?
191            let err2 = cvt(statx(0, ptr::null(), 0, libc::STATX_BASIC_STATS | libc::STATX_BTIME, ptr::null_mut()))
192                .err()
193                .and_then(|e| e.raw_os_error());
194            if err2 == Some(libc::EFAULT) {
195                STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed);
196                return Some(Err(err));
197            } else {
198                STATX_SAVED_STATE.store(STATX_STATE::Unavailable as u8, Ordering::Relaxed);
199                return None;
200            }
201        }
202        if statx_availability == STATX_STATE::Unknown as u8 {
203            STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed);
204        }
205
206        // We cannot fill `stat64` exhaustively because of private padding fields.
207        let mut stat: stat64 = mem::zeroed();
208        // `c_ulong` on gnu-mips, `dev_t` otherwise
209        stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
210        stat.st_ino = buf.stx_ino as libc::ino64_t;
211        stat.st_nlink = buf.stx_nlink as libc::nlink_t;
212        stat.st_mode = buf.stx_mode as libc::mode_t;
213        stat.st_uid = buf.stx_uid as libc::uid_t;
214        stat.st_gid = buf.stx_gid as libc::gid_t;
215        stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
216        stat.st_size = buf.stx_size as off64_t;
217        stat.st_blksize = buf.stx_blksize as libc::blksize_t;
218        stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
219        stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
220        // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
221        stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
222        stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
223        stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
224        stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
225        stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
226
227        let extra = StatxExtraFields {
228            stx_mask: buf.stx_mask,
229            stx_btime: buf.stx_btime,
230            // Store full times to avoid 32-bit `time_t` truncation.
231            #[cfg(target_pointer_width = "32")]
232            stx_atime: buf.stx_atime,
233            #[cfg(target_pointer_width = "32")]
234            stx_ctime: buf.stx_ctime,
235            #[cfg(target_pointer_width = "32")]
236            stx_mtime: buf.stx_mtime,
237        };
238
239        Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
240    }
241
242} else {
243    #[derive(Clone)]
244    pub struct FileAttr {
245        stat: stat64,
246    }
247}}
248
249// all DirEntry's will have a reference to this struct
250struct InnerReadDir {
251    dirp: Dir,
252    root: PathBuf,
253}
254
255pub struct ReadDir {
256    inner: Arc<InnerReadDir>,
257    end_of_stream: bool,
258}
259
260impl ReadDir {
261    fn new(inner: InnerReadDir) -> Self {
262        Self { inner: Arc::new(inner), end_of_stream: false }
263    }
264}
265
266struct Dir(*mut libc::DIR);
267
268unsafe impl Send for Dir {}
269unsafe impl Sync for Dir {}
270
271#[cfg(any(
272    target_os = "android",
273    target_os = "linux",
274    target_os = "solaris",
275    target_os = "illumos",
276    target_os = "fuchsia",
277    target_os = "redox",
278    target_os = "aix",
279    target_os = "nto",
280    target_os = "vita",
281    target_os = "hurd",
282))]
283pub struct DirEntry {
284    dir: Arc<InnerReadDir>,
285    entry: dirent64_min,
286    // We need to store an owned copy of the entry name on platforms that use
287    // readdir() (not readdir_r()), because a) struct dirent may use a flexible
288    // array to store the name, b) it lives only until the next readdir() call.
289    name: crate::ffi::CString,
290}
291
292// Define a minimal subset of fields we need from `dirent64`, especially since
293// we're not using the immediate `d_name` on these targets. Keeping this as an
294// `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
295#[cfg(any(
296    target_os = "android",
297    target_os = "linux",
298    target_os = "solaris",
299    target_os = "illumos",
300    target_os = "fuchsia",
301    target_os = "redox",
302    target_os = "aix",
303    target_os = "nto",
304    target_os = "vita",
305    target_os = "hurd",
306))]
307struct dirent64_min {
308    d_ino: u64,
309    #[cfg(not(any(
310        target_os = "solaris",
311        target_os = "illumos",
312        target_os = "aix",
313        target_os = "nto",
314        target_os = "vita",
315    )))]
316    d_type: u8,
317}
318
319#[cfg(not(any(
320    target_os = "android",
321    target_os = "linux",
322    target_os = "solaris",
323    target_os = "illumos",
324    target_os = "fuchsia",
325    target_os = "redox",
326    target_os = "aix",
327    target_os = "nto",
328    target_os = "vita",
329    target_os = "hurd",
330)))]
331pub struct DirEntry {
332    dir: Arc<InnerReadDir>,
333    // The full entry includes a fixed-length `d_name`.
334    entry: dirent64,
335}
336
337#[derive(Clone)]
338pub struct OpenOptions {
339    // generic
340    read: bool,
341    write: bool,
342    append: bool,
343    truncate: bool,
344    create: bool,
345    create_new: bool,
346    // system-specific
347    custom_flags: i32,
348    mode: mode_t,
349}
350
351#[derive(Clone, PartialEq, Eq)]
352pub struct FilePermissions {
353    mode: mode_t,
354}
355
356#[derive(Copy, Clone, Debug, Default)]
357pub struct FileTimes {
358    accessed: Option<SystemTime>,
359    modified: Option<SystemTime>,
360    #[cfg(target_vendor = "apple")]
361    created: Option<SystemTime>,
362}
363
364#[derive(Copy, Clone, Eq)]
365pub struct FileType {
366    mode: mode_t,
367}
368
369impl PartialEq for FileType {
370    fn eq(&self, other: &Self) -> bool {
371        self.masked() == other.masked()
372    }
373}
374
375impl core::hash::Hash for FileType {
376    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
377        self.masked().hash(state);
378    }
379}
380
381pub struct DirBuilder {
382    mode: mode_t,
383}
384
385#[derive(Copy, Clone)]
386struct Mode(mode_t);
387
388cfg_has_statx! {{
389    impl FileAttr {
390        fn from_stat64(stat: stat64) -> Self {
391            Self { stat, statx_extra_fields: None }
392        }
393
394        #[cfg(target_pointer_width = "32")]
395        pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
396            if let Some(ext) = &self.statx_extra_fields {
397                if (ext.stx_mask & libc::STATX_MTIME) != 0 {
398                    return Some(&ext.stx_mtime);
399                }
400            }
401            None
402        }
403
404        #[cfg(target_pointer_width = "32")]
405        pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
406            if let Some(ext) = &self.statx_extra_fields {
407                if (ext.stx_mask & libc::STATX_ATIME) != 0 {
408                    return Some(&ext.stx_atime);
409                }
410            }
411            None
412        }
413
414        #[cfg(target_pointer_width = "32")]
415        pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
416            if let Some(ext) = &self.statx_extra_fields {
417                if (ext.stx_mask & libc::STATX_CTIME) != 0 {
418                    return Some(&ext.stx_ctime);
419                }
420            }
421            None
422        }
423    }
424} else {
425    impl FileAttr {
426        fn from_stat64(stat: stat64) -> Self {
427            Self { stat }
428        }
429    }
430}}
431
432impl FileAttr {
433    pub fn size(&self) -> u64 {
434        self.stat.st_size as u64
435    }
436    pub fn perm(&self) -> FilePermissions {
437        FilePermissions { mode: (self.stat.st_mode as mode_t) }
438    }
439
440    pub fn file_type(&self) -> FileType {
441        FileType { mode: self.stat.st_mode as mode_t }
442    }
443}
444
445#[cfg(target_os = "netbsd")]
446impl FileAttr {
447    pub fn modified(&self) -> io::Result<SystemTime> {
448        SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64)
449    }
450
451    pub fn accessed(&self) -> io::Result<SystemTime> {
452        SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64)
453    }
454
455    pub fn created(&self) -> io::Result<SystemTime> {
456        SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64)
457    }
458}
459
460#[cfg(target_os = "aix")]
461impl FileAttr {
462    pub fn modified(&self) -> io::Result<SystemTime> {
463        SystemTime::new(self.stat.st_mtime.tv_sec as i64, self.stat.st_mtime.tv_nsec as i64)
464    }
465
466    pub fn accessed(&self) -> io::Result<SystemTime> {
467        SystemTime::new(self.stat.st_atime.tv_sec as i64, self.stat.st_atime.tv_nsec as i64)
468    }
469
470    pub fn created(&self) -> io::Result<SystemTime> {
471        SystemTime::new(self.stat.st_ctime.tv_sec as i64, self.stat.st_ctime.tv_nsec as i64)
472    }
473}
474
475#[cfg(not(any(target_os = "netbsd", target_os = "nto", target_os = "aix")))]
476impl FileAttr {
477    #[cfg(not(any(
478        target_os = "vxworks",
479        target_os = "espidf",
480        target_os = "horizon",
481        target_os = "vita",
482        target_os = "hurd",
483        target_os = "rtems",
484        target_os = "nuttx",
485    )))]
486    pub fn modified(&self) -> io::Result<SystemTime> {
487        #[cfg(target_pointer_width = "32")]
488        cfg_has_statx! {
489            if let Some(mtime) = self.stx_mtime() {
490                return SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64);
491            }
492        }
493
494        SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64)
495    }
496
497    #[cfg(any(
498        target_os = "vxworks",
499        target_os = "espidf",
500        target_os = "vita",
501        target_os = "rtems",
502    ))]
503    pub fn modified(&self) -> io::Result<SystemTime> {
504        SystemTime::new(self.stat.st_mtime as i64, 0)
505    }
506
507    #[cfg(any(target_os = "horizon", target_os = "hurd", target_os = "nuttx"))]
508    pub fn modified(&self) -> io::Result<SystemTime> {
509        SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64)
510    }
511
512    #[cfg(not(any(
513        target_os = "vxworks",
514        target_os = "espidf",
515        target_os = "horizon",
516        target_os = "vita",
517        target_os = "hurd",
518        target_os = "rtems",
519        target_os = "nuttx",
520    )))]
521    pub fn accessed(&self) -> io::Result<SystemTime> {
522        #[cfg(target_pointer_width = "32")]
523        cfg_has_statx! {
524            if let Some(atime) = self.stx_atime() {
525                return SystemTime::new(atime.tv_sec, atime.tv_nsec as i64);
526            }
527        }
528
529        SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64)
530    }
531
532    #[cfg(any(
533        target_os = "vxworks",
534        target_os = "espidf",
535        target_os = "vita",
536        target_os = "rtems"
537    ))]
538    pub fn accessed(&self) -> io::Result<SystemTime> {
539        SystemTime::new(self.stat.st_atime as i64, 0)
540    }
541
542    #[cfg(any(target_os = "horizon", target_os = "hurd", target_os = "nuttx"))]
543    pub fn accessed(&self) -> io::Result<SystemTime> {
544        SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64)
545    }
546
547    #[cfg(any(
548        target_os = "freebsd",
549        target_os = "openbsd",
550        target_vendor = "apple",
551        target_os = "cygwin",
552    ))]
553    pub fn created(&self) -> io::Result<SystemTime> {
554        SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64)
555    }
556
557    #[cfg(not(any(
558        target_os = "freebsd",
559        target_os = "openbsd",
560        target_os = "vita",
561        target_vendor = "apple",
562        target_os = "cygwin",
563    )))]
564    pub fn created(&self) -> io::Result<SystemTime> {
565        cfg_has_statx! {
566            if let Some(ext) = &self.statx_extra_fields {
567                return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
568                    SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64)
569                } else {
570                    Err(io::const_error!(
571                        io::ErrorKind::Unsupported,
572                        "creation time is not available for the filesystem",
573                    ))
574                };
575            }
576        }
577
578        Err(io::const_error!(
579            io::ErrorKind::Unsupported,
580            "creation time is not available on this platform currently",
581        ))
582    }
583
584    #[cfg(target_os = "vita")]
585    pub fn created(&self) -> io::Result<SystemTime> {
586        SystemTime::new(self.stat.st_ctime as i64, 0)
587    }
588}
589
590#[cfg(target_os = "nto")]
591impl FileAttr {
592    pub fn modified(&self) -> io::Result<SystemTime> {
593        SystemTime::new(self.stat.st_mtim.tv_sec, self.stat.st_mtim.tv_nsec)
594    }
595
596    pub fn accessed(&self) -> io::Result<SystemTime> {
597        SystemTime::new(self.stat.st_atim.tv_sec, self.stat.st_atim.tv_nsec)
598    }
599
600    pub fn created(&self) -> io::Result<SystemTime> {
601        SystemTime::new(self.stat.st_ctim.tv_sec, self.stat.st_ctim.tv_nsec)
602    }
603}
604
605impl AsInner<stat64> for FileAttr {
606    #[inline]
607    fn as_inner(&self) -> &stat64 {
608        &self.stat
609    }
610}
611
612impl FilePermissions {
613    pub fn readonly(&self) -> bool {
614        // check if any class (owner, group, others) has write permission
615        self.mode & 0o222 == 0
616    }
617
618    pub fn set_readonly(&mut self, readonly: bool) {
619        if readonly {
620            // remove write permission for all classes; equivalent to `chmod a-w <file>`
621            self.mode &= !0o222;
622        } else {
623            // add write permission for all classes; equivalent to `chmod a+w <file>`
624            self.mode |= 0o222;
625        }
626    }
627    pub fn mode(&self) -> u32 {
628        self.mode as u32
629    }
630}
631
632impl FileTimes {
633    pub fn set_accessed(&mut self, t: SystemTime) {
634        self.accessed = Some(t);
635    }
636
637    pub fn set_modified(&mut self, t: SystemTime) {
638        self.modified = Some(t);
639    }
640
641    #[cfg(target_vendor = "apple")]
642    pub fn set_created(&mut self, t: SystemTime) {
643        self.created = Some(t);
644    }
645}
646
647impl FileType {
648    pub fn is_dir(&self) -> bool {
649        self.is(libc::S_IFDIR)
650    }
651    pub fn is_file(&self) -> bool {
652        self.is(libc::S_IFREG)
653    }
654    pub fn is_symlink(&self) -> bool {
655        self.is(libc::S_IFLNK)
656    }
657
658    pub fn is(&self, mode: mode_t) -> bool {
659        self.masked() == mode
660    }
661
662    fn masked(&self) -> mode_t {
663        self.mode & libc::S_IFMT
664    }
665}
666
667impl fmt::Debug for FileType {
668    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
669        let FileType { mode } = self;
670        f.debug_struct("FileType").field("mode", &Mode(*mode)).finish()
671    }
672}
673
674impl FromInner<u32> for FilePermissions {
675    fn from_inner(mode: u32) -> FilePermissions {
676        FilePermissions { mode: mode as mode_t }
677    }
678}
679
680impl fmt::Debug for FilePermissions {
681    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
682        let FilePermissions { mode } = self;
683        f.debug_struct("FilePermissions").field("mode", &Mode(*mode)).finish()
684    }
685}
686
687impl fmt::Debug for ReadDir {
688    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689        // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
690        // Thus the result will be e g 'ReadDir("/home")'
691        fmt::Debug::fmt(&*self.inner.root, f)
692    }
693}
694
695impl Iterator for ReadDir {
696    type Item = io::Result<DirEntry>;
697
698    #[cfg(any(
699        target_os = "android",
700        target_os = "linux",
701        target_os = "solaris",
702        target_os = "fuchsia",
703        target_os = "redox",
704        target_os = "illumos",
705        target_os = "aix",
706        target_os = "nto",
707        target_os = "vita",
708        target_os = "hurd",
709    ))]
710    fn next(&mut self) -> Option<io::Result<DirEntry>> {
711        use crate::sys::os::{errno, set_errno};
712
713        if self.end_of_stream {
714            return None;
715        }
716
717        unsafe {
718            loop {
719                // As of POSIX.1-2017, readdir() is not required to be thread safe; only
720                // readdir_r() is. However, readdir_r() cannot correctly handle platforms
721                // with unlimited or variable NAME_MAX. Many modern platforms guarantee
722                // thread safety for readdir() as long an individual DIR* is not accessed
723                // concurrently, which is sufficient for Rust.
724                set_errno(0);
725                let entry_ptr: *const dirent64 = readdir64(self.inner.dirp.0);
726                if entry_ptr.is_null() {
727                    // We either encountered an error, or reached the end. Either way,
728                    // the next call to next() should return None.
729                    self.end_of_stream = true;
730
731                    // To distinguish between errors and end-of-directory, we had to clear
732                    // errno beforehand to check for an error now.
733                    return match errno() {
734                        0 => None,
735                        e => Some(Err(Error::from_raw_os_error(e))),
736                    };
737                }
738
739                // The dirent64 struct is a weird imaginary thing that isn't ever supposed
740                // to be worked with by value. Its trailing d_name field is declared
741                // variously as [c_char; 256] or [c_char; 1] on different systems but
742                // either way that size is meaningless; only the offset of d_name is
743                // meaningful. The dirent64 pointers that libc returns from readdir64 are
744                // allowed to point to allocations smaller _or_ LARGER than implied by the
745                // definition of the struct.
746                //
747                // As such, we need to be even more careful with dirent64 than if its
748                // contents were "simply" partially initialized data.
749                //
750                // Like for uninitialized contents, converting entry_ptr to `&dirent64`
751                // would not be legal. However, we can use `&raw const (*entry_ptr).d_name`
752                // to refer the fields individually, because that operation is equivalent
753                // to `byte_offset` and thus does not require the full extent of `*entry_ptr`
754                // to be in bounds of the same allocation, only the offset of the field
755                // being referenced.
756
757                // d_name is guaranteed to be null-terminated.
758                let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast());
759                let name_bytes = name.to_bytes();
760                if name_bytes == b"." || name_bytes == b".." {
761                    continue;
762                }
763
764                // When loading from a field, we can skip the `&raw const`; `(*entry_ptr).d_ino` as
765                // a value expression will do the right thing: `byte_offset` to the field and then
766                // only access those bytes.
767                #[cfg(not(target_os = "vita"))]
768                let entry = dirent64_min {
769                    d_ino: (*entry_ptr).d_ino as u64,
770                    #[cfg(not(any(
771                        target_os = "solaris",
772                        target_os = "illumos",
773                        target_os = "aix",
774                        target_os = "nto",
775                    )))]
776                    d_type: (*entry_ptr).d_type as u8,
777                };
778
779                #[cfg(target_os = "vita")]
780                let entry = dirent64_min { d_ino: 0u64 };
781
782                return Some(Ok(DirEntry {
783                    entry,
784                    name: name.to_owned(),
785                    dir: Arc::clone(&self.inner),
786                }));
787            }
788        }
789    }
790
791    #[cfg(not(any(
792        target_os = "android",
793        target_os = "linux",
794        target_os = "solaris",
795        target_os = "fuchsia",
796        target_os = "redox",
797        target_os = "illumos",
798        target_os = "aix",
799        target_os = "nto",
800        target_os = "vita",
801        target_os = "hurd",
802    )))]
803    fn next(&mut self) -> Option<io::Result<DirEntry>> {
804        if self.end_of_stream {
805            return None;
806        }
807
808        unsafe {
809            let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
810            let mut entry_ptr = ptr::null_mut();
811            loop {
812                let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
813                if err != 0 {
814                    if entry_ptr.is_null() {
815                        // We encountered an error (which will be returned in this iteration), but
816                        // we also reached the end of the directory stream. The `end_of_stream`
817                        // flag is enabled to make sure that we return `None` in the next iteration
818                        // (instead of looping forever)
819                        self.end_of_stream = true;
820                    }
821                    return Some(Err(Error::from_raw_os_error(err)));
822                }
823                if entry_ptr.is_null() {
824                    return None;
825                }
826                if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
827                    return Some(Ok(ret));
828                }
829            }
830        }
831    }
832}
833
834/// Aborts the process if a file desceriptor is not open, if debug asserts are enabled
835///
836/// Many IO syscalls can't be fully trusted about EBADF error codes because those
837/// might get bubbled up from a remote FUSE server rather than the file descriptor
838/// in the current process being invalid.
839///
840/// So we check file flags instead which live on the file descriptor and not the underlying file.
841/// The downside is that it costs an extra syscall, so we only do it for debug.
842#[inline]
843pub(crate) fn debug_assert_fd_is_open(fd: RawFd) {
844    use crate::sys::os::errno;
845
846    // this is similar to assert_unsafe_precondition!() but it doesn't require const
847    if core::ub_checks::check_library_ub() {
848        if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 && errno() == libc::EBADF {
849            rtabort!("IO Safety violation: owned file descriptor already closed");
850        }
851    }
852}
853
854impl Drop for Dir {
855    fn drop(&mut self) {
856        // dirfd isn't supported everywhere
857        #[cfg(not(any(
858            miri,
859            target_os = "redox",
860            target_os = "nto",
861            target_os = "vita",
862            target_os = "hurd",
863            target_os = "espidf",
864            target_os = "horizon",
865            target_os = "vxworks",
866            target_os = "rtems",
867            target_os = "nuttx",
868        )))]
869        {
870            let fd = unsafe { libc::dirfd(self.0) };
871            debug_assert_fd_is_open(fd);
872        }
873        let r = unsafe { libc::closedir(self.0) };
874        assert!(
875            r == 0 || crate::io::Error::last_os_error().is_interrupted(),
876            "unexpected error during closedir: {:?}",
877            crate::io::Error::last_os_error()
878        );
879    }
880}
881
882impl DirEntry {
883    pub fn path(&self) -> PathBuf {
884        self.dir.root.join(self.file_name_os_str())
885    }
886
887    pub fn file_name(&self) -> OsString {
888        self.file_name_os_str().to_os_string()
889    }
890
891    #[cfg(all(
892        any(
893            all(target_os = "linux", not(target_env = "musl")),
894            target_os = "android",
895            target_os = "fuchsia",
896            target_os = "hurd",
897            target_os = "illumos",
898        ),
899        not(miri) // no dirfd on Miri
900    ))]
901    pub fn metadata(&self) -> io::Result<FileAttr> {
902        let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
903        let name = self.name_cstr().as_ptr();
904
905        cfg_has_statx! {
906            if let Some(ret) = unsafe { try_statx(
907                fd,
908                name,
909                libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
910                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
911            ) } {
912                return ret;
913            }
914        }
915
916        let mut stat: stat64 = unsafe { mem::zeroed() };
917        cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
918        Ok(FileAttr::from_stat64(stat))
919    }
920
921    #[cfg(any(
922        not(any(
923            all(target_os = "linux", not(target_env = "musl")),
924            target_os = "android",
925            target_os = "fuchsia",
926            target_os = "hurd",
927            target_os = "illumos",
928        )),
929        miri
930    ))]
931    pub fn metadata(&self) -> io::Result<FileAttr> {
932        run_path_with_cstr(&self.path(), &lstat)
933    }
934
935    #[cfg(any(
936        target_os = "solaris",
937        target_os = "illumos",
938        target_os = "haiku",
939        target_os = "vxworks",
940        target_os = "aix",
941        target_os = "nto",
942        target_os = "vita",
943    ))]
944    pub fn file_type(&self) -> io::Result<FileType> {
945        self.metadata().map(|m| m.file_type())
946    }
947
948    #[cfg(not(any(
949        target_os = "solaris",
950        target_os = "illumos",
951        target_os = "haiku",
952        target_os = "vxworks",
953        target_os = "aix",
954        target_os = "nto",
955        target_os = "vita",
956    )))]
957    pub fn file_type(&self) -> io::Result<FileType> {
958        match self.entry.d_type {
959            libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
960            libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
961            libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
962            libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
963            libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
964            libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
965            libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
966            _ => self.metadata().map(|m| m.file_type()),
967        }
968    }
969
970    #[cfg(any(
971        target_os = "linux",
972        target_os = "cygwin",
973        target_os = "emscripten",
974        target_os = "android",
975        target_os = "solaris",
976        target_os = "illumos",
977        target_os = "haiku",
978        target_os = "l4re",
979        target_os = "fuchsia",
980        target_os = "redox",
981        target_os = "vxworks",
982        target_os = "espidf",
983        target_os = "horizon",
984        target_os = "vita",
985        target_os = "aix",
986        target_os = "nto",
987        target_os = "hurd",
988        target_os = "rtems",
989        target_vendor = "apple",
990    ))]
991    pub fn ino(&self) -> u64 {
992        self.entry.d_ino as u64
993    }
994
995    #[cfg(any(
996        target_os = "freebsd",
997        target_os = "openbsd",
998        target_os = "netbsd",
999        target_os = "dragonfly"
1000    ))]
1001    pub fn ino(&self) -> u64 {
1002        self.entry.d_fileno as u64
1003    }
1004
1005    #[cfg(target_os = "nuttx")]
1006    pub fn ino(&self) -> u64 {
1007        // Leave this 0 for now, as NuttX does not provide an inode number
1008        // in its directory entries.
1009        0
1010    }
1011
1012    #[cfg(any(
1013        target_os = "netbsd",
1014        target_os = "openbsd",
1015        target_os = "freebsd",
1016        target_os = "dragonfly",
1017        target_vendor = "apple",
1018    ))]
1019    fn name_bytes(&self) -> &[u8] {
1020        use crate::slice;
1021        unsafe {
1022            slice::from_raw_parts(
1023                self.entry.d_name.as_ptr() as *const u8,
1024                self.entry.d_namlen as usize,
1025            )
1026        }
1027    }
1028    #[cfg(not(any(
1029        target_os = "netbsd",
1030        target_os = "openbsd",
1031        target_os = "freebsd",
1032        target_os = "dragonfly",
1033        target_vendor = "apple",
1034    )))]
1035    fn name_bytes(&self) -> &[u8] {
1036        self.name_cstr().to_bytes()
1037    }
1038
1039    #[cfg(not(any(
1040        target_os = "android",
1041        target_os = "linux",
1042        target_os = "solaris",
1043        target_os = "illumos",
1044        target_os = "fuchsia",
1045        target_os = "redox",
1046        target_os = "aix",
1047        target_os = "nto",
1048        target_os = "vita",
1049        target_os = "hurd",
1050    )))]
1051    fn name_cstr(&self) -> &CStr {
1052        unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
1053    }
1054    #[cfg(any(
1055        target_os = "android",
1056        target_os = "linux",
1057        target_os = "solaris",
1058        target_os = "illumos",
1059        target_os = "fuchsia",
1060        target_os = "redox",
1061        target_os = "aix",
1062        target_os = "nto",
1063        target_os = "vita",
1064        target_os = "hurd",
1065    ))]
1066    fn name_cstr(&self) -> &CStr {
1067        &self.name
1068    }
1069
1070    pub fn file_name_os_str(&self) -> &OsStr {
1071        OsStr::from_bytes(self.name_bytes())
1072    }
1073}
1074
1075impl OpenOptions {
1076    pub fn new() -> OpenOptions {
1077        OpenOptions {
1078            // generic
1079            read: false,
1080            write: false,
1081            append: false,
1082            truncate: false,
1083            create: false,
1084            create_new: false,
1085            // system-specific
1086            custom_flags: 0,
1087            mode: 0o666,
1088        }
1089    }
1090
1091    pub fn read(&mut self, read: bool) {
1092        self.read = read;
1093    }
1094    pub fn write(&mut self, write: bool) {
1095        self.write = write;
1096    }
1097    pub fn append(&mut self, append: bool) {
1098        self.append = append;
1099    }
1100    pub fn truncate(&mut self, truncate: bool) {
1101        self.truncate = truncate;
1102    }
1103    pub fn create(&mut self, create: bool) {
1104        self.create = create;
1105    }
1106    pub fn create_new(&mut self, create_new: bool) {
1107        self.create_new = create_new;
1108    }
1109
1110    pub fn custom_flags(&mut self, flags: i32) {
1111        self.custom_flags = flags;
1112    }
1113    pub fn mode(&mut self, mode: u32) {
1114        self.mode = mode as mode_t;
1115    }
1116
1117    fn get_access_mode(&self) -> io::Result<c_int> {
1118        match (self.read, self.write, self.append) {
1119            (true, false, false) => Ok(libc::O_RDONLY),
1120            (false, true, false) => Ok(libc::O_WRONLY),
1121            (true, true, false) => Ok(libc::O_RDWR),
1122            (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
1123            (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
1124            (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
1125        }
1126    }
1127
1128    fn get_creation_mode(&self) -> io::Result<c_int> {
1129        match (self.write, self.append) {
1130            (true, false) => {}
1131            (false, false) => {
1132                if self.truncate || self.create || self.create_new {
1133                    return Err(Error::from_raw_os_error(libc::EINVAL));
1134                }
1135            }
1136            (_, true) => {
1137                if self.truncate && !self.create_new {
1138                    return Err(Error::from_raw_os_error(libc::EINVAL));
1139                }
1140            }
1141        }
1142
1143        Ok(match (self.create, self.truncate, self.create_new) {
1144            (false, false, false) => 0,
1145            (true, false, false) => libc::O_CREAT,
1146            (false, true, false) => libc::O_TRUNC,
1147            (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
1148            (_, _, true) => libc::O_CREAT | libc::O_EXCL,
1149        })
1150    }
1151}
1152
1153impl fmt::Debug for OpenOptions {
1154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1155        let OpenOptions { read, write, append, truncate, create, create_new, custom_flags, mode } =
1156            self;
1157        f.debug_struct("OpenOptions")
1158            .field("read", read)
1159            .field("write", write)
1160            .field("append", append)
1161            .field("truncate", truncate)
1162            .field("create", create)
1163            .field("create_new", create_new)
1164            .field("custom_flags", custom_flags)
1165            .field("mode", &Mode(*mode))
1166            .finish()
1167    }
1168}
1169
1170impl File {
1171    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
1172        run_path_with_cstr(path, &|path| File::open_c(path, opts))
1173    }
1174
1175    pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
1176        let flags = libc::O_CLOEXEC
1177            | opts.get_access_mode()?
1178            | opts.get_creation_mode()?
1179            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
1180        // The third argument of `open64` is documented to have type `mode_t`. On
1181        // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
1182        // However, since this is a variadic function, C integer promotion rules mean that on
1183        // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
1184        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
1185        Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
1186    }
1187
1188    pub fn file_attr(&self) -> io::Result<FileAttr> {
1189        let fd = self.as_raw_fd();
1190
1191        cfg_has_statx! {
1192            if let Some(ret) = unsafe { try_statx(
1193                fd,
1194                c"".as_ptr() as *const c_char,
1195                libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
1196                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1197            ) } {
1198                return ret;
1199            }
1200        }
1201
1202        let mut stat: stat64 = unsafe { mem::zeroed() };
1203        cvt(unsafe { fstat64(fd, &mut stat) })?;
1204        Ok(FileAttr::from_stat64(stat))
1205    }
1206
1207    pub fn fsync(&self) -> io::Result<()> {
1208        cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
1209        return Ok(());
1210
1211        #[cfg(target_vendor = "apple")]
1212        unsafe fn os_fsync(fd: c_int) -> c_int {
1213            libc::fcntl(fd, libc::F_FULLFSYNC)
1214        }
1215        #[cfg(not(target_vendor = "apple"))]
1216        unsafe fn os_fsync(fd: c_int) -> c_int {
1217            libc::fsync(fd)
1218        }
1219    }
1220
1221    pub fn datasync(&self) -> io::Result<()> {
1222        cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1223        return Ok(());
1224
1225        #[cfg(target_vendor = "apple")]
1226        unsafe fn os_datasync(fd: c_int) -> c_int {
1227            libc::fcntl(fd, libc::F_FULLFSYNC)
1228        }
1229        #[cfg(any(
1230            target_os = "freebsd",
1231            target_os = "fuchsia",
1232            target_os = "linux",
1233            target_os = "cygwin",
1234            target_os = "android",
1235            target_os = "netbsd",
1236            target_os = "openbsd",
1237            target_os = "nto",
1238            target_os = "hurd",
1239        ))]
1240        unsafe fn os_datasync(fd: c_int) -> c_int {
1241            libc::fdatasync(fd)
1242        }
1243        #[cfg(not(any(
1244            target_os = "android",
1245            target_os = "fuchsia",
1246            target_os = "freebsd",
1247            target_os = "linux",
1248            target_os = "cygwin",
1249            target_os = "netbsd",
1250            target_os = "openbsd",
1251            target_os = "nto",
1252            target_os = "hurd",
1253            target_vendor = "apple",
1254        )))]
1255        unsafe fn os_datasync(fd: c_int) -> c_int {
1256            libc::fsync(fd)
1257        }
1258    }
1259
1260    #[cfg(any(
1261        target_os = "freebsd",
1262        target_os = "fuchsia",
1263        target_os = "linux",
1264        target_os = "netbsd",
1265        target_vendor = "apple",
1266    ))]
1267    pub fn lock(&self) -> io::Result<()> {
1268        cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1269        return Ok(());
1270    }
1271
1272    #[cfg(not(any(
1273        target_os = "freebsd",
1274        target_os = "fuchsia",
1275        target_os = "linux",
1276        target_os = "netbsd",
1277        target_vendor = "apple",
1278    )))]
1279    pub fn lock(&self) -> io::Result<()> {
1280        Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported"))
1281    }
1282
1283    #[cfg(any(
1284        target_os = "freebsd",
1285        target_os = "fuchsia",
1286        target_os = "linux",
1287        target_os = "netbsd",
1288        target_vendor = "apple",
1289    ))]
1290    pub fn lock_shared(&self) -> io::Result<()> {
1291        cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1292        return Ok(());
1293    }
1294
1295    #[cfg(not(any(
1296        target_os = "freebsd",
1297        target_os = "fuchsia",
1298        target_os = "linux",
1299        target_os = "netbsd",
1300        target_vendor = "apple",
1301    )))]
1302    pub fn lock_shared(&self) -> io::Result<()> {
1303        Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported"))
1304    }
1305
1306    #[cfg(any(
1307        target_os = "freebsd",
1308        target_os = "fuchsia",
1309        target_os = "linux",
1310        target_os = "netbsd",
1311        target_vendor = "apple",
1312    ))]
1313    pub fn try_lock(&self) -> io::Result<bool> {
1314        let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1315        if let Err(ref err) = result {
1316            if err.kind() == io::ErrorKind::WouldBlock {
1317                return Ok(false);
1318            }
1319        }
1320        result?;
1321        return Ok(true);
1322    }
1323
1324    #[cfg(not(any(
1325        target_os = "freebsd",
1326        target_os = "fuchsia",
1327        target_os = "linux",
1328        target_os = "netbsd",
1329        target_vendor = "apple",
1330    )))]
1331    pub fn try_lock(&self) -> io::Result<bool> {
1332        Err(io::const_error!(io::ErrorKind::Unsupported, "try_lock() not supported"))
1333    }
1334
1335    #[cfg(any(
1336        target_os = "freebsd",
1337        target_os = "fuchsia",
1338        target_os = "linux",
1339        target_os = "netbsd",
1340        target_vendor = "apple",
1341    ))]
1342    pub fn try_lock_shared(&self) -> io::Result<bool> {
1343        let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1344        if let Err(ref err) = result {
1345            if err.kind() == io::ErrorKind::WouldBlock {
1346                return Ok(false);
1347            }
1348        }
1349        result?;
1350        return Ok(true);
1351    }
1352
1353    #[cfg(not(any(
1354        target_os = "freebsd",
1355        target_os = "fuchsia",
1356        target_os = "linux",
1357        target_os = "netbsd",
1358        target_vendor = "apple",
1359    )))]
1360    pub fn try_lock_shared(&self) -> io::Result<bool> {
1361        Err(io::const_error!(io::ErrorKind::Unsupported, "try_lock_shared() not supported"))
1362    }
1363
1364    #[cfg(any(
1365        target_os = "freebsd",
1366        target_os = "fuchsia",
1367        target_os = "linux",
1368        target_os = "netbsd",
1369        target_vendor = "apple",
1370    ))]
1371    pub fn unlock(&self) -> io::Result<()> {
1372        cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1373        return Ok(());
1374    }
1375
1376    #[cfg(not(any(
1377        target_os = "freebsd",
1378        target_os = "fuchsia",
1379        target_os = "linux",
1380        target_os = "netbsd",
1381        target_vendor = "apple",
1382    )))]
1383    pub fn unlock(&self) -> io::Result<()> {
1384        Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported"))
1385    }
1386
1387    pub fn truncate(&self, size: u64) -> io::Result<()> {
1388        let size: off64_t =
1389            size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1390        cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1391    }
1392
1393    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1394        self.0.read(buf)
1395    }
1396
1397    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1398        self.0.read_vectored(bufs)
1399    }
1400
1401    #[inline]
1402    pub fn is_read_vectored(&self) -> bool {
1403        self.0.is_read_vectored()
1404    }
1405
1406    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1407        self.0.read_at(buf, offset)
1408    }
1409
1410    pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1411        self.0.read_buf(cursor)
1412    }
1413
1414    pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
1415        self.0.read_vectored_at(bufs, offset)
1416    }
1417
1418    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1419        self.0.write(buf)
1420    }
1421
1422    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1423        self.0.write_vectored(bufs)
1424    }
1425
1426    #[inline]
1427    pub fn is_write_vectored(&self) -> bool {
1428        self.0.is_write_vectored()
1429    }
1430
1431    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1432        self.0.write_at(buf, offset)
1433    }
1434
1435    pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
1436        self.0.write_vectored_at(bufs, offset)
1437    }
1438
1439    #[inline]
1440    pub fn flush(&self) -> io::Result<()> {
1441        Ok(())
1442    }
1443
1444    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1445        let (whence, pos) = match pos {
1446            // Casting to `i64` is fine, too large values will end up as
1447            // negative which will cause an error in `lseek64`.
1448            SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1449            SeekFrom::End(off) => (libc::SEEK_END, off),
1450            SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1451        };
1452        let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1453        Ok(n as u64)
1454    }
1455
1456    pub fn tell(&self) -> io::Result<u64> {
1457        self.seek(SeekFrom::Current(0))
1458    }
1459
1460    pub fn duplicate(&self) -> io::Result<File> {
1461        self.0.duplicate().map(File)
1462    }
1463
1464    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1465        cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1466        Ok(())
1467    }
1468
1469    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1470        #[cfg(not(any(
1471            target_os = "redox",
1472            target_os = "espidf",
1473            target_os = "horizon",
1474            target_os = "vxworks",
1475            target_os = "nuttx",
1476        )))]
1477        let to_timespec = |time: Option<SystemTime>| match time {
1478            Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1479            Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
1480                io::ErrorKind::InvalidInput,
1481                "timestamp is too large to set as a file time",
1482            )),
1483            Some(_) => Err(io::const_error!(
1484                io::ErrorKind::InvalidInput,
1485                "timestamp is too small to set as a file time",
1486            )),
1487            None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
1488        };
1489        cfg_if::cfg_if! {
1490            if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", target_os = "vxworks", target_os = "nuttx"))] {
1491                // Redox doesn't appear to support `UTIME_OMIT`.
1492                // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1493                // the same as for Redox.
1494                // `futimens` and `UTIME_OMIT` are a work in progress for vxworks.
1495                let _ = times;
1496                Err(io::const_error!(
1497                    io::ErrorKind::Unsupported,
1498                    "setting file times not supported",
1499                ))
1500            } else if #[cfg(target_vendor = "apple")] {
1501                let mut buf = [mem::MaybeUninit::<libc::timespec>::uninit(); 3];
1502                let mut num_times = 0;
1503                let mut attrlist: libc::attrlist = unsafe { mem::zeroed() };
1504                attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1505                if times.created.is_some() {
1506                    buf[num_times].write(to_timespec(times.created)?);
1507                    num_times += 1;
1508                    attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1509                }
1510                if times.modified.is_some() {
1511                    buf[num_times].write(to_timespec(times.modified)?);
1512                    num_times += 1;
1513                    attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1514                }
1515                if times.accessed.is_some() {
1516                    buf[num_times].write(to_timespec(times.accessed)?);
1517                    num_times += 1;
1518                    attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1519                }
1520                cvt(unsafe { libc::fsetattrlist(
1521                    self.as_raw_fd(),
1522                    (&raw const attrlist).cast::<libc::c_void>().cast_mut(),
1523                    buf.as_ptr().cast::<libc::c_void>().cast_mut(),
1524                    num_times * size_of::<libc::timespec>(),
1525                    0
1526                ) })?;
1527                Ok(())
1528            } else if #[cfg(target_os = "android")] {
1529                let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1530                // futimens requires Android API level 19
1531                cvt(unsafe {
1532                    weak!(
1533                        fn futimens(fd: c_int, times: *const libc::timespec) -> c_int;
1534                    );
1535                    match futimens.get() {
1536                        Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1537                        None => return Err(io::const_error!(
1538                            io::ErrorKind::Unsupported,
1539                            "setting file times requires Android API level >= 19",
1540                        )),
1541                    }
1542                })?;
1543                Ok(())
1544            } else {
1545                #[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "32", not(target_arch = "riscv32")))]
1546                {
1547                    use crate::sys::{time::__timespec64, weak::weak};
1548
1549                    // Added in glibc 2.34
1550                    weak!(
1551                        fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int;
1552                    );
1553
1554                    if let Some(futimens64) = __futimens64.get() {
1555                        let to_timespec = |time: Option<SystemTime>| time.map(|time| time.t.to_timespec64())
1556                            .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _));
1557                        let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1558                        cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1559                        return Ok(());
1560                    }
1561                }
1562                let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1563                cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1564                Ok(())
1565            }
1566        }
1567    }
1568}
1569
1570impl DirBuilder {
1571    pub fn new() -> DirBuilder {
1572        DirBuilder { mode: 0o777 }
1573    }
1574
1575    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1576        run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1577    }
1578
1579    pub fn set_mode(&mut self, mode: u32) {
1580        self.mode = mode as mode_t;
1581    }
1582}
1583
1584impl fmt::Debug for DirBuilder {
1585    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1586        let DirBuilder { mode } = self;
1587        f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1588    }
1589}
1590
1591impl AsInner<FileDesc> for File {
1592    #[inline]
1593    fn as_inner(&self) -> &FileDesc {
1594        &self.0
1595    }
1596}
1597
1598impl AsInnerMut<FileDesc> for File {
1599    #[inline]
1600    fn as_inner_mut(&mut self) -> &mut FileDesc {
1601        &mut self.0
1602    }
1603}
1604
1605impl IntoInner<FileDesc> for File {
1606    fn into_inner(self) -> FileDesc {
1607        self.0
1608    }
1609}
1610
1611impl FromInner<FileDesc> for File {
1612    fn from_inner(file_desc: FileDesc) -> Self {
1613        Self(file_desc)
1614    }
1615}
1616
1617impl AsFd for File {
1618    #[inline]
1619    fn as_fd(&self) -> BorrowedFd<'_> {
1620        self.0.as_fd()
1621    }
1622}
1623
1624impl AsRawFd for File {
1625    #[inline]
1626    fn as_raw_fd(&self) -> RawFd {
1627        self.0.as_raw_fd()
1628    }
1629}
1630
1631impl IntoRawFd for File {
1632    fn into_raw_fd(self) -> RawFd {
1633        self.0.into_raw_fd()
1634    }
1635}
1636
1637impl FromRawFd for File {
1638    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1639        Self(FromRawFd::from_raw_fd(raw_fd))
1640    }
1641}
1642
1643impl fmt::Debug for File {
1644    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1645        #[cfg(any(target_os = "linux", target_os = "illumos", target_os = "solaris"))]
1646        fn get_path(fd: c_int) -> Option<PathBuf> {
1647            let mut p = PathBuf::from("/proc/self/fd");
1648            p.push(&fd.to_string());
1649            run_path_with_cstr(&p, &readlink).ok()
1650        }
1651
1652        #[cfg(any(target_vendor = "apple", target_os = "netbsd"))]
1653        fn get_path(fd: c_int) -> Option<PathBuf> {
1654            // FIXME: The use of PATH_MAX is generally not encouraged, but it
1655            // is inevitable in this case because Apple targets and NetBSD define `fcntl`
1656            // with `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1657            // alternatives. If a better method is invented, it should be used
1658            // instead.
1659            let mut buf = vec![0; libc::PATH_MAX as usize];
1660            let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1661            if n == -1 {
1662                cfg_if::cfg_if! {
1663                    if #[cfg(target_os = "netbsd")] {
1664                        // fallback to procfs as last resort
1665                        let mut p = PathBuf::from("/proc/self/fd");
1666                        p.push(&fd.to_string());
1667                        return run_path_with_cstr(&p, &readlink).ok()
1668                    } else {
1669                        return None;
1670                    }
1671                }
1672            }
1673            let l = buf.iter().position(|&c| c == 0).unwrap();
1674            buf.truncate(l as usize);
1675            buf.shrink_to_fit();
1676            Some(PathBuf::from(OsString::from_vec(buf)))
1677        }
1678
1679        #[cfg(target_os = "freebsd")]
1680        fn get_path(fd: c_int) -> Option<PathBuf> {
1681            let info = Box::<libc::kinfo_file>::new_zeroed();
1682            let mut info = unsafe { info.assume_init() };
1683            info.kf_structsize = size_of::<libc::kinfo_file>() as libc::c_int;
1684            let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
1685            if n == -1 {
1686                return None;
1687            }
1688            let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
1689            Some(PathBuf::from(OsString::from_vec(buf)))
1690        }
1691
1692        #[cfg(target_os = "vxworks")]
1693        fn get_path(fd: c_int) -> Option<PathBuf> {
1694            let mut buf = vec![0; libc::PATH_MAX as usize];
1695            let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1696            if n == -1 {
1697                return None;
1698            }
1699            let l = buf.iter().position(|&c| c == 0).unwrap();
1700            buf.truncate(l as usize);
1701            Some(PathBuf::from(OsString::from_vec(buf)))
1702        }
1703
1704        #[cfg(not(any(
1705            target_os = "linux",
1706            target_os = "vxworks",
1707            target_os = "freebsd",
1708            target_os = "netbsd",
1709            target_os = "illumos",
1710            target_os = "solaris",
1711            target_vendor = "apple",
1712        )))]
1713        fn get_path(_fd: c_int) -> Option<PathBuf> {
1714            // FIXME(#24570): implement this for other Unix platforms
1715            None
1716        }
1717
1718        fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1719            let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1720            if mode == -1 {
1721                return None;
1722            }
1723            match mode & libc::O_ACCMODE {
1724                libc::O_RDONLY => Some((true, false)),
1725                libc::O_RDWR => Some((true, true)),
1726                libc::O_WRONLY => Some((false, true)),
1727                _ => None,
1728            }
1729        }
1730
1731        let fd = self.as_raw_fd();
1732        let mut b = f.debug_struct("File");
1733        b.field("fd", &fd);
1734        if let Some(path) = get_path(fd) {
1735            b.field("path", &path);
1736        }
1737        if let Some((read, write)) = get_mode(fd) {
1738            b.field("read", &read).field("write", &write);
1739        }
1740        b.finish()
1741    }
1742}
1743
1744// Format in octal, followed by the mode format used in `ls -l`.
1745//
1746// References:
1747//   https://pubs.opengroup.org/onlinepubs/009696899/utilities/ls.html
1748//   https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html
1749//   https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
1750//
1751// Example:
1752//   0o100664 (-rw-rw-r--)
1753impl fmt::Debug for Mode {
1754    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1755        let Self(mode) = *self;
1756        write!(f, "0o{mode:06o}")?;
1757
1758        let entry_type = match mode & libc::S_IFMT {
1759            libc::S_IFDIR => 'd',
1760            libc::S_IFBLK => 'b',
1761            libc::S_IFCHR => 'c',
1762            libc::S_IFLNK => 'l',
1763            libc::S_IFIFO => 'p',
1764            libc::S_IFREG => '-',
1765            _ => return Ok(()),
1766        };
1767
1768        f.write_str(" (")?;
1769        f.write_char(entry_type)?;
1770
1771        // Owner permissions
1772        f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1773        f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1774        let owner_executable = mode & libc::S_IXUSR != 0;
1775        let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1776        f.write_char(match (owner_executable, setuid) {
1777            (true, true) => 's',  // executable and setuid
1778            (false, true) => 'S', // setuid
1779            (true, false) => 'x', // executable
1780            (false, false) => '-',
1781        })?;
1782
1783        // Group permissions
1784        f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1785        f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1786        let group_executable = mode & libc::S_IXGRP != 0;
1787        let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1788        f.write_char(match (group_executable, setgid) {
1789            (true, true) => 's',  // executable and setgid
1790            (false, true) => 'S', // setgid
1791            (true, false) => 'x', // executable
1792            (false, false) => '-',
1793        })?;
1794
1795        // Other permissions
1796        f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1797        f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1798        let other_executable = mode & libc::S_IXOTH != 0;
1799        let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1800        f.write_char(match (entry_type, other_executable, sticky) {
1801            ('d', true, true) => 't',  // searchable and restricted deletion
1802            ('d', false, true) => 'T', // restricted deletion
1803            (_, true, _) => 'x',       // executable
1804            (_, false, _) => '-',
1805        })?;
1806
1807        f.write_char(')')
1808    }
1809}
1810
1811pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1812    let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1813    if ptr.is_null() {
1814        Err(Error::last_os_error())
1815    } else {
1816        let root = path.to_path_buf();
1817        let inner = InnerReadDir { dirp: Dir(ptr), root };
1818        Ok(ReadDir::new(inner))
1819    }
1820}
1821
1822pub fn unlink(p: &CStr) -> io::Result<()> {
1823    cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ())
1824}
1825
1826pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
1827    cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1828}
1829
1830pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1831    cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
1832}
1833
1834pub fn rmdir(p: &CStr) -> io::Result<()> {
1835    cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ())
1836}
1837
1838pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> {
1839    let p = c_path.as_ptr();
1840
1841    let mut buf = Vec::with_capacity(256);
1842
1843    loop {
1844        let buf_read =
1845            cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1846
1847        unsafe {
1848            buf.set_len(buf_read);
1849        }
1850
1851        if buf_read != buf.capacity() {
1852            buf.shrink_to_fit();
1853
1854            return Ok(PathBuf::from(OsString::from_vec(buf)));
1855        }
1856
1857        // Trigger the internal buffer resizing logic of `Vec` by requiring
1858        // more space than the current capacity. The length is guaranteed to be
1859        // the same as the capacity due to the if statement above.
1860        buf.reserve(1);
1861    }
1862}
1863
1864pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> {
1865    cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
1866}
1867
1868pub fn link(original: &CStr, link: &CStr) -> io::Result<()> {
1869    cfg_if::cfg_if! {
1870        if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon", target_os = "vita", target_env = "nto70"))] {
1871            // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1872            // it implementation-defined whether `link` follows symlinks, so rely on the
1873            // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1874            // Android has `linkat` on newer versions, but we happen to know `link`
1875            // always has the correct behavior, so it's here as well.
1876            cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1877        } else {
1878            // Where we can, use `linkat` instead of `link`; see the comment above
1879            // this one for details on why.
1880            cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1881        }
1882    }
1883    Ok(())
1884}
1885
1886pub fn stat(p: &CStr) -> io::Result<FileAttr> {
1887    cfg_has_statx! {
1888        if let Some(ret) = unsafe { try_statx(
1889            libc::AT_FDCWD,
1890            p.as_ptr(),
1891            libc::AT_STATX_SYNC_AS_STAT,
1892            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1893        ) } {
1894            return ret;
1895        }
1896    }
1897
1898    let mut stat: stat64 = unsafe { mem::zeroed() };
1899    cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1900    Ok(FileAttr::from_stat64(stat))
1901}
1902
1903pub fn lstat(p: &CStr) -> io::Result<FileAttr> {
1904    cfg_has_statx! {
1905        if let Some(ret) = unsafe { try_statx(
1906            libc::AT_FDCWD,
1907            p.as_ptr(),
1908            libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1909            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1910        ) } {
1911            return ret;
1912        }
1913    }
1914
1915    let mut stat: stat64 = unsafe { mem::zeroed() };
1916    cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1917    Ok(FileAttr::from_stat64(stat))
1918}
1919
1920pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
1921    let r = unsafe { libc::realpath(path.as_ptr(), ptr::null_mut()) };
1922    if r.is_null() {
1923        return Err(io::Error::last_os_error());
1924    }
1925    Ok(PathBuf::from(OsString::from_vec(unsafe {
1926        let buf = CStr::from_ptr(r).to_bytes().to_vec();
1927        libc::free(r as *mut _);
1928        buf
1929    })))
1930}
1931
1932fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1933    use crate::fs::File;
1934    use crate::sys::fs::common::NOT_FILE_ERROR;
1935
1936    let reader = File::open(from)?;
1937    let metadata = reader.metadata()?;
1938    if !metadata.is_file() {
1939        return Err(NOT_FILE_ERROR);
1940    }
1941    Ok((reader, metadata))
1942}
1943
1944#[cfg(target_os = "espidf")]
1945fn open_to_and_set_permissions(
1946    to: &Path,
1947    _reader_metadata: &crate::fs::Metadata,
1948) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1949    use crate::fs::OpenOptions;
1950    let writer = OpenOptions::new().open(to)?;
1951    let writer_metadata = writer.metadata()?;
1952    Ok((writer, writer_metadata))
1953}
1954
1955#[cfg(not(target_os = "espidf"))]
1956fn open_to_and_set_permissions(
1957    to: &Path,
1958    reader_metadata: &crate::fs::Metadata,
1959) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1960    use crate::fs::OpenOptions;
1961    use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1962
1963    let perm = reader_metadata.permissions();
1964    let writer = OpenOptions::new()
1965        // create the file with the correct mode right away
1966        .mode(perm.mode())
1967        .write(true)
1968        .create(true)
1969        .truncate(true)
1970        .open(to)?;
1971    let writer_metadata = writer.metadata()?;
1972    // fchmod is broken on vita
1973    #[cfg(not(target_os = "vita"))]
1974    if writer_metadata.is_file() {
1975        // Set the correct file permissions, in case the file already existed.
1976        // Don't set the permissions on already existing non-files like
1977        // pipes/FIFOs or device nodes.
1978        writer.set_permissions(perm)?;
1979    }
1980    Ok((writer, writer_metadata))
1981}
1982
1983mod cfm {
1984    use crate::fs::{File, Metadata};
1985    use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
1986
1987    #[allow(dead_code)]
1988    pub struct CachedFileMetadata(pub File, pub Metadata);
1989
1990    impl Read for CachedFileMetadata {
1991        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1992            self.0.read(buf)
1993        }
1994        fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
1995            self.0.read_vectored(bufs)
1996        }
1997        fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
1998            self.0.read_buf(cursor)
1999        }
2000        #[inline]
2001        fn is_read_vectored(&self) -> bool {
2002            self.0.is_read_vectored()
2003        }
2004        fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2005            self.0.read_to_end(buf)
2006        }
2007        fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2008            self.0.read_to_string(buf)
2009        }
2010    }
2011    impl Write for CachedFileMetadata {
2012        fn write(&mut self, buf: &[u8]) -> Result<usize> {
2013            self.0.write(buf)
2014        }
2015        fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2016            self.0.write_vectored(bufs)
2017        }
2018        #[inline]
2019        fn is_write_vectored(&self) -> bool {
2020            self.0.is_write_vectored()
2021        }
2022        #[inline]
2023        fn flush(&mut self) -> Result<()> {
2024            self.0.flush()
2025        }
2026    }
2027}
2028#[cfg(any(target_os = "linux", target_os = "android"))]
2029pub(crate) use cfm::CachedFileMetadata;
2030
2031#[cfg(not(target_vendor = "apple"))]
2032pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2033    let (reader, reader_metadata) = open_from(from)?;
2034    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2035
2036    io::copy(
2037        &mut cfm::CachedFileMetadata(reader, reader_metadata),
2038        &mut cfm::CachedFileMetadata(writer, writer_metadata),
2039    )
2040}
2041
2042#[cfg(target_vendor = "apple")]
2043pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2044    const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2045
2046    struct FreeOnDrop(libc::copyfile_state_t);
2047    impl Drop for FreeOnDrop {
2048        fn drop(&mut self) {
2049            // The code below ensures that `FreeOnDrop` is never a null pointer
2050            unsafe {
2051                // `copyfile_state_free` returns -1 if the `to` or `from` files
2052                // cannot be closed. However, this is not considered an error.
2053                libc::copyfile_state_free(self.0);
2054            }
2055        }
2056    }
2057
2058    let (reader, reader_metadata) = open_from(from)?;
2059
2060    let clonefile_result = run_path_with_cstr(to, &|to| {
2061        cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2062    });
2063    match clonefile_result {
2064        Ok(_) => return Ok(reader_metadata.len()),
2065        Err(e) => match e.raw_os_error() {
2066            // `fclonefileat` will fail on non-APFS volumes, if the
2067            // destination already exists, or if the source and destination
2068            // are on different devices. In all these cases `fcopyfile`
2069            // should succeed.
2070            Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2071            _ => return Err(e),
2072        },
2073    }
2074
2075    // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
2076    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2077
2078    // We ensure that `FreeOnDrop` never contains a null pointer so it is
2079    // always safe to call `copyfile_state_free`
2080    let state = unsafe {
2081        let state = libc::copyfile_state_alloc();
2082        if state.is_null() {
2083            return Err(crate::io::Error::last_os_error());
2084        }
2085        FreeOnDrop(state)
2086    };
2087
2088    let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2089
2090    cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2091
2092    let mut bytes_copied: libc::off_t = 0;
2093    cvt(unsafe {
2094        libc::copyfile_state_get(
2095            state.0,
2096            libc::COPYFILE_STATE_COPIED as u32,
2097            (&raw mut bytes_copied) as *mut libc::c_void,
2098        )
2099    })?;
2100    Ok(bytes_copied as u64)
2101}
2102
2103pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2104    run_path_with_cstr(path, &|path| {
2105        cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2106            .map(|_| ())
2107    })
2108}
2109
2110pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2111    cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2112    Ok(())
2113}
2114
2115#[cfg(not(target_os = "vxworks"))]
2116pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2117    run_path_with_cstr(path, &|path| {
2118        cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2119            .map(|_| ())
2120    })
2121}
2122
2123#[cfg(target_os = "vxworks")]
2124pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2125    let (_, _, _) = (path, uid, gid);
2126    Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2127}
2128
2129#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
2130pub fn chroot(dir: &Path) -> io::Result<()> {
2131    run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2132}
2133
2134#[cfg(target_os = "vxworks")]
2135pub fn chroot(dir: &Path) -> io::Result<()> {
2136    let _ = dir;
2137    Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2138}
2139
2140pub use remove_dir_impl::remove_dir_all;
2141
2142// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri
2143#[cfg(any(
2144    target_os = "redox",
2145    target_os = "espidf",
2146    target_os = "horizon",
2147    target_os = "vita",
2148    target_os = "nto",
2149    target_os = "vxworks",
2150    miri
2151))]
2152mod remove_dir_impl {
2153    pub use crate::sys::fs::common::remove_dir_all;
2154}
2155
2156// Modern implementation using openat(), unlinkat() and fdopendir()
2157#[cfg(not(any(
2158    target_os = "redox",
2159    target_os = "espidf",
2160    target_os = "horizon",
2161    target_os = "vita",
2162    target_os = "nto",
2163    target_os = "vxworks",
2164    miri
2165)))]
2166mod remove_dir_impl {
2167    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2168    use libc::{fdopendir, openat, unlinkat};
2169    #[cfg(all(target_os = "linux", target_env = "gnu"))]
2170    use libc::{fdopendir, openat64 as openat, unlinkat};
2171
2172    use super::{Dir, DirEntry, InnerReadDir, ReadDir, lstat};
2173    use crate::ffi::CStr;
2174    use crate::io;
2175    use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
2176    use crate::os::unix::prelude::{OwnedFd, RawFd};
2177    use crate::path::{Path, PathBuf};
2178    use crate::sys::common::small_c_string::run_path_with_cstr;
2179    use crate::sys::{cvt, cvt_r};
2180    use crate::sys_common::ignore_notfound;
2181
2182    pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2183        let fd = cvt_r(|| unsafe {
2184            openat(
2185                parent_fd.unwrap_or(libc::AT_FDCWD),
2186                p.as_ptr(),
2187                libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2188            )
2189        })?;
2190        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2191    }
2192
2193    fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2194        let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2195        if ptr.is_null() {
2196            return Err(io::Error::last_os_error());
2197        }
2198        let dirp = Dir(ptr);
2199        // file descriptor is automatically closed by libc::closedir() now, so give up ownership
2200        let new_parent_fd = dir_fd.into_raw_fd();
2201        // a valid root is not needed because we do not call any functions involving the full path
2202        // of the `DirEntry`s.
2203        let dummy_root = PathBuf::new();
2204        let inner = InnerReadDir { dirp, root: dummy_root };
2205        Ok((ReadDir::new(inner), new_parent_fd))
2206    }
2207
2208    #[cfg(any(
2209        target_os = "solaris",
2210        target_os = "illumos",
2211        target_os = "haiku",
2212        target_os = "vxworks",
2213        target_os = "aix",
2214    ))]
2215    fn is_dir(_ent: &DirEntry) -> Option<bool> {
2216        None
2217    }
2218
2219    #[cfg(not(any(
2220        target_os = "solaris",
2221        target_os = "illumos",
2222        target_os = "haiku",
2223        target_os = "vxworks",
2224        target_os = "aix",
2225    )))]
2226    fn is_dir(ent: &DirEntry) -> Option<bool> {
2227        match ent.entry.d_type {
2228            libc::DT_UNKNOWN => None,
2229            libc::DT_DIR => Some(true),
2230            _ => Some(false),
2231        }
2232    }
2233
2234    fn is_enoent(result: &io::Result<()>) -> bool {
2235        if let Err(err) = result
2236            && matches!(err.raw_os_error(), Some(libc::ENOENT))
2237        {
2238            true
2239        } else {
2240            false
2241        }
2242    }
2243
2244    fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2245        // try opening as directory
2246        let fd = match openat_nofollow_dironly(parent_fd, &path) {
2247            Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2248                // not a directory - don't traverse further
2249                // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
2250                return match parent_fd {
2251                    // unlink...
2252                    Some(parent_fd) => {
2253                        cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2254                    }
2255                    // ...unless this was supposed to be the deletion root directory
2256                    None => Err(err),
2257                };
2258            }
2259            result => result?,
2260        };
2261
2262        // open the directory passing ownership of the fd
2263        let (dir, fd) = fdreaddir(fd)?;
2264        for child in dir {
2265            let child = child?;
2266            let child_name = child.name_cstr();
2267            // we need an inner try block, because if one of these
2268            // directories has already been deleted, then we need to
2269            // continue the loop, not return ok.
2270            let result: io::Result<()> = try {
2271                match is_dir(&child) {
2272                    Some(true) => {
2273                        remove_dir_all_recursive(Some(fd), child_name)?;
2274                    }
2275                    Some(false) => {
2276                        cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
2277                    }
2278                    None => {
2279                        // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
2280                        // if the process has the appropriate privileges. This however can causing orphaned
2281                        // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
2282                        // into it first instead of trying to unlink() it.
2283                        remove_dir_all_recursive(Some(fd), child_name)?;
2284                    }
2285                }
2286            };
2287            if result.is_err() && !is_enoent(&result) {
2288                return result;
2289            }
2290        }
2291
2292        // unlink the directory after removing its contents
2293        ignore_notfound(cvt(unsafe {
2294            unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2295        }))?;
2296        Ok(())
2297    }
2298
2299    fn remove_dir_all_modern(p: &CStr) -> io::Result<()> {
2300        // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
2301        // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
2302        // into symlinks.
2303        let attr = lstat(p)?;
2304        if attr.file_type().is_symlink() {
2305            super::unlink(p)
2306        } else {
2307            remove_dir_all_recursive(None, &p)
2308        }
2309    }
2310
2311    pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2312        run_path_with_cstr(p, &remove_dir_all_modern)
2313    }
2314}