Skip to main content

std/sys/fs/
unix.rs

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