Skip to main content

std/sys/fs/
unix.rs

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