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