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