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