std/sys/pal/unix/
fs.rs

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