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