Skip to main content

std/sys/fs/
unix.rs

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