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