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