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