Skip to main content

std/sys/fs/
unix.rs

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