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