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