Skip to main content

std/sys/fs/
unix.rs

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