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