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