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(not(any(
1608            target_os = "redox",
1609            target_os = "espidf",
1610            target_os = "horizon",
1611            target_os = "nuttx",
1612        )))]
1613        let to_timespec = |time: Option<SystemTime>| match time {
1614            Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1615            Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
1616                io::ErrorKind::InvalidInput,
1617                "timestamp is too large to set as a file time",
1618            )),
1619            Some(_) => Err(io::const_error!(
1620                io::ErrorKind::InvalidInput,
1621                "timestamp is too small to set as a file time",
1622            )),
1623            None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
1624        };
1625        cfg_select! {
1626            any(target_os = "redox", target_os = "espidf", target_os = "horizon", target_os = "nuttx") => {
1627                // Redox doesn't appear to support `UTIME_OMIT`.
1628                // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1629                // the same as for Redox.
1630                let _ = times;
1631                Err(io::const_error!(
1632                    io::ErrorKind::Unsupported,
1633                    "setting file times not supported",
1634                ))
1635            }
1636            target_vendor = "apple" => {
1637                let mut buf = [mem::MaybeUninit::<libc::timespec>::uninit(); 3];
1638                let mut num_times = 0;
1639                let mut attrlist: libc::attrlist = unsafe { mem::zeroed() };
1640                attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1641                if times.created.is_some() {
1642                    buf[num_times].write(to_timespec(times.created)?);
1643                    num_times += 1;
1644                    attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1645                }
1646                if times.modified.is_some() {
1647                    buf[num_times].write(to_timespec(times.modified)?);
1648                    num_times += 1;
1649                    attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1650                }
1651                if times.accessed.is_some() {
1652                    buf[num_times].write(to_timespec(times.accessed)?);
1653                    num_times += 1;
1654                    attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1655                }
1656                cvt(unsafe { libc::fsetattrlist(
1657                    self.as_raw_fd(),
1658                    (&raw const attrlist).cast::<libc::c_void>().cast_mut(),
1659                    buf.as_ptr().cast::<libc::c_void>().cast_mut(),
1660                    num_times * size_of::<libc::timespec>(),
1661                    0
1662                ) })?;
1663                Ok(())
1664            }
1665            target_os = "android" => {
1666                let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1667                // futimens requires Android API level 19
1668                cvt(unsafe {
1669                    weak!(
1670                        fn futimens(fd: c_int, times: *const libc::timespec) -> c_int;
1671                    );
1672                    match futimens.get() {
1673                        Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1674                        None => return Err(io::const_error!(
1675                            io::ErrorKind::Unsupported,
1676                            "setting file times requires Android API level >= 19",
1677                        )),
1678                    }
1679                })?;
1680                Ok(())
1681            }
1682            _ => {
1683                #[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "32", not(target_arch = "riscv32")))]
1684                {
1685                    use crate::sys::{time::__timespec64, weak::weak};
1686
1687                    // Added in glibc 2.34
1688                    weak!(
1689                        fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int;
1690                    );
1691
1692                    if let Some(futimens64) = __futimens64.get() {
1693                        let to_timespec = |time: Option<SystemTime>| time.map(|time| time.t.to_timespec64())
1694                            .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _));
1695                        let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1696                        cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1697                        return Ok(());
1698                    }
1699                }
1700                let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1701                cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1702                Ok(())
1703            }
1704        }
1705    }
1706}
1707
1708impl DirBuilder {
1709    pub fn new() -> DirBuilder {
1710        DirBuilder { mode: 0o777 }
1711    }
1712
1713    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1714        run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1715    }
1716
1717    pub fn set_mode(&mut self, mode: u32) {
1718        self.mode = mode as mode_t;
1719    }
1720}
1721
1722impl fmt::Debug for DirBuilder {
1723    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1724        let DirBuilder { mode } = self;
1725        f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1726    }
1727}
1728
1729impl AsInner<FileDesc> for File {
1730    #[inline]
1731    fn as_inner(&self) -> &FileDesc {
1732        &self.0
1733    }
1734}
1735
1736impl AsInnerMut<FileDesc> for File {
1737    #[inline]
1738    fn as_inner_mut(&mut self) -> &mut FileDesc {
1739        &mut self.0
1740    }
1741}
1742
1743impl IntoInner<FileDesc> for File {
1744    fn into_inner(self) -> FileDesc {
1745        self.0
1746    }
1747}
1748
1749impl FromInner<FileDesc> for File {
1750    fn from_inner(file_desc: FileDesc) -> Self {
1751        Self(file_desc)
1752    }
1753}
1754
1755impl AsFd for File {
1756    #[inline]
1757    fn as_fd(&self) -> BorrowedFd<'_> {
1758        self.0.as_fd()
1759    }
1760}
1761
1762impl AsRawFd for File {
1763    #[inline]
1764    fn as_raw_fd(&self) -> RawFd {
1765        self.0.as_raw_fd()
1766    }
1767}
1768
1769impl IntoRawFd for File {
1770    fn into_raw_fd(self) -> RawFd {
1771        self.0.into_raw_fd()
1772    }
1773}
1774
1775impl FromRawFd for File {
1776    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1777        Self(FromRawFd::from_raw_fd(raw_fd))
1778    }
1779}
1780
1781impl fmt::Debug for File {
1782    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1783        #[cfg(any(target_os = "linux", target_os = "illumos", target_os = "solaris"))]
1784        fn get_path(fd: c_int) -> Option<PathBuf> {
1785            let mut p = PathBuf::from("/proc/self/fd");
1786            p.push(&fd.to_string());
1787            run_path_with_cstr(&p, &readlink).ok()
1788        }
1789
1790        #[cfg(any(target_vendor = "apple", target_os = "netbsd"))]
1791        fn get_path(fd: c_int) -> Option<PathBuf> {
1792            // FIXME: The use of PATH_MAX is generally not encouraged, but it
1793            // is inevitable in this case because Apple targets and NetBSD define `fcntl`
1794            // with `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1795            // alternatives. If a better method is invented, it should be used
1796            // instead.
1797            let mut buf = vec![0; libc::PATH_MAX as usize];
1798            let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1799            if n == -1 {
1800                cfg_select! {
1801                    target_os = "netbsd" => {
1802                        // fallback to procfs as last resort
1803                        let mut p = PathBuf::from("/proc/self/fd");
1804                        p.push(&fd.to_string());
1805                        return run_path_with_cstr(&p, &readlink).ok()
1806                    }
1807                    _ => {
1808                        return None;
1809                    }
1810                }
1811            }
1812            let l = buf.iter().position(|&c| c == 0).unwrap();
1813            buf.truncate(l as usize);
1814            buf.shrink_to_fit();
1815            Some(PathBuf::from(OsString::from_vec(buf)))
1816        }
1817
1818        #[cfg(target_os = "freebsd")]
1819        fn get_path(fd: c_int) -> Option<PathBuf> {
1820            let info = Box::<libc::kinfo_file>::new_zeroed();
1821            let mut info = unsafe { info.assume_init() };
1822            info.kf_structsize = size_of::<libc::kinfo_file>() as libc::c_int;
1823            let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
1824            if n == -1 {
1825                return None;
1826            }
1827            let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
1828            Some(PathBuf::from(OsString::from_vec(buf)))
1829        }
1830
1831        #[cfg(target_os = "vxworks")]
1832        fn get_path(fd: c_int) -> Option<PathBuf> {
1833            let mut buf = vec![0; libc::PATH_MAX as usize];
1834            let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1835            if n == -1 {
1836                return None;
1837            }
1838            let l = buf.iter().position(|&c| c == 0).unwrap();
1839            buf.truncate(l as usize);
1840            Some(PathBuf::from(OsString::from_vec(buf)))
1841        }
1842
1843        #[cfg(not(any(
1844            target_os = "linux",
1845            target_os = "vxworks",
1846            target_os = "freebsd",
1847            target_os = "netbsd",
1848            target_os = "illumos",
1849            target_os = "solaris",
1850            target_vendor = "apple",
1851        )))]
1852        fn get_path(_fd: c_int) -> Option<PathBuf> {
1853            // FIXME(#24570): implement this for other Unix platforms
1854            None
1855        }
1856
1857        fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1858            let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1859            if mode == -1 {
1860                return None;
1861            }
1862            match mode & libc::O_ACCMODE {
1863                libc::O_RDONLY => Some((true, false)),
1864                libc::O_RDWR => Some((true, true)),
1865                libc::O_WRONLY => Some((false, true)),
1866                _ => None,
1867            }
1868        }
1869
1870        let fd = self.as_raw_fd();
1871        let mut b = f.debug_struct("File");
1872        b.field("fd", &fd);
1873        if let Some(path) = get_path(fd) {
1874            b.field("path", &path);
1875        }
1876        if let Some((read, write)) = get_mode(fd) {
1877            b.field("read", &read).field("write", &write);
1878        }
1879        b.finish()
1880    }
1881}
1882
1883// Format in octal, followed by the mode format used in `ls -l`.
1884//
1885// References:
1886//   https://pubs.opengroup.org/onlinepubs/009696899/utilities/ls.html
1887//   https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html
1888//   https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
1889//
1890// Example:
1891//   0o100664 (-rw-rw-r--)
1892impl fmt::Debug for Mode {
1893    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894        let Self(mode) = *self;
1895        write!(f, "0o{mode:06o}")?;
1896
1897        let entry_type = match mode & libc::S_IFMT {
1898            libc::S_IFDIR => 'd',
1899            libc::S_IFBLK => 'b',
1900            libc::S_IFCHR => 'c',
1901            libc::S_IFLNK => 'l',
1902            libc::S_IFIFO => 'p',
1903            libc::S_IFREG => '-',
1904            _ => return Ok(()),
1905        };
1906
1907        f.write_str(" (")?;
1908        f.write_char(entry_type)?;
1909
1910        // Owner permissions
1911        f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1912        f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1913        let owner_executable = mode & libc::S_IXUSR != 0;
1914        let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1915        f.write_char(match (owner_executable, setuid) {
1916            (true, true) => 's',  // executable and setuid
1917            (false, true) => 'S', // setuid
1918            (true, false) => 'x', // executable
1919            (false, false) => '-',
1920        })?;
1921
1922        // Group permissions
1923        f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1924        f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1925        let group_executable = mode & libc::S_IXGRP != 0;
1926        let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1927        f.write_char(match (group_executable, setgid) {
1928            (true, true) => 's',  // executable and setgid
1929            (false, true) => 'S', // setgid
1930            (true, false) => 'x', // executable
1931            (false, false) => '-',
1932        })?;
1933
1934        // Other permissions
1935        f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1936        f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1937        let other_executable = mode & libc::S_IXOTH != 0;
1938        let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1939        f.write_char(match (entry_type, other_executable, sticky) {
1940            ('d', true, true) => 't',  // searchable and restricted deletion
1941            ('d', false, true) => 'T', // restricted deletion
1942            (_, true, _) => 'x',       // executable
1943            (_, false, _) => '-',
1944        })?;
1945
1946        f.write_char(')')
1947    }
1948}
1949
1950pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1951    let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1952    if ptr.is_null() {
1953        Err(Error::last_os_error())
1954    } else {
1955        let root = path.to_path_buf();
1956        let inner = InnerReadDir { dirp: Dir(ptr), root };
1957        Ok(ReadDir::new(inner))
1958    }
1959}
1960
1961pub fn unlink(p: &CStr) -> io::Result<()> {
1962    cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ())
1963}
1964
1965pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
1966    cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1967}
1968
1969pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1970    cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
1971}
1972
1973pub fn rmdir(p: &CStr) -> io::Result<()> {
1974    cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ())
1975}
1976
1977pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> {
1978    let p = c_path.as_ptr();
1979
1980    let mut buf = Vec::with_capacity(256);
1981
1982    loop {
1983        let buf_read =
1984            cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1985
1986        unsafe {
1987            buf.set_len(buf_read);
1988        }
1989
1990        if buf_read != buf.capacity() {
1991            buf.shrink_to_fit();
1992
1993            return Ok(PathBuf::from(OsString::from_vec(buf)));
1994        }
1995
1996        // Trigger the internal buffer resizing logic of `Vec` by requiring
1997        // more space than the current capacity. The length is guaranteed to be
1998        // the same as the capacity due to the if statement above.
1999        buf.reserve(1);
2000    }
2001}
2002
2003pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> {
2004    cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
2005}
2006
2007pub fn link(original: &CStr, link: &CStr) -> io::Result<()> {
2008    cfg_select! {
2009        any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon", target_os = "vita", target_env = "nto70") => {
2010            // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
2011            // it implementation-defined whether `link` follows symlinks, so rely on the
2012            // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
2013            // Android has `linkat` on newer versions, but we happen to know `link`
2014            // always has the correct behavior, so it's here as well.
2015            cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
2016        }
2017        _ => {
2018            // Where we can, use `linkat` instead of `link`; see the comment above
2019            // this one for details on why.
2020            cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
2021        }
2022    }
2023    Ok(())
2024}
2025
2026pub fn stat(p: &CStr) -> io::Result<FileAttr> {
2027    cfg_has_statx! {
2028        if let Some(ret) = unsafe { try_statx(
2029            libc::AT_FDCWD,
2030            p.as_ptr(),
2031            libc::AT_STATX_SYNC_AS_STAT,
2032            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2033        ) } {
2034            return ret;
2035        }
2036    }
2037
2038    let mut stat: stat64 = unsafe { mem::zeroed() };
2039    cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
2040    Ok(FileAttr::from_stat64(stat))
2041}
2042
2043pub fn lstat(p: &CStr) -> io::Result<FileAttr> {
2044    cfg_has_statx! {
2045        if let Some(ret) = unsafe { try_statx(
2046            libc::AT_FDCWD,
2047            p.as_ptr(),
2048            libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
2049            libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2050        ) } {
2051            return ret;
2052        }
2053    }
2054
2055    let mut stat: stat64 = unsafe { mem::zeroed() };
2056    cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
2057    Ok(FileAttr::from_stat64(stat))
2058}
2059
2060pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
2061    let r = unsafe { libc::realpath(path.as_ptr(), ptr::null_mut()) };
2062    if r.is_null() {
2063        return Err(io::Error::last_os_error());
2064    }
2065    Ok(PathBuf::from(OsString::from_vec(unsafe {
2066        let buf = CStr::from_ptr(r).to_bytes().to_vec();
2067        libc::free(r as *mut _);
2068        buf
2069    })))
2070}
2071
2072fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2073    use crate::fs::File;
2074    use crate::sys::fs::common::NOT_FILE_ERROR;
2075
2076    let reader = File::open(from)?;
2077    let metadata = reader.metadata()?;
2078    if !metadata.is_file() {
2079        return Err(NOT_FILE_ERROR);
2080    }
2081    Ok((reader, metadata))
2082}
2083
2084#[cfg(target_os = "espidf")]
2085fn open_to_and_set_permissions(
2086    to: &Path,
2087    _reader_metadata: &crate::fs::Metadata,
2088) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2089    use crate::fs::OpenOptions;
2090    let writer = OpenOptions::new().open(to)?;
2091    let writer_metadata = writer.metadata()?;
2092    Ok((writer, writer_metadata))
2093}
2094
2095#[cfg(not(target_os = "espidf"))]
2096fn open_to_and_set_permissions(
2097    to: &Path,
2098    reader_metadata: &crate::fs::Metadata,
2099) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2100    use crate::fs::OpenOptions;
2101    use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
2102
2103    let perm = reader_metadata.permissions();
2104    let writer = OpenOptions::new()
2105        // create the file with the correct mode right away
2106        .mode(perm.mode())
2107        .write(true)
2108        .create(true)
2109        .truncate(true)
2110        .open(to)?;
2111    let writer_metadata = writer.metadata()?;
2112    // fchmod is broken on vita
2113    #[cfg(not(target_os = "vita"))]
2114    if writer_metadata.is_file() {
2115        // Set the correct file permissions, in case the file already existed.
2116        // Don't set the permissions on already existing non-files like
2117        // pipes/FIFOs or device nodes.
2118        writer.set_permissions(perm)?;
2119    }
2120    Ok((writer, writer_metadata))
2121}
2122
2123mod cfm {
2124    use crate::fs::{File, Metadata};
2125    use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
2126
2127    #[allow(dead_code)]
2128    pub struct CachedFileMetadata(pub File, pub Metadata);
2129
2130    impl Read for CachedFileMetadata {
2131        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2132            self.0.read(buf)
2133        }
2134        fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2135            self.0.read_vectored(bufs)
2136        }
2137        fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
2138            self.0.read_buf(cursor)
2139        }
2140        #[inline]
2141        fn is_read_vectored(&self) -> bool {
2142            self.0.is_read_vectored()
2143        }
2144        fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2145            self.0.read_to_end(buf)
2146        }
2147        fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2148            self.0.read_to_string(buf)
2149        }
2150    }
2151    impl Write for CachedFileMetadata {
2152        fn write(&mut self, buf: &[u8]) -> Result<usize> {
2153            self.0.write(buf)
2154        }
2155        fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2156            self.0.write_vectored(bufs)
2157        }
2158        #[inline]
2159        fn is_write_vectored(&self) -> bool {
2160            self.0.is_write_vectored()
2161        }
2162        #[inline]
2163        fn flush(&mut self) -> Result<()> {
2164            self.0.flush()
2165        }
2166    }
2167}
2168#[cfg(any(target_os = "linux", target_os = "android"))]
2169pub(crate) use cfm::CachedFileMetadata;
2170
2171#[cfg(not(target_vendor = "apple"))]
2172pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2173    let (reader, reader_metadata) = open_from(from)?;
2174    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2175
2176    io::copy(
2177        &mut cfm::CachedFileMetadata(reader, reader_metadata),
2178        &mut cfm::CachedFileMetadata(writer, writer_metadata),
2179    )
2180}
2181
2182#[cfg(target_vendor = "apple")]
2183pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2184    const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2185
2186    struct FreeOnDrop(libc::copyfile_state_t);
2187    impl Drop for FreeOnDrop {
2188        fn drop(&mut self) {
2189            // The code below ensures that `FreeOnDrop` is never a null pointer
2190            unsafe {
2191                // `copyfile_state_free` returns -1 if the `to` or `from` files
2192                // cannot be closed. However, this is not considered an error.
2193                libc::copyfile_state_free(self.0);
2194            }
2195        }
2196    }
2197
2198    let (reader, reader_metadata) = open_from(from)?;
2199
2200    let clonefile_result = run_path_with_cstr(to, &|to| {
2201        cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2202    });
2203    match clonefile_result {
2204        Ok(_) => return Ok(reader_metadata.len()),
2205        Err(e) => match e.raw_os_error() {
2206            // `fclonefileat` will fail on non-APFS volumes, if the
2207            // destination already exists, or if the source and destination
2208            // are on different devices. In all these cases `fcopyfile`
2209            // should succeed.
2210            Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2211            _ => return Err(e),
2212        },
2213    }
2214
2215    // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
2216    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2217
2218    // We ensure that `FreeOnDrop` never contains a null pointer so it is
2219    // always safe to call `copyfile_state_free`
2220    let state = unsafe {
2221        let state = libc::copyfile_state_alloc();
2222        if state.is_null() {
2223            return Err(crate::io::Error::last_os_error());
2224        }
2225        FreeOnDrop(state)
2226    };
2227
2228    let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2229
2230    cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2231
2232    let mut bytes_copied: libc::off_t = 0;
2233    cvt(unsafe {
2234        libc::copyfile_state_get(
2235            state.0,
2236            libc::COPYFILE_STATE_COPIED as u32,
2237            (&raw mut bytes_copied) as *mut libc::c_void,
2238        )
2239    })?;
2240    Ok(bytes_copied as u64)
2241}
2242
2243pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2244    run_path_with_cstr(path, &|path| {
2245        cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2246            .map(|_| ())
2247    })
2248}
2249
2250pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2251    cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2252    Ok(())
2253}
2254
2255#[cfg(not(target_os = "vxworks"))]
2256pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2257    run_path_with_cstr(path, &|path| {
2258        cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2259            .map(|_| ())
2260    })
2261}
2262
2263#[cfg(target_os = "vxworks")]
2264pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2265    let (_, _, _) = (path, uid, gid);
2266    Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2267}
2268
2269#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
2270pub fn chroot(dir: &Path) -> io::Result<()> {
2271    run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2272}
2273
2274#[cfg(target_os = "vxworks")]
2275pub fn chroot(dir: &Path) -> io::Result<()> {
2276    let _ = dir;
2277    Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2278}
2279
2280pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
2281    run_path_with_cstr(path, &|path| {
2282        cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
2283    })
2284}
2285
2286pub use remove_dir_impl::remove_dir_all;
2287
2288// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri
2289#[cfg(any(
2290    target_os = "redox",
2291    target_os = "espidf",
2292    target_os = "horizon",
2293    target_os = "vita",
2294    target_os = "nto",
2295    target_os = "vxworks",
2296    miri
2297))]
2298mod remove_dir_impl {
2299    pub use crate::sys::fs::common::remove_dir_all;
2300}
2301
2302// Modern implementation using openat(), unlinkat() and fdopendir()
2303#[cfg(not(any(
2304    target_os = "redox",
2305    target_os = "espidf",
2306    target_os = "horizon",
2307    target_os = "vita",
2308    target_os = "nto",
2309    target_os = "vxworks",
2310    miri
2311)))]
2312mod remove_dir_impl {
2313    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2314    use libc::{fdopendir, openat, unlinkat};
2315    #[cfg(all(target_os = "linux", target_env = "gnu"))]
2316    use libc::{fdopendir, openat64 as openat, unlinkat};
2317
2318    use super::{Dir, DirEntry, InnerReadDir, ReadDir, lstat};
2319    use crate::ffi::CStr;
2320    use crate::io;
2321    use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
2322    use crate::os::unix::prelude::{OwnedFd, RawFd};
2323    use crate::path::{Path, PathBuf};
2324    use crate::sys::common::small_c_string::run_path_with_cstr;
2325    use crate::sys::{cvt, cvt_r};
2326    use crate::sys_common::ignore_notfound;
2327
2328    pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2329        let fd = cvt_r(|| unsafe {
2330            openat(
2331                parent_fd.unwrap_or(libc::AT_FDCWD),
2332                p.as_ptr(),
2333                libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2334            )
2335        })?;
2336        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2337    }
2338
2339    fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2340        let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2341        if ptr.is_null() {
2342            return Err(io::Error::last_os_error());
2343        }
2344        let dirp = Dir(ptr);
2345        // file descriptor is automatically closed by libc::closedir() now, so give up ownership
2346        let new_parent_fd = dir_fd.into_raw_fd();
2347        // a valid root is not needed because we do not call any functions involving the full path
2348        // of the `DirEntry`s.
2349        let dummy_root = PathBuf::new();
2350        let inner = InnerReadDir { dirp, root: dummy_root };
2351        Ok((ReadDir::new(inner), new_parent_fd))
2352    }
2353
2354    #[cfg(any(
2355        target_os = "solaris",
2356        target_os = "illumos",
2357        target_os = "haiku",
2358        target_os = "vxworks",
2359        target_os = "aix",
2360    ))]
2361    fn is_dir(_ent: &DirEntry) -> Option<bool> {
2362        None
2363    }
2364
2365    #[cfg(not(any(
2366        target_os = "solaris",
2367        target_os = "illumos",
2368        target_os = "haiku",
2369        target_os = "vxworks",
2370        target_os = "aix",
2371    )))]
2372    fn is_dir(ent: &DirEntry) -> Option<bool> {
2373        match ent.entry.d_type {
2374            libc::DT_UNKNOWN => None,
2375            libc::DT_DIR => Some(true),
2376            _ => Some(false),
2377        }
2378    }
2379
2380    fn is_enoent(result: &io::Result<()>) -> bool {
2381        if let Err(err) = result
2382            && matches!(err.raw_os_error(), Some(libc::ENOENT))
2383        {
2384            true
2385        } else {
2386            false
2387        }
2388    }
2389
2390    fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2391        // try opening as directory
2392        let fd = match openat_nofollow_dironly(parent_fd, &path) {
2393            Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2394                // not a directory - don't traverse further
2395                // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
2396                return match parent_fd {
2397                    // unlink...
2398                    Some(parent_fd) => {
2399                        cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2400                    }
2401                    // ...unless this was supposed to be the deletion root directory
2402                    None => Err(err),
2403                };
2404            }
2405            result => result?,
2406        };
2407
2408        // open the directory passing ownership of the fd
2409        let (dir, fd) = fdreaddir(fd)?;
2410        for child in dir {
2411            let child = child?;
2412            let child_name = child.name_cstr();
2413            // we need an inner try block, because if one of these
2414            // directories has already been deleted, then we need to
2415            // continue the loop, not return ok.
2416            let result: io::Result<()> = try {
2417                match is_dir(&child) {
2418                    Some(true) => {
2419                        remove_dir_all_recursive(Some(fd), child_name)?;
2420                    }
2421                    Some(false) => {
2422                        cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
2423                    }
2424                    None => {
2425                        // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
2426                        // if the process has the appropriate privileges. This however can causing orphaned
2427                        // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
2428                        // into it first instead of trying to unlink() it.
2429                        remove_dir_all_recursive(Some(fd), child_name)?;
2430                    }
2431                }
2432            };
2433            if result.is_err() && !is_enoent(&result) {
2434                return result;
2435            }
2436        }
2437
2438        // unlink the directory after removing its contents
2439        ignore_notfound(cvt(unsafe {
2440            unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2441        }))?;
2442        Ok(())
2443    }
2444
2445    fn remove_dir_all_modern(p: &CStr) -> io::Result<()> {
2446        // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
2447        // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
2448        // into symlinks.
2449        let attr = lstat(p)?;
2450        if attr.file_type().is_symlink() {
2451            super::unlink(p)
2452        } else {
2453            remove_dir_all_recursive(None, &p)
2454        }
2455    }
2456
2457    pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2458        run_path_with_cstr(p, &remove_dir_all_modern)
2459    }
2460}