Skip to main content

std/sys/fs/
unix.rs

1#![allow(nonstandard_style)]
2#![allow(unsafe_op_in_unsafe_fn)]
3// miri has some special hacks here that make things unused.
4#![cfg_attr(miri, allow(unused))]
5
6#[cfg(test)]
7mod tests;
8
9#[cfg(all(target_os = "linux", target_env = "gnu"))]
10use libc::c_char;
11#[cfg(any(
12    all(target_os = "linux", not(target_env = "musl")),
13    target_os = "android",
14    target_os = "fuchsia",
15    target_os = "hurd",
16    target_os = "illumos",
17    target_vendor = "apple",
18))]
19use libc::dirfd;
20#[cfg(any(target_os = "fuchsia", target_os = "illumos", target_vendor = "apple"))]
21use libc::fstatat as fstatat64;
22#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
23use libc::fstatat64;
24use libc::{c_int, mode_t};
25#[cfg(target_os = "android")]
26use libc::{
27    dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
28    lstat as lstat64, off64_t, open as open64, stat as stat64,
29};
30#[cfg(not(any(
31    all(target_os = "linux", not(target_env = "musl")),
32    target_os = "android",
33    target_os = "hurd",
34    target_os = "l4re",
35)))]
36use libc::{
37    dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
38    lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
39};
40#[cfg(target_os = "l4re")]
41use libc::{
42    dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64, lstat as lstat64,
43    off_t as off64_t, open as open64, stat as stat64,
44};
45#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
46use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
47
48use crate::ffi::{CStr, OsStr, OsString};
49use crate::fmt::{self, Write as _};
50use crate::fs::TryLockError;
51use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
52use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
53#[cfg(target_family = "unix")]
54use crate::os::unix::prelude::*;
55#[cfg(target_os = "wasi")]
56use crate::os::wasi::prelude::*;
57use crate::path::{Path, PathBuf};
58use crate::sync::Arc;
59use crate::sys::fd::FileDesc;
60pub use crate::sys::fs::common::exists;
61use crate::sys::helpers::run_path_with_cstr;
62use crate::sys::time::SystemTime;
63#[cfg(all(target_os = "linux", target_env = "gnu"))]
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        target_os = "rtems",
594    ))]
595    pub fn modified(&self) -> io::Result<SystemTime> {
596        SystemTime::new(self.stat.st_mtime as i64, 0)
597    }
598
599    #[cfg(any(
600        target_os = "horizon",
601        target_os = "hurd",
602        target_os = "nuttx",
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        target_os = "rtems"
634    ))]
635    pub fn accessed(&self) -> io::Result<SystemTime> {
636        SystemTime::new(self.stat.st_atime as i64, 0)
637    }
638
639    #[cfg(any(
640        target_os = "horizon",
641        target_os = "hurd",
642        target_os = "nuttx",
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 fmt::Debug for ReadDir {
791    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792        // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
793        // Thus the result will be e g 'ReadDir("/home")'
794        fmt::Debug::fmt(&*self.inner.root, f)
795    }
796}
797
798impl Iterator for ReadDir {
799    type Item = io::Result<DirEntry>;
800
801    fn next(&mut self) -> Option<io::Result<DirEntry>> {
802        if self.end_of_stream {
803            return None;
804        }
805
806        unsafe {
807            loop {
808                // POSIX.1-2024 formalized what was already guaranteed by a lot
809                // of implementations and required readdir() to be thread-safe as
810                // long as an individual DIR* is not accessed concurrently. Taking
811                // a mutable reference to the `ReadDir` iterator prevents that.
812                // Even POSIX.1-1994 specified that the data in the returned
813                // dirent
814                // > is not overwritten by another call to readdir() on a
815                // > different directory stream.
816                //
817                // and that guarantee together with the requirement that the
818                // underlying syscalls need to be thread-safe because of readdir_r
819                // make it very unlikely for an implementation to be non-conforming.
820                // Nevertheless, there are still some platforms where we either
821                // cannot confirm `readdir` to be thread-safe or know that it
822                // isn't.
823                cfg_select! {
824                    any(
825                        target_os = "espidf", // readdir truly isn't thread-safe.
826                        target_os = "lynxos178",
827                        target_os = "qurt",
828                        target_os = "rtems",
829                        target_os = "vxworks",
830                    ) => {
831                        use crate::mem::MaybeUninit;
832
833                        let mut entry = MaybeUninit::uninit();
834                        let mut entry_ptr: *mut dirent64 = ptr::null_mut();
835                        let err =
836                            libc::readdir_r(self.inner.dirp.0, entry.as_mut_ptr(), &mut entry_ptr);
837                        if err != 0 {
838                            if entry_ptr.is_null() {
839                                // We encountered an error (which will be returned in this iteration), but
840                                // we also reached the end of the directory stream. The `end_of_stream`
841                                // flag is enabled to make sure that we return `None` in the next iteration
842                                // (instead of looping forever)
843                                self.end_of_stream = true;
844                            }
845                            return Some(Err(Error::from_raw_os_error(err)));
846                        }
847                        if entry_ptr.is_null() {
848                            return None;
849                        }
850
851                        let entry_ptr = entry_ptr.cast_const();
852                    }
853                    _ => {
854                        #[cfg(not(any(
855                            all(target_os = "linux", not(target_env = "musl")),
856                            target_os = "hurd",
857                            target_os = "l4re",
858                        )))]
859                        use libc::readdir as readdir64;
860                        #[cfg(any(
861                            all(target_os = "linux", not(target_env = "musl")),
862                            target_os = "hurd",
863                            target_os = "l4re"
864                        ))]
865                        use libc::readdir64;
866
867                        use crate::sys::io::{errno, set_errno};
868
869                        set_errno(0);
870                        let entry_ptr: *const dirent64 = readdir64(self.inner.dirp.0);
871                        if entry_ptr.is_null() {
872                            // We either encountered an error, or reached the end. Either way,
873                            // the next call to next() should return None.
874                            self.end_of_stream = true;
875
876                            // To distinguish between errors and end-of-directory, we had to clear
877                            // errno beforehand to check for an error now.
878                            return match errno() {
879                                0 => None,
880                                e => Some(Err(Error::from_raw_os_error(e))),
881                            };
882                        }
883                    }
884                }
885
886                // The dirent64 struct is a weird imaginary thing that isn't ever supposed
887                // to be worked with by value. Its trailing d_name field is declared
888                // variously as [c_char; 256] or [c_char; 1] on different systems but
889                // either way that size is meaningless; only the offset of d_name is
890                // meaningful. The dirent64 pointers that libc returns from readdir64 are
891                // allowed to point to allocations smaller _or_ LARGER than implied by the
892                // definition of the struct.
893                //
894                // As such, we need to be even more careful with dirent64 than if its
895                // contents were "simply" partially initialized data.
896                //
897                // Like for uninitialized contents, converting entry_ptr to `&dirent64`
898                // would not be legal. However, we can use `&raw const (*entry_ptr).d_name`
899                // to refer the fields individually, because that operation is equivalent
900                // to `byte_offset` and thus does not require the full extent of `*entry_ptr`
901                // to be in bounds of the same allocation, only the offset of the field
902                // being referenced.
903
904                // d_name is guaranteed to be null-terminated.
905                let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast());
906                let name_bytes = name.to_bytes();
907                if name_bytes == b"." || name_bytes == b".." {
908                    continue;
909                }
910
911                // When loading from a field, we can skip the `&raw const`; `(*entry_ptr).d_ino` as
912                // a value expression will do the right thing: `byte_offset` to the field and then
913                // only access those bytes.
914                let entry = dirent64_min {
915                    #[cfg(any(
916                        target_os = "dragonfly",
917                        target_os = "freebsd",
918                        target_os = "netbsd",
919                        target_os = "openbsd",
920                    ))]
921                    d_ino: (*entry_ptr).d_fileno,
922                    #[cfg(any(target_os = "nuttx", target_os = "vita",))]
923                    d_ino: 0,
924                    #[cfg(not(any(
925                        target_os = "dragonfly",
926                        target_os = "freebsd",
927                        target_os = "netbsd",
928                        target_os = "nuttx",
929                        target_os = "openbsd",
930                        target_os = "vita",
931                    )))]
932                    d_ino: (*entry_ptr).d_ino as u64,
933                    #[cfg(not(any(
934                        target_os = "solaris",
935                        target_os = "illumos",
936                        target_os = "haiku",
937                        target_os = "vxworks",
938                        target_os = "aix",
939                        target_os = "nto",
940                        target_os = "qnx",
941                        target_os = "vita",
942                    )))]
943                    d_type: (*entry_ptr).d_type as u8,
944                };
945
946                return Some(Ok(DirEntry {
947                    entry,
948                    name: name.to_owned(),
949                    dir: Arc::clone(&self.inner),
950                }));
951            }
952        }
953    }
954}
955
956/// Aborts the process if a file descriptor is not open, if debug asserts are enabled
957///
958/// Many IO syscalls can't be fully trusted about EBADF error codes because those
959/// might get bubbled up from a remote FUSE server rather than the file descriptor
960/// in the current process being invalid.
961///
962/// So we check file flags instead which live on the file descriptor and not the underlying file.
963/// The downside is that it costs an extra syscall, so we only do it for debug.
964#[inline]
965pub(crate) fn debug_assert_fd_is_open(fd: RawFd) {
966    use crate::sys::io::errno;
967
968    // this is similar to assert_unsafe_precondition!() but it doesn't require const
969    if core::ub_checks::check_library_ub() {
970        if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 && errno() == libc::EBADF {
971            rtabort!("IO Safety violation: owned file descriptor already closed");
972        }
973    }
974}
975
976impl Drop for DirStream {
977    fn drop(&mut self) {
978        // dirfd isn't supported everywhere
979        #[cfg(not(any(
980            miri,
981            target_os = "redox",
982            target_os = "nto",
983            target_os = "qnx",
984            target_os = "vita",
985            target_os = "hurd",
986            target_os = "espidf",
987            target_os = "horizon",
988            target_os = "vxworks",
989            target_os = "rtems",
990            target_os = "nuttx",
991        )))]
992        {
993            let fd = unsafe { libc::dirfd(self.0) };
994            debug_assert_fd_is_open(fd);
995        }
996        let r = unsafe { libc::closedir(self.0) };
997        assert!(
998            r == 0 || crate::io::Error::last_os_error().is_interrupted(),
999            "unexpected error during closedir: {:?}",
1000            crate::io::Error::last_os_error()
1001        );
1002    }
1003}
1004
1005// SAFETY: `int dirfd (DIR *dirstream)` is MT-safe, implying that the pointer
1006// may be safely sent among threads.
1007unsafe impl Send for DirStream {}
1008unsafe impl Sync for DirStream {}
1009
1010impl DirEntry {
1011    pub fn path(&self) -> PathBuf {
1012        self.dir.root.join(self.file_name_os_str())
1013    }
1014
1015    pub fn file_name(&self) -> OsString {
1016        self.file_name_os_str().to_os_string()
1017    }
1018
1019    #[cfg(all(
1020        any(
1021            all(target_os = "linux", not(target_env = "musl")),
1022            target_os = "android",
1023            target_os = "fuchsia",
1024            target_os = "hurd",
1025            target_os = "illumos",
1026            target_vendor = "apple",
1027        ),
1028        not(miri) // no dirfd on Miri
1029    ))]
1030    pub fn metadata(&self) -> io::Result<FileAttr> {
1031        let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
1032        let name = self.name.as_ptr();
1033
1034        cfg_has_statx! {
1035            if let Some(ret) = unsafe { try_statx(
1036                fd,
1037                name,
1038                libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1039                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1040            ) } {
1041                return ret;
1042            }
1043        }
1044
1045        let mut stat: stat64 = unsafe { mem::zeroed() };
1046        cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
1047        Ok(FileAttr::from_stat64(stat))
1048    }
1049
1050    #[cfg(any(
1051        not(any(
1052            all(target_os = "linux", not(target_env = "musl")),
1053            target_os = "android",
1054            target_os = "fuchsia",
1055            target_os = "hurd",
1056            target_os = "illumos",
1057            target_vendor = "apple",
1058        )),
1059        miri // no dirfd on Miri
1060    ))]
1061    pub fn metadata(&self) -> io::Result<FileAttr> {
1062        run_path_with_cstr(&self.path(), &lstat)
1063    }
1064
1065    #[cfg(any(
1066        target_os = "solaris",
1067        target_os = "illumos",
1068        target_os = "haiku",
1069        target_os = "vxworks",
1070        target_os = "aix",
1071        target_os = "nto",
1072        target_os = "qnx",
1073        target_os = "vita",
1074        target_os = "l4re",
1075    ))]
1076    pub fn file_type(&self) -> io::Result<FileType> {
1077        self.metadata().map(|m| m.file_type())
1078    }
1079
1080    #[cfg(not(any(
1081        target_os = "solaris",
1082        target_os = "illumos",
1083        target_os = "haiku",
1084        target_os = "vxworks",
1085        target_os = "aix",
1086        target_os = "nto",
1087        target_os = "qnx",
1088        target_os = "vita",
1089        target_os = "l4re",
1090    )))]
1091    pub fn file_type(&self) -> io::Result<FileType> {
1092        match self.entry.d_type {
1093            libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
1094            libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
1095            libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
1096            libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
1097            libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
1098            libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
1099            libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
1100            _ => self.metadata().map(|m| m.file_type()),
1101        }
1102    }
1103
1104    pub fn ino(&self) -> u64 {
1105        self.entry.d_ino
1106    }
1107
1108    pub fn file_name_os_str(&self) -> &OsStr {
1109        OsStr::from_bytes(self.name.as_bytes())
1110    }
1111}
1112
1113impl OpenOptions {
1114    pub fn new() -> OpenOptions {
1115        OpenOptions {
1116            // generic
1117            read: false,
1118            write: false,
1119            append: false,
1120            truncate: false,
1121            create: false,
1122            create_new: false,
1123            // system-specific
1124            custom_flags: 0,
1125            mode: 0o666,
1126        }
1127    }
1128
1129    pub fn read(&mut self, read: bool) {
1130        self.read = read;
1131    }
1132    pub fn write(&mut self, write: bool) {
1133        self.write = write;
1134    }
1135    pub fn append(&mut self, append: bool) {
1136        self.append = append;
1137    }
1138    pub fn truncate(&mut self, truncate: bool) {
1139        self.truncate = truncate;
1140    }
1141    pub fn create(&mut self, create: bool) {
1142        self.create = create;
1143    }
1144    pub fn create_new(&mut self, create_new: bool) {
1145        self.create_new = create_new;
1146    }
1147
1148    pub fn custom_flags(&mut self, flags: i32) {
1149        self.custom_flags = flags;
1150    }
1151    #[cfg(not(target_os = "wasi"))]
1152    pub fn mode(&mut self, mode: u32) {
1153        self.mode = mode as mode_t;
1154    }
1155
1156    fn get_access_mode(&self) -> io::Result<c_int> {
1157        match (self.read, self.write, self.append) {
1158            (true, false, false) => Ok(libc::O_RDONLY),
1159            (false, true, false) => Ok(libc::O_WRONLY),
1160            (true, true, false) => Ok(libc::O_RDWR),
1161            (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
1162            (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
1163            (false, false, false) => {
1164                // If no access mode is set, check if any creation flags are set
1165                // to provide a more descriptive error message
1166                if self.create || self.create_new || self.truncate {
1167                    Err(io::Error::new(
1168                        io::ErrorKind::InvalidInput,
1169                        "creating or truncating a file requires write or append access",
1170                    ))
1171                } else {
1172                    Err(io::Error::new(
1173                        io::ErrorKind::InvalidInput,
1174                        "must specify at least one of read, write, or append access",
1175                    ))
1176                }
1177            }
1178        }
1179    }
1180
1181    fn get_creation_mode(&self) -> io::Result<c_int> {
1182        match (self.write, self.append) {
1183            (true, false) => {}
1184            (false, false) => {
1185                if self.truncate || self.create || self.create_new {
1186                    return Err(io::Error::new(
1187                        io::ErrorKind::InvalidInput,
1188                        "creating or truncating a file requires write or append access",
1189                    ));
1190                }
1191            }
1192            (_, true) => {
1193                if self.truncate && !self.create_new {
1194                    return Err(io::Error::new(
1195                        io::ErrorKind::InvalidInput,
1196                        "append and truncate cannot both be enabled",
1197                    ));
1198                }
1199            }
1200        }
1201
1202        Ok(match (self.create, self.truncate, self.create_new) {
1203            (false, false, false) => 0,
1204            (true, false, false) => libc::O_CREAT,
1205            (false, true, false) => libc::O_TRUNC,
1206            (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
1207            (_, _, true) => libc::O_CREAT | libc::O_EXCL,
1208        })
1209    }
1210}
1211
1212impl fmt::Debug for OpenOptions {
1213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214        let OpenOptions { read, write, append, truncate, create, create_new, custom_flags, mode } =
1215            self;
1216        f.debug_struct("OpenOptions")
1217            .field("read", read)
1218            .field("write", write)
1219            .field("append", append)
1220            .field("truncate", truncate)
1221            .field("create", create)
1222            .field("create_new", create_new)
1223            .field("custom_flags", custom_flags)
1224            .field("mode", &Mode(*mode))
1225            .finish()
1226    }
1227}
1228
1229impl File {
1230    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
1231        run_path_with_cstr(path, &|path| File::open_c(path, opts))
1232    }
1233
1234    pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
1235        let flags = libc::O_CLOEXEC
1236            | opts.get_access_mode()?
1237            | opts.get_creation_mode()?
1238            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
1239        // The third argument of `open64` is documented to have type `mode_t`. On
1240        // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
1241        // However, since this is a variadic function, C integer promotion rules mean that on
1242        // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
1243        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
1244        Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
1245    }
1246
1247    pub fn file_attr(&self) -> io::Result<FileAttr> {
1248        let fd = self.as_raw_fd();
1249
1250        cfg_has_statx! {
1251            if let Some(ret) = unsafe { try_statx(
1252                fd,
1253                c"".as_ptr() as *const c_char,
1254                libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
1255                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1256            ) } {
1257                return ret;
1258            }
1259        }
1260
1261        let mut stat: stat64 = unsafe { mem::zeroed() };
1262        cvt(unsafe { fstat64(fd, &mut stat) })?;
1263        Ok(FileAttr::from_stat64(stat))
1264    }
1265
1266    pub fn fsync(&self) -> io::Result<()> {
1267        cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
1268        return Ok(());
1269
1270        #[cfg(target_vendor = "apple")]
1271        unsafe fn os_fsync(fd: c_int) -> c_int {
1272            libc::fcntl(fd, libc::F_FULLFSYNC)
1273        }
1274        #[cfg(not(target_vendor = "apple"))]
1275        unsafe fn os_fsync(fd: c_int) -> c_int {
1276            libc::fsync(fd)
1277        }
1278    }
1279
1280    pub fn datasync(&self) -> io::Result<()> {
1281        cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1282        return Ok(());
1283
1284        #[cfg(target_vendor = "apple")]
1285        unsafe fn os_datasync(fd: c_int) -> c_int {
1286            libc::fcntl(fd, libc::F_FULLFSYNC)
1287        }
1288        #[cfg(any(
1289            target_os = "freebsd",
1290            target_os = "fuchsia",
1291            target_os = "linux",
1292            target_os = "cygwin",
1293            target_os = "android",
1294            target_os = "netbsd",
1295            target_os = "openbsd",
1296            target_os = "nto",
1297            target_os = "qnx",
1298            target_os = "hurd",
1299            target_os = "l4re",
1300        ))]
1301        unsafe fn os_datasync(fd: c_int) -> c_int {
1302            libc::fdatasync(fd)
1303        }
1304        #[cfg(not(any(
1305            target_os = "android",
1306            target_os = "fuchsia",
1307            target_os = "freebsd",
1308            target_os = "linux",
1309            target_os = "cygwin",
1310            target_os = "netbsd",
1311            target_os = "openbsd",
1312            target_os = "nto",
1313            target_os = "qnx",
1314            target_os = "hurd",
1315            target_os = "l4re",
1316            target_vendor = "apple",
1317        )))]
1318        unsafe fn os_datasync(fd: c_int) -> c_int {
1319            libc::fsync(fd)
1320        }
1321    }
1322
1323    pub fn lock(&self) -> io::Result<()> {
1324        cfg_select! {
1325            any(
1326                target_os = "freebsd",
1327                target_os = "fuchsia",
1328                target_os = "hurd",
1329                target_os = "linux",
1330                target_os = "netbsd",
1331                target_os = "openbsd",
1332                target_os = "cygwin",
1333                target_os = "illumos",
1334                target_os = "aix",
1335                target_os = "android",
1336                target_vendor = "apple",
1337            ) => {
1338                cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1339                Ok(())
1340            }
1341            _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported")),
1342        }
1343    }
1344
1345    pub fn lock_shared(&self) -> io::Result<()> {
1346        cfg_select! {
1347            any(
1348                target_os = "freebsd",
1349                target_os = "fuchsia",
1350                target_os = "hurd",
1351                target_os = "linux",
1352                target_os = "netbsd",
1353                target_os = "openbsd",
1354                target_os = "cygwin",
1355                target_os = "illumos",
1356                target_os = "aix",
1357                target_os = "android",
1358                target_vendor = "apple",
1359            ) => {
1360                cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1361                Ok(())
1362            }
1363            _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported")),
1364        }
1365    }
1366
1367    pub fn try_lock(&self) -> Result<(), TryLockError> {
1368        cfg_select! {
1369            any(
1370                target_os = "freebsd",
1371                target_os = "fuchsia",
1372                target_os = "hurd",
1373                target_os = "linux",
1374                target_os = "netbsd",
1375                target_os = "openbsd",
1376                target_os = "cygwin",
1377                target_os = "illumos",
1378                target_os = "aix",
1379                target_os = "android",
1380                target_vendor = "apple",
1381            ) => {
1382                let result =
1383                    cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1384                if let Err(err) = result {
1385                    if err.kind() == io::ErrorKind::WouldBlock {
1386                        Err(TryLockError::WouldBlock)
1387                    } else {
1388                        Err(TryLockError::Error(err))
1389                    }
1390                } else {
1391                    Ok(())
1392                }
1393            }
1394            _ => Err(TryLockError::Error(io::const_error!(
1395                io::ErrorKind::Unsupported,
1396                "try_lock() not supported"
1397            ))),
1398        }
1399    }
1400
1401    pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
1402        cfg_select! {
1403            any(
1404                target_os = "freebsd",
1405                target_os = "fuchsia",
1406                target_os = "hurd",
1407                target_os = "linux",
1408                target_os = "netbsd",
1409                target_os = "openbsd",
1410                target_os = "cygwin",
1411                target_os = "illumos",
1412                target_os = "aix",
1413                target_os = "android",
1414                target_vendor = "apple",
1415            ) => {
1416                let result =
1417                    cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1418                if let Err(err) = result {
1419                    if err.kind() == io::ErrorKind::WouldBlock {
1420                        Err(TryLockError::WouldBlock)
1421                    } else {
1422                        Err(TryLockError::Error(err))
1423                    }
1424                } else {
1425                    Ok(())
1426                }
1427            }
1428            _ => Err(TryLockError::Error(io::const_error!(
1429                io::ErrorKind::Unsupported,
1430                "try_lock_shared() not supported"
1431            ))),
1432        }
1433    }
1434
1435    pub fn unlock(&self) -> io::Result<()> {
1436        cfg_select! {
1437            any(
1438                target_os = "freebsd",
1439                target_os = "fuchsia",
1440                target_os = "hurd",
1441                target_os = "linux",
1442                target_os = "netbsd",
1443                target_os = "openbsd",
1444                target_os = "cygwin",
1445                target_os = "illumos",
1446                target_os = "aix",
1447                target_os = "android",
1448                target_vendor = "apple",
1449            ) => {
1450                cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1451                Ok(())
1452            }
1453            _ => Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported")),
1454        }
1455    }
1456
1457    pub fn truncate(&self, size: u64) -> io::Result<()> {
1458        let size: off64_t =
1459            size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1460        cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1461    }
1462
1463    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1464        self.0.read(buf)
1465    }
1466
1467    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1468        self.0.read_vectored(bufs)
1469    }
1470
1471    #[inline]
1472    pub fn is_read_vectored(&self) -> bool {
1473        self.0.is_read_vectored()
1474    }
1475
1476    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1477        self.0.read_at(buf, offset)
1478    }
1479
1480    pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
1481        self.0.read_buf(cursor)
1482    }
1483
1484    pub fn read_buf_at(&self, cursor: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
1485        self.0.read_buf_at(cursor, offset)
1486    }
1487
1488    pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
1489        self.0.read_vectored_at(bufs, offset)
1490    }
1491
1492    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1493        self.0.write(buf)
1494    }
1495
1496    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1497        self.0.write_vectored(bufs)
1498    }
1499
1500    #[inline]
1501    pub fn is_write_vectored(&self) -> bool {
1502        self.0.is_write_vectored()
1503    }
1504
1505    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1506        self.0.write_at(buf, offset)
1507    }
1508
1509    pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
1510        self.0.write_vectored_at(bufs, offset)
1511    }
1512
1513    #[inline]
1514    pub fn flush(&self) -> io::Result<()> {
1515        Ok(())
1516    }
1517
1518    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1519        let (whence, pos) = match pos {
1520            // Casting to `i64` is fine, too large values will end up as
1521            // negative which will cause an error in `lseek64`.
1522            SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1523            SeekFrom::End(off) => (libc::SEEK_END, off),
1524            SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1525        };
1526        let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1527        Ok(n as u64)
1528    }
1529
1530    pub fn size(&self) -> Option<io::Result<u64>> {
1531        match self.file_attr().map(|attr| attr.size()) {
1532            // Fall back to default implementation if the returned size is 0,
1533            // we might be in a proc mount.
1534            Ok(0) => None,
1535            result => Some(result),
1536        }
1537    }
1538
1539    pub fn tell(&self) -> io::Result<u64> {
1540        self.seek(SeekFrom::Current(0))
1541    }
1542
1543    pub fn duplicate(&self) -> io::Result<File> {
1544        self.0.duplicate().map(File)
1545    }
1546
1547    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1548        cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1549        Ok(())
1550    }
1551
1552    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1553        cfg_select! {
1554            any(
1555                target_os = "redox",
1556                target_os = "espidf",
1557                target_os = "horizon",
1558                target_os = "nuttx",
1559                target_os = "l4re"
1560            ) => {
1561                // Redox doesn't appear to support `UTIME_OMIT`.
1562                // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1563                // the same as for Redox.
1564                let _ = times;
1565                Err(io::const_error!(
1566                    io::ErrorKind::Unsupported,
1567                    "setting file times not supported",
1568                ))
1569            }
1570            target_vendor = "apple" => {
1571                let ta = TimesAttrlist::from_times(&times)?;
1572                cvt(unsafe {
1573                    libc::fsetattrlist(
1574                        self.as_raw_fd(),
1575                        ta.attrlist(),
1576                        ta.times_buf(),
1577                        ta.times_buf_size(),
1578                        0,
1579                    )
1580                })?;
1581                Ok(())
1582            }
1583            target_os = "android" => {
1584                let times = [
1585                    file_time_to_timespec(times.accessed)?,
1586                    file_time_to_timespec(times.modified)?,
1587                ];
1588                // futimens requires Android API level 19
1589                cvt(unsafe {
1590                    weak!(
1591                        fn futimens(fd: c_int, times: *const libc::timespec) -> c_int;
1592                    );
1593                    match futimens.get() {
1594                        Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1595                        None => {
1596                            return Err(io::const_error!(
1597                                io::ErrorKind::Unsupported,
1598                                "setting file times requires Android API level >= 19",
1599                            ));
1600                        }
1601                    }
1602                })?;
1603                Ok(())
1604            }
1605            _ => {
1606                #[cfg(all(
1607                    target_os = "linux",
1608                    target_env = "gnu",
1609                    target_pointer_width = "32",
1610                    not(target_arch = "riscv32")
1611                ))]
1612                {
1613                    use crate::sys::pal::time::__timespec64;
1614                    use crate::sys::pal::weak::weak;
1615
1616                    // Added in glibc 2.34
1617                    weak!(
1618                        fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int;
1619                    );
1620
1621                    if let Some(futimens64) = __futimens64.get() {
1622                        let to_timespec = |time: Option<SystemTime>| {
1623                            time.map(|time| time.t.to_timespec64())
1624                                .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
1625                        };
1626                        let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1627                        cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1628                        return Ok(());
1629                    }
1630                }
1631                let times = [
1632                    file_time_to_timespec(times.accessed)?,
1633                    file_time_to_timespec(times.modified)?,
1634                ];
1635                cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1636                Ok(())
1637            }
1638        }
1639    }
1640}
1641
1642#[cfg(not(any(
1643    target_os = "redox",
1644    target_os = "espidf",
1645    target_os = "horizon",
1646    target_os = "nuttx",
1647)))]
1648fn file_time_to_timespec(time: Option<SystemTime>) -> io::Result<libc::timespec> {
1649    match time {
1650        Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1651        Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
1652            io::ErrorKind::InvalidInput,
1653            "timestamp is too large to set as a file time",
1654        )),
1655        Some(_) => Err(io::const_error!(
1656            io::ErrorKind::InvalidInput,
1657            "timestamp is too small to set as a file time",
1658        )),
1659        None => Ok({
1660            let mut ts = libc::timespec::default();
1661            ts.tv_sec = 0;
1662            ts.tv_nsec = libc::UTIME_OMIT as _;
1663            ts
1664        }),
1665    }
1666}
1667
1668#[cfg(target_vendor = "apple")]
1669struct TimesAttrlist {
1670    buf: [mem::MaybeUninit<libc::timespec>; 3],
1671    attrlist: libc::attrlist,
1672    num_times: usize,
1673}
1674
1675#[cfg(target_vendor = "apple")]
1676impl TimesAttrlist {
1677    fn from_times(times: &FileTimes) -> io::Result<Self> {
1678        let mut this = Self {
1679            buf: [mem::MaybeUninit::<libc::timespec>::uninit(); 3],
1680            attrlist: unsafe { mem::zeroed() },
1681            num_times: 0,
1682        };
1683        this.attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1684        if times.created.is_some() {
1685            this.buf[this.num_times].write(file_time_to_timespec(times.created)?);
1686            this.num_times += 1;
1687            this.attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1688        }
1689        if times.modified.is_some() {
1690            this.buf[this.num_times].write(file_time_to_timespec(times.modified)?);
1691            this.num_times += 1;
1692            this.attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1693        }
1694        if times.accessed.is_some() {
1695            this.buf[this.num_times].write(file_time_to_timespec(times.accessed)?);
1696            this.num_times += 1;
1697            this.attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1698        }
1699        Ok(this)
1700    }
1701
1702    fn attrlist(&self) -> *mut libc::c_void {
1703        (&raw const self.attrlist).cast::<libc::c_void>().cast_mut()
1704    }
1705
1706    fn times_buf(&self) -> *mut libc::c_void {
1707        self.buf.as_ptr().cast::<libc::c_void>().cast_mut()
1708    }
1709
1710    fn times_buf_size(&self) -> usize {
1711        self.num_times * size_of::<libc::timespec>()
1712    }
1713}
1714
1715impl DirBuilder {
1716    pub fn new() -> DirBuilder {
1717        DirBuilder { mode: 0o777 }
1718    }
1719
1720    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1721        run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1722    }
1723
1724    #[cfg(not(target_os = "wasi"))]
1725    pub fn set_mode(&mut self, mode: u32) {
1726        self.mode = mode as mode_t;
1727    }
1728}
1729
1730impl fmt::Debug for DirBuilder {
1731    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1732        let DirBuilder { mode } = self;
1733        f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1734    }
1735}
1736
1737impl AsInner<FileDesc> for File {
1738    #[inline]
1739    fn as_inner(&self) -> &FileDesc {
1740        &self.0
1741    }
1742}
1743
1744impl AsInnerMut<FileDesc> for File {
1745    #[inline]
1746    fn as_inner_mut(&mut self) -> &mut FileDesc {
1747        &mut self.0
1748    }
1749}
1750
1751impl IntoInner<FileDesc> for File {
1752    fn into_inner(self) -> FileDesc {
1753        self.0
1754    }
1755}
1756
1757impl FromInner<FileDesc> for File {
1758    fn from_inner(file_desc: FileDesc) -> Self {
1759        Self(file_desc)
1760    }
1761}
1762
1763impl AsFd for File {
1764    #[inline]
1765    fn as_fd(&self) -> BorrowedFd<'_> {
1766        self.0.as_fd()
1767    }
1768}
1769
1770impl AsRawFd for File {
1771    #[inline]
1772    fn as_raw_fd(&self) -> RawFd {
1773        self.0.as_raw_fd()
1774    }
1775}
1776
1777impl IntoRawFd for File {
1778    fn into_raw_fd(self) -> RawFd {
1779        self.0.into_raw_fd()
1780    }
1781}
1782
1783impl FromRawFd for File {
1784    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1785        Self(FromRawFd::from_raw_fd(raw_fd))
1786    }
1787}
1788
1789impl fmt::Debug for File {
1790    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1791        let fd = self.as_raw_fd();
1792        let mut b = debug_path_fd(fd, f, "File");
1793        b.finish()
1794    }
1795}
1796
1797// Format in octal, followed by the mode format used in `ls -l`.
1798//
1799// References:
1800//   https://pubs.opengroup.org/onlinepubs/9799919799/utilities/ls.html
1801//   https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html
1802//   https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
1803//
1804// Example:
1805//   0o100664 (-rw-rw-r--)
1806impl fmt::Debug for Mode {
1807    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1808        let Self(mode) = *self;
1809        write!(f, "0o{mode:06o}")?;
1810
1811        let entry_type = match mode & libc::S_IFMT {
1812            libc::S_IFDIR => 'd',
1813            libc::S_IFBLK => 'b',
1814            libc::S_IFCHR => 'c',
1815            libc::S_IFLNK => 'l',
1816            libc::S_IFIFO => 'p',
1817            libc::S_IFREG => '-',
1818            _ => return Ok(()),
1819        };
1820
1821        f.write_str(" (")?;
1822        f.write_char(entry_type)?;
1823
1824        // Owner permissions
1825        f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1826        f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1827        let owner_executable = mode & libc::S_IXUSR != 0;
1828        let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1829        f.write_char(match (owner_executable, setuid) {
1830            (true, true) => 's',  // executable and setuid
1831            (false, true) => 'S', // setuid
1832            (true, false) => 'x', // executable
1833            (false, false) => '-',
1834        })?;
1835
1836        // Group permissions
1837        f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1838        f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1839        let group_executable = mode & libc::S_IXGRP != 0;
1840        let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1841        f.write_char(match (group_executable, setgid) {
1842            (true, true) => 's',  // executable and setgid
1843            (false, true) => 'S', // setgid
1844            (true, false) => 'x', // executable
1845            (false, false) => '-',
1846        })?;
1847
1848        // Other permissions
1849        f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1850        f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1851        let other_executable = mode & libc::S_IXOTH != 0;
1852        let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1853        f.write_char(match (entry_type, other_executable, sticky) {
1854            ('d', true, true) => 't',  // searchable and restricted deletion
1855            ('d', false, true) => 'T', // restricted deletion
1856            (_, true, _) => 'x',       // executable
1857            (_, false, _) => '-',
1858        })?;
1859
1860        f.write_char(')')
1861    }
1862}
1863
1864pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1865    let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1866    if ptr.is_null() {
1867        Err(Error::last_os_error())
1868    } else {
1869        let root = path.to_path_buf();
1870        let inner = InnerReadDir { dirp: DirStream(ptr), root };
1871        Ok(ReadDir::new(inner))
1872    }
1873}
1874
1875pub fn unlink(p: &CStr) -> io::Result<()> {
1876    cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ())
1877}
1878
1879pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
1880    cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1881}
1882
1883pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1884    cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
1885}
1886
1887#[cfg(target_os = "vxworks")]
1888pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1889    // VxWorks has no `O_NOFOLLOW`, and its `fchmodat` rejects
1890    // `AT_SYMLINK_NOFOLLOW` with `ENOTSUP`, so a no-follow chmod is unsupported.
1891    Err(crate::io::ErrorKind::Unsupported.into())
1892}
1893
1894#[cfg(target_os = "android")]
1895pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1896    // Currently Android seems to be having inconsistent behavior with fchmodat
1897    // with `AT_SYMLINK_NOFOLLOW` or openat with `O_NOFOLLOW` + fchmod.
1898    // See this issue here mentioning inconsistent behavior on fchmodat:
1899    // https://github.com/android/ndk/issues/1258
1900    // On the arm-android CI job, using fchmodat with `AT_SYMLINK_NOFOLLOW` +
1901    // fallback behavior on a symlink sets the target file's permissions,
1902    // which is incorrect behavior.
1903    Err(crate::io::ErrorKind::Unsupported.into())
1904}
1905
1906#[cfg(not(any(target_os = "android", target_os = "vxworks")))]
1907pub fn set_perm_nofollow(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1908    #[inline]
1909    /// Helper function for fallback open with `O_NOFOLLOW` + `fchmod` behavior
1910    fn open_and_set_permissions(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1911        use crate::fs::{OpenOptions, Permissions};
1912
1913        let mut options = OpenOptions::new();
1914
1915        // ESP-IDF and Horizon do not support O_NOFOLLOW, so we skip setting it.
1916        // Their filesystems do not have symbolic links, so no special handling is required.
1917        #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
1918        {
1919            #[cfg(not(target_os = "wasi"))]
1920            use crate::os::unix::fs::OpenOptionsExt;
1921            #[cfg(target_os = "wasi")]
1922            use crate::os::wasi::fs::OpenOptionsExt;
1923            options.read(true).custom_flags(libc::O_NOFOLLOW);
1924        }
1925
1926        // SAFETY: Since this function is called with `with_native_path`
1927        // and that successfully converted the `&Path` to a `CString`,
1928        // it should be safe to convert the `&CStr` back to a `Path`.
1929        let os_str = unsafe { OsStr::from_encoded_bytes_unchecked(p.to_bytes()) };
1930        options.open(Path::new(os_str))?.set_permissions(Permissions::from_inner(perm))
1931    }
1932
1933    // This res value is modified for platforms that support the `fchmodat` syscall.
1934    #[allow(unused)]
1935    let mut res: Result<(), core::io::Error> = Err(crate::io::ErrorKind::Unsupported.into());
1936
1937    // These platforms support `fchmodat`, so utilize this syscall over `open` + `fchmod`
1938    #[cfg(any(
1939        target_os = "linux",
1940        target_os = "macos",
1941        target_os = "freebsd",
1942        target_os = "openbsd",
1943        target_os = "netbsd",
1944        target_os = "dragonfly",
1945        target_os = "nto",
1946        target_os = "qnx"
1947    ))]
1948    {
1949        res = cvt_r(|| unsafe {
1950            libc::fchmodat(libc::AT_FDCWD, p.as_ptr(), perm.mode, libc::AT_SYMLINK_NOFOLLOW)
1951        })
1952        .map(|_| ());
1953    }
1954
1955    // If fchmodat fails with `ErrorKind::Unsupported` fallback to using open + fchmod. This is just in case
1956    // for older systems like Ubuntu 20.04 where fchmodat fails with EOPNOTSUPP on both regular files and
1957    // symlinks when AT_SYMLINK_NOFOLLOW is passed in.
1958    match res {
1959        Ok(_) => Ok(()),
1960        Err(err) => {
1961            if err.kind() == crate::io::ErrorKind::Unsupported {
1962                match open_and_set_permissions(p, perm) {
1963                    Ok(_) => return Ok(()),
1964                    Err(e) => {
1965                        if e.kind() == crate::io::ErrorKind::FilesystemLoop {
1966                            // When open is used with O_NOFOLLOW flag, if the trailing component of
1967                            // a path is a symbolic link, it should fail with ELOOP error. Instead of
1968                            // returning `FilesystemLoop`, this returns `Unsupported` to keep it consistent
1969                            // with what `fchmodat` would return when chmoding a symlink using AT_SYMLINK_NOFOLLOW.
1970                            return Err(err);
1971                        }
1972                        return Err(e);
1973                    }
1974                }
1975            }
1976
1977            Err(err)
1978        }
1979    }
1980}
1981
1982pub fn rmdir(p: &CStr) -> io::Result<()> {
1983    cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ())
1984}
1985
1986pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> {
1987    let p = c_path.as_ptr();
1988
1989    let mut buf = Vec::with_capacity(256);
1990
1991    loop {
1992        let buf_read =
1993            cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1994
1995        unsafe {
1996            buf.set_len(buf_read);
1997        }
1998
1999        if buf_read != buf.capacity() {
2000            buf.shrink_to_fit();
2001
2002            return Ok(PathBuf::from(OsString::from_vec(buf)));
2003        }
2004
2005        // Trigger the internal buffer resizing logic of `Vec` by requiring
2006        // more space than the current capacity. The length is guaranteed to be
2007        // the same as the capacity due to the if statement above.
2008        buf.reserve(1);
2009    }
2010}
2011
2012pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> {
2013    cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
2014}
2015
2016pub fn link(original: &CStr, link: &CStr) -> io::Result<()> {
2017    cfg_select! {
2018        any(
2019            // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead.
2020            // POSIX leaves it implementation-defined whether `link` follows
2021            // symlinks, so rely on the `symlink_hard_link` test in
2022            // library/std/src/fs/tests.rs to check the behavior.
2023            target_os = "vxworks",
2024            target_os = "redox",
2025            target_os = "espidf",
2026            // Other misc platforms
2027            target_os = "horizon",
2028            target_os = "vita",
2029            target_os = "l4re",
2030            target_env = "nto70",
2031        ) => {
2032            cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
2033        }
2034        _ => {
2035            // Where we can, use `linkat` instead of `link`; see the comment above
2036            // this one for details on why.
2037            cvt(unsafe {
2038                libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0)
2039            })?;
2040        }
2041    }
2042    Ok(())
2043}
2044
2045pub fn stat(p: &CStr) -> io::Result<FileAttr> {
2046    cfg_has_statx! {
2047        if let Some(ret) = unsafe { try_statx(
2048            libc::AT_FDCWD,
2049            p.as_ptr(),
2050            libc::AT_STATX_SYNC_AS_STAT,
2051            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2052        ) } {
2053            return ret;
2054        }
2055    }
2056
2057    let mut stat: stat64 = unsafe { mem::zeroed() };
2058    cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
2059    Ok(FileAttr::from_stat64(stat))
2060}
2061
2062pub fn lstat(p: &CStr) -> io::Result<FileAttr> {
2063    cfg_has_statx! {
2064        if let Some(ret) = unsafe { try_statx(
2065            libc::AT_FDCWD,
2066            p.as_ptr(),
2067            libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
2068            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2069        ) } {
2070            return ret;
2071        }
2072    }
2073
2074    let mut stat: stat64 = unsafe { mem::zeroed() };
2075    cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
2076    Ok(FileAttr::from_stat64(stat))
2077}
2078
2079pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
2080    let r = unsafe { libc::realpath(path.as_ptr(), ptr::null_mut()) };
2081    if r.is_null() {
2082        return Err(io::Error::last_os_error());
2083    }
2084    Ok(PathBuf::from(OsString::from_vec(unsafe {
2085        let buf = CStr::from_ptr(r).to_bytes().to_vec();
2086        libc::free(r as *mut _);
2087        buf
2088    })))
2089}
2090
2091fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2092    use crate::fs::File;
2093    use crate::sys::fs::common::NOT_FILE_ERROR;
2094
2095    let reader = File::open(from)?;
2096    let metadata = reader.metadata()?;
2097    if !metadata.is_file() {
2098        return Err(NOT_FILE_ERROR);
2099    }
2100    Ok((reader, metadata))
2101}
2102
2103fn set_times_impl(p: &CStr, times: FileTimes, follow_symlinks: bool) -> io::Result<()> {
2104    cfg_select! {
2105        any(
2106            target_os = "redox",
2107            target_os = "espidf",
2108            target_os = "horizon",
2109            target_os = "nuttx",
2110            target_os = "vita",
2111            target_os = "rtems"
2112        ) => {
2113            let _ = (p, times, follow_symlinks);
2114            Err(io::const_error!(io::ErrorKind::Unsupported, "setting file times not supported"))
2115        }
2116        target_vendor = "apple" => {
2117            // Apple platforms use setattrlist which supports setting times on symlinks
2118            let ta = TimesAttrlist::from_times(&times)?;
2119            let options = if follow_symlinks { 0 } else { libc::FSOPT_NOFOLLOW };
2120
2121            cvt(unsafe {
2122                libc::setattrlist(
2123                    p.as_ptr(),
2124                    ta.attrlist(),
2125                    ta.times_buf(),
2126                    ta.times_buf_size(),
2127                    options as u32,
2128                )
2129            })?;
2130            Ok(())
2131        }
2132        target_os = "android" => {
2133            let times =
2134                [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2135            let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2136            // utimensat requires Android API level 19
2137            cvt(unsafe {
2138                weak!(
2139                    fn utimensat(
2140                        dirfd: c_int,
2141                        path: *const libc::c_char,
2142                        times: *const libc::timespec,
2143                        flags: c_int,
2144                    ) -> c_int;
2145                );
2146                match utimensat.get() {
2147                    Some(utimensat) => utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags),
2148                    None => {
2149                        return Err(io::const_error!(
2150                            io::ErrorKind::Unsupported,
2151                            "setting file times requires Android API level >= 19",
2152                        ));
2153                    }
2154                }
2155            })?;
2156            Ok(())
2157        }
2158        _ => {
2159            let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2160            #[cfg(all(
2161                target_os = "linux",
2162                target_env = "gnu",
2163                target_pointer_width = "32",
2164                not(target_arch = "riscv32")
2165            ))]
2166            {
2167                use crate::sys::pal::time::__timespec64;
2168                use crate::sys::pal::weak::weak;
2169
2170                // Added in glibc 2.34
2171                weak!(
2172                    fn __utimensat64(
2173                        dirfd: c_int,
2174                        path: *const c_char,
2175                        times: *const __timespec64,
2176                        flags: c_int,
2177                    ) -> c_int;
2178                );
2179
2180                if let Some(utimensat64) = __utimensat64.get() {
2181                    let to_timespec = |time: Option<SystemTime>| {
2182                        time.map(|time| time.t.to_timespec64())
2183                            .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
2184                    };
2185                    let times = [to_timespec(times.accessed), to_timespec(times.modified)];
2186                    cvt(unsafe { utimensat64(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2187                    return Ok(());
2188                }
2189            }
2190            let times =
2191                [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2192            cvt(unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2193            Ok(())
2194        }
2195    }
2196}
2197
2198#[inline(always)]
2199pub fn set_times(p: &CStr, times: FileTimes) -> io::Result<()> {
2200    set_times_impl(p, times, true)
2201}
2202
2203#[inline(always)]
2204pub fn set_times_nofollow(p: &CStr, times: FileTimes) -> io::Result<()> {
2205    set_times_impl(p, times, false)
2206}
2207
2208#[cfg(any(target_os = "espidf", target_os = "wasi"))]
2209fn open_to_and_set_permissions(
2210    to: &Path,
2211    _reader_metadata: &crate::fs::Metadata,
2212) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2213    use crate::fs::OpenOptions;
2214    let writer = OpenOptions::new().write(true).create(true).truncate(true).open(to)?;
2215    let writer_metadata = writer.metadata()?;
2216    Ok((writer, writer_metadata))
2217}
2218
2219#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
2220fn open_to_and_set_permissions(
2221    to: &Path,
2222    reader_metadata: &crate::fs::Metadata,
2223) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2224    use crate::fs::OpenOptions;
2225    use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
2226
2227    let perm = reader_metadata.permissions();
2228    let writer = OpenOptions::new()
2229        // create the file with the correct mode right away
2230        .mode(perm.mode())
2231        .write(true)
2232        .create(true)
2233        .truncate(true)
2234        .open(to)?;
2235    let writer_metadata = writer.metadata()?;
2236    // fchmod is broken on vita
2237    #[cfg(not(target_os = "vita"))]
2238    if writer_metadata.is_file() {
2239        // Set the correct file permissions, in case the file already existed.
2240        // Don't set the permissions on already existing non-files like
2241        // pipes/FIFOs or device nodes.
2242        writer.set_permissions(perm)?;
2243    }
2244    Ok((writer, writer_metadata))
2245}
2246
2247mod cfm {
2248    use crate::fs::{File, Metadata};
2249    use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
2250
2251    #[allow(dead_code)]
2252    pub struct CachedFileMetadata(pub File, pub Metadata);
2253
2254    impl Read for CachedFileMetadata {
2255        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2256            self.0.read(buf)
2257        }
2258        fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2259            self.0.read_vectored(bufs)
2260        }
2261        fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
2262            self.0.read_buf(cursor)
2263        }
2264        #[inline]
2265        fn is_read_vectored(&self) -> bool {
2266            self.0.is_read_vectored()
2267        }
2268        fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2269            self.0.read_to_end(buf)
2270        }
2271        fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2272            self.0.read_to_string(buf)
2273        }
2274    }
2275    impl Write for CachedFileMetadata {
2276        fn write(&mut self, buf: &[u8]) -> Result<usize> {
2277            self.0.write(buf)
2278        }
2279        fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2280            self.0.write_vectored(bufs)
2281        }
2282        #[inline]
2283        fn is_write_vectored(&self) -> bool {
2284            self.0.is_write_vectored()
2285        }
2286        #[inline]
2287        fn flush(&mut self) -> Result<()> {
2288            self.0.flush()
2289        }
2290    }
2291}
2292#[cfg(any(target_os = "linux", target_os = "android"))]
2293pub(in crate::sys) use cfm::CachedFileMetadata;
2294
2295#[cfg(not(target_vendor = "apple"))]
2296pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2297    let (reader, reader_metadata) = open_from(from)?;
2298    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2299
2300    io::copy(
2301        &mut cfm::CachedFileMetadata(reader, reader_metadata),
2302        &mut cfm::CachedFileMetadata(writer, writer_metadata),
2303    )
2304}
2305
2306#[cfg(target_vendor = "apple")]
2307pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2308    const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2309
2310    struct FreeOnDrop(libc::copyfile_state_t);
2311    impl Drop for FreeOnDrop {
2312        fn drop(&mut self) {
2313            // The code below ensures that `FreeOnDrop` is never a null pointer
2314            unsafe {
2315                // `copyfile_state_free` returns -1 if the `to` or `from` files
2316                // cannot be closed. However, this is not considered an error.
2317                libc::copyfile_state_free(self.0);
2318            }
2319        }
2320    }
2321
2322    let (reader, reader_metadata) = open_from(from)?;
2323
2324    let clonefile_result = run_path_with_cstr(to, &|to| {
2325        cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2326    });
2327    match clonefile_result {
2328        Ok(_) => return Ok(reader_metadata.len()),
2329        Err(e) => match e.raw_os_error() {
2330            // `fclonefileat` will fail on non-APFS volumes, if the
2331            // destination already exists, or if the source and destination
2332            // are on different devices. In all these cases `fcopyfile`
2333            // should succeed.
2334            Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2335            _ => return Err(e),
2336        },
2337    }
2338
2339    // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
2340    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2341
2342    // We ensure that `FreeOnDrop` never contains a null pointer so it is
2343    // always safe to call `copyfile_state_free`
2344    let state = unsafe {
2345        let state = libc::copyfile_state_alloc();
2346        if state.is_null() {
2347            return Err(crate::io::Error::last_os_error());
2348        }
2349        FreeOnDrop(state)
2350    };
2351
2352    let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2353
2354    cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2355
2356    let mut bytes_copied: libc::off_t = 0;
2357    cvt(unsafe {
2358        libc::copyfile_state_get(
2359            state.0,
2360            libc::COPYFILE_STATE_COPIED as u32,
2361            (&raw mut bytes_copied) as *mut libc::c_void,
2362        )
2363    })?;
2364    Ok(bytes_copied as u64)
2365}
2366
2367#[cfg(not(target_os = "wasi"))]
2368pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2369    run_path_with_cstr(path, &|path| {
2370        cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2371            .map(|_| ())
2372    })
2373}
2374
2375#[cfg(not(target_os = "wasi"))]
2376pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2377    cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2378    Ok(())
2379}
2380
2381#[cfg(not(any(target_os = "vxworks", target_os = "wasi")))]
2382pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2383    run_path_with_cstr(path, &|path| {
2384        cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2385            .map(|_| ())
2386    })
2387}
2388
2389#[cfg(target_os = "vxworks")]
2390pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2391    let (_, _, _) = (path, uid, gid);
2392    Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2393}
2394
2395#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks", target_os = "wasi")))]
2396pub fn chroot(dir: &Path) -> io::Result<()> {
2397    run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2398}
2399
2400#[cfg(target_os = "vxworks")]
2401pub fn chroot(dir: &Path) -> io::Result<()> {
2402    let _ = dir;
2403    Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2404}
2405
2406#[cfg(not(target_os = "wasi"))]
2407pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
2408    run_path_with_cstr(path, &|path| {
2409        cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
2410    })
2411}
2412
2413pub use remove_dir_impl::remove_dir_all;
2414
2415// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri
2416#[cfg(any(
2417    target_os = "redox",
2418    target_os = "espidf",
2419    target_os = "horizon",
2420    target_os = "vita",
2421    target_os = "nto",
2422    target_os = "qnx",
2423    target_os = "vxworks",
2424    target_os = "l4re",
2425    miri
2426))]
2427mod remove_dir_impl {
2428    pub use crate::sys::fs::common::remove_dir_all;
2429}
2430
2431// Modern implementation using openat(), unlinkat() and fdopendir()
2432#[cfg(not(any(
2433    target_os = "redox",
2434    target_os = "espidf",
2435    target_os = "horizon",
2436    target_os = "vita",
2437    target_os = "nto",
2438    target_os = "qnx",
2439    target_os = "vxworks",
2440    target_os = "l4re",
2441    miri
2442)))]
2443mod remove_dir_impl {
2444    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2445    use libc::{fdopendir, openat, unlinkat};
2446    #[cfg(all(target_os = "linux", target_env = "gnu"))]
2447    use libc::{fdopendir, openat64 as openat, unlinkat};
2448
2449    use super::{
2450        AsRawFd, DirEntry, DirStream, FromRawFd, InnerReadDir, IntoRawFd, OwnedFd, RawFd, ReadDir,
2451        lstat,
2452    };
2453    use crate::ffi::CStr;
2454    use crate::io;
2455    use crate::path::{Path, PathBuf};
2456    use crate::sys::helpers::{ignore_notfound, run_path_with_cstr};
2457    use crate::sys::{cvt, cvt_r};
2458
2459    pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2460        let fd = cvt_r(|| unsafe {
2461            openat(
2462                parent_fd.unwrap_or(libc::AT_FDCWD),
2463                p.as_ptr(),
2464                libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2465            )
2466        })?;
2467        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2468    }
2469
2470    fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2471        let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2472        if ptr.is_null() {
2473            return Err(io::Error::last_os_error());
2474        }
2475        let dirp = DirStream(ptr);
2476        // file descriptor is automatically closed by libc::closedir() now, so give up ownership
2477        let new_parent_fd = dir_fd.into_raw_fd();
2478        // a valid root is not needed because we do not call any functions involving the full path
2479        // of the `DirEntry`s.
2480        let dummy_root = PathBuf::new();
2481        let inner = InnerReadDir { dirp, root: dummy_root };
2482        Ok((ReadDir::new(inner), new_parent_fd))
2483    }
2484
2485    #[cfg(any(
2486        target_os = "solaris",
2487        target_os = "illumos",
2488        target_os = "haiku",
2489        target_os = "vxworks",
2490        target_os = "aix",
2491    ))]
2492    fn is_dir(_ent: &DirEntry) -> Option<bool> {
2493        None
2494    }
2495
2496    #[cfg(not(any(
2497        target_os = "solaris",
2498        target_os = "illumos",
2499        target_os = "haiku",
2500        target_os = "vxworks",
2501        target_os = "aix",
2502    )))]
2503    fn is_dir(ent: &DirEntry) -> Option<bool> {
2504        match ent.entry.d_type {
2505            libc::DT_UNKNOWN => None,
2506            libc::DT_DIR => Some(true),
2507            _ => Some(false),
2508        }
2509    }
2510
2511    fn is_enoent(result: &io::Result<()>) -> bool {
2512        if let Err(err) = result
2513            && matches!(err.raw_os_error(), Some(libc::ENOENT))
2514        {
2515            true
2516        } else {
2517            false
2518        }
2519    }
2520
2521    fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2522        // try opening as directory
2523        let fd = match openat_nofollow_dironly(parent_fd, path) {
2524            Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2525                // not a directory - don't traverse further
2526                // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
2527                return match parent_fd {
2528                    // unlink...
2529                    Some(parent_fd) => {
2530                        cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2531                    }
2532                    // ...unless this was supposed to be the deletion root directory
2533                    None => Err(err),
2534                };
2535            }
2536            result => result?,
2537        };
2538
2539        // open the directory passing ownership of the fd
2540        let (dir, fd) = fdreaddir(fd)?;
2541
2542        // For WASI all directory entries for this directory are read first
2543        // before any removal is done. This works around the fact that the
2544        // WASIp1 API for reading directories is not well-designed for handling
2545        // mutations between invocations of reading a directory. By reading all
2546        // the entries at once this ensures that, at least without concurrent
2547        // modifications, it should be possible to delete everything.
2548        #[cfg(target_os = "wasi")]
2549        let dir = dir.collect::<Vec<_>>();
2550
2551        for child in dir {
2552            let child = child?;
2553            // we need an inner try block, because if one of these
2554            // directories has already been deleted, then we need to
2555            // continue the loop, not return ok.
2556            let result: io::Result<()> = try {
2557                match is_dir(&child) {
2558                    Some(true) => {
2559                        remove_dir_all_recursive(Some(fd), &child.name)?;
2560                    }
2561                    Some(false) => {
2562                        cvt(unsafe { unlinkat(fd, child.name.as_ptr(), 0) })?;
2563                    }
2564                    None => {
2565                        // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
2566                        // if the process has the appropriate privileges. This however can causing orphaned
2567                        // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
2568                        // into it first instead of trying to unlink() it.
2569                        remove_dir_all_recursive(Some(fd), &child.name)?;
2570                    }
2571                }
2572            };
2573            if result.is_err() && !is_enoent(&result) {
2574                return result;
2575            }
2576        }
2577
2578        // unlink the directory after removing its contents
2579        ignore_notfound(cvt(unsafe {
2580            unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2581        }))?;
2582        Ok(())
2583    }
2584
2585    fn remove_dir_all_modern(p: &CStr) -> io::Result<()> {
2586        // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
2587        // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
2588        // into symlinks.
2589        let attr = lstat(p)?;
2590        if attr.file_type().is_symlink() {
2591            super::unlink(p)
2592        } else {
2593            remove_dir_all_recursive(None, p)
2594        }
2595    }
2596
2597    pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2598        run_path_with_cstr(p, &remove_dir_all_modern)
2599    }
2600}