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