Skip to main content

std/sys/fs/
unix.rs

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