1 use crate::os::unix::prelude::*;
3 use crate::ffi::{CStr, OsStr, OsString};
5 use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
10 target_os = "solaris",
11 target_os = "fuchsia",
15 use crate::mem::MaybeUninit;
16 use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
17 use crate::path::{Path, PathBuf};
20 use crate::sys::common::small_c_string::run_path_with_cstr;
21 use crate::sys::fd::FileDesc;
22 use crate::sys::time::SystemTime;
23 use crate::sys::{cvt, cvt_r};
24 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
27 all(target_os = "linux", target_env = "gnu"),
30 target_os = "watchos",
32 use crate::sys::weak::syscall;
33 #[cfg(any(target_os = "android", target_os = "macos"))]
34 use crate::sys::weak::weak;
36 use libc::{c_int, mode_t};
41 target_os = "watchos",
42 all(target_os = "linux", target_env = "gnu")
45 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
47 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
50 target_os = "android",
51 target_os = "solaris",
52 target_os = "fuchsia",
56 use libc::readdir as readdir64;
57 #[cfg(target_os = "linux")]
59 #[cfg(any(target_os = "emscripten", target_os = "l4re"))]
60 use libc::readdir64_r;
62 target_os = "android",
64 target_os = "emscripten",
65 target_os = "solaris",
66 target_os = "illumos",
68 target_os = "fuchsia",
71 use libc::readdir_r as readdir64_r;
72 #[cfg(target_os = "android")]
74 dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
75 lstat as lstat64, off64_t, open as open64, stat as stat64,
79 target_os = "emscripten",
84 dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
85 lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
87 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
88 use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
90 pub use crate::sys_common::fs::try_exists;
92 pub struct File(FileDesc);
94 // FIXME: This should be available on Linux with all `target_env`.
95 // But currently only glibc exposes `statx` fn and structs.
96 // We don't want to import unverified raw C structs here directly.
97 // https://github.com/rust-lang/rust/pull/67774
98 macro_rules! cfg_has_statx {
99 ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
101 if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
108 ($($block_inner:tt)*) => {
109 #[cfg(all(target_os = "linux", target_env = "gnu"))]
118 pub struct FileAttr {
120 statx_extra_fields: Option<StatxExtraFields>,
124 struct StatxExtraFields {
125 // This is needed to check if btime is supported by the filesystem.
127 stx_btime: libc::statx_timestamp,
128 // With statx, we can overcome 32-bit `time_t` too.
129 #[cfg(target_pointer_width = "32")]
130 stx_atime: libc::statx_timestamp,
131 #[cfg(target_pointer_width = "32")]
132 stx_ctime: libc::statx_timestamp,
133 #[cfg(target_pointer_width = "32")]
134 stx_mtime: libc::statx_timestamp,
138 // We prefer `statx` on Linux if available, which contains file creation time,
139 // as well as 64-bit timestamps of all kinds.
140 // Default `stat64` contains no creation time and may have 32-bit `time_t`.
146 ) -> Option<io::Result<FileAttr>> {
147 use crate::sync::atomic::{AtomicU8, Ordering};
149 // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
150 // We store the availability in global to avoid unnecessary syscalls.
154 static STATX_STATE: AtomicU8 = AtomicU8::new(0);
158 pathname: *const c_char,
161 statxbuf: *mut libc::statx
165 match STATX_STATE.load(Ordering::Relaxed) {
167 // It is a trick to call `statx` with null pointers to check if the syscall
168 // is available. According to the manual, it is expected to fail with EFAULT.
169 // We do this mainly for performance, since it is nearly hundreds times
170 // faster than a normal successful call.
171 let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
173 .and_then(|e| e.raw_os_error());
174 // We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
175 // and returns `EPERM`. Listing all possible errors seems not a good idea.
176 // See: https://github.com/rust-lang/rust/issues/65662
177 if err != Some(libc::EFAULT) {
178 STATX_STATE.store(1, Ordering::Relaxed);
181 STATX_STATE.store(2, Ordering::Relaxed);
187 let mut buf: libc::statx = mem::zeroed();
188 if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
189 return Some(Err(err));
192 // We cannot fill `stat64` exhaustively because of private padding fields.
193 let mut stat: stat64 = mem::zeroed();
194 // `c_ulong` on gnu-mips, `dev_t` otherwise
195 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
196 stat.st_ino = buf.stx_ino as libc::ino64_t;
197 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
198 stat.st_mode = buf.stx_mode as libc::mode_t;
199 stat.st_uid = buf.stx_uid as libc::uid_t;
200 stat.st_gid = buf.stx_gid as libc::gid_t;
201 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
202 stat.st_size = buf.stx_size as off64_t;
203 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
204 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
205 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
206 // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
207 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
208 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
209 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
210 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
211 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
213 let extra = StatxExtraFields {
214 stx_mask: buf.stx_mask,
215 stx_btime: buf.stx_btime,
216 // Store full times to avoid 32-bit `time_t` truncation.
217 #[cfg(target_pointer_width = "32")]
218 stx_atime: buf.stx_atime,
219 #[cfg(target_pointer_width = "32")]
220 stx_ctime: buf.stx_ctime,
221 #[cfg(target_pointer_width = "32")]
222 stx_mtime: buf.stx_mtime,
225 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
230 pub struct FileAttr {
235 // all DirEntry's will have a reference to this struct
236 struct InnerReadDir {
242 inner: Arc<InnerReadDir>,
244 target_os = "android",
246 target_os = "solaris",
247 target_os = "illumos",
248 target_os = "fuchsia",
254 struct Dir(*mut libc::DIR);
256 unsafe impl Send for Dir {}
257 unsafe impl Sync for Dir {}
260 target_os = "android",
262 target_os = "solaris",
263 target_os = "illumos",
264 target_os = "fuchsia",
267 pub struct DirEntry {
268 dir: Arc<InnerReadDir>,
270 // We need to store an owned copy of the entry name on platforms that use
271 // readdir() (not readdir_r()), because a) struct dirent may use a flexible
272 // array to store the name, b) it lives only until the next readdir() call.
273 name: crate::ffi::CString,
276 // Define a minimal subset of fields we need from `dirent64`, especially since
277 // we're not using the immediate `d_name` on these targets. Keeping this as an
278 // `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
280 target_os = "android",
282 target_os = "solaris",
283 target_os = "illumos",
284 target_os = "fuchsia",
287 struct dirent64_min {
289 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
294 target_os = "android",
296 target_os = "solaris",
297 target_os = "illumos",
298 target_os = "fuchsia",
301 pub struct DirEntry {
302 dir: Arc<InnerReadDir>,
303 // The full entry includes a fixed-length `d_name`.
307 #[derive(Clone, Debug)]
308 pub struct OpenOptions {
321 #[derive(Clone, PartialEq, Eq, Debug)]
322 pub struct FilePermissions {
326 #[derive(Copy, Clone, Debug, Default)]
327 pub struct FileTimes {
328 accessed: Option<SystemTime>,
329 modified: Option<SystemTime>,
332 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
333 pub struct FileType {
338 pub struct DirBuilder {
344 fn from_stat64(stat: stat64) -> Self {
345 Self { stat, statx_extra_fields: None }
348 #[cfg(target_pointer_width = "32")]
349 pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
350 if let Some(ext) = &self.statx_extra_fields {
351 if (ext.stx_mask & libc::STATX_MTIME) != 0 {
352 return Some(&ext.stx_mtime);
358 #[cfg(target_pointer_width = "32")]
359 pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
360 if let Some(ext) = &self.statx_extra_fields {
361 if (ext.stx_mask & libc::STATX_ATIME) != 0 {
362 return Some(&ext.stx_atime);
368 #[cfg(target_pointer_width = "32")]
369 pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
370 if let Some(ext) = &self.statx_extra_fields {
371 if (ext.stx_mask & libc::STATX_CTIME) != 0 {
372 return Some(&ext.stx_ctime);
380 fn from_stat64(stat: stat64) -> Self {
387 pub fn size(&self) -> u64 {
388 self.stat.st_size as u64
390 pub fn perm(&self) -> FilePermissions {
391 FilePermissions { mode: (self.stat.st_mode as mode_t) }
394 pub fn file_type(&self) -> FileType {
395 FileType { mode: self.stat.st_mode as mode_t }
399 #[cfg(target_os = "netbsd")]
401 pub fn modified(&self) -> io::Result<SystemTime> {
402 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64))
405 pub fn accessed(&self) -> io::Result<SystemTime> {
406 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64))
409 pub fn created(&self) -> io::Result<SystemTime> {
410 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64))
414 #[cfg(not(target_os = "netbsd"))]
416 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
417 pub fn modified(&self) -> io::Result<SystemTime> {
418 #[cfg(target_pointer_width = "32")]
420 if let Some(mtime) = self.stx_mtime() {
421 return Ok(SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64));
425 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64))
428 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
429 pub fn modified(&self) -> io::Result<SystemTime> {
430 Ok(SystemTime::new(self.stat.st_mtime as i64, 0))
433 #[cfg(target_os = "horizon")]
434 pub fn modified(&self) -> io::Result<SystemTime> {
435 Ok(SystemTime::from(self.stat.st_mtim))
438 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
439 pub fn accessed(&self) -> io::Result<SystemTime> {
440 #[cfg(target_pointer_width = "32")]
442 if let Some(atime) = self.stx_atime() {
443 return Ok(SystemTime::new(atime.tv_sec, atime.tv_nsec as i64));
447 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64))
450 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
451 pub fn accessed(&self) -> io::Result<SystemTime> {
452 Ok(SystemTime::new(self.stat.st_atime as i64, 0))
455 #[cfg(target_os = "horizon")]
456 pub fn accessed(&self) -> io::Result<SystemTime> {
457 Ok(SystemTime::from(self.stat.st_atim))
461 target_os = "freebsd",
462 target_os = "openbsd",
465 target_os = "watchos",
467 pub fn created(&self) -> io::Result<SystemTime> {
468 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64))
472 target_os = "freebsd",
473 target_os = "openbsd",
476 target_os = "watchos",
478 pub fn created(&self) -> io::Result<SystemTime> {
480 if let Some(ext) = &self.statx_extra_fields {
481 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
482 Ok(SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64))
484 Err(io::const_io_error!(
485 io::ErrorKind::Uncategorized,
486 "creation time is not available for the filesystem",
492 Err(io::const_io_error!(
493 io::ErrorKind::Unsupported,
494 "creation time is not available on this platform \
500 impl AsInner<stat64> for FileAttr {
501 fn as_inner(&self) -> &stat64 {
506 impl FilePermissions {
507 pub fn readonly(&self) -> bool {
508 // check if any class (owner, group, others) has write permission
509 self.mode & 0o222 == 0
512 pub fn set_readonly(&mut self, readonly: bool) {
514 // remove write permission for all classes; equivalent to `chmod a-w <file>`
517 // add write permission for all classes; equivalent to `chmod a+w <file>`
521 pub fn mode(&self) -> u32 {
527 pub fn set_accessed(&mut self, t: SystemTime) {
528 self.accessed = Some(t);
531 pub fn set_modified(&mut self, t: SystemTime) {
532 self.modified = Some(t);
537 pub fn is_dir(&self) -> bool {
538 self.is(libc::S_IFDIR)
540 pub fn is_file(&self) -> bool {
541 self.is(libc::S_IFREG)
543 pub fn is_symlink(&self) -> bool {
544 self.is(libc::S_IFLNK)
547 pub fn is(&self, mode: mode_t) -> bool {
548 self.mode & libc::S_IFMT == mode
552 impl FromInner<u32> for FilePermissions {
553 fn from_inner(mode: u32) -> FilePermissions {
554 FilePermissions { mode: mode as mode_t }
558 impl fmt::Debug for ReadDir {
559 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
561 // Thus the result will be e g 'ReadDir("/home")'
562 fmt::Debug::fmt(&*self.inner.root, f)
566 impl Iterator for ReadDir {
567 type Item = io::Result<DirEntry>;
570 target_os = "android",
572 target_os = "solaris",
573 target_os = "fuchsia",
575 target_os = "illumos"
577 fn next(&mut self) -> Option<io::Result<DirEntry>> {
580 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
581 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
582 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
583 // thread safety for readdir() as long an individual DIR* is not accessed
584 // concurrently, which is sufficient for Rust.
585 super::os::set_errno(0);
586 let entry_ptr = readdir64(self.inner.dirp.0);
587 if entry_ptr.is_null() {
588 // null can mean either the end is reached or an error occurred.
589 // So we had to clear errno beforehand to check for an error now.
590 return match super::os::errno() {
592 e => Some(Err(Error::from_raw_os_error(e))),
596 // The dirent64 struct is a weird imaginary thing that isn't ever supposed
597 // to be worked with by value. Its trailing d_name field is declared
598 // variously as [c_char; 256] or [c_char; 1] on different systems but
599 // either way that size is meaningless; only the offset of d_name is
600 // meaningful. The dirent64 pointers that libc returns from readdir64 are
601 // allowed to point to allocations smaller _or_ LARGER than implied by the
602 // definition of the struct.
604 // As such, we need to be even more careful with dirent64 than if its
605 // contents were "simply" partially initialized data.
607 // Like for uninitialized contents, converting entry_ptr to `&dirent64`
608 // would not be legal. However, unique to dirent64 is that we don't even
609 // get to use `addr_of!((*entry_ptr).d_name)` because that operation
610 // requires the full extent of *entry_ptr to be in bounds of the same
611 // allocation, which is not necessarily the case here.
613 // Absent any other way to obtain a pointer to `(*entry_ptr).d_name`
614 // legally in Rust analogously to how it would be done in C, we instead
615 // need to make our own non-libc allocation that conforms to the weird
616 // imaginary definition of dirent64, and use that for a field offset
618 macro_rules! offset_ptr {
619 ($entry_ptr:expr, $field:ident) => {{
620 const OFFSET: isize = {
621 let delusion = MaybeUninit::<dirent64>::uninit();
622 let entry_ptr = delusion.as_ptr();
624 ptr::addr_of!((*entry_ptr).$field)
626 .offset_from(entry_ptr.cast::<u8>())
630 // Cast to the same type determined by the else branch.
631 $entry_ptr.byte_offset(OFFSET).cast::<_>()
633 #[allow(deref_nullptr)]
635 ptr::addr_of!((*ptr::null::<dirent64>()).$field)
641 // d_name is guaranteed to be null-terminated.
642 let name = CStr::from_ptr(offset_ptr!(entry_ptr, d_name).cast());
643 let name_bytes = name.to_bytes();
644 if name_bytes == b"." || name_bytes == b".." {
648 let entry = dirent64_min {
649 d_ino: *offset_ptr!(entry_ptr, d_ino) as u64,
650 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
651 d_type: *offset_ptr!(entry_ptr, d_type) as u8,
654 return Some(Ok(DirEntry {
656 name: name.to_owned(),
657 dir: Arc::clone(&self.inner),
664 target_os = "android",
666 target_os = "solaris",
667 target_os = "fuchsia",
669 target_os = "illumos"
671 fn next(&mut self) -> Option<io::Result<DirEntry>> {
672 if self.end_of_stream {
677 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
678 let mut entry_ptr = ptr::null_mut();
680 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
682 if entry_ptr.is_null() {
683 // We encountered an error (which will be returned in this iteration), but
684 // we also reached the end of the directory stream. The `end_of_stream`
685 // flag is enabled to make sure that we return `None` in the next iteration
686 // (instead of looping forever)
687 self.end_of_stream = true;
689 return Some(Err(Error::from_raw_os_error(err)));
691 if entry_ptr.is_null() {
694 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
695 return Some(Ok(ret));
704 let r = unsafe { libc::closedir(self.0) };
706 r == 0 || crate::io::Error::last_os_error().kind() == crate::io::ErrorKind::Interrupted,
707 "unexpected error during closedir: {:?}",
708 crate::io::Error::last_os_error()
714 pub fn path(&self) -> PathBuf {
715 self.dir.root.join(self.file_name_os_str())
718 pub fn file_name(&self) -> OsString {
719 self.file_name_os_str().to_os_string()
723 any(target_os = "linux", target_os = "emscripten", target_os = "android"),
726 pub fn metadata(&self) -> io::Result<FileAttr> {
727 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
728 let name = self.name_cstr().as_ptr();
731 if let Some(ret) = unsafe { try_statx(
734 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
741 let mut stat: stat64 = unsafe { mem::zeroed() };
742 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
743 Ok(FileAttr::from_stat64(stat))
747 not(any(target_os = "linux", target_os = "emscripten", target_os = "android")),
750 pub fn metadata(&self) -> io::Result<FileAttr> {
755 target_os = "solaris",
756 target_os = "illumos",
758 target_os = "vxworks"
760 pub fn file_type(&self) -> io::Result<FileType> {
761 self.metadata().map(|m| m.file_type())
765 target_os = "solaris",
766 target_os = "illumos",
768 target_os = "vxworks"
770 pub fn file_type(&self) -> io::Result<FileType> {
771 match self.entry.d_type {
772 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
773 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
774 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
775 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
776 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
777 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
778 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
779 _ => self.metadata().map(|m| m.file_type()),
786 target_os = "watchos",
788 target_os = "emscripten",
789 target_os = "android",
790 target_os = "solaris",
791 target_os = "illumos",
794 target_os = "fuchsia",
796 target_os = "vxworks",
797 target_os = "espidf",
798 target_os = "horizon"
800 pub fn ino(&self) -> u64 {
801 self.entry.d_ino as u64
805 target_os = "freebsd",
806 target_os = "openbsd",
807 target_os = "netbsd",
808 target_os = "dragonfly"
810 pub fn ino(&self) -> u64 {
811 self.entry.d_fileno as u64
817 target_os = "watchos",
818 target_os = "netbsd",
819 target_os = "openbsd",
820 target_os = "freebsd",
821 target_os = "dragonfly"
823 fn name_bytes(&self) -> &[u8] {
826 slice::from_raw_parts(
827 self.entry.d_name.as_ptr() as *const u8,
828 self.entry.d_namlen as usize,
835 target_os = "watchos",
836 target_os = "netbsd",
837 target_os = "openbsd",
838 target_os = "freebsd",
839 target_os = "dragonfly"
841 fn name_bytes(&self) -> &[u8] {
842 self.name_cstr().to_bytes()
846 target_os = "android",
848 target_os = "solaris",
849 target_os = "illumos",
850 target_os = "fuchsia",
853 #[cfg_attr(miri, allow(unused))]
854 fn name_cstr(&self) -> &CStr {
855 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
858 target_os = "android",
860 target_os = "solaris",
861 target_os = "illumos",
862 target_os = "fuchsia",
865 #[cfg_attr(miri, allow(unused))]
866 fn name_cstr(&self) -> &CStr {
870 pub fn file_name_os_str(&self) -> &OsStr {
871 OsStr::from_bytes(self.name_bytes())
876 pub fn new() -> OpenOptions {
891 pub fn read(&mut self, read: bool) {
894 pub fn write(&mut self, write: bool) {
897 pub fn append(&mut self, append: bool) {
898 self.append = append;
900 pub fn truncate(&mut self, truncate: bool) {
901 self.truncate = truncate;
903 pub fn create(&mut self, create: bool) {
904 self.create = create;
906 pub fn create_new(&mut self, create_new: bool) {
907 self.create_new = create_new;
910 pub fn custom_flags(&mut self, flags: i32) {
911 self.custom_flags = flags;
913 pub fn mode(&mut self, mode: u32) {
914 self.mode = mode as mode_t;
917 fn get_access_mode(&self) -> io::Result<c_int> {
918 match (self.read, self.write, self.append) {
919 (true, false, false) => Ok(libc::O_RDONLY),
920 (false, true, false) => Ok(libc::O_WRONLY),
921 (true, true, false) => Ok(libc::O_RDWR),
922 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
923 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
924 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
928 fn get_creation_mode(&self) -> io::Result<c_int> {
929 match (self.write, self.append) {
932 if self.truncate || self.create || self.create_new {
933 return Err(Error::from_raw_os_error(libc::EINVAL));
937 if self.truncate && !self.create_new {
938 return Err(Error::from_raw_os_error(libc::EINVAL));
943 Ok(match (self.create, self.truncate, self.create_new) {
944 (false, false, false) => 0,
945 (true, false, false) => libc::O_CREAT,
946 (false, true, false) => libc::O_TRUNC,
947 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
948 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
954 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
955 run_path_with_cstr(path, |path| File::open_c(path, opts))
958 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
959 let flags = libc::O_CLOEXEC
960 | opts.get_access_mode()?
961 | opts.get_creation_mode()?
962 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
963 // The third argument of `open64` is documented to have type `mode_t`. On
964 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
965 // However, since this is a variadic function, C integer promotion rules mean that on
966 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
967 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
968 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
971 pub fn file_attr(&self) -> io::Result<FileAttr> {
972 let fd = self.as_raw_fd();
975 if let Some(ret) = unsafe { try_statx(
977 b"\0" as *const _ as *const c_char,
978 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
985 let mut stat: stat64 = unsafe { mem::zeroed() };
986 cvt(unsafe { fstat64(fd, &mut stat) })?;
987 Ok(FileAttr::from_stat64(stat))
990 pub fn fsync(&self) -> io::Result<()> {
991 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
994 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
995 unsafe fn os_fsync(fd: c_int) -> c_int {
996 libc::fcntl(fd, libc::F_FULLFSYNC)
998 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "watchos")))]
999 unsafe fn os_fsync(fd: c_int) -> c_int {
1004 pub fn datasync(&self) -> io::Result<()> {
1005 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1008 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
1009 unsafe fn os_datasync(fd: c_int) -> c_int {
1010 libc::fcntl(fd, libc::F_FULLFSYNC)
1013 target_os = "freebsd",
1014 target_os = "linux",
1015 target_os = "android",
1016 target_os = "netbsd",
1017 target_os = "openbsd"
1019 unsafe fn os_datasync(fd: c_int) -> c_int {
1023 target_os = "android",
1024 target_os = "freebsd",
1026 target_os = "linux",
1027 target_os = "macos",
1028 target_os = "netbsd",
1029 target_os = "openbsd",
1030 target_os = "watchos",
1032 unsafe fn os_datasync(fd: c_int) -> c_int {
1037 pub fn truncate(&self, size: u64) -> io::Result<()> {
1039 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1040 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1043 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1047 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1048 self.0.read_vectored(bufs)
1052 pub fn is_read_vectored(&self) -> bool {
1053 self.0.is_read_vectored()
1056 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1057 self.0.read_at(buf, offset)
1060 pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1061 self.0.read_buf(cursor)
1064 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1068 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1069 self.0.write_vectored(bufs)
1073 pub fn is_write_vectored(&self) -> bool {
1074 self.0.is_write_vectored()
1077 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1078 self.0.write_at(buf, offset)
1081 pub fn flush(&self) -> io::Result<()> {
1085 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1086 let (whence, pos) = match pos {
1087 // Casting to `i64` is fine, too large values will end up as
1088 // negative which will cause an error in `lseek64`.
1089 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1090 SeekFrom::End(off) => (libc::SEEK_END, off),
1091 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1093 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1097 pub fn duplicate(&self) -> io::Result<File> {
1098 self.0.duplicate().map(File)
1101 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1102 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1106 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1107 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))]
1108 let to_timespec = |time: Option<SystemTime>| {
1110 Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1111 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")),
1112 Some(_) => Err(io::const_io_error!(io::ErrorKind::InvalidInput, "timestamp is too small to set as a file time")),
1113 None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
1116 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))]
1117 let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1119 if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon"))] {
1120 // Redox doesn't appear to support `UTIME_OMIT`.
1121 // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1122 // the same as for Redox.
1124 Err(io::const_io_error!(
1125 io::ErrorKind::Unsupported,
1126 "setting file times not supported",
1128 } else if #[cfg(any(target_os = "android", target_os = "macos"))] {
1129 // futimens requires macOS 10.13, and Android API level 19
1131 weak!(fn futimens(c_int, *const libc::timespec) -> c_int);
1132 match futimens.get() {
1133 Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1134 #[cfg(target_os = "macos")]
1136 fn ts_to_tv(ts: &libc::timespec) -> libc::timeval {
1139 tv_usec: (ts.tv_nsec / 1000) as _
1142 let timevals = [ts_to_tv(×[0]), ts_to_tv(×[1])];
1143 libc::futimes(self.as_raw_fd(), timevals.as_ptr())
1145 // futimes requires even newer Android.
1146 #[cfg(target_os = "android")]
1147 None => return Err(io::const_io_error!(
1148 io::ErrorKind::Unsupported,
1149 "setting file times requires Android API level >= 19",
1155 cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1163 pub fn new() -> DirBuilder {
1164 DirBuilder { mode: 0o777 }
1167 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1168 run_path_with_cstr(p, |p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1171 pub fn set_mode(&mut self, mode: u32) {
1172 self.mode = mode as mode_t;
1176 impl AsInner<FileDesc> for File {
1177 fn as_inner(&self) -> &FileDesc {
1182 impl AsInnerMut<FileDesc> for File {
1183 fn as_inner_mut(&mut self) -> &mut FileDesc {
1188 impl IntoInner<FileDesc> for File {
1189 fn into_inner(self) -> FileDesc {
1194 impl FromInner<FileDesc> for File {
1195 fn from_inner(file_desc: FileDesc) -> Self {
1200 impl AsFd for File {
1201 fn as_fd(&self) -> BorrowedFd<'_> {
1206 impl AsRawFd for File {
1207 fn as_raw_fd(&self) -> RawFd {
1212 impl IntoRawFd for File {
1213 fn into_raw_fd(self) -> RawFd {
1214 self.0.into_raw_fd()
1218 impl FromRawFd for File {
1219 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1220 Self(FromRawFd::from_raw_fd(raw_fd))
1224 impl fmt::Debug for File {
1225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 target_os = "linux",
1228 target_os = "netbsd",
1229 target_os = "illumos",
1230 target_os = "solaris"
1232 fn get_path(fd: c_int) -> Option<PathBuf> {
1233 let mut p = PathBuf::from("/proc/self/fd");
1234 p.push(&fd.to_string());
1238 #[cfg(target_os = "macos")]
1239 fn get_path(fd: c_int) -> Option<PathBuf> {
1240 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1241 // is inevitable in this case because macOS defines `fcntl` with
1242 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1243 // alternatives. If a better method is invented, it should be used
1245 let mut buf = vec![0; libc::PATH_MAX as usize];
1246 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1250 let l = buf.iter().position(|&c| c == 0).unwrap();
1251 buf.truncate(l as usize);
1252 buf.shrink_to_fit();
1253 Some(PathBuf::from(OsString::from_vec(buf)))
1256 #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
1257 fn get_path(fd: c_int) -> Option<PathBuf> {
1258 let info = Box::<libc::kinfo_file>::new_zeroed();
1259 let mut info = unsafe { info.assume_init() };
1260 info.kf_structsize = mem::size_of::<libc::kinfo_file>() as libc::c_int;
1261 let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
1265 let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
1266 Some(PathBuf::from(OsString::from_vec(buf)))
1269 #[cfg(target_os = "vxworks")]
1270 fn get_path(fd: c_int) -> Option<PathBuf> {
1271 let mut buf = vec![0; libc::PATH_MAX as usize];
1272 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1276 let l = buf.iter().position(|&c| c == 0).unwrap();
1277 buf.truncate(l as usize);
1278 Some(PathBuf::from(OsString::from_vec(buf)))
1282 target_os = "linux",
1283 target_os = "macos",
1284 target_os = "vxworks",
1285 all(target_os = "freebsd", target_arch = "x86_64"),
1286 target_os = "netbsd",
1287 target_os = "illumos",
1288 target_os = "solaris"
1290 fn get_path(_fd: c_int) -> Option<PathBuf> {
1291 // FIXME(#24570): implement this for other Unix platforms
1296 target_os = "linux",
1297 target_os = "macos",
1298 target_os = "freebsd",
1299 target_os = "netbsd",
1300 target_os = "openbsd",
1301 target_os = "vxworks"
1303 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1304 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1308 match mode & libc::O_ACCMODE {
1309 libc::O_RDONLY => Some((true, false)),
1310 libc::O_RDWR => Some((true, true)),
1311 libc::O_WRONLY => Some((false, true)),
1317 target_os = "linux",
1318 target_os = "macos",
1319 target_os = "freebsd",
1320 target_os = "netbsd",
1321 target_os = "openbsd",
1322 target_os = "vxworks"
1324 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1325 // FIXME(#24570): implement this for other Unix platforms
1329 let fd = self.as_raw_fd();
1330 let mut b = f.debug_struct("File");
1332 if let Some(path) = get_path(fd) {
1333 b.field("path", &path);
1335 if let Some((read, write)) = get_mode(fd) {
1336 b.field("read", &read).field("write", &write);
1342 pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1343 let ptr = run_path_with_cstr(path, |p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1345 Err(Error::last_os_error())
1347 let root = path.to_path_buf();
1348 let inner = InnerReadDir { dirp: Dir(ptr), root };
1350 inner: Arc::new(inner),
1352 target_os = "android",
1353 target_os = "linux",
1354 target_os = "solaris",
1355 target_os = "illumos",
1356 target_os = "fuchsia",
1357 target_os = "redox",
1359 end_of_stream: false,
1364 pub fn unlink(p: &Path) -> io::Result<()> {
1365 run_path_with_cstr(p, |p| cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ()))
1368 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1369 run_path_with_cstr(old, |old| {
1370 run_path_with_cstr(new, |new| {
1371 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1376 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1377 run_path_with_cstr(p, |p| cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ()))
1380 pub fn rmdir(p: &Path) -> io::Result<()> {
1381 run_path_with_cstr(p, |p| cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ()))
1384 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1385 run_path_with_cstr(p, |c_path| {
1386 let p = c_path.as_ptr();
1388 let mut buf = Vec::with_capacity(256);
1392 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })?
1396 buf.set_len(buf_read);
1399 if buf_read != buf.capacity() {
1400 buf.shrink_to_fit();
1402 return Ok(PathBuf::from(OsString::from_vec(buf)));
1405 // Trigger the internal buffer resizing logic of `Vec` by requiring
1406 // more space than the current capacity. The length is guaranteed to be
1407 // the same as the capacity due to the if statement above.
1413 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1414 run_path_with_cstr(original, |original| {
1415 run_path_with_cstr(link, |link| {
1416 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
1421 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1422 run_path_with_cstr(original, |original| {
1423 run_path_with_cstr(link, |link| {
1425 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon"))] {
1426 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1427 // it implementation-defined whether `link` follows symlinks, so rely on the
1428 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1429 // Android has `linkat` on newer versions, but we happen to know `link`
1430 // always has the correct behavior, so it's here as well.
1431 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1432 } else if #[cfg(target_os = "macos")] {
1433 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1434 // versions have it. We want to use linkat if it is available, so we use weak!
1435 // to check. `linkat` is preferable to `link` because it gives us a flag to
1436 // specify how symlinks should be handled. We pass 0 as the flags argument,
1437 // meaning it shouldn't follow symlinks.
1438 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1440 if let Some(f) = linkat.get() {
1441 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1443 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1446 // Where we can, use `linkat` instead of `link`; see the comment above
1447 // this one for details on why.
1448 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1456 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1457 run_path_with_cstr(p, |p| {
1459 if let Some(ret) = unsafe { try_statx(
1462 libc::AT_STATX_SYNC_AS_STAT,
1469 let mut stat: stat64 = unsafe { mem::zeroed() };
1470 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1471 Ok(FileAttr::from_stat64(stat))
1475 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1476 run_path_with_cstr(p, |p| {
1478 if let Some(ret) = unsafe { try_statx(
1481 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1488 let mut stat: stat64 = unsafe { mem::zeroed() };
1489 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1490 Ok(FileAttr::from_stat64(stat))
1494 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1495 let r = run_path_with_cstr(p, |path| unsafe {
1496 Ok(libc::realpath(path.as_ptr(), ptr::null_mut()))
1499 return Err(io::Error::last_os_error());
1501 Ok(PathBuf::from(OsString::from_vec(unsafe {
1502 let buf = CStr::from_ptr(r).to_bytes().to_vec();
1503 libc::free(r as *mut _);
1508 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1509 use crate::fs::File;
1510 use crate::sys_common::fs::NOT_FILE_ERROR;
1512 let reader = File::open(from)?;
1513 let metadata = reader.metadata()?;
1514 if !metadata.is_file() {
1515 return Err(NOT_FILE_ERROR);
1517 Ok((reader, metadata))
1520 #[cfg(target_os = "espidf")]
1521 fn open_to_and_set_permissions(
1523 reader_metadata: crate::fs::Metadata,
1524 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1525 use crate::fs::OpenOptions;
1526 let writer = OpenOptions::new().open(to)?;
1527 let writer_metadata = writer.metadata()?;
1528 Ok((writer, writer_metadata))
1531 #[cfg(not(target_os = "espidf"))]
1532 fn open_to_and_set_permissions(
1534 reader_metadata: crate::fs::Metadata,
1535 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1536 use crate::fs::OpenOptions;
1537 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1539 let perm = reader_metadata.permissions();
1540 let writer = OpenOptions::new()
1541 // create the file with the correct mode right away
1547 let writer_metadata = writer.metadata()?;
1548 if writer_metadata.is_file() {
1549 // Set the correct file permissions, in case the file already existed.
1550 // Don't set the permissions on already existing non-files like
1551 // pipes/FIFOs or device nodes.
1552 writer.set_permissions(perm)?;
1554 Ok((writer, writer_metadata))
1558 target_os = "linux",
1559 target_os = "android",
1560 target_os = "macos",
1562 target_os = "watchos",
1564 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1565 let (mut reader, reader_metadata) = open_from(from)?;
1566 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1568 io::copy(&mut reader, &mut writer)
1571 #[cfg(any(target_os = "linux", target_os = "android"))]
1572 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1573 let (mut reader, reader_metadata) = open_from(from)?;
1574 let max_len = u64::MAX;
1575 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1577 use super::kernel_copy::{copy_regular_files, CopyResult};
1579 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1580 CopyResult::Ended(bytes) => Ok(bytes),
1581 CopyResult::Error(e, _) => Err(e),
1582 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1583 Ok(bytes) => Ok(bytes + written),
1589 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
1590 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1591 use crate::sync::atomic::{AtomicBool, Ordering};
1593 const COPYFILE_ACL: u32 = 1 << 0;
1594 const COPYFILE_STAT: u32 = 1 << 1;
1595 const COPYFILE_XATTR: u32 = 1 << 2;
1596 const COPYFILE_DATA: u32 = 1 << 3;
1598 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1599 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1600 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1602 const COPYFILE_STATE_COPIED: u32 = 8;
1604 #[allow(non_camel_case_types)]
1605 type copyfile_state_t = *mut libc::c_void;
1606 #[allow(non_camel_case_types)]
1607 type copyfile_flags_t = u32;
1613 state: copyfile_state_t,
1614 flags: copyfile_flags_t,
1616 fn copyfile_state_alloc() -> copyfile_state_t;
1617 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1618 fn copyfile_state_get(
1619 state: copyfile_state_t,
1621 dst: *mut libc::c_void,
1625 struct FreeOnDrop(copyfile_state_t);
1626 impl Drop for FreeOnDrop {
1627 fn drop(&mut self) {
1628 // The code below ensures that `FreeOnDrop` is never a null pointer
1630 // `copyfile_state_free` returns -1 if the `to` or `from` files
1631 // cannot be closed. However, this is not considered this an
1633 copyfile_state_free(self.0);
1638 // MacOS prior to 10.12 don't support `fclonefileat`
1639 // We store the availability in a global to avoid unnecessary syscalls
1640 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1644 dst_dirfd: libc::c_int,
1650 let (reader, reader_metadata) = open_from(from)?;
1652 // Opportunistically attempt to create a copy-on-write clone of `from`
1653 // using `fclonefileat`.
1654 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1655 let clonefile_result = run_path_with_cstr(to, |to| {
1656 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
1658 match clonefile_result {
1659 Ok(_) => return Ok(reader_metadata.len()),
1660 Err(err) => match err.raw_os_error() {
1661 // `fclonefileat` will fail on non-APFS volumes, if the
1662 // destination already exists, or if the source and destination
1663 // are on different devices. In all these cases `fcopyfile`
1665 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1666 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1667 _ => return Err(err),
1672 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1673 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1675 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1676 // always safe to call `copyfile_state_free`
1677 let state = unsafe {
1678 let state = copyfile_state_alloc();
1679 if state.is_null() {
1680 return Err(crate::io::Error::last_os_error());
1685 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1687 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1689 let mut bytes_copied: libc::off_t = 0;
1693 COPYFILE_STATE_COPIED,
1694 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1697 Ok(bytes_copied as u64)
1700 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1701 run_path_with_cstr(path, |path| {
1702 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
1707 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1708 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1712 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1713 run_path_with_cstr(path, |path| {
1714 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
1719 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1720 pub fn chroot(dir: &Path) -> io::Result<()> {
1721 run_path_with_cstr(dir, |dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
1724 pub use remove_dir_impl::remove_dir_all;
1726 // Fallback for REDOX, ESP-ID, Horizon, and Miri
1727 #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri))]
1728 mod remove_dir_impl {
1729 pub use crate::sys_common::fs::remove_dir_all;
1732 // Modern implementation using openat(), unlinkat() and fdopendir()
1733 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri)))]
1734 mod remove_dir_impl {
1735 use super::{lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1736 use crate::ffi::CStr;
1738 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1739 use crate::os::unix::prelude::{OwnedFd, RawFd};
1740 use crate::path::{Path, PathBuf};
1741 use crate::sync::Arc;
1742 use crate::sys::common::small_c_string::run_path_with_cstr;
1743 use crate::sys::{cvt, cvt_r};
1745 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64")),))]
1746 use libc::{fdopendir, openat, unlinkat};
1747 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1748 use macos_weak::{fdopendir, openat, unlinkat};
1750 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1752 use crate::sys::weak::weak;
1753 use libc::{c_char, c_int, DIR};
1755 fn get_openat_fn() -> Option<unsafe extern "C" fn(c_int, *const c_char, c_int) -> c_int> {
1756 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1760 pub fn has_openat() -> bool {
1761 get_openat_fn().is_some()
1764 pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1765 get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| {
1766 crate::sys::unix::os::set_errno(libc::ENOSYS);
1771 pub unsafe fn fdopendir(fd: c_int) -> *mut DIR {
1772 #[cfg(all(target_os = "macos", target_arch = "x86"))]
1773 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64$UNIX2003");
1774 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1775 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1776 fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| {
1777 crate::sys::unix::os::set_errno(libc::ENOSYS);
1778 crate::ptr::null_mut()
1782 pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1783 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1784 unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| {
1785 crate::sys::unix::os::set_errno(libc::ENOSYS);
1791 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1792 let fd = cvt_r(|| unsafe {
1794 parent_fd.unwrap_or(libc::AT_FDCWD),
1796 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1799 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1802 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1803 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1805 return Err(io::Error::last_os_error());
1807 let dirp = Dir(ptr);
1808 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1809 let new_parent_fd = dir_fd.into_raw_fd();
1810 // a valid root is not needed because we do not call any functions involving the full path
1811 // of the DirEntrys.
1812 let dummy_root = PathBuf::new();
1815 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1817 target_os = "android",
1818 target_os = "linux",
1819 target_os = "solaris",
1820 target_os = "illumos",
1821 target_os = "fuchsia",
1822 target_os = "redox",
1824 end_of_stream: false,
1831 target_os = "solaris",
1832 target_os = "illumos",
1833 target_os = "haiku",
1834 target_os = "vxworks",
1836 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1841 target_os = "solaris",
1842 target_os = "illumos",
1843 target_os = "haiku",
1844 target_os = "vxworks",
1846 fn is_dir(ent: &DirEntry) -> Option<bool> {
1847 match ent.entry.d_type {
1848 libc::DT_UNKNOWN => None,
1849 libc::DT_DIR => Some(true),
1854 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
1855 // try opening as directory
1856 let fd = match openat_nofollow_dironly(parent_fd, &path) {
1857 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
1858 // not a directory - don't traverse further
1859 // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
1860 return match parent_fd {
1862 Some(parent_fd) => {
1863 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
1865 // ...unless this was supposed to be the deletion root directory
1872 // open the directory passing ownership of the fd
1873 let (dir, fd) = fdreaddir(fd)?;
1876 let child_name = child.name_cstr();
1877 match is_dir(&child) {
1879 remove_dir_all_recursive(Some(fd), child_name)?;
1882 cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
1885 // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
1886 // if the process has the appropriate privileges. This however can causing orphaned
1887 // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
1888 // into it first instead of trying to unlink() it.
1889 remove_dir_all_recursive(Some(fd), child_name)?;
1894 // unlink the directory after removing its contents
1896 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
1901 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1902 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1903 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1905 let attr = lstat(p)?;
1906 if attr.file_type().is_symlink() {
1907 crate::fs::remove_file(p)
1909 run_path_with_cstr(p, |p| remove_dir_all_recursive(None, &p))
1913 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64"))))]
1914 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1915 remove_dir_all_modern(p)
1918 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1919 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1920 if macos_weak::has_openat() {
1921 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1922 remove_dir_all_modern(p)
1924 // fall back to classic implementation
1925 crate::sys_common::fs::remove_dir_all(p)