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 currently",
572        ))
573    }
574
575    #[cfg(target_os = "vita")]
576    pub fn created(&self) -> io::Result<SystemTime> {
577        SystemTime::new(self.stat.st_ctime as i64, 0)
578    }
579}
580
581#[cfg(target_os = "nto")]
582impl FileAttr {
583    pub fn modified(&self) -> io::Result<SystemTime> {
584        SystemTime::new(self.stat.st_mtim.tv_sec, self.stat.st_mtim.tv_nsec)
585    }
586
587    pub fn accessed(&self) -> io::Result<SystemTime> {
588        SystemTime::new(self.stat.st_atim.tv_sec, self.stat.st_atim.tv_nsec)
589    }
590
591    pub fn created(&self) -> io::Result<SystemTime> {
592        SystemTime::new(self.stat.st_ctim.tv_sec, self.stat.st_ctim.tv_nsec)
593    }
594}
595
596impl AsInner<stat64> for FileAttr {
597    #[inline]
598    fn as_inner(&self) -> &stat64 {
599        &self.stat
600    }
601}
602
603impl FilePermissions {
604    pub fn readonly(&self) -> bool {
605        // check if any class (owner, group, others) has write permission
606        self.mode & 0o222 == 0
607    }
608
609    pub fn set_readonly(&mut self, readonly: bool) {
610        if readonly {
611            // remove write permission for all classes; equivalent to `chmod a-w <file>`
612            self.mode &= !0o222;
613        } else {
614            // add write permission for all classes; equivalent to `chmod a+w <file>`
615            self.mode |= 0o222;
616        }
617    }
618    pub fn mode(&self) -> u32 {
619        self.mode as u32
620    }
621}
622
623impl FileTimes {
624    pub fn set_accessed(&mut self, t: SystemTime) {
625        self.accessed = Some(t);
626    }
627
628    pub fn set_modified(&mut self, t: SystemTime) {
629        self.modified = Some(t);
630    }
631
632    #[cfg(target_vendor = "apple")]
633    pub fn set_created(&mut self, t: SystemTime) {
634        self.created = Some(t);
635    }
636}
637
638impl FileType {
639    pub fn is_dir(&self) -> bool {
640        self.is(libc::S_IFDIR)
641    }
642    pub fn is_file(&self) -> bool {
643        self.is(libc::S_IFREG)
644    }
645    pub fn is_symlink(&self) -> bool {
646        self.is(libc::S_IFLNK)
647    }
648
649    pub fn is(&self, mode: mode_t) -> bool {
650        self.masked() == mode
651    }
652
653    fn masked(&self) -> mode_t {
654        self.mode & libc::S_IFMT
655    }
656}
657
658impl fmt::Debug for FileType {
659    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
660        let FileType { mode } = self;
661        f.debug_struct("FileType").field("mode", &Mode(*mode)).finish()
662    }
663}
664
665impl FromInner<u32> for FilePermissions {
666    fn from_inner(mode: u32) -> FilePermissions {
667        FilePermissions { mode: mode as mode_t }
668    }
669}
670
671impl fmt::Debug for FilePermissions {
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        let FilePermissions { mode } = self;
674        f.debug_struct("FilePermissions").field("mode", &Mode(*mode)).finish()
675    }
676}
677
678impl fmt::Debug for ReadDir {
679    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680        // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
681        // Thus the result will be e g 'ReadDir("/home")'
682        fmt::Debug::fmt(&*self.inner.root, f)
683    }
684}
685
686impl Iterator for ReadDir {
687    type Item = io::Result<DirEntry>;
688
689    #[cfg(any(
690        target_os = "android",
691        target_os = "linux",
692        target_os = "solaris",
693        target_os = "fuchsia",
694        target_os = "redox",
695        target_os = "illumos",
696        target_os = "aix",
697        target_os = "nto",
698        target_os = "vita",
699        target_os = "hurd",
700    ))]
701    fn next(&mut self) -> Option<io::Result<DirEntry>> {
702        if self.end_of_stream {
703            return None;
704        }
705
706        unsafe {
707            loop {
708                // As of POSIX.1-2017, readdir() is not required to be thread safe; only
709                // readdir_r() is. However, readdir_r() cannot correctly handle platforms
710                // with unlimited or variable NAME_MAX. Many modern platforms guarantee
711                // thread safety for readdir() as long an individual DIR* is not accessed
712                // concurrently, which is sufficient for Rust.
713                super::os::set_errno(0);
714                let entry_ptr: *const dirent64 = readdir64(self.inner.dirp.0);
715                if entry_ptr.is_null() {
716                    // We either encountered an error, or reached the end. Either way,
717                    // the next call to next() should return None.
718                    self.end_of_stream = true;
719
720                    // To distinguish between errors and end-of-directory, we had to clear
721                    // errno beforehand to check for an error now.
722                    return match super::os::errno() {
723                        0 => None,
724                        e => Some(Err(Error::from_raw_os_error(e))),
725                    };
726                }
727
728                // The dirent64 struct is a weird imaginary thing that isn't ever supposed
729                // to be worked with by value. Its trailing d_name field is declared
730                // variously as [c_char; 256] or [c_char; 1] on different systems but
731                // either way that size is meaningless; only the offset of d_name is
732                // meaningful. The dirent64 pointers that libc returns from readdir64 are
733                // allowed to point to allocations smaller _or_ LARGER than implied by the
734                // definition of the struct.
735                //
736                // As such, we need to be even more careful with dirent64 than if its
737                // contents were "simply" partially initialized data.
738                //
739                // Like for uninitialized contents, converting entry_ptr to `&dirent64`
740                // would not be legal. However, we can use `&raw const (*entry_ptr).d_name`
741                // to refer the fields individually, because that operation is equivalent
742                // to `byte_offset` and thus does not require the full extent of `*entry_ptr`
743                // to be in bounds of the same allocation, only the offset of the field
744                // being referenced.
745
746                // d_name is guaranteed to be null-terminated.
747                let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast());
748                let name_bytes = name.to_bytes();
749                if name_bytes == b"." || name_bytes == b".." {
750                    continue;
751                }
752
753                // When loading from a field, we can skip the `&raw const`; `(*entry_ptr).d_ino` as
754                // a value expression will do the right thing: `byte_offset` to the field and then
755                // only access those bytes.
756                #[cfg(not(target_os = "vita"))]
757                let entry = dirent64_min {
758                    d_ino: (*entry_ptr).d_ino as u64,
759                    #[cfg(not(any(
760                        target_os = "solaris",
761                        target_os = "illumos",
762                        target_os = "aix",
763                        target_os = "nto",
764                    )))]
765                    d_type: (*entry_ptr).d_type as u8,
766                };
767
768                #[cfg(target_os = "vita")]
769                let entry = dirent64_min { d_ino: 0u64 };
770
771                return Some(Ok(DirEntry {
772                    entry,
773                    name: name.to_owned(),
774                    dir: Arc::clone(&self.inner),
775                }));
776            }
777        }
778    }
779
780    #[cfg(not(any(
781        target_os = "android",
782        target_os = "linux",
783        target_os = "solaris",
784        target_os = "fuchsia",
785        target_os = "redox",
786        target_os = "illumos",
787        target_os = "aix",
788        target_os = "nto",
789        target_os = "vita",
790        target_os = "hurd",
791    )))]
792    fn next(&mut self) -> Option<io::Result<DirEntry>> {
793        if self.end_of_stream {
794            return None;
795        }
796
797        unsafe {
798            let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
799            let mut entry_ptr = ptr::null_mut();
800            loop {
801                let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
802                if err != 0 {
803                    if entry_ptr.is_null() {
804                        // We encountered an error (which will be returned in this iteration), but
805                        // we also reached the end of the directory stream. The `end_of_stream`
806                        // flag is enabled to make sure that we return `None` in the next iteration
807                        // (instead of looping forever)
808                        self.end_of_stream = true;
809                    }
810                    return Some(Err(Error::from_raw_os_error(err)));
811                }
812                if entry_ptr.is_null() {
813                    return None;
814                }
815                if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
816                    return Some(Ok(ret));
817                }
818            }
819        }
820    }
821}
822
823/// Aborts the process if a file desceriptor is not open, if debug asserts are enabled
824///
825/// Many IO syscalls can't be fully trusted about EBADF error codes because those
826/// might get bubbled up from a remote FUSE server rather than the file descriptor
827/// in the current process being invalid.
828///
829/// So we check file flags instead which live on the file descriptor and not the underlying file.
830/// The downside is that it costs an extra syscall, so we only do it for debug.
831#[inline]
832pub(crate) fn debug_assert_fd_is_open(fd: RawFd) {
833    use crate::sys::os::errno;
834
835    // this is similar to assert_unsafe_precondition!() but it doesn't require const
836    if core::ub_checks::check_library_ub() {
837        if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 && errno() == libc::EBADF {
838            rtabort!("IO Safety violation: owned file descriptor already closed");
839        }
840    }
841}
842
843impl Drop for Dir {
844    fn drop(&mut self) {
845        // dirfd isn't supported everywhere
846        #[cfg(not(any(
847            miri,
848            target_os = "redox",
849            target_os = "nto",
850            target_os = "vita",
851            target_os = "hurd",
852            target_os = "espidf",
853            target_os = "horizon",
854            target_os = "vxworks",
855            target_os = "rtems",
856            target_os = "nuttx",
857        )))]
858        {
859            let fd = unsafe { libc::dirfd(self.0) };
860            debug_assert_fd_is_open(fd);
861        }
862        let r = unsafe { libc::closedir(self.0) };
863        assert!(
864            r == 0 || crate::io::Error::last_os_error().is_interrupted(),
865            "unexpected error during closedir: {:?}",
866            crate::io::Error::last_os_error()
867        );
868    }
869}
870
871impl DirEntry {
872    pub fn path(&self) -> PathBuf {
873        self.dir.root.join(self.file_name_os_str())
874    }
875
876    pub fn file_name(&self) -> OsString {
877        self.file_name_os_str().to_os_string()
878    }
879
880    #[cfg(all(
881        any(
882            all(target_os = "linux", not(target_env = "musl")),
883            target_os = "android",
884            target_os = "fuchsia",
885            target_os = "hurd"
886        ),
887        not(miri) // no dirfd on Miri
888    ))]
889    pub fn metadata(&self) -> io::Result<FileAttr> {
890        let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
891        let name = self.name_cstr().as_ptr();
892
893        cfg_has_statx! {
894            if let Some(ret) = unsafe { try_statx(
895                fd,
896                name,
897                libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
898                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
899            ) } {
900                return ret;
901            }
902        }
903
904        let mut stat: stat64 = unsafe { mem::zeroed() };
905        cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
906        Ok(FileAttr::from_stat64(stat))
907    }
908
909    #[cfg(any(
910        not(any(
911            all(target_os = "linux", not(target_env = "musl")),
912            target_os = "android",
913            target_os = "fuchsia",
914            target_os = "hurd",
915        )),
916        miri
917    ))]
918    pub fn metadata(&self) -> io::Result<FileAttr> {
919        lstat(&self.path())
920    }
921
922    #[cfg(any(
923        target_os = "solaris",
924        target_os = "illumos",
925        target_os = "haiku",
926        target_os = "vxworks",
927        target_os = "aix",
928        target_os = "nto",
929        target_os = "vita",
930    ))]
931    pub fn file_type(&self) -> io::Result<FileType> {
932        self.metadata().map(|m| m.file_type())
933    }
934
935    #[cfg(not(any(
936        target_os = "solaris",
937        target_os = "illumos",
938        target_os = "haiku",
939        target_os = "vxworks",
940        target_os = "aix",
941        target_os = "nto",
942        target_os = "vita",
943    )))]
944    pub fn file_type(&self) -> io::Result<FileType> {
945        match self.entry.d_type {
946            libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
947            libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
948            libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
949            libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
950            libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
951            libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
952            libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
953            _ => self.metadata().map(|m| m.file_type()),
954        }
955    }
956
957    #[cfg(any(
958        target_os = "linux",
959        target_os = "emscripten",
960        target_os = "android",
961        target_os = "solaris",
962        target_os = "illumos",
963        target_os = "haiku",
964        target_os = "l4re",
965        target_os = "fuchsia",
966        target_os = "redox",
967        target_os = "vxworks",
968        target_os = "espidf",
969        target_os = "horizon",
970        target_os = "vita",
971        target_os = "aix",
972        target_os = "nto",
973        target_os = "hurd",
974        target_os = "rtems",
975        target_vendor = "apple",
976    ))]
977    pub fn ino(&self) -> u64 {
978        self.entry.d_ino as u64
979    }
980
981    #[cfg(any(
982        target_os = "freebsd",
983        target_os = "openbsd",
984        target_os = "netbsd",
985        target_os = "dragonfly"
986    ))]
987    pub fn ino(&self) -> u64 {
988        self.entry.d_fileno as u64
989    }
990
991    #[cfg(target_os = "nuttx")]
992    pub fn ino(&self) -> u64 {
993        // Leave this 0 for now, as NuttX does not provide an inode number
994        // in its directory entries.
995        0
996    }
997
998    #[cfg(any(
999        target_os = "netbsd",
1000        target_os = "openbsd",
1001        target_os = "freebsd",
1002        target_os = "dragonfly",
1003        target_vendor = "apple",
1004    ))]
1005    fn name_bytes(&self) -> &[u8] {
1006        use crate::slice;
1007        unsafe {
1008            slice::from_raw_parts(
1009                self.entry.d_name.as_ptr() as *const u8,
1010                self.entry.d_namlen as usize,
1011            )
1012        }
1013    }
1014    #[cfg(not(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        self.name_cstr().to_bytes()
1023    }
1024
1025    #[cfg(not(any(
1026        target_os = "android",
1027        target_os = "linux",
1028        target_os = "solaris",
1029        target_os = "illumos",
1030        target_os = "fuchsia",
1031        target_os = "redox",
1032        target_os = "aix",
1033        target_os = "nto",
1034        target_os = "vita",
1035        target_os = "hurd",
1036    )))]
1037    fn name_cstr(&self) -> &CStr {
1038        unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
1039    }
1040    #[cfg(any(
1041        target_os = "android",
1042        target_os = "linux",
1043        target_os = "solaris",
1044        target_os = "illumos",
1045        target_os = "fuchsia",
1046        target_os = "redox",
1047        target_os = "aix",
1048        target_os = "nto",
1049        target_os = "vita",
1050        target_os = "hurd",
1051    ))]
1052    fn name_cstr(&self) -> &CStr {
1053        &self.name
1054    }
1055
1056    pub fn file_name_os_str(&self) -> &OsStr {
1057        OsStr::from_bytes(self.name_bytes())
1058    }
1059}
1060
1061impl OpenOptions {
1062    pub fn new() -> OpenOptions {
1063        OpenOptions {
1064            // generic
1065            read: false,
1066            write: false,
1067            append: false,
1068            truncate: false,
1069            create: false,
1070            create_new: false,
1071            // system-specific
1072            custom_flags: 0,
1073            mode: 0o666,
1074        }
1075    }
1076
1077    pub fn read(&mut self, read: bool) {
1078        self.read = read;
1079    }
1080    pub fn write(&mut self, write: bool) {
1081        self.write = write;
1082    }
1083    pub fn append(&mut self, append: bool) {
1084        self.append = append;
1085    }
1086    pub fn truncate(&mut self, truncate: bool) {
1087        self.truncate = truncate;
1088    }
1089    pub fn create(&mut self, create: bool) {
1090        self.create = create;
1091    }
1092    pub fn create_new(&mut self, create_new: bool) {
1093        self.create_new = create_new;
1094    }
1095
1096    pub fn custom_flags(&mut self, flags: i32) {
1097        self.custom_flags = flags;
1098    }
1099    pub fn mode(&mut self, mode: u32) {
1100        self.mode = mode as mode_t;
1101    }
1102
1103    fn get_access_mode(&self) -> io::Result<c_int> {
1104        match (self.read, self.write, self.append) {
1105            (true, false, false) => Ok(libc::O_RDONLY),
1106            (false, true, false) => Ok(libc::O_WRONLY),
1107            (true, true, false) => Ok(libc::O_RDWR),
1108            (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
1109            (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
1110            (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
1111        }
1112    }
1113
1114    fn get_creation_mode(&self) -> io::Result<c_int> {
1115        match (self.write, self.append) {
1116            (true, false) => {}
1117            (false, false) => {
1118                if self.truncate || self.create || self.create_new {
1119                    return Err(Error::from_raw_os_error(libc::EINVAL));
1120                }
1121            }
1122            (_, true) => {
1123                if self.truncate && !self.create_new {
1124                    return Err(Error::from_raw_os_error(libc::EINVAL));
1125                }
1126            }
1127        }
1128
1129        Ok(match (self.create, self.truncate, self.create_new) {
1130            (false, false, false) => 0,
1131            (true, false, false) => libc::O_CREAT,
1132            (false, true, false) => libc::O_TRUNC,
1133            (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
1134            (_, _, true) => libc::O_CREAT | libc::O_EXCL,
1135        })
1136    }
1137}
1138
1139impl fmt::Debug for OpenOptions {
1140    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1141        let OpenOptions { read, write, append, truncate, create, create_new, custom_flags, mode } =
1142            self;
1143        f.debug_struct("OpenOptions")
1144            .field("read", read)
1145            .field("write", write)
1146            .field("append", append)
1147            .field("truncate", truncate)
1148            .field("create", create)
1149            .field("create_new", create_new)
1150            .field("custom_flags", custom_flags)
1151            .field("mode", &Mode(*mode))
1152            .finish()
1153    }
1154}
1155
1156impl File {
1157    pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
1158        run_path_with_cstr(path, &|path| File::open_c(path, opts))
1159    }
1160
1161    pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
1162        let flags = libc::O_CLOEXEC
1163            | opts.get_access_mode()?
1164            | opts.get_creation_mode()?
1165            | (opts.custom_flags as c_int & !libc::O_ACCMODE);
1166        // The third argument of `open64` is documented to have type `mode_t`. On
1167        // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
1168        // However, since this is a variadic function, C integer promotion rules mean that on
1169        // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
1170        let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
1171        Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
1172    }
1173
1174    pub fn file_attr(&self) -> io::Result<FileAttr> {
1175        let fd = self.as_raw_fd();
1176
1177        cfg_has_statx! {
1178            if let Some(ret) = unsafe { try_statx(
1179                fd,
1180                c"".as_ptr() as *const c_char,
1181                libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
1182                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1183            ) } {
1184                return ret;
1185            }
1186        }
1187
1188        let mut stat: stat64 = unsafe { mem::zeroed() };
1189        cvt(unsafe { fstat64(fd, &mut stat) })?;
1190        Ok(FileAttr::from_stat64(stat))
1191    }
1192
1193    pub fn fsync(&self) -> io::Result<()> {
1194        cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
1195        return Ok(());
1196
1197        #[cfg(target_vendor = "apple")]
1198        unsafe fn os_fsync(fd: c_int) -> c_int {
1199            libc::fcntl(fd, libc::F_FULLFSYNC)
1200        }
1201        #[cfg(not(target_vendor = "apple"))]
1202        unsafe fn os_fsync(fd: c_int) -> c_int {
1203            libc::fsync(fd)
1204        }
1205    }
1206
1207    pub fn datasync(&self) -> io::Result<()> {
1208        cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1209        return Ok(());
1210
1211        #[cfg(target_vendor = "apple")]
1212        unsafe fn os_datasync(fd: c_int) -> c_int {
1213            libc::fcntl(fd, libc::F_FULLFSYNC)
1214        }
1215        #[cfg(any(
1216            target_os = "freebsd",
1217            target_os = "fuchsia",
1218            target_os = "linux",
1219            target_os = "android",
1220            target_os = "netbsd",
1221            target_os = "openbsd",
1222            target_os = "nto",
1223            target_os = "hurd",
1224        ))]
1225        unsafe fn os_datasync(fd: c_int) -> c_int {
1226            libc::fdatasync(fd)
1227        }
1228        #[cfg(not(any(
1229            target_os = "android",
1230            target_os = "fuchsia",
1231            target_os = "freebsd",
1232            target_os = "linux",
1233            target_os = "netbsd",
1234            target_os = "openbsd",
1235            target_os = "nto",
1236            target_os = "hurd",
1237            target_vendor = "apple",
1238        )))]
1239        unsafe fn os_datasync(fd: c_int) -> c_int {
1240            libc::fsync(fd)
1241        }
1242    }
1243
1244    #[cfg(any(
1245        target_os = "freebsd",
1246        target_os = "fuchsia",
1247        target_os = "linux",
1248        target_os = "netbsd",
1249        target_vendor = "apple",
1250    ))]
1251    pub fn lock(&self) -> io::Result<()> {
1252        cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1253        return Ok(());
1254    }
1255
1256    #[cfg(not(any(
1257        target_os = "freebsd",
1258        target_os = "fuchsia",
1259        target_os = "linux",
1260        target_os = "netbsd",
1261        target_vendor = "apple",
1262    )))]
1263    pub fn lock(&self) -> io::Result<()> {
1264        Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported"))
1265    }
1266
1267    #[cfg(any(
1268        target_os = "freebsd",
1269        target_os = "fuchsia",
1270        target_os = "linux",
1271        target_os = "netbsd",
1272        target_vendor = "apple",
1273    ))]
1274    pub fn lock_shared(&self) -> io::Result<()> {
1275        cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1276        return Ok(());
1277    }
1278
1279    #[cfg(not(any(
1280        target_os = "freebsd",
1281        target_os = "fuchsia",
1282        target_os = "linux",
1283        target_os = "netbsd",
1284        target_vendor = "apple",
1285    )))]
1286    pub fn lock_shared(&self) -> io::Result<()> {
1287        Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported"))
1288    }
1289
1290    #[cfg(any(
1291        target_os = "freebsd",
1292        target_os = "fuchsia",
1293        target_os = "linux",
1294        target_os = "netbsd",
1295        target_vendor = "apple",
1296    ))]
1297    pub fn try_lock(&self) -> io::Result<bool> {
1298        let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1299        if let Err(ref err) = result {
1300            if err.kind() == io::ErrorKind::WouldBlock {
1301                return Ok(false);
1302            }
1303        }
1304        result?;
1305        return Ok(true);
1306    }
1307
1308    #[cfg(not(any(
1309        target_os = "freebsd",
1310        target_os = "fuchsia",
1311        target_os = "linux",
1312        target_os = "netbsd",
1313        target_vendor = "apple",
1314    )))]
1315    pub fn try_lock(&self) -> io::Result<bool> {
1316        Err(io::const_error!(io::ErrorKind::Unsupported, "try_lock() not supported"))
1317    }
1318
1319    #[cfg(any(
1320        target_os = "freebsd",
1321        target_os = "fuchsia",
1322        target_os = "linux",
1323        target_os = "netbsd",
1324        target_vendor = "apple",
1325    ))]
1326    pub fn try_lock_shared(&self) -> io::Result<bool> {
1327        let result = cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1328        if let Err(ref err) = result {
1329            if err.kind() == io::ErrorKind::WouldBlock {
1330                return Ok(false);
1331            }
1332        }
1333        result?;
1334        return Ok(true);
1335    }
1336
1337    #[cfg(not(any(
1338        target_os = "freebsd",
1339        target_os = "fuchsia",
1340        target_os = "linux",
1341        target_os = "netbsd",
1342        target_vendor = "apple",
1343    )))]
1344    pub fn try_lock_shared(&self) -> io::Result<bool> {
1345        Err(io::const_error!(io::ErrorKind::Unsupported, "try_lock_shared() not supported"))
1346    }
1347
1348    #[cfg(any(
1349        target_os = "freebsd",
1350        target_os = "fuchsia",
1351        target_os = "linux",
1352        target_os = "netbsd",
1353        target_vendor = "apple",
1354    ))]
1355    pub fn unlock(&self) -> io::Result<()> {
1356        cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1357        return Ok(());
1358    }
1359
1360    #[cfg(not(any(
1361        target_os = "freebsd",
1362        target_os = "fuchsia",
1363        target_os = "linux",
1364        target_os = "netbsd",
1365        target_vendor = "apple",
1366    )))]
1367    pub fn unlock(&self) -> io::Result<()> {
1368        Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported"))
1369    }
1370
1371    pub fn truncate(&self, size: u64) -> io::Result<()> {
1372        let size: off64_t =
1373            size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1374        cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1375    }
1376
1377    pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1378        self.0.read(buf)
1379    }
1380
1381    pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1382        self.0.read_vectored(bufs)
1383    }
1384
1385    #[inline]
1386    pub fn is_read_vectored(&self) -> bool {
1387        self.0.is_read_vectored()
1388    }
1389
1390    pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1391        self.0.read_at(buf, offset)
1392    }
1393
1394    pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1395        self.0.read_buf(cursor)
1396    }
1397
1398    pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
1399        self.0.read_vectored_at(bufs, offset)
1400    }
1401
1402    pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1403        self.0.write(buf)
1404    }
1405
1406    pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1407        self.0.write_vectored(bufs)
1408    }
1409
1410    #[inline]
1411    pub fn is_write_vectored(&self) -> bool {
1412        self.0.is_write_vectored()
1413    }
1414
1415    pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1416        self.0.write_at(buf, offset)
1417    }
1418
1419    pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
1420        self.0.write_vectored_at(bufs, offset)
1421    }
1422
1423    #[inline]
1424    pub fn flush(&self) -> io::Result<()> {
1425        Ok(())
1426    }
1427
1428    pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1429        let (whence, pos) = match pos {
1430            // Casting to `i64` is fine, too large values will end up as
1431            // negative which will cause an error in `lseek64`.
1432            SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1433            SeekFrom::End(off) => (libc::SEEK_END, off),
1434            SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1435        };
1436        let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1437        Ok(n as u64)
1438    }
1439
1440    pub fn tell(&self) -> io::Result<u64> {
1441        self.seek(SeekFrom::Current(0))
1442    }
1443
1444    pub fn duplicate(&self) -> io::Result<File> {
1445        self.0.duplicate().map(File)
1446    }
1447
1448    pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1449        cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1450        Ok(())
1451    }
1452
1453    pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1454        #[cfg(not(any(
1455            target_os = "redox",
1456            target_os = "espidf",
1457            target_os = "horizon",
1458            target_os = "vxworks",
1459            target_os = "nuttx",
1460        )))]
1461        let to_timespec = |time: Option<SystemTime>| match time {
1462            Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1463            Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
1464                io::ErrorKind::InvalidInput,
1465                "timestamp is too large to set as a file time",
1466            )),
1467            Some(_) => Err(io::const_error!(
1468                io::ErrorKind::InvalidInput,
1469                "timestamp is too small to set as a file time",
1470            )),
1471            None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
1472        };
1473        cfg_if::cfg_if! {
1474            if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", target_os = "vxworks", target_os = "nuttx"))] {
1475                // Redox doesn't appear to support `UTIME_OMIT`.
1476                // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1477                // the same as for Redox.
1478                // `futimens` and `UTIME_OMIT` are a work in progress for vxworks.
1479                let _ = times;
1480                Err(io::const_error!(
1481                    io::ErrorKind::Unsupported,
1482                    "setting file times not supported",
1483                ))
1484            } else if #[cfg(target_vendor = "apple")] {
1485                let mut buf = [mem::MaybeUninit::<libc::timespec>::uninit(); 3];
1486                let mut num_times = 0;
1487                let mut attrlist: libc::attrlist = unsafe { mem::zeroed() };
1488                attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1489                if times.created.is_some() {
1490                    buf[num_times].write(to_timespec(times.created)?);
1491                    num_times += 1;
1492                    attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1493                }
1494                if times.modified.is_some() {
1495                    buf[num_times].write(to_timespec(times.modified)?);
1496                    num_times += 1;
1497                    attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1498                }
1499                if times.accessed.is_some() {
1500                    buf[num_times].write(to_timespec(times.accessed)?);
1501                    num_times += 1;
1502                    attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1503                }
1504                cvt(unsafe { libc::fsetattrlist(
1505                    self.as_raw_fd(),
1506                    (&raw const attrlist).cast::<libc::c_void>().cast_mut(),
1507                    buf.as_ptr().cast::<libc::c_void>().cast_mut(),
1508                    num_times * mem::size_of::<libc::timespec>(),
1509                    0
1510                ) })?;
1511                Ok(())
1512            } else if #[cfg(target_os = "android")] {
1513                let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1514                // futimens requires Android API level 19
1515                cvt(unsafe {
1516                    weak!(fn futimens(c_int, *const libc::timespec) -> c_int);
1517                    match futimens.get() {
1518                        Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1519                        None => return Err(io::const_error!(
1520                            io::ErrorKind::Unsupported,
1521                            "setting file times requires Android API level >= 19",
1522                        )),
1523                    }
1524                })?;
1525                Ok(())
1526            } else {
1527                #[cfg(all(target_os = "linux", target_env = "gnu", target_pointer_width = "32", not(target_arch = "riscv32")))]
1528                {
1529                    use crate::sys::{time::__timespec64, weak::weak};
1530
1531                    // Added in glibc 2.34
1532                    weak!(fn __futimens64(libc::c_int, *const __timespec64) -> libc::c_int);
1533
1534                    if let Some(futimens64) = __futimens64.get() {
1535                        let to_timespec = |time: Option<SystemTime>| time.map(|time| time.t.to_timespec64())
1536                            .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _));
1537                        let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1538                        cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1539                        return Ok(());
1540                    }
1541                }
1542                let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1543                cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1544                Ok(())
1545            }
1546        }
1547    }
1548}
1549
1550impl DirBuilder {
1551    pub fn new() -> DirBuilder {
1552        DirBuilder { mode: 0o777 }
1553    }
1554
1555    pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1556        run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1557    }
1558
1559    pub fn set_mode(&mut self, mode: u32) {
1560        self.mode = mode as mode_t;
1561    }
1562}
1563
1564impl fmt::Debug for DirBuilder {
1565    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1566        let DirBuilder { mode } = self;
1567        f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1568    }
1569}
1570
1571impl AsInner<FileDesc> for File {
1572    #[inline]
1573    fn as_inner(&self) -> &FileDesc {
1574        &self.0
1575    }
1576}
1577
1578impl AsInnerMut<FileDesc> for File {
1579    #[inline]
1580    fn as_inner_mut(&mut self) -> &mut FileDesc {
1581        &mut self.0
1582    }
1583}
1584
1585impl IntoInner<FileDesc> for File {
1586    fn into_inner(self) -> FileDesc {
1587        self.0
1588    }
1589}
1590
1591impl FromInner<FileDesc> for File {
1592    fn from_inner(file_desc: FileDesc) -> Self {
1593        Self(file_desc)
1594    }
1595}
1596
1597impl AsFd for File {
1598    #[inline]
1599    fn as_fd(&self) -> BorrowedFd<'_> {
1600        self.0.as_fd()
1601    }
1602}
1603
1604impl AsRawFd for File {
1605    #[inline]
1606    fn as_raw_fd(&self) -> RawFd {
1607        self.0.as_raw_fd()
1608    }
1609}
1610
1611impl IntoRawFd for File {
1612    fn into_raw_fd(self) -> RawFd {
1613        self.0.into_raw_fd()
1614    }
1615}
1616
1617impl FromRawFd for File {
1618    unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1619        Self(FromRawFd::from_raw_fd(raw_fd))
1620    }
1621}
1622
1623impl fmt::Debug for File {
1624    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1625        #[cfg(any(target_os = "linux", target_os = "illumos", target_os = "solaris"))]
1626        fn get_path(fd: c_int) -> Option<PathBuf> {
1627            let mut p = PathBuf::from("/proc/self/fd");
1628            p.push(&fd.to_string());
1629            readlink(&p).ok()
1630        }
1631
1632        #[cfg(any(target_vendor = "apple", target_os = "netbsd"))]
1633        fn get_path(fd: c_int) -> Option<PathBuf> {
1634            // FIXME: The use of PATH_MAX is generally not encouraged, but it
1635            // is inevitable in this case because Apple targets and NetBSD define `fcntl`
1636            // with `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1637            // alternatives. If a better method is invented, it should be used
1638            // instead.
1639            let mut buf = vec![0; libc::PATH_MAX as usize];
1640            let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1641            if n == -1 {
1642                cfg_if::cfg_if! {
1643                    if #[cfg(target_os = "netbsd")] {
1644                        // fallback to procfs as last resort
1645                        let mut p = PathBuf::from("/proc/self/fd");
1646                        p.push(&fd.to_string());
1647                        return readlink(&p).ok();
1648                    } else {
1649                        return None;
1650                    }
1651                }
1652            }
1653            let l = buf.iter().position(|&c| c == 0).unwrap();
1654            buf.truncate(l as usize);
1655            buf.shrink_to_fit();
1656            Some(PathBuf::from(OsString::from_vec(buf)))
1657        }
1658
1659        #[cfg(target_os = "freebsd")]
1660        fn get_path(fd: c_int) -> Option<PathBuf> {
1661            let info = Box::<libc::kinfo_file>::new_zeroed();
1662            let mut info = unsafe { info.assume_init() };
1663            info.kf_structsize = mem::size_of::<libc::kinfo_file>() as libc::c_int;
1664            let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
1665            if n == -1 {
1666                return None;
1667            }
1668            let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
1669            Some(PathBuf::from(OsString::from_vec(buf)))
1670        }
1671
1672        #[cfg(target_os = "vxworks")]
1673        fn get_path(fd: c_int) -> Option<PathBuf> {
1674            let mut buf = vec![0; libc::PATH_MAX as usize];
1675            let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1676            if n == -1 {
1677                return None;
1678            }
1679            let l = buf.iter().position(|&c| c == 0).unwrap();
1680            buf.truncate(l as usize);
1681            Some(PathBuf::from(OsString::from_vec(buf)))
1682        }
1683
1684        #[cfg(not(any(
1685            target_os = "linux",
1686            target_os = "vxworks",
1687            target_os = "freebsd",
1688            target_os = "netbsd",
1689            target_os = "illumos",
1690            target_os = "solaris",
1691            target_vendor = "apple",
1692        )))]
1693        fn get_path(_fd: c_int) -> Option<PathBuf> {
1694            // FIXME(#24570): implement this for other Unix platforms
1695            None
1696        }
1697
1698        fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1699            let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1700            if mode == -1 {
1701                return None;
1702            }
1703            match mode & libc::O_ACCMODE {
1704                libc::O_RDONLY => Some((true, false)),
1705                libc::O_RDWR => Some((true, true)),
1706                libc::O_WRONLY => Some((false, true)),
1707                _ => None,
1708            }
1709        }
1710
1711        let fd = self.as_raw_fd();
1712        let mut b = f.debug_struct("File");
1713        b.field("fd", &fd);
1714        if let Some(path) = get_path(fd) {
1715            b.field("path", &path);
1716        }
1717        if let Some((read, write)) = get_mode(fd) {
1718            b.field("read", &read).field("write", &write);
1719        }
1720        b.finish()
1721    }
1722}
1723
1724// Format in octal, followed by the mode format used in `ls -l`.
1725//
1726// References:
1727//   https://pubs.opengroup.org/onlinepubs/009696899/utilities/ls.html
1728//   https://www.gnu.org/software/libc/manual/html_node/Testing-File-Type.html
1729//   https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html
1730//
1731// Example:
1732//   0o100664 (-rw-rw-r--)
1733impl fmt::Debug for Mode {
1734    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1735        let Self(mode) = *self;
1736        write!(f, "0o{mode:06o}")?;
1737
1738        let entry_type = match mode & libc::S_IFMT {
1739            libc::S_IFDIR => 'd',
1740            libc::S_IFBLK => 'b',
1741            libc::S_IFCHR => 'c',
1742            libc::S_IFLNK => 'l',
1743            libc::S_IFIFO => 'p',
1744            libc::S_IFREG => '-',
1745            _ => return Ok(()),
1746        };
1747
1748        f.write_str(" (")?;
1749        f.write_char(entry_type)?;
1750
1751        // Owner permissions
1752        f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1753        f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1754        let owner_executable = mode & libc::S_IXUSR != 0;
1755        let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1756        f.write_char(match (owner_executable, setuid) {
1757            (true, true) => 's',  // executable and setuid
1758            (false, true) => 'S', // setuid
1759            (true, false) => 'x', // executable
1760            (false, false) => '-',
1761        })?;
1762
1763        // Group permissions
1764        f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1765        f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1766        let group_executable = mode & libc::S_IXGRP != 0;
1767        let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1768        f.write_char(match (group_executable, setgid) {
1769            (true, true) => 's',  // executable and setgid
1770            (false, true) => 'S', // setgid
1771            (true, false) => 'x', // executable
1772            (false, false) => '-',
1773        })?;
1774
1775        // Other permissions
1776        f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1777        f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1778        let other_executable = mode & libc::S_IXOTH != 0;
1779        let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1780        f.write_char(match (entry_type, other_executable, sticky) {
1781            ('d', true, true) => 't',  // searchable and restricted deletion
1782            ('d', false, true) => 'T', // restricted deletion
1783            (_, true, _) => 'x',       // executable
1784            (_, false, _) => '-',
1785        })?;
1786
1787        f.write_char(')')
1788    }
1789}
1790
1791pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1792    let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1793    if ptr.is_null() {
1794        Err(Error::last_os_error())
1795    } else {
1796        let root = path.to_path_buf();
1797        let inner = InnerReadDir { dirp: Dir(ptr), root };
1798        Ok(ReadDir::new(inner))
1799    }
1800}
1801
1802pub fn unlink(p: &Path) -> io::Result<()> {
1803    run_path_with_cstr(p, &|p| cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ()))
1804}
1805
1806pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1807    run_path_with_cstr(old, &|old| {
1808        run_path_with_cstr(new, &|new| {
1809            cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1810        })
1811    })
1812}
1813
1814pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1815    run_path_with_cstr(p, &|p| cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ()))
1816}
1817
1818pub fn rmdir(p: &Path) -> io::Result<()> {
1819    run_path_with_cstr(p, &|p| cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ()))
1820}
1821
1822pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1823    run_path_with_cstr(p, &|c_path| {
1824        let p = c_path.as_ptr();
1825
1826        let mut buf = Vec::with_capacity(256);
1827
1828        loop {
1829            let buf_read =
1830                cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })?
1831                    as usize;
1832
1833            unsafe {
1834                buf.set_len(buf_read);
1835            }
1836
1837            if buf_read != buf.capacity() {
1838                buf.shrink_to_fit();
1839
1840                return Ok(PathBuf::from(OsString::from_vec(buf)));
1841            }
1842
1843            // Trigger the internal buffer resizing logic of `Vec` by requiring
1844            // more space than the current capacity. The length is guaranteed to be
1845            // the same as the capacity due to the if statement above.
1846            buf.reserve(1);
1847        }
1848    })
1849}
1850
1851pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1852    run_path_with_cstr(original, &|original| {
1853        run_path_with_cstr(link, &|link| {
1854            cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
1855        })
1856    })
1857}
1858
1859pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1860    run_path_with_cstr(original, &|original| {
1861        run_path_with_cstr(link, &|link| {
1862            cfg_if::cfg_if! {
1863                if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon", target_os = "vita", target_env = "nto70"))] {
1864                    // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1865                    // it implementation-defined whether `link` follows symlinks, so rely on the
1866                    // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1867                    // Android has `linkat` on newer versions, but we happen to know `link`
1868                    // always has the correct behavior, so it's here as well.
1869                    cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1870                } else {
1871                    // Where we can, use `linkat` instead of `link`; see the comment above
1872                    // this one for details on why.
1873                    cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1874                }
1875            }
1876            Ok(())
1877        })
1878    })
1879}
1880
1881pub fn stat(p: &Path) -> io::Result<FileAttr> {
1882    run_path_with_cstr(p, &|p| {
1883        cfg_has_statx! {
1884            if let Some(ret) = unsafe { try_statx(
1885                libc::AT_FDCWD,
1886                p.as_ptr(),
1887                libc::AT_STATX_SYNC_AS_STAT,
1888                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1889            ) } {
1890                return ret;
1891            }
1892        }
1893
1894        let mut stat: stat64 = unsafe { mem::zeroed() };
1895        cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1896        Ok(FileAttr::from_stat64(stat))
1897    })
1898}
1899
1900pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1901    run_path_with_cstr(p, &|p| {
1902        cfg_has_statx! {
1903            if let Some(ret) = unsafe { try_statx(
1904                libc::AT_FDCWD,
1905                p.as_ptr(),
1906                libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1907                libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1908            ) } {
1909                return ret;
1910            }
1911        }
1912
1913        let mut stat: stat64 = unsafe { mem::zeroed() };
1914        cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1915        Ok(FileAttr::from_stat64(stat))
1916    })
1917}
1918
1919pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1920    let r = run_path_with_cstr(p, &|path| unsafe {
1921        Ok(libc::realpath(path.as_ptr(), ptr::null_mut()))
1922    })?;
1923    if r.is_null() {
1924        return Err(io::Error::last_os_error());
1925    }
1926    Ok(PathBuf::from(OsString::from_vec(unsafe {
1927        let buf = CStr::from_ptr(r).to_bytes().to_vec();
1928        libc::free(r as *mut _);
1929        buf
1930    })))
1931}
1932
1933fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1934    use crate::fs::File;
1935    use crate::sys_common::fs::NOT_FILE_ERROR;
1936
1937    let reader = File::open(from)?;
1938    let metadata = reader.metadata()?;
1939    if !metadata.is_file() {
1940        return Err(NOT_FILE_ERROR);
1941    }
1942    Ok((reader, metadata))
1943}
1944
1945#[cfg(target_os = "espidf")]
1946fn open_to_and_set_permissions(
1947    to: &Path,
1948    _reader_metadata: &crate::fs::Metadata,
1949) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1950    use crate::fs::OpenOptions;
1951    let writer = OpenOptions::new().open(to)?;
1952    let writer_metadata = writer.metadata()?;
1953    Ok((writer, writer_metadata))
1954}
1955
1956#[cfg(not(target_os = "espidf"))]
1957fn open_to_and_set_permissions(
1958    to: &Path,
1959    reader_metadata: &crate::fs::Metadata,
1960) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1961    use crate::fs::OpenOptions;
1962    use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1963
1964    let perm = reader_metadata.permissions();
1965    let writer = OpenOptions::new()
1966        // create the file with the correct mode right away
1967        .mode(perm.mode())
1968        .write(true)
1969        .create(true)
1970        .truncate(true)
1971        .open(to)?;
1972    let writer_metadata = writer.metadata()?;
1973    // fchmod is broken on vita
1974    #[cfg(not(target_os = "vita"))]
1975    if writer_metadata.is_file() {
1976        // Set the correct file permissions, in case the file already existed.
1977        // Don't set the permissions on already existing non-files like
1978        // pipes/FIFOs or device nodes.
1979        writer.set_permissions(perm)?;
1980    }
1981    Ok((writer, writer_metadata))
1982}
1983
1984mod cfm {
1985    use crate::fs::{File, Metadata};
1986    use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
1987
1988    #[allow(dead_code)]
1989    pub struct CachedFileMetadata(pub File, pub Metadata);
1990
1991    impl Read for CachedFileMetadata {
1992        fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
1993            self.0.read(buf)
1994        }
1995        fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
1996            self.0.read_vectored(bufs)
1997        }
1998        fn read_buf(&mut self, cursor: BorrowedCursor<'_>) -> Result<()> {
1999            self.0.read_buf(cursor)
2000        }
2001        #[inline]
2002        fn is_read_vectored(&self) -> bool {
2003            self.0.is_read_vectored()
2004        }
2005        fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2006            self.0.read_to_end(buf)
2007        }
2008        fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2009            self.0.read_to_string(buf)
2010        }
2011    }
2012    impl Write for CachedFileMetadata {
2013        fn write(&mut self, buf: &[u8]) -> Result<usize> {
2014            self.0.write(buf)
2015        }
2016        fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2017            self.0.write_vectored(bufs)
2018        }
2019        #[inline]
2020        fn is_write_vectored(&self) -> bool {
2021            self.0.is_write_vectored()
2022        }
2023        #[inline]
2024        fn flush(&mut self) -> Result<()> {
2025            self.0.flush()
2026        }
2027    }
2028}
2029#[cfg(any(target_os = "linux", target_os = "android"))]
2030pub(crate) use cfm::CachedFileMetadata;
2031
2032#[cfg(not(target_vendor = "apple"))]
2033pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2034    let (reader, reader_metadata) = open_from(from)?;
2035    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2036
2037    io::copy(
2038        &mut cfm::CachedFileMetadata(reader, reader_metadata),
2039        &mut cfm::CachedFileMetadata(writer, writer_metadata),
2040    )
2041}
2042
2043#[cfg(target_vendor = "apple")]
2044pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2045    const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2046
2047    struct FreeOnDrop(libc::copyfile_state_t);
2048    impl Drop for FreeOnDrop {
2049        fn drop(&mut self) {
2050            // The code below ensures that `FreeOnDrop` is never a null pointer
2051            unsafe {
2052                // `copyfile_state_free` returns -1 if the `to` or `from` files
2053                // cannot be closed. However, this is not considered an error.
2054                libc::copyfile_state_free(self.0);
2055            }
2056        }
2057    }
2058
2059    let (reader, reader_metadata) = open_from(from)?;
2060
2061    let clonefile_result = run_path_with_cstr(to, &|to| {
2062        cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2063    });
2064    match clonefile_result {
2065        Ok(_) => return Ok(reader_metadata.len()),
2066        Err(e) => match e.raw_os_error() {
2067            // `fclonefileat` will fail on non-APFS volumes, if the
2068            // destination already exists, or if the source and destination
2069            // are on different devices. In all these cases `fcopyfile`
2070            // should succeed.
2071            Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2072            _ => return Err(e),
2073        },
2074    }
2075
2076    // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
2077    let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2078
2079    // We ensure that `FreeOnDrop` never contains a null pointer so it is
2080    // always safe to call `copyfile_state_free`
2081    let state = unsafe {
2082        let state = libc::copyfile_state_alloc();
2083        if state.is_null() {
2084            return Err(crate::io::Error::last_os_error());
2085        }
2086        FreeOnDrop(state)
2087    };
2088
2089    let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2090
2091    cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2092
2093    let mut bytes_copied: libc::off_t = 0;
2094    cvt(unsafe {
2095        libc::copyfile_state_get(
2096            state.0,
2097            libc::COPYFILE_STATE_COPIED as u32,
2098            (&raw mut bytes_copied) as *mut libc::c_void,
2099        )
2100    })?;
2101    Ok(bytes_copied as u64)
2102}
2103
2104pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2105    run_path_with_cstr(path, &|path| {
2106        cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2107            .map(|_| ())
2108    })
2109}
2110
2111pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2112    cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2113    Ok(())
2114}
2115
2116#[cfg(not(target_os = "vxworks"))]
2117pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2118    run_path_with_cstr(path, &|path| {
2119        cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2120            .map(|_| ())
2121    })
2122}
2123
2124#[cfg(target_os = "vxworks")]
2125pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2126    let (_, _, _) = (path, uid, gid);
2127    Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2128}
2129
2130#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
2131pub fn chroot(dir: &Path) -> io::Result<()> {
2132    run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2133}
2134
2135#[cfg(target_os = "vxworks")]
2136pub fn chroot(dir: &Path) -> io::Result<()> {
2137    let _ = dir;
2138    Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2139}
2140
2141pub use remove_dir_impl::remove_dir_all;
2142
2143// Fallback for REDOX, ESP-ID, Horizon, Vita, Vxworks and Miri
2144#[cfg(any(
2145    target_os = "redox",
2146    target_os = "espidf",
2147    target_os = "horizon",
2148    target_os = "vita",
2149    target_os = "nto",
2150    target_os = "vxworks",
2151    miri
2152))]
2153mod remove_dir_impl {
2154    pub use crate::sys_common::fs::remove_dir_all;
2155}
2156
2157// Modern implementation using openat(), unlinkat() and fdopendir()
2158#[cfg(not(any(
2159    target_os = "redox",
2160    target_os = "espidf",
2161    target_os = "horizon",
2162    target_os = "vita",
2163    target_os = "nto",
2164    target_os = "vxworks",
2165    miri
2166)))]
2167mod remove_dir_impl {
2168    #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2169    use libc::{fdopendir, openat, unlinkat};
2170    #[cfg(all(target_os = "linux", target_env = "gnu"))]
2171    use libc::{fdopendir, openat64 as openat, unlinkat};
2172
2173    use super::{Dir, DirEntry, InnerReadDir, ReadDir, lstat};
2174    use crate::ffi::CStr;
2175    use crate::io;
2176    use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
2177    use crate::os::unix::prelude::{OwnedFd, RawFd};
2178    use crate::path::{Path, PathBuf};
2179    use crate::sys::common::small_c_string::run_path_with_cstr;
2180    use crate::sys::{cvt, cvt_r};
2181    use crate::sys_common::ignore_notfound;
2182
2183    pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2184        let fd = cvt_r(|| unsafe {
2185            openat(
2186                parent_fd.unwrap_or(libc::AT_FDCWD),
2187                p.as_ptr(),
2188                libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2189            )
2190        })?;
2191        Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2192    }
2193
2194    fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2195        let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2196        if ptr.is_null() {
2197            return Err(io::Error::last_os_error());
2198        }
2199        let dirp = Dir(ptr);
2200        // file descriptor is automatically closed by libc::closedir() now, so give up ownership
2201        let new_parent_fd = dir_fd.into_raw_fd();
2202        // a valid root is not needed because we do not call any functions involving the full path
2203        // of the `DirEntry`s.
2204        let dummy_root = PathBuf::new();
2205        let inner = InnerReadDir { dirp, root: dummy_root };
2206        Ok((ReadDir::new(inner), new_parent_fd))
2207    }
2208
2209    #[cfg(any(
2210        target_os = "solaris",
2211        target_os = "illumos",
2212        target_os = "haiku",
2213        target_os = "vxworks",
2214        target_os = "aix",
2215    ))]
2216    fn is_dir(_ent: &DirEntry) -> Option<bool> {
2217        None
2218    }
2219
2220    #[cfg(not(any(
2221        target_os = "solaris",
2222        target_os = "illumos",
2223        target_os = "haiku",
2224        target_os = "vxworks",
2225        target_os = "aix",
2226    )))]
2227    fn is_dir(ent: &DirEntry) -> Option<bool> {
2228        match ent.entry.d_type {
2229            libc::DT_UNKNOWN => None,
2230            libc::DT_DIR => Some(true),
2231            _ => Some(false),
2232        }
2233    }
2234
2235    fn is_enoent(result: &io::Result<()>) -> bool {
2236        if let Err(err) = result
2237            && matches!(err.raw_os_error(), Some(libc::ENOENT))
2238        {
2239            true
2240        } else {
2241            false
2242        }
2243    }
2244
2245    fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2246        // try opening as directory
2247        let fd = match openat_nofollow_dironly(parent_fd, &path) {
2248            Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2249                // not a directory - don't traverse further
2250                // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
2251                return match parent_fd {
2252                    // unlink...
2253                    Some(parent_fd) => {
2254                        cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2255                    }
2256                    // ...unless this was supposed to be the deletion root directory
2257                    None => Err(err),
2258                };
2259            }
2260            result => result?,
2261        };
2262
2263        // open the directory passing ownership of the fd
2264        let (dir, fd) = fdreaddir(fd)?;
2265        for child in dir {
2266            let child = child?;
2267            let child_name = child.name_cstr();
2268            // we need an inner try block, because if one of these
2269            // directories has already been deleted, then we need to
2270            // continue the loop, not return ok.
2271            let result: io::Result<()> = try {
2272                match is_dir(&child) {
2273                    Some(true) => {
2274                        remove_dir_all_recursive(Some(fd), child_name)?;
2275                    }
2276                    Some(false) => {
2277                        cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
2278                    }
2279                    None => {
2280                        // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
2281                        // if the process has the appropriate privileges. This however can causing orphaned
2282                        // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
2283                        // into it first instead of trying to unlink() it.
2284                        remove_dir_all_recursive(Some(fd), child_name)?;
2285                    }
2286                }
2287            };
2288            if result.is_err() && !is_enoent(&result) {
2289                return result;
2290            }
2291        }
2292
2293        // unlink the directory after removing its contents
2294        ignore_notfound(cvt(unsafe {
2295            unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2296        }))?;
2297        Ok(())
2298    }
2299
2300    fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
2301        // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
2302        // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
2303        // into symlinks.
2304        let attr = lstat(p)?;
2305        if attr.file_type().is_symlink() {
2306            crate::fs::remove_file(p)
2307        } else {
2308            run_path_with_cstr(p, &|p| remove_dir_all_recursive(None, &p))
2309        }
2310    }
2311
2312    pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2313        remove_dir_all_modern(p)
2314    }
2315}