std/sys/fs/
unix.rs

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