std/sys/fs/
unix.rs

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