Skip to main content

std/sys/fs/
unix.rs

1#![allow(nonstandard_style)]
2#![allow(unsafe_op_in_unsafe_fn)]
3
4#[cfg(test)]
5mod tests;
6
7// Import the file operations under consistent names.
8cfg_select! {
9    not(any(
10        all(target_os = "linux", not(target_env = "musl")),
11        target_os = "android",
12        target_os = "hurd",
13        target_os = "l4re",
14    )) => {
15        use libc::{
16            dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
17            lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
18        };
19    }
20    target_os = "android" => {
21        // Android's `stat`, `dirent`, and related functions are always 64-bit LFS compatible, and
22        // `open` already implies `O_LARGEFILE`, so all those don't need to follow Linux.
23        // However, we still need off64_t, ftruncate64, and lseek64.
24        use libc::{
25            dirent as dirent64, fstat as fstat64, ftruncate64, lseek64, lstat as lstat64, off64_t,
26            open as open64, stat as stat64,
27        };
28    }
29    target_os = "l4re" => {
30        use libc::{
31            dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
32            lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
33        };
34    }
35    _ => {
36        use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
37    }
38}
39
40#[cfg(all(target_os = "linux", target_env = "gnu"))]
41use libc::c_char;
42#[cfg(any(
43    all(target_os = "linux", not(target_env = "musl")),
44    target_os = "android",
45    target_os = "fuchsia",
46    target_os = "hurd",
47    target_os = "illumos",
48    target_vendor = "apple",
49))]
50use libc::dirfd;
51use libc::{c_int, mode_t};
52
53use crate::ffi::{CStr, OsStr, OsString};
54use crate::fmt::{self, Write as _};
55use crate::fs::TryLockError;
56use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
57use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
58#[cfg(not(target_os = "wasi"))]
59pub use crate::os::unix::fs::dirs::{ExtraHomeDirs, ExtraMediaDirs};
60#[cfg(target_family = "unix")]
61use crate::os::unix::prelude::*;
62#[cfg(target_os = "wasi")]
63use crate::os::wasi::prelude::*;
64use crate::path::{Path, PathBuf};
65use crate::sync::Arc;
66use crate::sys::fd::FileDesc;
67pub use crate::sys::fs::common::exists;
68#[cfg(target_os = "wasi")]
69pub use crate::sys::fs::common::{ExtraHomeDirs, ExtraMediaDirs};
70use crate::sys::helpers::run_path_with_cstr;
71use crate::sys::time::SystemTime;
72#[cfg(any(target_os = "linux", target_os = "android"))]
73use crate::sys::weak::syscall;
74#[cfg(target_os = "android")]
75use crate::sys::weak::weak;
76use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner, cvt, cvt_r};
77use crate::{mem, ptr};
78
79// Used by rustc for checking the definitions of other function with the same symbol names
80//
81// See the `invalid_runtime_symbols_definitions` lint.
82#[cfg(not(test))]
83mod runtime_symbols {
84    use core::ffi::{c_char, c_int, c_size_t, c_ssize_t, c_void};
85
86    unsafe extern "C" {
87        #[rustc_canonical_symbol]
88        fn open(pathname: *const c_char, flags: c_int, ...) -> c_int;
89
90        #[rustc_canonical_symbol]
91        fn read(fd: c_int, buf: *mut c_void, count: c_size_t) -> c_ssize_t;
92
93        #[rustc_canonical_symbol]
94        fn write(fd: c_int, buf: *const c_void, count: c_size_t) -> c_ssize_t;
95
96        #[rustc_canonical_symbol]
97        fn close(fd: c_int) -> c_int;
98    }
99}
100
101pub struct File(FileDesc);
102
103// FIXME: This should be available on Linux with all `target_env`.
104// But currently only glibc exposes `statx` fn and structs.
105// We don't want to import unverified raw C structs here directly.
106// https://github.com/rust-lang/rust/pull/67774
107macro_rules! cfg_has_statx {
108    ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
109        cfg_select! {
110            all(target_os = "linux", target_env = "gnu") => {
111                $($then_tt)*
112            }
113            _ => {
114                $($else_tt)*
115            }
116        }
117    };
118    ($($block_inner:tt)*) => {
119        #[cfg(all(target_os = "linux", target_env = "gnu"))]
120        {
121            $($block_inner)*
122        }
123    };
124}
125
126cfg_has_statx! {{
127    #[derive(#[automatically_derived]
impl ::core::clone::Clone for FileAttr {
    #[inline]
    fn clone(&self) -> Self {
        FileAttr {
            stat: ::core::clone::Clone::clone(&self.stat),
            statx_extra_fields: ::core::clone::Clone::clone(&self.statx_extra_fields),
        }
    }
}Clone)]
128    pub struct FileAttr {
129        stat: stat64,
130        statx_extra_fields: Option<StatxExtraFields>,
131    }
132
133    #[derive(#[automatically_derived]
impl ::core::clone::Clone for StatxExtraFields {
    #[inline]
    fn clone(&self) -> Self {
        StatxExtraFields {
            stx_mask: ::core::clone::Clone::clone(&self.stx_mask),
            stx_btime: ::core::clone::Clone::clone(&self.stx_btime),
        }
    }
}Clone)]
134    struct StatxExtraFields {
135        // This is needed to check if btime is supported by the filesystem.
136        stx_mask: u32,
137        stx_btime: libc::statx_timestamp,
138        // With statx, we can overcome 32-bit `time_t` too.
139        #[cfg(target_pointer_width = "32")]
140        stx_atime: libc::statx_timestamp,
141        #[cfg(target_pointer_width = "32")]
142        stx_ctime: libc::statx_timestamp,
143        #[cfg(target_pointer_width = "32")]
144        stx_mtime: libc::statx_timestamp,
145
146    }
147
148    // We prefer `statx` on Linux if available, which contains file creation time,
149    // as well as 64-bit timestamps of all kinds.
150    // Default `stat64` contains no creation time and may have 32-bit `time_t`.
151    unsafe fn try_statx(
152        fd: c_int,
153        path: *const c_char,
154        flags: i32,
155        mask: u32,
156    ) -> Option<io::Result<FileAttr>> {
157        use crate::sync::atomic::{Atomic, AtomicU8, Ordering};
158
159        // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`.
160        // We check for it on first failure and remember availability to avoid having to
161        // do it again.
162        #[repr(u8)]
163        enum STATX_STATE{ Unknown = 0, Present, Unavailable }
164        static STATX_SAVED_STATE: Atomic<u8> = AtomicU8::new(STATX_STATE::Unknown as u8);
165
166        unsafe fn statx(fd: c_int, pathname: *const c_char, flags: c_int,
    mask: libc::c_uint, statxbuf: *mut libc::statx) -> c_int {
    let ref statx:
            ExternWeak<unsafe extern "C" fn(c_int, *const c_char, c_int,
                libc::c_uint, *mut libc::statx) -> c_int> =
        {
            unsafe extern "C" {
                #[linkage = "extern_weak"]
                static statx:
                    Option<unsafe extern "C" fn(c_int, *const c_char, c_int,
                        libc::c_uint, *mut libc::statx) -> c_int>;
            }

            #[allow(unused_unsafe)]
            ExternWeak::new(unsafe { statx })
        };
    if let Some(fun) = statx.get() {
        unsafe { fun(fd, pathname, flags, mask, statxbuf) }
    } else {
        unsafe {
            libc::syscall(libc::SYS_statx, fd, pathname, flags, mask,
                    statxbuf) as c_int
        }
    }
}syscall!(
167            fn statx(
168                fd: c_int,
169                pathname: *const c_char,
170                flags: c_int,
171                mask: libc::c_uint,
172                statxbuf: *mut libc::statx,
173            ) -> c_int;
174        );
175
176        let statx_availability = STATX_SAVED_STATE.load(Ordering::Relaxed);
177        if statx_availability == STATX_STATE::Unavailable as u8 {
178            return None;
179        }
180
181        let mut buf: libc::statx = mem::zeroed();
182        if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
183            if STATX_SAVED_STATE.load(Ordering::Relaxed) == STATX_STATE::Present as u8 {
184                return Some(Err(err));
185            }
186
187            // We're not yet entirely sure whether `statx` is usable on this kernel
188            // or not. Syscalls can return errors from things other than the kernel
189            // per se, e.g. `EPERM` can be returned if seccomp is used to block the
190            // syscall, or `ENOSYS` might be returned from a faulty FUSE driver.
191            //
192            // Availability is checked by performing a call which expects `EFAULT`
193            // if the syscall is usable.
194            //
195            // See: https://github.com/rust-lang/rust/issues/65662
196            //
197            // FIXME what about transient conditions like `ENOMEM`?
198            let err2 = cvt(statx(0, ptr::null(), 0, libc::STATX_BASIC_STATS | libc::STATX_BTIME, ptr::null_mut()))
199                .err()
200                .and_then(|e| e.raw_os_error());
201            if err2 == Some(libc::EFAULT) {
202                STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed);
203                return Some(Err(err));
204            } else {
205                STATX_SAVED_STATE.store(STATX_STATE::Unavailable as u8, Ordering::Relaxed);
206                return None;
207            }
208        }
209        if statx_availability == STATX_STATE::Unknown as u8 {
210            STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed);
211        }
212
213        // We cannot fill `stat64` exhaustively because of private padding fields.
214        let mut stat: stat64 = mem::zeroed();
215        // `c_ulong` on gnu-mips, `dev_t` otherwise
216        stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
217        stat.st_ino = buf.stx_ino as libc::ino64_t;
218        stat.st_nlink = buf.stx_nlink as libc::nlink_t;
219        stat.st_mode = buf.stx_mode as libc::mode_t;
220        stat.st_uid = buf.stx_uid as libc::uid_t;
221        stat.st_gid = buf.stx_gid as libc::gid_t;
222        stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
223        stat.st_size = buf.stx_size as off64_t;
224        stat.st_blksize = buf.stx_blksize as libc::blksize_t;
225        stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
226        stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
227        // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
228        stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
229        stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
230        stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
231        stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
232        stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
233
234        let extra = StatxExtraFields {
235            stx_mask: buf.stx_mask,
236            stx_btime: buf.stx_btime,
237            // Store full times to avoid 32-bit `time_t` truncation.
238            #[cfg(target_pointer_width = "32")]
239            stx_atime: buf.stx_atime,
240            #[cfg(target_pointer_width = "32")]
241            stx_ctime: buf.stx_ctime,
242            #[cfg(target_pointer_width = "32")]
243            stx_mtime: buf.stx_mtime,
244        };
245
246        Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
247    }
248
249} else {
250    #[derive(Clone)]
251    pub struct FileAttr {
252        stat: stat64,
253    }
254}}
255
256// all DirEntry's will have a reference to this struct
257struct InnerReadDir {
258    dirp: DirStream,
259    root: PathBuf,
260}
261
262pub struct ReadDir {
263    inner: Arc<InnerReadDir>,
264    end_of_stream: bool,
265}
266
267impl ReadDir {
268    fn new(inner: InnerReadDir) -> Self {
269        Self { inner: Arc::new(inner), end_of_stream: false }
270    }
271}
272
273struct DirStream(*mut libc::DIR);
274
275// dir::Dir requires openat support
276cfg_select! {
277    any(
278        target_os = "redox",
279        target_os = "espidf",
280        target_os = "horizon",
281        target_os = "vita",
282        target_os = "nto",
283        target_os = "qnx",
284        target_os = "vxworks",
285        target_os = "l4re",
286    ) => {
287        pub use crate::sys::fs::common::Dir;
288    }
289    _ => {
290        mod dir;
291        pub use dir::Dir;
292    }
293}
294
295fn debug_path_fd<'a, 'b>(
296    fd: c_int,
297    f: &'a mut fmt::Formatter<'b>,
298    name: &str,
299) -> fmt::DebugStruct<'a, 'b> {
300    let mut b = f.debug_struct(name);
301
302    fn get_mode(fd: c_int) -> Option<(bool, bool)> {
303        let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
304        if mode == -1 {
305            return None;
306        }
307        match mode & libc::O_ACCMODE {
308            libc::O_RDONLY => Some((true, false)),
309            libc::O_RDWR => Some((true, true)),
310            libc::O_WRONLY => Some((false, true)),
311            _ => None,
312        }
313    }
314
315    b.field("fd", &fd);
316    if let Some(path) = get_path_from_fd(fd) {
317        b.field("path", &path);
318    }
319    if let Some((read, write)) = get_mode(fd) {
320        b.field("read", &read).field("write", &write);
321    }
322
323    b
324}
325
326fn get_path_from_fd(fd: c_int) -> Option<PathBuf> {
327    #[cfg(any(target_os = "linux", target_os = "illumos", target_os = "solaris"))]
328    fn get_path(fd: c_int) -> Option<PathBuf> {
329        let mut p = PathBuf::from("/proc/self/fd");
330        p.push(&fd.to_string());
331        run_path_with_cstr(&p, &readlink).ok()
332    }
333
334    #[cfg(any(target_vendor = "apple", target_os = "netbsd"))]
335    fn get_path(fd: c_int) -> Option<PathBuf> {
336        // FIXME: The use of PATH_MAX is generally not encouraged, but it
337        // is inevitable in this case because Apple targets and NetBSD define `fcntl`
338        // with `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
339        // alternatives. If a better method is invented, it should be used
340        // instead.
341        let mut buf = vec![0; libc::PATH_MAX as usize];
342        let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_mut_ptr()) };
343        if n == -1 {
344            cfg_select! {
345                target_os = "netbsd" => {
346                    // fallback to procfs as last resort
347                    let mut p = PathBuf::from("/proc/self/fd");
348                    p.push(&fd.to_string());
349                    return run_path_with_cstr(&p, &readlink).ok();
350                }
351                _ => {
352                    return None;
353                }
354            }
355        }
356        let l = buf.iter().position(|&c| c == 0).unwrap();
357        buf.truncate(l as usize);
358        buf.shrink_to_fit();
359        Some(PathBuf::from(OsString::from_vec(buf)))
360    }
361
362    #[cfg(target_os = "freebsd")]
363    fn get_path(fd: c_int) -> Option<PathBuf> {
364        let info = Box::<libc::kinfo_file>::new_zeroed();
365        let mut info = unsafe { info.assume_init() };
366        info.kf_structsize = size_of::<libc::kinfo_file>() as libc::c_int;
367        let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
368        if n == -1 {
369            return None;
370        }
371        let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
372        Some(PathBuf::from(OsString::from_vec(buf)))
373    }
374
375    #[cfg(target_os = "vxworks")]
376    fn get_path(fd: c_int) -> Option<PathBuf> {
377        let mut buf = vec![0; libc::PATH_MAX as usize];
378        let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_mut_ptr()) };
379        if n == -1 {
380            return None;
381        }
382        let l = buf.iter().position(|&c| c == 0).unwrap();
383        buf.truncate(l as usize);
384        Some(PathBuf::from(OsString::from_vec(buf)))
385    }
386
387    #[cfg(not(any(
388        target_os = "linux",
389        target_os = "vxworks",
390        target_os = "freebsd",
391        target_os = "netbsd",
392        target_os = "illumos",
393        target_os = "solaris",
394        target_vendor = "apple",
395    )))]
396    fn get_path(_fd: c_int) -> Option<PathBuf> {
397        // FIXME(#24570): implement this for other Unix platforms
398        None
399    }
400
401    get_path(fd)
402}
403
404pub struct DirEntry {
405    dir: Arc<InnerReadDir>,
406    entry: dirent64_min,
407    // We need to store an owned copy of the entry name on platforms that use
408    // readdir() (not readdir_r()), because a) struct dirent may use a flexible
409    // array to store the name, b) it lives only until the next readdir() call.
410    name: crate::ffi::CString,
411}
412
413// Define a minimal subset of fields we need from `dirent64`, especially since
414// we're not using the immediate `d_name` on these targets. Keeping this as an
415// `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
416struct dirent64_min {
417    d_ino: u64,
418    #[cfg(not(any(
419        target_os = "solaris",
420        target_os = "illumos",
421        target_os = "haiku",
422        target_os = "vxworks",
423        target_os = "aix",
424        target_os = "nto",
425        target_os = "qnx",
426        target_os = "vita",
427    )))]
428    d_type: u8,
429}
430
431#[derive(#[automatically_derived]
impl ::core::clone::Clone for OpenOptions {
    #[inline]
    fn clone(&self) -> Self {
        OpenOptions {
            read: ::core::clone::Clone::clone(&self.read),
            write: ::core::clone::Clone::clone(&self.write),
            append: ::core::clone::Clone::clone(&self.append),
            truncate: ::core::clone::Clone::clone(&self.truncate),
            create: ::core::clone::Clone::clone(&self.create),
            create_new: ::core::clone::Clone::clone(&self.create_new),
            custom_flags: ::core::clone::Clone::clone(&self.custom_flags),
            mode: ::core::clone::Clone::clone(&self.mode),
        }
    }
}Clone)]
432pub struct OpenOptions {
433    // generic
434    read: bool,
435    write: bool,
436    append: bool,
437    truncate: bool,
438    create: bool,
439    create_new: bool,
440    // system-specific
441    custom_flags: i32,
442    mode: mode_t,
443}
444
445#[derive(#[automatically_derived]
impl ::core::clone::Clone for FilePermissions {
    #[inline]
    fn clone(&self) -> Self {
        FilePermissions { mode: ::core::clone::Clone::clone(&self.mode) }
    }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for FilePermissions { }
#[automatically_derived]
impl ::core::cmp::PartialEq for FilePermissions {
    #[inline]
    fn eq(&self, other: &Self) -> bool { self.mode == other.mode }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for FilePermissions {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<mode_t>;
    }
}Eq)]
446pub struct FilePermissions {
447    mode: mode_t,
448}
449
450#[derive(#[automatically_derived]
impl ::core::marker::Copy for FileTimes { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FileTimes { }
#[automatically_derived]
impl ::core::clone::Clone for FileTimes {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<Option<SystemTime>>;
        let _: ::core::clone::AssertParamIsClone<Option<SystemTime>>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for FileTimes {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f, "FileTimes",
            "accessed", &self.accessed, "modified", &&self.modified)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for FileTimes {
    #[inline]
    fn default() -> Self {
        FileTimes {
            accessed: ::core::default::Default::default(),
            modified: ::core::default::Default::default(),
        }
    }
}Default)]
451pub struct FileTimes {
452    accessed: Option<SystemTime>,
453    modified: Option<SystemTime>,
454    #[cfg(target_vendor = "apple")]
455    created: Option<SystemTime>,
456}
457
458#[derive(#[automatically_derived]
impl ::core::marker::Copy for FileType { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for FileType { }
#[automatically_derived]
impl ::core::clone::Clone for FileType {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<mode_t>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for FileType {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<mode_t>;
    }
}Eq)]
459pub struct FileType {
460    mode: mode_t,
461}
462
463impl PartialEq for FileType {
464    fn eq(&self, other: &Self) -> bool {
465        self.masked() == other.masked()
466    }
467}
468
469impl core::hash::Hash for FileType {
470    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
471        self.masked().hash(state);
472    }
473}
474
475pub struct DirBuilder {
476    mode: mode_t,
477}
478
479#[derive(#[automatically_derived]
impl ::core::marker::Copy for Mode { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Mode { }
#[automatically_derived]
impl ::core::clone::Clone for Mode {
    #[inline]
    fn clone(&self) -> Self {
        let _: ::core::clone::AssertParamIsClone<mode_t>;
        *self
    }
}Clone)]
480struct Mode(mode_t);
481
482cfg_has_statx! {{
483    impl FileAttr {
484        fn from_stat64(stat: stat64) -> Self {
485            Self { stat, statx_extra_fields: None }
486        }
487
488        #[cfg(target_pointer_width = "32")]
489        pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
490            if let Some(ext) = &self.statx_extra_fields {
491                if (ext.stx_mask & libc::STATX_MTIME) != 0 {
492                    return Some(&ext.stx_mtime);
493                }
494            }
495            None
496        }
497
498        #[cfg(target_pointer_width = "32")]
499        pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
500            if let Some(ext) = &self.statx_extra_fields {
501                if (ext.stx_mask & libc::STATX_ATIME) != 0 {
502                    return Some(&ext.stx_atime);
503                }
504            }
505            None
506        }
507
508        #[cfg(target_pointer_width = "32")]
509        pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
510            if let Some(ext) = &self.statx_extra_fields {
511                if (ext.stx_mask & libc::STATX_CTIME) != 0 {
512                    return Some(&ext.stx_ctime);
513                }
514            }
515            None
516        }
517    }
518} else {
519    impl FileAttr {
520        fn from_stat64(stat: stat64) -> Self {
521            Self { stat }
522        }
523    }
524}}
525
526impl FileAttr {
527    pub fn size(&self) -> u64 {
528        self.stat.st_size as u64
529    }
530    pub fn perm(&self) -> FilePermissions {
531        FilePermissions { mode: (self.stat.st_mode as mode_t) }
532    }
533
534    pub fn file_type(&self) -> FileType {
535        FileType { mode: self.stat.st_mode as mode_t }
536    }
537}
538
539#[cfg(target_os = "netbsd")]
540impl FileAttr {
541    pub fn modified(&self) -> io::Result<SystemTime> {
542        SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64)
543    }
544
545    pub fn accessed(&self) -> io::Result<SystemTime> {
546        SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64)
547    }
548
549    pub fn created(&self) -> io::Result<SystemTime> {
550        SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64)
551    }
552}
553
554#[cfg(target_os = "aix")]
555impl FileAttr {
556    pub fn modified(&self) -> io::Result<SystemTime> {
557        SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64)
558    }
559
560    pub fn accessed(&self) -> io::Result<SystemTime> {
561        SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64)
562    }
563
564    pub fn created(&self) -> io::Result<SystemTime> {
565        SystemTime::new(self.stat.st_ctim.tv_sec as i64, self.stat.st_ctim.tv_nsec as i64)
566    }
567}
568
569#[cfg(not(any(
570    target_os = "netbsd",
571    target_os = "nto",
572    target_os = "qnx",
573    target_os = "aix",
574    target_os = "wasi",
575    target_os = "l4re"
576)))]
577impl FileAttr {
578    #[cfg(not(any(
579        target_os = "vxworks",
580        target_os = "espidf",
581        target_os = "horizon",
582        target_os = "vita",
583        target_os = "hurd",
584        target_os = "rtems",
585        target_os = "nuttx",
586    )))]
587    pub fn modified(&self) -> io::Result<SystemTime> {
588        #[cfg(target_pointer_width = "32")]
589        cfg_has_statx! {
590            if let Some(mtime) = self.stx_mtime() {
591                return SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64);
592            }
593        }
594
595        SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64)
596    }
597
598    #[cfg(any(
599        all(target_os = "vxworks", vxworks_lt_25_09),
600        target_os = "espidf",
601        target_os = "vita",
602        target_os = "rtems",
603    ))]
604    pub fn modified(&self) -> io::Result<SystemTime> {
605        SystemTime::new(self.stat.st_mtime as i64, 0)
606    }
607
608    #[cfg(any(
609        target_os = "horizon",
610        target_os = "hurd",
611        target_os = "nuttx",
612        all(target_os = "vxworks", not(vxworks_lt_25_09))
613    ))]
614    pub fn modified(&self) -> io::Result<SystemTime> {
615        SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64)
616    }
617
618    #[cfg(not(any(
619        target_os = "vxworks",
620        target_os = "espidf",
621        target_os = "horizon",
622        target_os = "vita",
623        target_os = "hurd",
624        target_os = "rtems",
625        target_os = "nuttx",
626    )))]
627    pub fn accessed(&self) -> io::Result<SystemTime> {
628        #[cfg(target_pointer_width = "32")]
629        cfg_has_statx! {
630            if let Some(atime) = self.stx_atime() {
631                return SystemTime::new(atime.tv_sec, atime.tv_nsec as i64);
632            }
633        }
634
635        SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64)
636    }
637
638    #[cfg(any(
639        all(target_os = "vxworks", vxworks_lt_25_09),
640        target_os = "espidf",
641        target_os = "vita",
642        target_os = "rtems"
643    ))]
644    pub fn accessed(&self) -> io::Result<SystemTime> {
645        SystemTime::new(self.stat.st_atime as i64, 0)
646    }
647
648    #[cfg(any(
649        target_os = "horizon",
650        target_os = "hurd",
651        target_os = "nuttx",
652        all(target_os = "vxworks", not(vxworks_lt_25_09))
653    ))]
654    pub fn accessed(&self) -> io::Result<SystemTime> {
655        SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64)
656    }
657
658    #[cfg(any(
659        target_os = "freebsd",
660        target_os = "openbsd",
661        target_vendor = "apple",
662        target_os = "cygwin",
663    ))]
664    pub fn created(&self) -> io::Result<SystemTime> {
665        SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64)
666    }
667
668    #[cfg(not(any(
669        target_os = "freebsd",
670        target_os = "openbsd",
671        target_os = "vita",
672        target_vendor = "apple",
673        target_os = "cygwin",
674    )))]
675    pub fn created(&self) -> io::Result<SystemTime> {
676        {
    if let Some(ext) = &self.statx_extra_fields {
        return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
                SystemTime::new(ext.stx_btime.tv_sec,
                    ext.stx_btime.tv_nsec as i64)
            } else {
                Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                                    &::core::io::SimpleMessage {
                                            kind: io::ErrorKind::Unsupported,
                                            message: "creation time is not available for the filesystem",
                                        }
                                })))
            };
    }
}cfg_has_statx! {
677            if let Some(ext) = &self.statx_extra_fields {
678                return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
679                    SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64)
680                } else {
681                    Err(io::const_error!(
682                        io::ErrorKind::Unsupported,
683                        "creation time is not available for the filesystem",
684                    ))
685                };
686            }
687        }
688
689        Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::Unsupported,
                        message: "creation time is not available on this platform currently",
                    }
            }))io::const_error!(
690            io::ErrorKind::Unsupported,
691            "creation time is not available on this platform currently",
692        ))
693    }
694
695    #[cfg(target_os = "vita")]
696    pub fn created(&self) -> io::Result<SystemTime> {
697        SystemTime::new(self.stat.st_ctime as i64, 0)
698    }
699}
700
701#[cfg(any(target_os = "nto", target_os = "qnx", target_os = "wasi", target_os = "l4re"))]
702impl FileAttr {
703    pub fn modified(&self) -> io::Result<SystemTime> {
704        SystemTime::new(self.stat.st_mtim.tv_sec, self.stat.st_mtim.tv_nsec.into())
705    }
706
707    pub fn accessed(&self) -> io::Result<SystemTime> {
708        SystemTime::new(self.stat.st_atim.tv_sec, self.stat.st_atim.tv_nsec.into())
709    }
710
711    pub fn created(&self) -> io::Result<SystemTime> {
712        SystemTime::new(self.stat.st_ctim.tv_sec, self.stat.st_ctim.tv_nsec.into())
713    }
714}
715
716impl AsInner<stat64> for FileAttr {
717    #[inline]
718    fn as_inner(&self) -> &stat64 {
719        &self.stat
720    }
721}
722
723impl FilePermissions {
724    pub fn readonly(&self) -> bool {
725        // check if any class (owner, group, others) has write permission
726        self.mode & 0o222 == 0
727    }
728
729    pub fn set_readonly(&mut self, readonly: bool) {
730        if readonly {
731            // remove write permission for all classes; equivalent to `chmod a-w <file>`
732            self.mode &= !0o222;
733        } else {
734            // add write permission for all classes; equivalent to `chmod a+w <file>`
735            self.mode |= 0o222;
736        }
737    }
738    #[cfg(not(target_os = "wasi"))]
739    pub fn mode(&self) -> u32 {
740        self.mode as u32
741    }
742}
743
744impl FileTimes {
745    pub fn set_accessed(&mut self, t: SystemTime) {
746        self.accessed = Some(t);
747    }
748
749    pub fn set_modified(&mut self, t: SystemTime) {
750        self.modified = Some(t);
751    }
752
753    #[cfg(target_vendor = "apple")]
754    pub fn set_created(&mut self, t: SystemTime) {
755        self.created = Some(t);
756    }
757}
758
759impl FileType {
760    pub fn is_dir(&self) -> bool {
761        self.is(libc::S_IFDIR)
762    }
763    pub fn is_file(&self) -> bool {
764        self.is(libc::S_IFREG)
765    }
766    pub fn is_symlink(&self) -> bool {
767        self.is(libc::S_IFLNK)
768    }
769
770    pub fn is(&self, mode: mode_t) -> bool {
771        self.masked() == mode
772    }
773
774    fn masked(&self) -> mode_t {
775        self.mode & libc::S_IFMT
776    }
777}
778
779impl fmt::Debug for FileType {
780    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
781        let FileType { mode } = self;
782        f.debug_struct("FileType").field("mode", &Mode(*mode)).finish()
783    }
784}
785
786impl FromInner<u32> for FilePermissions {
787    fn from_inner(mode: u32) -> FilePermissions {
788        FilePermissions { mode: mode as mode_t }
789    }
790}
791
792impl fmt::Debug for FilePermissions {
793    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
794        let FilePermissions { mode } = self;
795        f.debug_struct("FilePermissions").field("mode", &Mode(*mode)).finish()
796    }
797}
798
799impl fmt::Debug for ReadDir {
800    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
801        // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
802        // Thus the result will be e g 'ReadDir("/home")'
803        fmt::Debug::fmt(&*self.inner.root, f)
804    }
805}
806
807impl Iterator for ReadDir {
808    type Item = io::Result<DirEntry>;
809
810    fn next(&mut self) -> Option<io::Result<DirEntry>> {
811        if self.end_of_stream {
812            return None;
813        }
814
815        unsafe {
816            loop {
817                // POSIX.1-2024 formalized what was already guaranteed by a lot
818                // of implementations and required readdir() to be thread-safe as
819                // long as an individual DIR* is not accessed concurrently. Taking
820                // a mutable reference to the `ReadDir` iterator prevents that.
821                // Even POSIX.1-1994 specified that the data in the returned
822                // dirent
823                // > is not overwritten by another call to readdir() on a
824                // > different directory stream.
825                //
826                // and that guarantee together with the requirement that the
827                // underlying syscalls need to be thread-safe because of readdir_r
828                // make it very unlikely for an implementation to be non-conforming.
829                // Nevertheless, there are still some platforms where we either
830                // cannot confirm `readdir` to be thread-safe or know that it
831                // isn't.
832                cfg_select! {
833                    any(
834                        target_os = "espidf", // readdir truly isn't thread-safe.
835                        target_os = "lynxos178",
836                        target_os = "qurt",
837                        target_os = "rtems",
838                        target_os = "vxworks",
839                    ) => {
840                        use crate::mem::MaybeUninit;
841
842                        let mut entry = MaybeUninit::uninit();
843                        let mut entry_ptr: *mut dirent64 = ptr::null_mut();
844                        let err =
845                            libc::readdir_r(self.inner.dirp.0, entry.as_mut_ptr(), &mut entry_ptr);
846                        if err != 0 {
847                            if entry_ptr.is_null() {
848                                // We encountered an error (which will be returned in this iteration), but
849                                // we also reached the end of the directory stream. The `end_of_stream`
850                                // flag is enabled to make sure that we return `None` in the next iteration
851                                // (instead of looping forever)
852                                self.end_of_stream = true;
853                            }
854                            return Some(Err(Error::from_raw_os_error(err)));
855                        }
856                        if entry_ptr.is_null() {
857                            return None;
858                        }
859
860                        let entry_ptr = entry_ptr.cast_const();
861                    }
862                    _ => {
863                        #[cfg(not(any(
864                            all(target_os = "linux", not(target_env = "musl")),
865                            target_os = "hurd",
866                            target_os = "l4re",
867                        )))]
868                        use libc::readdir as readdir64;
869                        #[cfg(any(
870                            all(target_os = "linux", not(target_env = "musl")),
871                            target_os = "hurd",
872                            target_os = "l4re"
873                        ))]
874                        use libc::readdir64;
875
876                        use crate::sys::io::{errno, set_errno};
877
878                        set_errno(0);
879                        let entry_ptr: *const dirent64 = readdir64(self.inner.dirp.0);
880                        if entry_ptr.is_null() {
881                            // We either encountered an error, or reached the end. Either way,
882                            // the next call to next() should return None.
883                            self.end_of_stream = true;
884
885                            // To distinguish between errors and end-of-directory, we had to clear
886                            // errno beforehand to check for an error now.
887                            return match errno() {
888                                0 => None,
889                                e => Some(Err(Error::from_raw_os_error(e))),
890                            };
891                        }
892                    }
893                }
894
895                // The dirent64 struct is a weird imaginary thing that isn't ever supposed
896                // to be worked with by value. Its trailing d_name field is declared
897                // variously as [c_char; 256] or [c_char; 1] on different systems but
898                // either way that size is meaningless; only the offset of d_name is
899                // meaningful. The dirent64 pointers that libc returns from readdir64 are
900                // allowed to point to allocations smaller _or_ LARGER than implied by the
901                // definition of the struct.
902                //
903                // As such, we need to be even more careful with dirent64 than if its
904                // contents were "simply" partially initialized data.
905                //
906                // Like for uninitialized contents, converting entry_ptr to `&dirent64`
907                // would not be legal. However, we can use `&raw const (*entry_ptr).d_name`
908                // to refer the fields individually, because that operation is equivalent
909                // to `byte_offset` and thus does not require the full extent of `*entry_ptr`
910                // to be in bounds of the same allocation, only the offset of the field
911                // being referenced.
912
913                // d_name is guaranteed to be null-terminated.
914                let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast());
915                let name_bytes = name.to_bytes();
916                if name_bytes == b"." || name_bytes == b".." {
917                    continue;
918                }
919
920                // When loading from a field, we can skip the `&raw const`; `(*entry_ptr).d_ino` as
921                // a value expression will do the right thing: `byte_offset` to the field and then
922                // only access those bytes.
923                let entry = dirent64_min {
924                    #[cfg(any(
925                        target_os = "dragonfly",
926                        target_os = "freebsd",
927                        target_os = "netbsd",
928                        target_os = "openbsd",
929                    ))]
930                    d_ino: (*entry_ptr).d_fileno,
931                    #[cfg(any(target_os = "nuttx", target_os = "vita",))]
932                    d_ino: 0,
933                    #[cfg(not(any(
934                        target_os = "dragonfly",
935                        target_os = "freebsd",
936                        target_os = "netbsd",
937                        target_os = "nuttx",
938                        target_os = "openbsd",
939                        target_os = "vita",
940                    )))]
941                    d_ino: (*entry_ptr).d_ino as u64,
942                    #[cfg(not(any(
943                        target_os = "solaris",
944                        target_os = "illumos",
945                        target_os = "haiku",
946                        target_os = "vxworks",
947                        target_os = "aix",
948                        target_os = "nto",
949                        target_os = "qnx",
950                        target_os = "vita",
951                    )))]
952                    d_type: (*entry_ptr).d_type as u8,
953                };
954
955                return Some(Ok(DirEntry {
956                    entry,
957                    name: name.to_owned(),
958                    dir: Arc::clone(&self.inner),
959                }));
960            }
961        }
962    }
963}
964
965/// Aborts the process if a file descriptor is not open, if debug asserts are enabled
966///
967/// Many IO syscalls can't be fully trusted about EBADF error codes because those
968/// might get bubbled up from a remote FUSE server rather than the file descriptor
969/// in the current process being invalid.
970///
971/// So we check file flags instead which live on the file descriptor and not the underlying file.
972/// The downside is that it costs an extra syscall, so we only do it for debug.
973#[inline]
974pub(crate) fn debug_assert_fd_is_open(fd: RawFd) {
975    use crate::sys::io::errno;
976
977    // this is similar to assert_unsafe_precondition!() but it doesn't require const
978    if core::ub_checks::check_library_ub() {
979        if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 && errno() == libc::EBADF {
980            {
    if let Some(mut out) = crate::sys::stdio::panic_output() {
        let _ =
            crate::io::Write::write_fmt(&mut out,
                format_args!("fatal runtime error: {0}, aborting\n",
                    format_args!("IO Safety violation: owned file descriptor already closed")));
    };
    crate::process::abort();
};rtabort!("IO Safety violation: owned file descriptor already closed");
981        }
982    }
983}
984
985impl Drop for DirStream {
986    fn drop(&mut self) {
987        // dirfd isn't supported everywhere
988        #[cfg(not(any(
989            target_os = "redox",
990            target_os = "nto",
991            target_os = "qnx",
992            target_os = "vita",
993            target_os = "hurd",
994            target_os = "espidf",
995            target_os = "horizon",
996            target_os = "vxworks",
997            target_os = "rtems",
998            target_os = "nuttx",
999        )))]
1000        {
1001            let fd = unsafe { libc::dirfd(self.0) };
1002            debug_assert_fd_is_open(fd);
1003        }
1004        let r = unsafe { libc::closedir(self.0) };
1005        if !(r == 0 || crate::io::Error::last_os_error().is_interrupted()) {
    {
        ::core::panicking::panic_fmt(format_args!("unexpected error during closedir: {0:?}",
                crate::io::Error::last_os_error()));
    }
};assert!(
1006            r == 0 || crate::io::Error::last_os_error().is_interrupted(),
1007            "unexpected error during closedir: {:?}",
1008            crate::io::Error::last_os_error()
1009        );
1010    }
1011}
1012
1013// SAFETY: `int dirfd (DIR *dirstream)` is MT-safe, implying that the pointer
1014// may be safely sent among threads.
1015unsafe impl Send for DirStream {}
1016unsafe impl Sync for DirStream {}
1017
1018impl DirEntry {
1019    pub fn path(&self) -> PathBuf {
1020        self.dir.root.join(self.file_name_os_str())
1021    }
1022
1023    pub fn file_name(&self) -> OsString {
1024        self.file_name_os_str().to_os_string()
1025    }
1026
1027    pub fn metadata(&self) -> io::Result<FileAttr> {
1028        cfg_select! {
1029            // Use directory handle where possible
1030            any(
1031                all(target_os = "linux", not(target_env = "musl")),
1032                target_os = "android",
1033                target_os = "fuchsia",
1034                target_os = "hurd",
1035                target_os = "illumos",
1036                target_vendor = "apple",
1037            ) => {
1038                let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
1039
1040                // Make this FD into a directory handle. We don't actually drop it,
1041                // so having an `OwnedFd` is fine.
1042                let dir_handle =
1043                    mem::ManuallyDrop::new(dir::Dir(unsafe { OwnedFd::from_raw_fd(fd) }));
1044
1045                dir_handle.metadata_c(&self.name, /* symlink_nofollow */ true)
1046            }
1047
1048            // Fallback based on path
1049            _ => run_path_with_cstr(&self.path(), &lstat),
1050        }
1051    }
1052
1053    pub fn file_type(&self) -> io::Result<FileType> {
1054        // Use `entry.d_type` if available.
1055        #[cfg(not(any(
1056            target_os = "solaris",
1057            target_os = "illumos",
1058            target_os = "haiku",
1059            target_os = "vxworks",
1060            target_os = "aix",
1061            target_os = "nto",
1062            target_os = "qnx",
1063            target_os = "vita",
1064            target_os = "l4re",
1065        )))]
1066        match self.entry.d_type {
1067            libc::DT_CHR => return Ok(FileType { mode: libc::S_IFCHR }),
1068            libc::DT_FIFO => return Ok(FileType { mode: libc::S_IFIFO }),
1069            libc::DT_LNK => return Ok(FileType { mode: libc::S_IFLNK }),
1070            libc::DT_REG => return Ok(FileType { mode: libc::S_IFREG }),
1071            libc::DT_SOCK => return Ok(FileType { mode: libc::S_IFSOCK }),
1072            libc::DT_DIR => return Ok(FileType { mode: libc::S_IFDIR }),
1073            libc::DT_BLK => return Ok(FileType { mode: libc::S_IFBLK }),
1074            _ => {}
1075        }
1076
1077        // Fall back to loading the metadata.
1078        self.metadata().map(|m| m.file_type())
1079    }
1080
1081    pub fn ino(&self) -> u64 {
1082        self.entry.d_ino
1083    }
1084
1085    pub fn file_name_os_str(&self) -> &OsStr {
1086        OsStr::from_bytes(self.name.as_bytes())
1087    }
1088}
1089
1090impl OpenOptions {
1091    pub fn new() -> OpenOptions {
1092        OpenOptions {
1093            // generic
1094            read: false,
1095            write: false,
1096            append: false,
1097            truncate: false,
1098            create: false,
1099            create_new: false,
1100            // system-specific
1101            custom_flags: 0,
1102            mode: 0o666,
1103        }
1104    }
1105
1106    pub fn read(&mut self, read: bool) {
1107        self.read = read;
1108    }
1109    pub fn write(&mut self, write: bool) {
1110        self.write = write;
1111    }
1112    pub fn append(&mut self, append: bool) {
1113        self.append = append;
1114    }
1115    pub fn truncate(&mut self, truncate: bool) {
1116        self.truncate = truncate;
1117    }
1118    pub fn create(&mut self, create: bool) {
1119        self.create = create;
1120    }
1121    pub fn create_new(&mut self, create_new: bool) {
1122        self.create_new = create_new;
1123    }
1124
1125    pub fn custom_flags(&mut self, flags: i32) {
1126        self.custom_flags = flags;
1127    }
1128    #[cfg(not(target_os = "wasi"))]
1129    pub fn mode(&mut self, mode: u32) {
1130        self.mode = mode as mode_t;
1131    }
1132
1133    fn get_access_mode(&self) -> io::Result<c_int> {
1134        match (self.read, self.write, self.append) {
1135            (true, false, false) => Ok(libc::O_RDONLY),
1136            (false, true, false) => Ok(libc::O_WRONLY),
1137            (true, true, false) => Ok(libc::O_RDWR),
1138            (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
1139            (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
1140            (false, false, false) => {
1141                // If no access mode is set, check if any creation flags are set
1142                // to provide a more descriptive error message
1143                if self.create || self.create_new || self.truncate {
1144                    Err(io::Error::new(
1145                        io::ErrorKind::InvalidInput,
1146                        "creating or truncating a file requires write or append access",
1147                    ))
1148                } else {
1149                    Err(io::Error::new(
1150                        io::ErrorKind::InvalidInput,
1151                        "must specify at least one of read, write, or append access",
1152                    ))
1153                }
1154            }
1155        }
1156    }
1157
1158    fn get_creation_mode(&self) -> io::Result<c_int> {
1159        match (self.write, self.append) {
1160            (true, false) => {}
1161            (false, false) => {
1162                if self.truncate || self.create || self.create_new {
1163                    return Err(io::Error::new(
1164                        io::ErrorKind::InvalidInput,
1165                        "creating or truncating a file requires write or append access",
1166                    ));
1167                }
1168            }
1169            (_, true) => {
1170                if self.truncate && !self.create_new {
1171                    return Err(io::Error::new(
1172                        io::ErrorKind::InvalidInput,
1173                        "append and truncate cannot both be enabled",
1174                    ));
1175                }
1176            }
1177        }
1178
1179        Ok(match (self.create, self.truncate, self.create_new) {
1180            (false, false, false) => 0,
1181            (true, false, false) => libc::O_CREAT,
1182            (false, true, false) => libc::O_TRUNC,
1183            (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
1184            (_, _, true) => libc::O_CREAT | libc::O_EXCL,
1185        })
1186    }
1187}
1188
1189impl fmt::Debug for OpenOptions {
1190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1191        let OpenOptions { read, write, append, truncate, create, create_new, custom_flags, mode } =
1192            self;
1193        f.debug_struct("OpenOptions")
1194            .field("read", read)
1195            .field("write", write)
1196            .field("append", append)
1197            .field("truncate", truncate)
1198            .field("create", create)
1199            .field("create_new", create_new)
1200            .field("custom_flags", custom_flags)
1201            .field("mode", &Mode(*mode))
1202            .finish()
1203    }
1204}
1205
1206impl File {
1207    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
1208        run_path_with_cstr(path, &|path| File::open_c(path, opts))
1209    }
1210
1211    pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
1212        let flags = libc::O_CLOEXEC
1213            | opts.get_access_mode()?
1214            | opts.get_creation_mode()?
1215            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
1216        // The third argument of `open64` is documented to have type `mode_t`. On
1217        // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
1218        // However, since this is a variadic function, C integer promotion rules mean that on
1219        // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
1220        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
1221        Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
1222    }
1223
1224    pub fn file_attr(&self) -> io::Result<FileAttr> {
1225        let fd = self.as_raw_fd();
1226
1227        {
    if let Some(ret) =
            unsafe {
                try_statx(fd, c"".as_ptr() as *const c_char,
                    libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
                    libc::STATX_BASIC_STATS | libc::STATX_BTIME)
            } {
        return ret;
    }
}cfg_has_statx! {
1228            if let Some(ret) = unsafe { try_statx(
1229                fd,
1230                c"".as_ptr() as *const c_char,
1231                libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
1232                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1233            ) } {
1234                return ret;
1235            }
1236        }
1237
1238        let mut stat: stat64 = unsafe { mem::zeroed() };
1239        cvt(unsafe { fstat64(fd, &mut stat) })?;
1240        Ok(FileAttr::from_stat64(stat))
1241    }
1242
1243    pub fn fsync(&self) -> io::Result<()> {
1244        cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
1245        return Ok(());
1246
1247        #[cfg(target_vendor = "apple")]
1248        unsafe fn os_fsync(fd: c_int) -> c_int {
1249            libc::fcntl(fd, libc::F_FULLFSYNC)
1250        }
1251        #[cfg(not(target_vendor = "apple"))]
1252        unsafe fn os_fsync(fd: c_int) -> c_int {
1253            libc::fsync(fd)
1254        }
1255    }
1256
1257    pub fn datasync(&self) -> io::Result<()> {
1258        cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1259        return Ok(());
1260
1261        #[cfg(target_vendor = "apple")]
1262        unsafe fn os_datasync(fd: c_int) -> c_int {
1263            libc::fcntl(fd, libc::F_FULLFSYNC)
1264        }
1265        #[cfg(any(
1266            target_os = "freebsd",
1267            target_os = "fuchsia",
1268            target_os = "linux",
1269            target_os = "cygwin",
1270            target_os = "android",
1271            target_os = "netbsd",
1272            target_os = "openbsd",
1273            target_os = "nto",
1274            target_os = "qnx",
1275            target_os = "hurd",
1276            target_os = "l4re",
1277        ))]
1278        unsafe fn os_datasync(fd: c_int) -> c_int {
1279            libc::fdatasync(fd)
1280        }
1281        #[cfg(not(any(
1282            target_os = "android",
1283            target_os = "fuchsia",
1284            target_os = "freebsd",
1285            target_os = "linux",
1286            target_os = "cygwin",
1287            target_os = "netbsd",
1288            target_os = "openbsd",
1289            target_os = "nto",
1290            target_os = "qnx",
1291            target_os = "hurd",
1292            target_os = "l4re",
1293            target_vendor = "apple",
1294        )))]
1295        unsafe fn os_datasync(fd: c_int) -> c_int {
1296            libc::fsync(fd)
1297        }
1298    }
1299
1300    pub fn lock(&self) -> io::Result<()> {
1301        cfg_select! {
1302            any(
1303                target_os = "freebsd",
1304                target_os = "fuchsia",
1305                target_os = "hurd",
1306                target_os = "linux",
1307                target_os = "netbsd",
1308                target_os = "openbsd",
1309                target_os = "cygwin",
1310                target_os = "illumos",
1311                target_os = "aix",
1312                target_os = "haiku",
1313                target_os = "android",
1314                target_os = "redox",
1315                target_vendor = "apple",
1316            ) => {
1317                cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1318                Ok(())
1319            }
1320            _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported")),
1321        }
1322    }
1323
1324    pub fn lock_shared(&self) -> io::Result<()> {
1325        cfg_select! {
1326            any(
1327                target_os = "freebsd",
1328                target_os = "fuchsia",
1329                target_os = "hurd",
1330                target_os = "linux",
1331                target_os = "netbsd",
1332                target_os = "openbsd",
1333                target_os = "cygwin",
1334                target_os = "illumos",
1335                target_os = "aix",
1336                target_os = "haiku",
1337                target_os = "android",
1338                target_os = "redox",
1339                target_vendor = "apple",
1340            ) => {
1341                cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1342                Ok(())
1343            }
1344            _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported")),
1345        }
1346    }
1347
1348    pub fn try_lock(&self) -> Result<(), TryLockError> {
1349        cfg_select! {
1350            any(
1351                target_os = "freebsd",
1352                target_os = "fuchsia",
1353                target_os = "hurd",
1354                target_os = "linux",
1355                target_os = "netbsd",
1356                target_os = "openbsd",
1357                target_os = "cygwin",
1358                target_os = "illumos",
1359                target_os = "aix",
1360                target_os = "haiku",
1361                target_os = "android",
1362                target_os = "redox",
1363                target_vendor = "apple",
1364            ) => {
1365                let result =
1366                    cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1367                if let Err(err) = result {
1368                    if err.kind() == io::ErrorKind::WouldBlock {
1369                        Err(TryLockError::WouldBlock)
1370                    } else {
1371                        Err(TryLockError::Error(err))
1372                    }
1373                } else {
1374                    Ok(())
1375                }
1376            }
1377            _ => Err(TryLockError::Error(io::const_error!(
1378                io::ErrorKind::Unsupported,
1379                "try_lock() not supported"
1380            ))),
1381        }
1382    }
1383
1384    pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
1385        cfg_select! {
1386            any(
1387                target_os = "freebsd",
1388                target_os = "fuchsia",
1389                target_os = "hurd",
1390                target_os = "linux",
1391                target_os = "netbsd",
1392                target_os = "openbsd",
1393                target_os = "cygwin",
1394                target_os = "illumos",
1395                target_os = "aix",
1396                target_os = "haiku",
1397                target_os = "android",
1398                target_os = "redox",
1399                target_vendor = "apple",
1400            ) => {
1401                let result =
1402                    cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1403                if let Err(err) = result {
1404                    if err.kind() == io::ErrorKind::WouldBlock {
1405                        Err(TryLockError::WouldBlock)
1406                    } else {
1407                        Err(TryLockError::Error(err))
1408                    }
1409                } else {
1410                    Ok(())
1411                }
1412            }
1413            _ => Err(TryLockError::Error(io::const_error!(
1414                io::ErrorKind::Unsupported,
1415                "try_lock_shared() not supported"
1416            ))),
1417        }
1418    }
1419
1420    pub fn unlock(&self) -> io::Result<()> {
1421        cfg_select! {
1422            any(
1423                target_os = "freebsd",
1424                target_os = "fuchsia",
1425                target_os = "hurd",
1426                target_os = "linux",
1427                target_os = "netbsd",
1428                target_os = "openbsd",
1429                target_os = "cygwin",
1430                target_os = "illumos",
1431                target_os = "aix",
1432                target_os = "haiku",
1433                target_os = "android",
1434                target_os = "redox",
1435                target_vendor = "apple",
1436            ) => {
1437                cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1438                Ok(())
1439            }
1440            _ => Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported")),
1441        }
1442    }
1443
1444    pub fn truncate(&self, size: u64) -> io::Result<()> {
1445        let size: off64_t =
1446            size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1447        cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1448    }
1449
1450    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1451        self.0.read(buf)
1452    }
1453
1454    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1455        self.0.read_vectored(bufs)
1456    }
1457
1458    #[inline]
1459    pub fn is_read_vectored(&self) -> bool {
1460        self.0.is_read_vectored()
1461    }
1462
1463    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1464        self.0.read_at(buf, offset)
1465    }
1466
1467    pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
1468        self.0.read_buf(cursor)
1469    }
1470
1471    pub fn read_buf_at(&self, cursor: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
1472        self.0.read_buf_at(cursor, offset)
1473    }
1474
1475    pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
1476        self.0.read_vectored_at(bufs, offset)
1477    }
1478
1479    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1480        self.0.write(buf)
1481    }
1482
1483    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1484        self.0.write_vectored(bufs)
1485    }
1486
1487    #[inline]
1488    pub fn is_write_vectored(&self) -> bool {
1489        self.0.is_write_vectored()
1490    }
1491
1492    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1493        self.0.write_at(buf, offset)
1494    }
1495
1496    pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
1497        self.0.write_vectored_at(bufs, offset)
1498    }
1499
1500    #[inline]
1501    pub fn flush(&self) -> io::Result<()> {
1502        Ok(())
1503    }
1504
1505    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1506        let (whence, pos) = match pos {
1507            // Casting to `i64` is fine, too large values will end up as
1508            // negative which will cause an error in `lseek64`.
1509            SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1510            SeekFrom::End(off) => (libc::SEEK_END, off),
1511            SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1512        };
1513        let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1514        Ok(n as u64)
1515    }
1516
1517    pub fn size(&self) -> Option<io::Result<u64>> {
1518        match self.file_attr().map(|attr| attr.size()) {
1519            // Fall back to default implementation if the returned size is 0,
1520            // we might be in a proc mount.
1521            Ok(0) => None,
1522            result => Some(result),
1523        }
1524    }
1525
1526    pub fn tell(&self) -> io::Result<u64> {
1527        self.seek(SeekFrom::Current(0))
1528    }
1529
1530    pub fn duplicate(&self) -> io::Result<File> {
1531        self.0.duplicate().map(File)
1532    }
1533
1534    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1535        cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1536        Ok(())
1537    }
1538
1539    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1540        cfg_select! {
1541            any(
1542                target_os = "redox",
1543                target_os = "espidf",
1544                target_os = "horizon",
1545                target_os = "nuttx",
1546                target_os = "l4re"
1547            ) => {
1548                // Redox doesn't appear to support `UTIME_OMIT`.
1549                // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1550                // the same as for Redox.
1551                let _ = times;
1552                Err(io::const_error!(
1553                    io::ErrorKind::Unsupported,
1554                    "setting file times not supported",
1555                ))
1556            }
1557            target_vendor = "apple" => {
1558                let ta = TimesAttrlist::from_times(&times)?;
1559                cvt(unsafe {
1560                    libc::fsetattrlist(
1561                        self.as_raw_fd(),
1562                        ta.attrlist(),
1563                        ta.times_buf(),
1564                        ta.times_buf_size(),
1565                        0,
1566                    )
1567                })?;
1568                Ok(())
1569            }
1570            target_os = "android" => {
1571                let times = [
1572                    file_time_to_timespec(times.accessed)?,
1573                    file_time_to_timespec(times.modified)?,
1574                ];
1575                // futimens requires Android API level 19
1576                cvt(unsafe {
1577                    weak!(
1578                        fn futimens(fd: c_int, times: *const libc::timespec) -> c_int;
1579                    );
1580                    match futimens.get() {
1581                        Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1582                        None => {
1583                            return Err(io::const_error!(
1584                                io::ErrorKind::Unsupported,
1585                                "setting file times requires Android API level >= 19",
1586                            ));
1587                        }
1588                    }
1589                })?;
1590                Ok(())
1591            }
1592            _ => {
1593                #[cfg(all(
1594                    target_os = "linux",
1595                    target_env = "gnu",
1596                    target_pointer_width = "32",
1597                    not(target_arch = "riscv32")
1598                ))]
1599                {
1600                    use crate::sys::pal::time::__timespec64;
1601                    use crate::sys::pal::weak::weak;
1602
1603                    // Added in glibc 2.34
1604                    weak!(
1605                        fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int;
1606                    );
1607
1608                    if let Some(futimens64) = __futimens64.get() {
1609                        let to_timespec = |time: Option<SystemTime>| {
1610                            time.map(|time| time.t.to_timespec64())
1611                                .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
1612                        };
1613                        let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1614                        cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1615                        return Ok(());
1616                    }
1617                }
1618                let times = [
1619                    file_time_to_timespec(times.accessed)?,
1620                    file_time_to_timespec(times.modified)?,
1621                ];
1622                cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1623                Ok(())
1624            }
1625        }
1626    }
1627}
1628
1629#[cfg(not(any(
1630    target_os = "redox",
1631    target_os = "espidf",
1632    target_os = "horizon",
1633    target_os = "nuttx",
1634)))]
1635fn file_time_to_timespec(time: Option<SystemTime>) -> io::Result<libc::timespec> {
1636    match time {
1637        Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1638        Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "timestamp is too large to set as a file time",
                    }
            }))io::const_error!(
1639            io::ErrorKind::InvalidInput,
1640            "timestamp is too large to set as a file time",
1641        )),
1642        Some(_) => Err(::core::hint::must_use(::core::io::Error::from_static_message(const {
                &::core::io::SimpleMessage {
                        kind: io::ErrorKind::InvalidInput,
                        message: "timestamp is too small to set as a file time",
                    }
            }))io::const_error!(
1643            io::ErrorKind::InvalidInput,
1644            "timestamp is too small to set as a file time",
1645        )),
1646        None => Ok({
1647            let mut ts = libc::timespec::default();
1648            ts.tv_sec = 0;
1649            ts.tv_nsec = libc::UTIME_OMIT as _;
1650            ts
1651        }),
1652    }
1653}
1654
1655#[cfg(target_vendor = "apple")]
1656struct TimesAttrlist {
1657    buf: [mem::MaybeUninit<libc::timespec>; 3],
1658    attrlist: libc::attrlist,
1659    num_times: usize,
1660}
1661
1662#[cfg(target_vendor = "apple")]
1663impl TimesAttrlist {
1664    fn from_times(times: &FileTimes) -> io::Result<Self> {
1665        let mut this = Self {
1666            buf: [mem::MaybeUninit::<libc::timespec>::uninit(); 3],
1667            attrlist: unsafe { mem::zeroed() },
1668            num_times: 0,
1669        };
1670        this.attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1671        if times.created.is_some() {
1672            this.buf[this.num_times].write(file_time_to_timespec(times.created)?);
1673            this.num_times += 1;
1674            this.attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1675        }
1676        if times.modified.is_some() {
1677            this.buf[this.num_times].write(file_time_to_timespec(times.modified)?);
1678            this.num_times += 1;
1679            this.attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1680        }
1681        if times.accessed.is_some() {
1682            this.buf[this.num_times].write(file_time_to_timespec(times.accessed)?);
1683            this.num_times += 1;
1684            this.attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1685        }
1686        Ok(this)
1687    }
1688
1689    fn attrlist(&self) -> *mut libc::c_void {
1690        (&raw const self.attrlist).cast::<libc::c_void>().cast_mut()
1691    }
1692
1693    fn times_buf(&self) -> *mut libc::c_void {
1694        self.buf.as_ptr().cast::<libc::c_void>().cast_mut()
1695    }
1696
1697    fn times_buf_size(&self) -> usize {
1698        self.num_times * size_of::<libc::timespec>()
1699    }
1700}
1701
1702impl DirBuilder {
1703    pub fn new() -> DirBuilder {
1704        DirBuilder { mode: 0o777 }
1705    }
1706
1707    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1708        run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1709    }
1710
1711    #[cfg(not(target_os = "wasi"))]
1712    pub fn set_mode(&mut self, mode: u32) {
1713        self.mode = mode as mode_t;
1714    }
1715}
1716
1717impl fmt::Debug for DirBuilder {
1718    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1719        let DirBuilder { mode } = self;
1720        f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1721    }
1722}
1723
1724impl AsInner<FileDesc> for File {
1725    #[inline]
1726    fn as_inner(&self) -> &FileDesc {
1727        &self.0
1728    }
1729}
1730
1731impl AsInnerMut<FileDesc> for File {
1732    #[inline]
1733    fn as_inner_mut(&mut self) -> &mut FileDesc {
1734        &mut self.0
1735    }
1736}
1737
1738impl IntoInner<FileDesc> for File {
1739    fn into_inner(self) -> FileDesc {
1740        self.0
1741    }
1742}
1743
1744impl FromInner<FileDesc> for File {
1745    fn from_inner(file_desc: FileDesc) -> Self {
1746        Self(file_desc)
1747    }
1748}
1749
1750impl AsFd for File {
1751    #[inline]
1752    fn as_fd(&self) -> BorrowedFd<'_> {
1753        self.0.as_fd()
1754    }
1755}
1756
1757impl AsRawFd for File {
1758    #[inline]
1759    fn as_raw_fd(&self) -> RawFd {
1760        self.0.as_raw_fd()
1761    }
1762}
1763
1764impl IntoRawFd for File {
1765    fn into_raw_fd(self) -> RawFd {
1766        self.0.into_raw_fd()
1767    }
1768}
1769
1770impl FromRawFd for File {
1771    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1772        Self(FromRawFd::from_raw_fd(raw_fd))
1773    }
1774}
1775
1776impl fmt::Debug for File {
1777    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1778        let fd = self.as_raw_fd();
1779        let mut b = debug_path_fd(fd, f, "File");
1780        b.finish()
1781    }
1782}
1783
1784// Format in octal, followed by the mode format used in `ls -l`.
1785//
1786// References:
1787//   https://pubs.opengroup.org/onlinepubs/9799919799/utilities/ls.html
1788//   https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html
1789//   https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
1790//
1791// Example:
1792//   0o100664 (-rw-rw-r--)
1793impl fmt::Debug for Mode {
1794    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1795        let Self(mode) = *self;
1796        f.write_fmt(format_args!("0o{0:06o}", mode))write!(f, "0o{mode:06o}")?;
1797
1798        let entry_type = match mode & libc::S_IFMT {
1799            libc::S_IFDIR => 'd',
1800            libc::S_IFBLK => 'b',
1801            libc::S_IFCHR => 'c',
1802            libc::S_IFLNK => 'l',
1803            libc::S_IFIFO => 'p',
1804            libc::S_IFREG => '-',
1805            _ => return Ok(()),
1806        };
1807
1808        f.write_str(" (")?;
1809        f.write_char(entry_type)?;
1810
1811        // Owner permissions
1812        f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1813        f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1814        let owner_executable = mode & libc::S_IXUSR != 0;
1815        let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1816        f.write_char(match (owner_executable, setuid) {
1817            (true, true) => 's',  // executable and setuid
1818            (false, true) => 'S', // setuid
1819            (true, false) => 'x', // executable
1820            (false, false) => '-',
1821        })?;
1822
1823        // Group permissions
1824        f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1825        f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1826        let group_executable = mode & libc::S_IXGRP != 0;
1827        let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1828        f.write_char(match (group_executable, setgid) {
1829            (true, true) => 's',  // executable and setgid
1830            (false, true) => 'S', // setgid
1831            (true, false) => 'x', // executable
1832            (false, false) => '-',
1833        })?;
1834
1835        // Other permissions
1836        f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1837        f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1838        let other_executable = mode & libc::S_IXOTH != 0;
1839        let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1840        f.write_char(match (entry_type, other_executable, sticky) {
1841            ('d', true, true) => 't',  // searchable and restricted deletion
1842            ('d', false, true) => 'T', // restricted deletion
1843            (_, true, _) => 'x',       // executable
1844            (_, false, _) => '-',
1845        })?;
1846
1847        f.write_char(')')
1848    }
1849}
1850
1851pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1852    let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1853    if ptr.is_null() {
1854        Err(Error::last_os_error())
1855    } else {
1856        let root = path.to_path_buf();
1857        let inner = InnerReadDir { dirp: DirStream(ptr), root };
1858        Ok(ReadDir::new(inner))
1859    }
1860}
1861
1862pub fn unlink(p: &CStr) -> io::Result<()> {
1863    cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ())
1864}
1865
1866pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
1867    cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1868}
1869
1870#[cfg(any(target_os = "linux", target_os = "android"))]
1871pub fn rename_noreplace(old: &CStr, new: &CStr) -> io::Result<()> {
1872    unsafe fn renameat2(olddirfd: c_int, oldpath: *const libc::c_char,
    newdirfd: c_int, newpath: *const libc::c_char, flags: libc::c_uint)
    -> c_int {
    let ref renameat2:
            ExternWeak<unsafe extern "C" fn(c_int, *const libc::c_char, c_int,
                *const libc::c_char, libc::c_uint) -> c_int> =
        {
            unsafe extern "C" {
                #[linkage = "extern_weak"]
                static renameat2:
                    Option<unsafe extern "C" fn(c_int, *const libc::c_char,
                        c_int, *const libc::c_char, libc::c_uint) -> c_int>;
            }

            #[allow(unused_unsafe)]
            ExternWeak::new(unsafe { renameat2 })
        };
    if let Some(fun) = renameat2.get() {
        unsafe { fun(olddirfd, oldpath, newdirfd, newpath, flags) }
    } else {
        unsafe {
            libc::syscall(libc::SYS_renameat2, olddirfd, oldpath, newdirfd,
                    newpath, flags) as c_int
        }
    }
}syscall!(
1873        fn renameat2(
1874            olddirfd: c_int,
1875            oldpath: *const libc::c_char,
1876            newdirfd: c_int,
1877            newpath: *const libc::c_char,
1878            flags: libc::c_uint,
1879        ) -> c_int;
1880    );
1881
1882    // `RENAME_NOREPLACE` is `c_uint` on linux and `c_int` on Android, so casting is needed here.
1883    let flags = libc::RENAME_NOREPLACE as libc::c_uint;
1884    let res = cvt(unsafe {
1885        renameat2(libc::AT_FDCWD, old.as_ptr(), libc::AT_FDCWD, new.as_ptr(), flags)
1886    });
1887
1888    match res {
1889        Ok(_) => Ok(()),
1890        Err(err) => match err.raw_os_error() {
1891            // The kernel predates `renameat2`.
1892            Some(libc::ENOSYS) => link_then_unlink(old, new),
1893            // The filesystem does not support `RENAME_NOREPLACE`.
1894            // `EINVAL` also covers misuse, so report it unchanged unless the fallback found `new`.
1895            Some(libc::EINVAL) => match link_then_unlink(old, new) {
1896                Err(fallback) if fallback.raw_os_error() != Some(libc::EEXIST) => Err(err),
1897                res => res,
1898            },
1899            _ => Err(err),
1900        },
1901    }
1902}
1903
1904#[cfg(target_vendor = "apple")]
1905pub fn rename_noreplace(old: &CStr, new: &CStr) -> io::Result<()> {
1906    let res = cvt(unsafe { libc::renamex_np(old.as_ptr(), new.as_ptr(), libc::RENAME_EXCL) });
1907    match res {
1908        Ok(_) => Ok(()),
1909        Err(err) => match err.raw_os_error() {
1910            // The filesystem does not support `RENAME_EXCL`.
1911            // Unlike Linux, Darwin keeps `EINVAL` for misuse only.
1912            Some(libc::ENOTSUP) => link_then_unlink(old, new),
1913            _ => Err(err),
1914        },
1915    }
1916}
1917
1918#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
1919pub fn rename_noreplace(old: &CStr, new: &CStr) -> io::Result<()> {
1920    link_then_unlink(old, new)
1921}
1922
1923pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1924    cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
1925}
1926
1927#[cfg(target_os = "vxworks")]
1928pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1929    // VxWorks has no `O_NOFOLLOW`, and its `fchmodat` rejects
1930    // `AT_SYMLINK_NOFOLLOW` with `ENOTSUP`, so a no-follow chmod is unsupported.
1931    Err(crate::io::ErrorKind::Unsupported.into())
1932}
1933
1934#[cfg(not(target_os = "vxworks"))]
1935pub fn set_perm_nofollow(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1936    /// Helper function for fallback open with `O_NOFOLLOW` + `fchmod` behavior. This will
1937    /// successfully change the permissions of non-symlinks and fail when there's a symlink.
1938    #[inline]
1939    fn open_and_set_permissions(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1940        use crate::fs::{OpenOptions, Permissions};
1941
1942        let mut options = OpenOptions::new();
1943        options.read(true);
1944
1945        // ESP-IDF and Horizon do not support O_NOFOLLOW, so we skip setting it.
1946        // Their filesystems do not have symbolic links, so no special handling is required.
1947        #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
1948        {
1949            #[cfg(not(target_os = "wasi"))]
1950            use crate::os::unix::fs::OpenOptionsExt;
1951            #[cfg(target_os = "wasi")]
1952            use crate::os::wasi::fs::OpenOptionsExt;
1953
1954            options.custom_flags(libc::O_NOFOLLOW);
1955        }
1956
1957        // SAFETY: Since this function is called with `with_native_path`
1958        // and that successfully converted the `&Path` to a `CString`,
1959        // it should be safe to convert the `&CStr` back to a `Path`.
1960        let os_str = unsafe { OsStr::from_encoded_bytes_unchecked(p.to_bytes()) };
1961        options.open(Path::new(os_str))?.set_permissions(Permissions::from_inner(perm))
1962    }
1963
1964    // This res value is modified for platforms that support the `fchmodat` syscall.
1965    #[allow(unused)]
1966    let mut res: Result<(), core::io::Error> = Err(crate::io::ErrorKind::Unsupported.into());
1967
1968    // These platforms support `fchmodat`, so utilize this syscall over `open` + `fchmod`.
1969    // We can *not* use this on Android due to <https://github.com/android/ndk/issues/1258>.
1970    #[cfg(any(
1971        target_os = "linux",
1972        target_os = "macos",
1973        target_os = "freebsd",
1974        target_os = "openbsd",
1975        target_os = "netbsd",
1976        target_os = "dragonfly",
1977        target_os = "nto",
1978        target_os = "qnx"
1979    ))]
1980    {
1981        res = cvt_r(|| unsafe {
1982            libc::fchmodat(libc::AT_FDCWD, p.as_ptr(), perm.mode, libc::AT_SYMLINK_NOFOLLOW)
1983        })
1984        .map(|_| ());
1985    }
1986
1987    // If fchmodat fails with `ErrorKind::Unsupported` fallback to using open + fchmod. This is just in case
1988    // for older systems like Ubuntu 20.04 where fchmodat fails with EOPNOTSUPP on both regular files and
1989    // symlinks when AT_SYMLINK_NOFOLLOW is passed in.
1990    match res {
1991        Ok(_) => Ok(()),
1992        Err(err) => {
1993            if err.kind() == crate::io::ErrorKind::Unsupported {
1994                match open_and_set_permissions(p, perm) {
1995                    Ok(_) => return Ok(()),
1996                    Err(e) => {
1997                        if e.kind() == crate::io::ErrorKind::FilesystemLoop {
1998                            // When open is used with O_NOFOLLOW flag, if the trailing component of
1999                            // a path is a symbolic link, it should fail with ELOOP error. Instead of
2000                            // returning `FilesystemLoop`, this returns `Unsupported` to keep it consistent
2001                            // with what `fchmodat` would return when chmoding a symlink using AT_SYMLINK_NOFOLLOW.
2002                            return Err(err);
2003                        }
2004                        return Err(e);
2005                    }
2006                }
2007            }
2008
2009            Err(err)
2010        }
2011    }
2012}
2013
2014pub fn rmdir(p: &CStr) -> io::Result<()> {
2015    cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ())
2016}
2017
2018pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> {
2019    let p = c_path.as_ptr();
2020
2021    let mut buf = Vec::with_capacity(256);
2022
2023    loop {
2024        let buf_read =
2025            cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
2026
2027        unsafe {
2028            buf.set_len(buf_read);
2029        }
2030
2031        if buf_read != buf.capacity() {
2032            buf.shrink_to_fit();
2033
2034            return Ok(PathBuf::from(OsString::from_vec(buf)));
2035        }
2036
2037        // Trigger the internal buffer resizing logic of `Vec` by requiring
2038        // more space than the current capacity. The length is guaranteed to be
2039        // the same as the capacity due to the if statement above.
2040        buf.reserve(1);
2041    }
2042}
2043
2044pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> {
2045    cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
2046}
2047
2048pub fn link(original: &CStr, link: &CStr) -> io::Result<()> {
2049    cfg_select! {
2050        any(
2051            // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead.
2052            // POSIX leaves it implementation-defined whether `link` follows
2053            // symlinks, so rely on the `symlink_hard_link` test in
2054            // library/std/src/fs/tests.rs to check the behavior.
2055            target_os = "vxworks",
2056            target_os = "redox",
2057            target_os = "espidf",
2058            // Other misc platforms
2059            target_os = "horizon",
2060            target_os = "vita",
2061            target_os = "l4re",
2062            target_env = "nto70",
2063        ) => {
2064            cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
2065        }
2066        _ => {
2067            // Where we can, use `linkat` instead of `link`; see the comment above
2068            // this one for details on why.
2069            cvt(unsafe {
2070                libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0)
2071            })?;
2072        }
2073    }
2074    Ok(())
2075}
2076
2077pub fn stat(p: &CStr) -> io::Result<FileAttr> {
2078    {
    if let Some(ret) =
            unsafe {
                try_statx(libc::AT_FDCWD, p.as_ptr(),
                    libc::AT_STATX_SYNC_AS_STAT,
                    libc::STATX_BASIC_STATS | libc::STATX_BTIME)
            } {
        return ret;
    }
}cfg_has_statx! {
2079        if let Some(ret) = unsafe { try_statx(
2080            libc::AT_FDCWD,
2081            p.as_ptr(),
2082            libc::AT_STATX_SYNC_AS_STAT,
2083            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2084        ) } {
2085            return ret;
2086        }
2087    }
2088
2089    let mut stat: stat64 = unsafe { mem::zeroed() };
2090    cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
2091    Ok(FileAttr::from_stat64(stat))
2092}
2093
2094pub fn lstat(p: &CStr) -> io::Result<FileAttr> {
2095    {
    if let Some(ret) =
            unsafe {
                try_statx(libc::AT_FDCWD, p.as_ptr(),
                    libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
                    libc::STATX_BASIC_STATS | libc::STATX_BTIME)
            } {
        return ret;
    }
}cfg_has_statx! {
2096        if let Some(ret) = unsafe { try_statx(
2097            libc::AT_FDCWD,
2098            p.as_ptr(),
2099            libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
2100            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2101        ) } {
2102            return ret;
2103        }
2104    }
2105
2106    let mut stat: stat64 = unsafe { mem::zeroed() };
2107    cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
2108    Ok(FileAttr::from_stat64(stat))
2109}
2110
2111pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
2112    let r = unsafe { libc::realpath(path.as_ptr(), ptr::null_mut()) };
2113    if r.is_null() {
2114        return Err(io::Error::last_os_error());
2115    }
2116    Ok(PathBuf::from(OsString::from_vec(unsafe {
2117        let buf = CStr::from_ptr(r).to_bytes().to_vec();
2118        libc::free(r as *mut _);
2119        buf
2120    })))
2121}
2122
2123fn link_then_unlink(old: &CStr, new: &CStr) -> io::Result<()> {
2124    link(old, new)?;
2125    unlink(old)
2126}
2127
2128fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2129    use crate::fs::File;
2130    use crate::sys::fs::common::NOT_FILE_ERROR;
2131
2132    let reader = File::open(from)?;
2133    let metadata = reader.metadata()?;
2134    if !metadata.is_file() {
2135        return Err(NOT_FILE_ERROR);
2136    }
2137    Ok((reader, metadata))
2138}
2139
2140fn set_times_impl(p: &CStr, times: FileTimes, follow_symlinks: bool) -> io::Result<()> {
2141    cfg_select! {
2142        any(
2143            target_os = "redox",
2144            target_os = "espidf",
2145            target_os = "horizon",
2146            target_os = "nuttx",
2147            target_os = "vita",
2148            target_os = "rtems"
2149        ) => {
2150            let _ = (p, times, follow_symlinks);
2151            Err(io::const_error!(io::ErrorKind::Unsupported, "setting file times not supported"))
2152        }
2153        target_vendor = "apple" => {
2154            // Apple platforms use setattrlist which supports setting times on symlinks
2155            let ta = TimesAttrlist::from_times(&times)?;
2156            let options = if follow_symlinks { 0 } else { libc::FSOPT_NOFOLLOW };
2157
2158            cvt(unsafe {
2159                libc::setattrlist(
2160                    p.as_ptr(),
2161                    ta.attrlist(),
2162                    ta.times_buf(),
2163                    ta.times_buf_size(),
2164                    options as u32,
2165                )
2166            })?;
2167            Ok(())
2168        }
2169        target_os = "android" => {
2170            let times =
2171                [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2172            let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2173            // utimensat requires Android API level 19
2174            cvt(unsafe {
2175                weak!(
2176                    fn utimensat(
2177                        dirfd: c_int,
2178                        path: *const libc::c_char,
2179                        times: *const libc::timespec,
2180                        flags: c_int,
2181                    ) -> c_int;
2182                );
2183                match utimensat.get() {
2184                    Some(utimensat) => utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags),
2185                    None => {
2186                        return Err(io::const_error!(
2187                            io::ErrorKind::Unsupported,
2188                            "setting file times requires Android API level >= 19",
2189                        ));
2190                    }
2191                }
2192            })?;
2193            Ok(())
2194        }
2195        _ => {
2196            let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2197            #[cfg(all(
2198                target_os = "linux",
2199                target_env = "gnu",
2200                target_pointer_width = "32",
2201                not(target_arch = "riscv32")
2202            ))]
2203            {
2204                use crate::sys::pal::time::__timespec64;
2205                use crate::sys::pal::weak::weak;
2206
2207                // Added in glibc 2.34
2208                weak!(
2209                    fn __utimensat64(
2210                        dirfd: c_int,
2211                        path: *const c_char,
2212                        times: *const __timespec64,
2213                        flags: c_int,
2214                    ) -> c_int;
2215                );
2216
2217                if let Some(utimensat64) = __utimensat64.get() {
2218                    let to_timespec = |time: Option<SystemTime>| {
2219                        time.map(|time| time.t.to_timespec64())
2220                            .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
2221                    };
2222                    let times = [to_timespec(times.accessed), to_timespec(times.modified)];
2223                    cvt(unsafe { utimensat64(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2224                    return Ok(());
2225                }
2226            }
2227            let times =
2228                [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2229            cvt(unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2230            Ok(())
2231        }
2232    }
2233}
2234
2235#[inline(always)]
2236pub fn set_times(p: &CStr, times: FileTimes) -> io::Result<()> {
2237    set_times_impl(p, times, true)
2238}
2239
2240#[inline(always)]
2241pub fn set_times_nofollow(p: &CStr, times: FileTimes) -> io::Result<()> {
2242    set_times_impl(p, times, false)
2243}
2244
2245#[cfg(any(target_os = "espidf", target_os = "wasi"))]
2246fn open_to_and_set_permissions(
2247    to: &Path,
2248    _reader_metadata: &crate::fs::Metadata,
2249) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2250    use crate::fs::OpenOptions;
2251    let writer = OpenOptions::new().write(true).create(true).truncate(true).open(to)?;
2252    let writer_metadata = writer.metadata()?;
2253    Ok((writer, writer_metadata))
2254}
2255
2256#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
2257fn open_to_and_set_permissions(
2258    to: &Path,
2259    reader_metadata: &crate::fs::Metadata,
2260) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2261    use crate::fs::OpenOptions;
2262    use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
2263
2264    let perm = reader_metadata.permissions();
2265    let writer = OpenOptions::new()
2266        // create the file with the correct mode right away
2267        .mode(perm.mode())
2268        .write(true)
2269        .create(true)
2270        .truncate(true)
2271        .open(to)?;
2272    let writer_metadata = writer.metadata()?;
2273    // fchmod is broken on vita
2274    #[cfg(not(target_os = "vita"))]
2275    if writer_metadata.is_file() {
2276        // Set the correct file permissions, in case the file already existed.
2277        // Don't set the permissions on already existing non-files like
2278        // pipes/FIFOs or device nodes.
2279        writer.set_permissions(perm)?;
2280    }
2281    Ok((writer, writer_metadata))
2282}
2283
2284mod cfm {
2285    use crate::fs::{File, Metadata};
2286    use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
2287
2288    #[allow(dead_code)]
2289    pub struct CachedFileMetadata(pub File, pub Metadata);
2290
2291    impl Read for CachedFileMetadata {
2292        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2293            self.0.read(buf)
2294        }
2295        fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2296            self.0.read_vectored(bufs)
2297        }
2298        fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
2299            self.0.read_buf(cursor)
2300        }
2301        #[inline]
2302        fn is_read_vectored(&self) -> bool {
2303            self.0.is_read_vectored()
2304        }
2305        fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2306            self.0.read_to_end(buf)
2307        }
2308        fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2309            self.0.read_to_string(buf)
2310        }
2311    }
2312    impl Write for CachedFileMetadata {
2313        fn write(&mut self, buf: &[u8]) -> Result<usize> {
2314            self.0.write(buf)
2315        }
2316        fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2317            self.0.write_vectored(bufs)
2318        }
2319        #[inline]
2320        fn is_write_vectored(&self) -> bool {
2321            self.0.is_write_vectored()
2322        }
2323        #[inline]
2324        fn flush(&mut self) -> Result<()> {
2325            self.0.flush()
2326        }
2327    }
2328}
2329#[cfg(any(target_os = "linux", target_os = "android"))]
2330pub(in crate::sys) use cfm::CachedFileMetadata;
2331
2332#[cfg(not(target_vendor = "apple"))]
2333pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2334    let (reader, reader_metadata) = open_from(from)?;
2335    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2336
2337    io::copy(
2338        &mut cfm::CachedFileMetadata(reader, reader_metadata),
2339        &mut cfm::CachedFileMetadata(writer, writer_metadata),
2340    )
2341}
2342
2343#[cfg(target_vendor = "apple")]
2344pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2345    const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2346
2347    struct FreeOnDrop(libc::copyfile_state_t);
2348    impl Drop for FreeOnDrop {
2349        fn drop(&mut self) {
2350            // The code below ensures that `FreeOnDrop` is never a null pointer
2351            unsafe {
2352                // `copyfile_state_free` returns -1 if the `to` or `from` files
2353                // cannot be closed. However, this is not considered an error.
2354                libc::copyfile_state_free(self.0);
2355            }
2356        }
2357    }
2358
2359    let (reader, reader_metadata) = open_from(from)?;
2360
2361    let clonefile_result = run_path_with_cstr(to, &|to| {
2362        cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2363    });
2364    match clonefile_result {
2365        Ok(_) => return Ok(reader_metadata.len()),
2366        Err(e) => match e.raw_os_error() {
2367            // `fclonefileat` will fail on non-APFS volumes, if the
2368            // destination already exists, or if the source and destination
2369            // are on different devices. In all these cases `fcopyfile`
2370            // should succeed.
2371            Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2372            _ => return Err(e),
2373        },
2374    }
2375
2376    // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
2377    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2378
2379    // We ensure that `FreeOnDrop` never contains a null pointer so it is
2380    // always safe to call `copyfile_state_free`
2381    let state = unsafe {
2382        let state = libc::copyfile_state_alloc();
2383        if state.is_null() {
2384            return Err(crate::io::Error::last_os_error());
2385        }
2386        FreeOnDrop(state)
2387    };
2388
2389    let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2390
2391    cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2392
2393    let mut bytes_copied: libc::off_t = 0;
2394    cvt(unsafe {
2395        libc::copyfile_state_get(
2396            state.0,
2397            libc::COPYFILE_STATE_COPIED as u32,
2398            (&raw mut bytes_copied) as *mut libc::c_void,
2399        )
2400    })?;
2401    Ok(bytes_copied as u64)
2402}
2403
2404#[cfg(not(target_os = "wasi"))]
2405pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2406    run_path_with_cstr(path, &|path| {
2407        cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2408            .map(|_| ())
2409    })
2410}
2411
2412#[cfg(not(target_os = "wasi"))]
2413pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2414    cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2415    Ok(())
2416}
2417
2418#[cfg(not(any(target_os = "vxworks", target_os = "wasi")))]
2419pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2420    run_path_with_cstr(path, &|path| {
2421        cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2422            .map(|_| ())
2423    })
2424}
2425
2426#[cfg(target_os = "vxworks")]
2427pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2428    let (_, _, _) = (path, uid, gid);
2429    Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2430}
2431
2432#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks", target_os = "wasi")))]
2433pub fn chroot(dir: &Path) -> io::Result<()> {
2434    run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2435}
2436
2437#[cfg(target_os = "vxworks")]
2438pub fn chroot(dir: &Path) -> io::Result<()> {
2439    let _ = dir;
2440    Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2441}
2442
2443#[cfg(not(target_os = "wasi"))]
2444pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
2445    run_path_with_cstr(path, &|path| {
2446        cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
2447    })
2448}
2449
2450pub use remove_dir_impl::remove_dir_all;
2451
2452// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri
2453#[cfg(any(
2454    target_os = "redox",
2455    target_os = "espidf",
2456    target_os = "horizon",
2457    target_os = "vita",
2458    target_os = "nto",
2459    target_os = "qnx",
2460    target_os = "vxworks",
2461    target_os = "l4re",
2462    miri
2463))]
2464mod remove_dir_impl {
2465    pub use crate::sys::fs::common::remove_dir_all;
2466}
2467
2468// Modern implementation using openat(), unlinkat() and fdopendir()
2469#[cfg(not(any(
2470    target_os = "redox",
2471    target_os = "espidf",
2472    target_os = "horizon",
2473    target_os = "vita",
2474    target_os = "nto",
2475    target_os = "qnx",
2476    target_os = "vxworks",
2477    target_os = "l4re",
2478    miri
2479)))]
2480mod remove_dir_impl {
2481    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2482    use libc::{fdopendir, openat, unlinkat};
2483    #[cfg(all(target_os = "linux", target_env = "gnu"))]
2484    use libc::{fdopendir, openat64 as openat, unlinkat};
2485
2486    use super::{
2487        AsRawFd, DirEntry, DirStream, FromRawFd, InnerReadDir, IntoRawFd, OwnedFd, RawFd, ReadDir,
2488        lstat,
2489    };
2490    use crate::ffi::CStr;
2491    use crate::io;
2492    use crate::path::{Path, PathBuf};
2493    use crate::sys::helpers::{ignore_notfound, run_path_with_cstr};
2494    use crate::sys::{cvt, cvt_r};
2495
2496    pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2497        let fd = cvt_r(|| unsafe {
2498            openat(
2499                parent_fd.unwrap_or(libc::AT_FDCWD),
2500                p.as_ptr(),
2501                libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2502            )
2503        })?;
2504        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2505    }
2506
2507    fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2508        let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2509        if ptr.is_null() {
2510            return Err(io::Error::last_os_error());
2511        }
2512        let dirp = DirStream(ptr);
2513        // file descriptor is automatically closed by libc::closedir() now, so give up ownership
2514        let new_parent_fd = dir_fd.into_raw_fd();
2515        // a valid root is not needed because we do not call any functions involving the full path
2516        // of the `DirEntry`s.
2517        let dummy_root = PathBuf::new();
2518        let inner = InnerReadDir { dirp, root: dummy_root };
2519        Ok((ReadDir::new(inner), new_parent_fd))
2520    }
2521
2522    #[cfg(any(
2523        target_os = "solaris",
2524        target_os = "illumos",
2525        target_os = "haiku",
2526        target_os = "vxworks",
2527        target_os = "aix",
2528    ))]
2529    fn is_dir(_ent: &DirEntry) -> Option<bool> {
2530        None
2531    }
2532
2533    #[cfg(not(any(
2534        target_os = "solaris",
2535        target_os = "illumos",
2536        target_os = "haiku",
2537        target_os = "vxworks",
2538        target_os = "aix",
2539    )))]
2540    fn is_dir(ent: &DirEntry) -> Option<bool> {
2541        match ent.entry.d_type {
2542            libc::DT_UNKNOWN => None,
2543            libc::DT_DIR => Some(true),
2544            _ => Some(false),
2545        }
2546    }
2547
2548    fn is_enoent(result: &io::Result<()>) -> bool {
2549        if let Err(err) = result
2550            && #[allow(non_exhaustive_omitted_patterns)] match err.raw_os_error() {
    Some(libc::ENOENT) => true,
    _ => false,
}matches!(err.raw_os_error(), Some(libc::ENOENT))
2551        {
2552            true
2553        } else {
2554            false
2555        }
2556    }
2557
2558    fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2559        // try opening as directory
2560        let fd = match openat_nofollow_dironly(parent_fd, path) {
2561            Err(err) if #[allow(non_exhaustive_omitted_patterns)] match err.raw_os_error() {
    Some(libc::ENOTDIR | libc::ELOOP) => true,
    _ => false,
}matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2562                // not a directory - don't traverse further
2563                // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
2564                return match parent_fd {
2565                    // unlink...
2566                    Some(parent_fd) => {
2567                        cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2568                    }
2569                    // ...unless this was supposed to be the deletion root directory
2570                    None => Err(err),
2571                };
2572            }
2573            result => result?,
2574        };
2575
2576        // open the directory passing ownership of the fd
2577        let (dir, fd) = fdreaddir(fd)?;
2578
2579        // For WASI all directory entries for this directory are read first
2580        // before any removal is done. This works around the fact that the
2581        // WASIp1 API for reading directories is not well-designed for handling
2582        // mutations between invocations of reading a directory. By reading all
2583        // the entries at once this ensures that, at least without concurrent
2584        // modifications, it should be possible to delete everything.
2585        #[cfg(target_os = "wasi")]
2586        let dir = dir.collect::<Vec<_>>();
2587
2588        for child in dir {
2589            let child = child?;
2590            // we need an inner try block, because if one of these
2591            // directories has already been deleted, then we need to
2592            // continue the loop, not return ok.
2593            let result: io::Result<()> = try {
2594                match is_dir(&child) {
2595                    Some(true) => {
2596                        remove_dir_all_recursive(Some(fd), &child.name)?;
2597                    }
2598                    Some(false) => {
2599                        cvt(unsafe { unlinkat(fd, child.name.as_ptr(), 0) })?;
2600                    }
2601                    None => {
2602                        // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
2603                        // if the process has the appropriate privileges. This however can causing orphaned
2604                        // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
2605                        // into it first instead of trying to unlink() it.
2606                        remove_dir_all_recursive(Some(fd), &child.name)?;
2607                    }
2608                }
2609            };
2610            if result.is_err() && !is_enoent(&result) {
2611                return result;
2612            }
2613        }
2614
2615        // unlink the directory after removing its contents
2616        ignore_notfound(cvt(unsafe {
2617            unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2618        }))?;
2619        Ok(())
2620    }
2621
2622    fn remove_dir_all_modern(p: &CStr) -> io::Result<()> {
2623        // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
2624        // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
2625        // into symlinks.
2626        let attr = lstat(p)?;
2627        if attr.file_type().is_symlink() {
2628            super::unlink(p)
2629        } else {
2630            remove_dir_all_recursive(None, p)
2631        }
2632    }
2633
2634    pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2635        run_path_with_cstr(p, &remove_dir_all_modern)
2636    }
2637}