1 // miri has some special hacks here that make things unused.
2 #![cfg_attr(miri, allow(unused))]
4 use crate::os::unix::prelude::*;
6 use crate::ffi::{CStr, OsStr, OsString};
8 use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
11 target_os = "android",
13 target_os = "solaris",
14 target_os = "fuchsia",
18 use crate::mem::MaybeUninit;
19 use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
20 use crate::path::{Path, PathBuf};
23 use crate::sys::common::small_c_string::run_path_with_cstr;
24 use crate::sys::fd::FileDesc;
25 use crate::sys::time::SystemTime;
26 use crate::sys::{cvt, cvt_r};
27 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
30 all(target_os = "linux", target_env = "gnu"),
33 target_os = "watchos",
35 use crate::sys::weak::syscall;
36 #[cfg(any(target_os = "android", target_os = "macos"))]
37 use crate::sys::weak::weak;
39 use libc::{c_int, mode_t};
44 target_os = "watchos",
45 all(target_os = "linux", target_env = "gnu")
48 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
50 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
53 target_os = "android",
54 target_os = "solaris",
55 target_os = "fuchsia",
59 use libc::readdir as readdir64;
60 #[cfg(target_os = "linux")]
62 #[cfg(any(target_os = "emscripten", target_os = "l4re"))]
63 use libc::readdir64_r;
65 target_os = "android",
67 target_os = "emscripten",
68 target_os = "solaris",
69 target_os = "illumos",
71 target_os = "fuchsia",
74 use libc::readdir_r as readdir64_r;
75 #[cfg(target_os = "android")]
77 dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
78 lstat as lstat64, off64_t, open as open64, stat as stat64,
82 target_os = "emscripten",
87 dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
88 lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
90 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
91 use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
93 pub use crate::sys_common::fs::try_exists;
95 pub struct File(FileDesc);
97 // FIXME: This should be available on Linux with all `target_env`.
98 // But currently only glibc exposes `statx` fn and structs.
99 // We don't want to import unverified raw C structs here directly.
100 // https://github.com/rust-lang/rust/pull/67774
101 macro_rules! cfg_has_statx {
102 ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
104 if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
111 ($($block_inner:tt)*) => {
112 #[cfg(all(target_os = "linux", target_env = "gnu"))]
121 pub struct FileAttr {
123 statx_extra_fields: Option<StatxExtraFields>,
127 struct StatxExtraFields {
128 // This is needed to check if btime is supported by the filesystem.
130 stx_btime: libc::statx_timestamp,
131 // With statx, we can overcome 32-bit `time_t` too.
132 #[cfg(target_pointer_width = "32")]
133 stx_atime: libc::statx_timestamp,
134 #[cfg(target_pointer_width = "32")]
135 stx_ctime: libc::statx_timestamp,
136 #[cfg(target_pointer_width = "32")]
137 stx_mtime: libc::statx_timestamp,
141 // We prefer `statx` on Linux if available, which contains file creation time,
142 // as well as 64-bit timestamps of all kinds.
143 // Default `stat64` contains no creation time and may have 32-bit `time_t`.
149 ) -> Option<io::Result<FileAttr>> {
150 use crate::sync::atomic::{AtomicU8, Ordering};
152 // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
153 // We store the availability in global to avoid unnecessary syscalls.
157 static STATX_STATE: AtomicU8 = AtomicU8::new(0);
161 pathname: *const c_char,
164 statxbuf: *mut libc::statx
168 match STATX_STATE.load(Ordering::Relaxed) {
170 // It is a trick to call `statx` with null pointers to check if the syscall
171 // is available. According to the manual, it is expected to fail with EFAULT.
172 // We do this mainly for performance, since it is nearly hundreds times
173 // faster than a normal successful call.
174 let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
176 .and_then(|e| e.raw_os_error());
177 // We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
178 // and returns `EPERM`. Listing all possible errors seems not a good idea.
179 // See: https://github.com/rust-lang/rust/issues/65662
180 if err != Some(libc::EFAULT) {
181 STATX_STATE.store(1, Ordering::Relaxed);
184 STATX_STATE.store(2, Ordering::Relaxed);
190 let mut buf: libc::statx = mem::zeroed();
191 if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
192 return Some(Err(err));
195 // We cannot fill `stat64` exhaustively because of private padding fields.
196 let mut stat: stat64 = mem::zeroed();
197 // `c_ulong` on gnu-mips, `dev_t` otherwise
198 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
199 stat.st_ino = buf.stx_ino as libc::ino64_t;
200 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
201 stat.st_mode = buf.stx_mode as libc::mode_t;
202 stat.st_uid = buf.stx_uid as libc::uid_t;
203 stat.st_gid = buf.stx_gid as libc::gid_t;
204 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
205 stat.st_size = buf.stx_size as off64_t;
206 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
207 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
208 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
209 // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
210 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
211 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
212 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
213 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
214 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
216 let extra = StatxExtraFields {
217 stx_mask: buf.stx_mask,
218 stx_btime: buf.stx_btime,
219 // Store full times to avoid 32-bit `time_t` truncation.
220 #[cfg(target_pointer_width = "32")]
221 stx_atime: buf.stx_atime,
222 #[cfg(target_pointer_width = "32")]
223 stx_ctime: buf.stx_ctime,
224 #[cfg(target_pointer_width = "32")]
225 stx_mtime: buf.stx_mtime,
228 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
233 pub struct FileAttr {
238 // all DirEntry's will have a reference to this struct
239 struct InnerReadDir {
245 inner: Arc<InnerReadDir>,
250 fn new(inner: InnerReadDir) -> Self {
251 Self { inner: Arc::new(inner), end_of_stream: false }
255 struct Dir(*mut libc::DIR);
257 unsafe impl Send for Dir {}
258 unsafe impl Sync for Dir {}
261 target_os = "android",
263 target_os = "solaris",
264 target_os = "illumos",
265 target_os = "fuchsia",
268 pub struct DirEntry {
269 dir: Arc<InnerReadDir>,
271 // We need to store an owned copy of the entry name on platforms that use
272 // readdir() (not readdir_r()), because a) struct dirent may use a flexible
273 // array to store the name, b) it lives only until the next readdir() call.
274 name: crate::ffi::CString,
277 // Define a minimal subset of fields we need from `dirent64`, especially since
278 // we're not using the immediate `d_name` on these targets. Keeping this as an
279 // `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
281 target_os = "android",
283 target_os = "solaris",
284 target_os = "illumos",
285 target_os = "fuchsia",
288 struct dirent64_min {
290 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
295 target_os = "android",
297 target_os = "solaris",
298 target_os = "illumos",
299 target_os = "fuchsia",
302 pub struct DirEntry {
303 dir: Arc<InnerReadDir>,
304 // The full entry includes a fixed-length `d_name`.
308 #[derive(Clone, Debug)]
309 pub struct OpenOptions {
322 #[derive(Clone, PartialEq, Eq, Debug)]
323 pub struct FilePermissions {
327 #[derive(Copy, Clone, Debug, Default)]
328 pub struct FileTimes {
329 accessed: Option<SystemTime>,
330 modified: Option<SystemTime>,
333 #[derive(Copy, Clone, Eq, Debug)]
334 pub struct FileType {
338 impl PartialEq for FileType {
339 fn eq(&self, other: &Self) -> bool {
340 self.masked() == other.masked()
344 impl core::hash::Hash for FileType {
345 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
346 self.masked().hash(state);
351 pub struct DirBuilder {
357 fn from_stat64(stat: stat64) -> Self {
358 Self { stat, statx_extra_fields: None }
361 #[cfg(target_pointer_width = "32")]
362 pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
363 if let Some(ext) = &self.statx_extra_fields {
364 if (ext.stx_mask & libc::STATX_MTIME) != 0 {
365 return Some(&ext.stx_mtime);
371 #[cfg(target_pointer_width = "32")]
372 pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
373 if let Some(ext) = &self.statx_extra_fields {
374 if (ext.stx_mask & libc::STATX_ATIME) != 0 {
375 return Some(&ext.stx_atime);
381 #[cfg(target_pointer_width = "32")]
382 pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
383 if let Some(ext) = &self.statx_extra_fields {
384 if (ext.stx_mask & libc::STATX_CTIME) != 0 {
385 return Some(&ext.stx_ctime);
393 fn from_stat64(stat: stat64) -> Self {
400 pub fn size(&self) -> u64 {
401 self.stat.st_size as u64
403 pub fn perm(&self) -> FilePermissions {
404 FilePermissions { mode: (self.stat.st_mode as mode_t) }
407 pub fn file_type(&self) -> FileType {
408 FileType { mode: self.stat.st_mode as mode_t }
412 #[cfg(target_os = "netbsd")]
414 pub fn modified(&self) -> io::Result<SystemTime> {
415 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64))
418 pub fn accessed(&self) -> io::Result<SystemTime> {
419 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64))
422 pub fn created(&self) -> io::Result<SystemTime> {
423 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64))
427 #[cfg(not(target_os = "netbsd"))]
429 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
430 pub fn modified(&self) -> io::Result<SystemTime> {
431 #[cfg(target_pointer_width = "32")]
433 if let Some(mtime) = self.stx_mtime() {
434 return Ok(SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64));
438 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64))
441 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
442 pub fn modified(&self) -> io::Result<SystemTime> {
443 Ok(SystemTime::new(self.stat.st_mtime as i64, 0))
446 #[cfg(target_os = "horizon")]
447 pub fn modified(&self) -> io::Result<SystemTime> {
448 Ok(SystemTime::from(self.stat.st_mtim))
451 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
452 pub fn accessed(&self) -> io::Result<SystemTime> {
453 #[cfg(target_pointer_width = "32")]
455 if let Some(atime) = self.stx_atime() {
456 return Ok(SystemTime::new(atime.tv_sec, atime.tv_nsec as i64));
460 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64))
463 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
464 pub fn accessed(&self) -> io::Result<SystemTime> {
465 Ok(SystemTime::new(self.stat.st_atime as i64, 0))
468 #[cfg(target_os = "horizon")]
469 pub fn accessed(&self) -> io::Result<SystemTime> {
470 Ok(SystemTime::from(self.stat.st_atim))
474 target_os = "freebsd",
475 target_os = "openbsd",
478 target_os = "watchos",
480 pub fn created(&self) -> io::Result<SystemTime> {
481 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64))
485 target_os = "freebsd",
486 target_os = "openbsd",
489 target_os = "watchos",
491 pub fn created(&self) -> io::Result<SystemTime> {
493 if let Some(ext) = &self.statx_extra_fields {
494 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
495 Ok(SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64))
497 Err(io::const_io_error!(
498 io::ErrorKind::Uncategorized,
499 "creation time is not available for the filesystem",
505 Err(io::const_io_error!(
506 io::ErrorKind::Unsupported,
507 "creation time is not available on this platform \
513 impl AsInner<stat64> for FileAttr {
514 fn as_inner(&self) -> &stat64 {
519 impl FilePermissions {
520 pub fn readonly(&self) -> bool {
521 // check if any class (owner, group, others) has write permission
522 self.mode & 0o222 == 0
525 pub fn set_readonly(&mut self, readonly: bool) {
527 // remove write permission for all classes; equivalent to `chmod a-w <file>`
530 // add write permission for all classes; equivalent to `chmod a+w <file>`
534 pub fn mode(&self) -> u32 {
540 pub fn set_accessed(&mut self, t: SystemTime) {
541 self.accessed = Some(t);
544 pub fn set_modified(&mut self, t: SystemTime) {
545 self.modified = Some(t);
550 pub fn is_dir(&self) -> bool {
551 self.is(libc::S_IFDIR)
553 pub fn is_file(&self) -> bool {
554 self.is(libc::S_IFREG)
556 pub fn is_symlink(&self) -> bool {
557 self.is(libc::S_IFLNK)
560 pub fn is(&self, mode: mode_t) -> bool {
561 self.masked() == mode
564 fn masked(&self) -> mode_t {
565 self.mode & libc::S_IFMT
569 impl FromInner<u32> for FilePermissions {
570 fn from_inner(mode: u32) -> FilePermissions {
571 FilePermissions { mode: mode as mode_t }
575 impl fmt::Debug for ReadDir {
576 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
578 // Thus the result will be e g 'ReadDir("/home")'
579 fmt::Debug::fmt(&*self.inner.root, f)
583 impl Iterator for ReadDir {
584 type Item = io::Result<DirEntry>;
587 target_os = "android",
589 target_os = "solaris",
590 target_os = "fuchsia",
592 target_os = "illumos"
594 fn next(&mut self) -> Option<io::Result<DirEntry>> {
595 if self.end_of_stream {
601 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
602 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
603 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
604 // thread safety for readdir() as long an individual DIR* is not accessed
605 // concurrently, which is sufficient for Rust.
606 super::os::set_errno(0);
607 let entry_ptr = readdir64(self.inner.dirp.0);
608 if entry_ptr.is_null() {
609 // We either encountered an error, or reached the end. Either way,
610 // the next call to next() should return None.
611 self.end_of_stream = true;
613 // To distinguish between errors and end-of-directory, we had to clear
614 // errno beforehand to check for an error now.
615 return match super::os::errno() {
617 e => Some(Err(Error::from_raw_os_error(e))),
621 // The dirent64 struct is a weird imaginary thing that isn't ever supposed
622 // to be worked with by value. Its trailing d_name field is declared
623 // variously as [c_char; 256] or [c_char; 1] on different systems but
624 // either way that size is meaningless; only the offset of d_name is
625 // meaningful. The dirent64 pointers that libc returns from readdir64 are
626 // allowed to point to allocations smaller _or_ LARGER than implied by the
627 // definition of the struct.
629 // As such, we need to be even more careful with dirent64 than if its
630 // contents were "simply" partially initialized data.
632 // Like for uninitialized contents, converting entry_ptr to `&dirent64`
633 // would not be legal. However, unique to dirent64 is that we don't even
634 // get to use `addr_of!((*entry_ptr).d_name)` because that operation
635 // requires the full extent of *entry_ptr to be in bounds of the same
636 // allocation, which is not necessarily the case here.
638 // Absent any other way to obtain a pointer to `(*entry_ptr).d_name`
639 // legally in Rust analogously to how it would be done in C, we instead
640 // need to make our own non-libc allocation that conforms to the weird
641 // imaginary definition of dirent64, and use that for a field offset
643 macro_rules! offset_ptr {
644 ($entry_ptr:expr, $field:ident) => {{
645 const OFFSET: isize = {
646 let delusion = MaybeUninit::<dirent64>::uninit();
647 let entry_ptr = delusion.as_ptr();
649 ptr::addr_of!((*entry_ptr).$field)
651 .offset_from(entry_ptr.cast::<u8>())
655 // Cast to the same type determined by the else branch.
656 $entry_ptr.byte_offset(OFFSET).cast::<_>()
658 #[allow(deref_nullptr)]
660 ptr::addr_of!((*ptr::null::<dirent64>()).$field)
666 // d_name is guaranteed to be null-terminated.
667 let name = CStr::from_ptr(offset_ptr!(entry_ptr, d_name).cast());
668 let name_bytes = name.to_bytes();
669 if name_bytes == b"." || name_bytes == b".." {
673 let entry = dirent64_min {
674 d_ino: *offset_ptr!(entry_ptr, d_ino) as u64,
675 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
676 d_type: *offset_ptr!(entry_ptr, d_type) as u8,
679 return Some(Ok(DirEntry {
681 name: name.to_owned(),
682 dir: Arc::clone(&self.inner),
689 target_os = "android",
691 target_os = "solaris",
692 target_os = "fuchsia",
694 target_os = "illumos"
696 fn next(&mut self) -> Option<io::Result<DirEntry>> {
697 if self.end_of_stream {
702 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
703 let mut entry_ptr = ptr::null_mut();
705 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
707 if entry_ptr.is_null() {
708 // We encountered an error (which will be returned in this iteration), but
709 // we also reached the end of the directory stream. The `end_of_stream`
710 // flag is enabled to make sure that we return `None` in the next iteration
711 // (instead of looping forever)
712 self.end_of_stream = true;
714 return Some(Err(Error::from_raw_os_error(err)));
716 if entry_ptr.is_null() {
719 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
720 return Some(Ok(ret));
729 let r = unsafe { libc::closedir(self.0) };
731 r == 0 || crate::io::Error::last_os_error().kind() == crate::io::ErrorKind::Interrupted,
732 "unexpected error during closedir: {:?}",
733 crate::io::Error::last_os_error()
739 pub fn path(&self) -> PathBuf {
740 self.dir.root.join(self.file_name_os_str())
743 pub fn file_name(&self) -> OsString {
744 self.file_name_os_str().to_os_string()
748 any(target_os = "linux", target_os = "emscripten", target_os = "android"),
751 pub fn metadata(&self) -> io::Result<FileAttr> {
752 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
753 let name = self.name_cstr().as_ptr();
756 if let Some(ret) = unsafe { try_statx(
759 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
766 let mut stat: stat64 = unsafe { mem::zeroed() };
767 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
768 Ok(FileAttr::from_stat64(stat))
772 not(any(target_os = "linux", target_os = "emscripten", target_os = "android")),
775 pub fn metadata(&self) -> io::Result<FileAttr> {
780 target_os = "solaris",
781 target_os = "illumos",
783 target_os = "vxworks"
785 pub fn file_type(&self) -> io::Result<FileType> {
786 self.metadata().map(|m| m.file_type())
790 target_os = "solaris",
791 target_os = "illumos",
793 target_os = "vxworks"
795 pub fn file_type(&self) -> io::Result<FileType> {
796 match self.entry.d_type {
797 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
798 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
799 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
800 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
801 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
802 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
803 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
804 _ => self.metadata().map(|m| m.file_type()),
811 target_os = "watchos",
813 target_os = "emscripten",
814 target_os = "android",
815 target_os = "solaris",
816 target_os = "illumos",
819 target_os = "fuchsia",
821 target_os = "vxworks",
822 target_os = "espidf",
823 target_os = "horizon"
825 pub fn ino(&self) -> u64 {
826 self.entry.d_ino as u64
830 target_os = "freebsd",
831 target_os = "openbsd",
832 target_os = "netbsd",
833 target_os = "dragonfly"
835 pub fn ino(&self) -> u64 {
836 self.entry.d_fileno as u64
842 target_os = "watchos",
843 target_os = "netbsd",
844 target_os = "openbsd",
845 target_os = "freebsd",
846 target_os = "dragonfly"
848 fn name_bytes(&self) -> &[u8] {
851 slice::from_raw_parts(
852 self.entry.d_name.as_ptr() as *const u8,
853 self.entry.d_namlen as usize,
860 target_os = "watchos",
861 target_os = "netbsd",
862 target_os = "openbsd",
863 target_os = "freebsd",
864 target_os = "dragonfly"
866 fn name_bytes(&self) -> &[u8] {
867 self.name_cstr().to_bytes()
871 target_os = "android",
873 target_os = "solaris",
874 target_os = "illumos",
875 target_os = "fuchsia",
878 fn name_cstr(&self) -> &CStr {
879 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
882 target_os = "android",
884 target_os = "solaris",
885 target_os = "illumos",
886 target_os = "fuchsia",
889 fn name_cstr(&self) -> &CStr {
893 pub fn file_name_os_str(&self) -> &OsStr {
894 OsStr::from_bytes(self.name_bytes())
899 pub fn new() -> OpenOptions {
914 pub fn read(&mut self, read: bool) {
917 pub fn write(&mut self, write: bool) {
920 pub fn append(&mut self, append: bool) {
921 self.append = append;
923 pub fn truncate(&mut self, truncate: bool) {
924 self.truncate = truncate;
926 pub fn create(&mut self, create: bool) {
927 self.create = create;
929 pub fn create_new(&mut self, create_new: bool) {
930 self.create_new = create_new;
933 pub fn custom_flags(&mut self, flags: i32) {
934 self.custom_flags = flags;
936 pub fn mode(&mut self, mode: u32) {
937 self.mode = mode as mode_t;
940 fn get_access_mode(&self) -> io::Result<c_int> {
941 match (self.read, self.write, self.append) {
942 (true, false, false) => Ok(libc::O_RDONLY),
943 (false, true, false) => Ok(libc::O_WRONLY),
944 (true, true, false) => Ok(libc::O_RDWR),
945 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
946 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
947 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
951 fn get_creation_mode(&self) -> io::Result<c_int> {
952 match (self.write, self.append) {
955 if self.truncate || self.create || self.create_new {
956 return Err(Error::from_raw_os_error(libc::EINVAL));
960 if self.truncate && !self.create_new {
961 return Err(Error::from_raw_os_error(libc::EINVAL));
966 Ok(match (self.create, self.truncate, self.create_new) {
967 (false, false, false) => 0,
968 (true, false, false) => libc::O_CREAT,
969 (false, true, false) => libc::O_TRUNC,
970 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
971 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
977 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
978 run_path_with_cstr(path, |path| File::open_c(path, opts))
981 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
982 let flags = libc::O_CLOEXEC
983 | opts.get_access_mode()?
984 | opts.get_creation_mode()?
985 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
986 // The third argument of `open64` is documented to have type `mode_t`. On
987 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
988 // However, since this is a variadic function, C integer promotion rules mean that on
989 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
990 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
991 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
994 pub fn file_attr(&self) -> io::Result<FileAttr> {
995 let fd = self.as_raw_fd();
998 if let Some(ret) = unsafe { try_statx(
1000 b"\0" as *const _ as *const c_char,
1001 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
1008 let mut stat: stat64 = unsafe { mem::zeroed() };
1009 cvt(unsafe { fstat64(fd, &mut stat) })?;
1010 Ok(FileAttr::from_stat64(stat))
1013 pub fn fsync(&self) -> io::Result<()> {
1014 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
1017 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
1018 unsafe fn os_fsync(fd: c_int) -> c_int {
1019 libc::fcntl(fd, libc::F_FULLFSYNC)
1021 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "watchos")))]
1022 unsafe fn os_fsync(fd: c_int) -> c_int {
1027 pub fn datasync(&self) -> io::Result<()> {
1028 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1031 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
1032 unsafe fn os_datasync(fd: c_int) -> c_int {
1033 libc::fcntl(fd, libc::F_FULLFSYNC)
1036 target_os = "freebsd",
1037 target_os = "linux",
1038 target_os = "android",
1039 target_os = "netbsd",
1040 target_os = "openbsd"
1042 unsafe fn os_datasync(fd: c_int) -> c_int {
1046 target_os = "android",
1047 target_os = "freebsd",
1049 target_os = "linux",
1050 target_os = "macos",
1051 target_os = "netbsd",
1052 target_os = "openbsd",
1053 target_os = "watchos",
1055 unsafe fn os_datasync(fd: c_int) -> c_int {
1060 pub fn truncate(&self, size: u64) -> io::Result<()> {
1062 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1063 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1066 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1070 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1071 self.0.read_vectored(bufs)
1075 pub fn is_read_vectored(&self) -> bool {
1076 self.0.is_read_vectored()
1079 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1080 self.0.read_at(buf, offset)
1083 pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1084 self.0.read_buf(cursor)
1087 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1091 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1092 self.0.write_vectored(bufs)
1096 pub fn is_write_vectored(&self) -> bool {
1097 self.0.is_write_vectored()
1100 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1101 self.0.write_at(buf, offset)
1104 pub fn flush(&self) -> io::Result<()> {
1108 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1109 let (whence, pos) = match pos {
1110 // Casting to `i64` is fine, too large values will end up as
1111 // negative which will cause an error in `lseek64`.
1112 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1113 SeekFrom::End(off) => (libc::SEEK_END, off),
1114 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1116 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1120 pub fn duplicate(&self) -> io::Result<File> {
1121 self.0.duplicate().map(File)
1124 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1125 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1129 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1130 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))]
1131 let to_timespec = |time: Option<SystemTime>| {
1133 Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1134 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")),
1135 Some(_) => Err(io::const_io_error!(io::ErrorKind::InvalidInput, "timestamp is too small to set as a file time")),
1136 None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
1139 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))]
1140 let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1142 if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon"))] {
1143 // Redox doesn't appear to support `UTIME_OMIT`.
1144 // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1145 // the same as for Redox.
1147 Err(io::const_io_error!(
1148 io::ErrorKind::Unsupported,
1149 "setting file times not supported",
1151 } else if #[cfg(any(target_os = "android", target_os = "macos"))] {
1152 // futimens requires macOS 10.13, and Android API level 19
1154 weak!(fn futimens(c_int, *const libc::timespec) -> c_int);
1155 match futimens.get() {
1156 Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1157 #[cfg(target_os = "macos")]
1159 fn ts_to_tv(ts: &libc::timespec) -> libc::timeval {
1162 tv_usec: (ts.tv_nsec / 1000) as _
1165 let timevals = [ts_to_tv(×[0]), ts_to_tv(×[1])];
1166 libc::futimes(self.as_raw_fd(), timevals.as_ptr())
1168 // futimes requires even newer Android.
1169 #[cfg(target_os = "android")]
1170 None => return Err(io::const_io_error!(
1171 io::ErrorKind::Unsupported,
1172 "setting file times requires Android API level >= 19",
1178 cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1186 pub fn new() -> DirBuilder {
1187 DirBuilder { mode: 0o777 }
1190 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1191 run_path_with_cstr(p, |p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1194 pub fn set_mode(&mut self, mode: u32) {
1195 self.mode = mode as mode_t;
1199 impl AsInner<FileDesc> for File {
1200 fn as_inner(&self) -> &FileDesc {
1205 impl AsInnerMut<FileDesc> for File {
1206 fn as_inner_mut(&mut self) -> &mut FileDesc {
1211 impl IntoInner<FileDesc> for File {
1212 fn into_inner(self) -> FileDesc {
1217 impl FromInner<FileDesc> for File {
1218 fn from_inner(file_desc: FileDesc) -> Self {
1223 impl AsFd for File {
1224 fn as_fd(&self) -> BorrowedFd<'_> {
1229 impl AsRawFd for File {
1230 fn as_raw_fd(&self) -> RawFd {
1235 impl IntoRawFd for File {
1236 fn into_raw_fd(self) -> RawFd {
1237 self.0.into_raw_fd()
1241 impl FromRawFd for File {
1242 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1243 Self(FromRawFd::from_raw_fd(raw_fd))
1247 impl fmt::Debug for File {
1248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1250 target_os = "linux",
1251 target_os = "netbsd",
1252 target_os = "illumos",
1253 target_os = "solaris"
1255 fn get_path(fd: c_int) -> Option<PathBuf> {
1256 let mut p = PathBuf::from("/proc/self/fd");
1257 p.push(&fd.to_string());
1261 #[cfg(target_os = "macos")]
1262 fn get_path(fd: c_int) -> Option<PathBuf> {
1263 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1264 // is inevitable in this case because macOS defines `fcntl` with
1265 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1266 // alternatives. If a better method is invented, it should be used
1268 let mut buf = vec![0; libc::PATH_MAX as usize];
1269 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1273 let l = buf.iter().position(|&c| c == 0).unwrap();
1274 buf.truncate(l as usize);
1275 buf.shrink_to_fit();
1276 Some(PathBuf::from(OsString::from_vec(buf)))
1279 #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
1280 fn get_path(fd: c_int) -> Option<PathBuf> {
1281 let info = Box::<libc::kinfo_file>::new_zeroed();
1282 let mut info = unsafe { info.assume_init() };
1283 info.kf_structsize = mem::size_of::<libc::kinfo_file>() as libc::c_int;
1284 let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
1288 let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
1289 Some(PathBuf::from(OsString::from_vec(buf)))
1292 #[cfg(target_os = "vxworks")]
1293 fn get_path(fd: c_int) -> Option<PathBuf> {
1294 let mut buf = vec![0; libc::PATH_MAX as usize];
1295 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1299 let l = buf.iter().position(|&c| c == 0).unwrap();
1300 buf.truncate(l as usize);
1301 Some(PathBuf::from(OsString::from_vec(buf)))
1305 target_os = "linux",
1306 target_os = "macos",
1307 target_os = "vxworks",
1308 all(target_os = "freebsd", target_arch = "x86_64"),
1309 target_os = "netbsd",
1310 target_os = "illumos",
1311 target_os = "solaris"
1313 fn get_path(_fd: c_int) -> Option<PathBuf> {
1314 // FIXME(#24570): implement this for other Unix platforms
1319 target_os = "linux",
1320 target_os = "macos",
1321 target_os = "freebsd",
1322 target_os = "netbsd",
1323 target_os = "openbsd",
1324 target_os = "vxworks"
1326 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1327 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1331 match mode & libc::O_ACCMODE {
1332 libc::O_RDONLY => Some((true, false)),
1333 libc::O_RDWR => Some((true, true)),
1334 libc::O_WRONLY => Some((false, true)),
1340 target_os = "linux",
1341 target_os = "macos",
1342 target_os = "freebsd",
1343 target_os = "netbsd",
1344 target_os = "openbsd",
1345 target_os = "vxworks"
1347 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1348 // FIXME(#24570): implement this for other Unix platforms
1352 let fd = self.as_raw_fd();
1353 let mut b = f.debug_struct("File");
1355 if let Some(path) = get_path(fd) {
1356 b.field("path", &path);
1358 if let Some((read, write)) = get_mode(fd) {
1359 b.field("read", &read).field("write", &write);
1365 pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1366 let ptr = run_path_with_cstr(path, |p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1368 Err(Error::last_os_error())
1370 let root = path.to_path_buf();
1371 let inner = InnerReadDir { dirp: Dir(ptr), root };
1372 Ok(ReadDir::new(inner))
1376 pub fn unlink(p: &Path) -> io::Result<()> {
1377 run_path_with_cstr(p, |p| cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ()))
1380 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1381 run_path_with_cstr(old, |old| {
1382 run_path_with_cstr(new, |new| {
1383 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1388 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1389 run_path_with_cstr(p, |p| cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ()))
1392 pub fn rmdir(p: &Path) -> io::Result<()> {
1393 run_path_with_cstr(p, |p| cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ()))
1396 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1397 run_path_with_cstr(p, |c_path| {
1398 let p = c_path.as_ptr();
1400 let mut buf = Vec::with_capacity(256);
1404 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })?
1408 buf.set_len(buf_read);
1411 if buf_read != buf.capacity() {
1412 buf.shrink_to_fit();
1414 return Ok(PathBuf::from(OsString::from_vec(buf)));
1417 // Trigger the internal buffer resizing logic of `Vec` by requiring
1418 // more space than the current capacity. The length is guaranteed to be
1419 // the same as the capacity due to the if statement above.
1425 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1426 run_path_with_cstr(original, |original| {
1427 run_path_with_cstr(link, |link| {
1428 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
1433 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1434 run_path_with_cstr(original, |original| {
1435 run_path_with_cstr(link, |link| {
1437 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon"))] {
1438 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1439 // it implementation-defined whether `link` follows symlinks, so rely on the
1440 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1441 // Android has `linkat` on newer versions, but we happen to know `link`
1442 // always has the correct behavior, so it's here as well.
1443 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1444 } else if #[cfg(target_os = "macos")] {
1445 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1446 // versions have it. We want to use linkat if it is available, so we use weak!
1447 // to check. `linkat` is preferable to `link` because it gives us a flag to
1448 // specify how symlinks should be handled. We pass 0 as the flags argument,
1449 // meaning it shouldn't follow symlinks.
1450 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1452 if let Some(f) = linkat.get() {
1453 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1455 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1458 // Where we can, use `linkat` instead of `link`; see the comment above
1459 // this one for details on why.
1460 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1468 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1469 run_path_with_cstr(p, |p| {
1471 if let Some(ret) = unsafe { try_statx(
1474 libc::AT_STATX_SYNC_AS_STAT,
1481 let mut stat: stat64 = unsafe { mem::zeroed() };
1482 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1483 Ok(FileAttr::from_stat64(stat))
1487 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1488 run_path_with_cstr(p, |p| {
1490 if let Some(ret) = unsafe { try_statx(
1493 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1500 let mut stat: stat64 = unsafe { mem::zeroed() };
1501 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1502 Ok(FileAttr::from_stat64(stat))
1506 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1507 let r = run_path_with_cstr(p, |path| unsafe {
1508 Ok(libc::realpath(path.as_ptr(), ptr::null_mut()))
1511 return Err(io::Error::last_os_error());
1513 Ok(PathBuf::from(OsString::from_vec(unsafe {
1514 let buf = CStr::from_ptr(r).to_bytes().to_vec();
1515 libc::free(r as *mut _);
1520 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1521 use crate::fs::File;
1522 use crate::sys_common::fs::NOT_FILE_ERROR;
1524 let reader = File::open(from)?;
1525 let metadata = reader.metadata()?;
1526 if !metadata.is_file() {
1527 return Err(NOT_FILE_ERROR);
1529 Ok((reader, metadata))
1532 #[cfg(target_os = "espidf")]
1533 fn open_to_and_set_permissions(
1535 reader_metadata: crate::fs::Metadata,
1536 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1537 use crate::fs::OpenOptions;
1538 let writer = OpenOptions::new().open(to)?;
1539 let writer_metadata = writer.metadata()?;
1540 Ok((writer, writer_metadata))
1543 #[cfg(not(target_os = "espidf"))]
1544 fn open_to_and_set_permissions(
1546 reader_metadata: crate::fs::Metadata,
1547 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1548 use crate::fs::OpenOptions;
1549 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1551 let perm = reader_metadata.permissions();
1552 let writer = OpenOptions::new()
1553 // create the file with the correct mode right away
1559 let writer_metadata = writer.metadata()?;
1560 if writer_metadata.is_file() {
1561 // Set the correct file permissions, in case the file already existed.
1562 // Don't set the permissions on already existing non-files like
1563 // pipes/FIFOs or device nodes.
1564 writer.set_permissions(perm)?;
1566 Ok((writer, writer_metadata))
1570 target_os = "linux",
1571 target_os = "android",
1572 target_os = "macos",
1574 target_os = "watchos",
1576 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1577 let (mut reader, reader_metadata) = open_from(from)?;
1578 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1580 io::copy(&mut reader, &mut writer)
1583 #[cfg(any(target_os = "linux", target_os = "android"))]
1584 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1585 let (mut reader, reader_metadata) = open_from(from)?;
1586 let max_len = u64::MAX;
1587 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1589 use super::kernel_copy::{copy_regular_files, CopyResult};
1591 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1592 CopyResult::Ended(bytes) => Ok(bytes),
1593 CopyResult::Error(e, _) => Err(e),
1594 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1595 Ok(bytes) => Ok(bytes + written),
1601 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
1602 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1603 use crate::sync::atomic::{AtomicBool, Ordering};
1605 const COPYFILE_ACL: u32 = 1 << 0;
1606 const COPYFILE_STAT: u32 = 1 << 1;
1607 const COPYFILE_XATTR: u32 = 1 << 2;
1608 const COPYFILE_DATA: u32 = 1 << 3;
1610 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1611 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1612 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1614 const COPYFILE_STATE_COPIED: u32 = 8;
1616 #[allow(non_camel_case_types)]
1617 type copyfile_state_t = *mut libc::c_void;
1618 #[allow(non_camel_case_types)]
1619 type copyfile_flags_t = u32;
1625 state: copyfile_state_t,
1626 flags: copyfile_flags_t,
1628 fn copyfile_state_alloc() -> copyfile_state_t;
1629 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1630 fn copyfile_state_get(
1631 state: copyfile_state_t,
1633 dst: *mut libc::c_void,
1637 struct FreeOnDrop(copyfile_state_t);
1638 impl Drop for FreeOnDrop {
1639 fn drop(&mut self) {
1640 // The code below ensures that `FreeOnDrop` is never a null pointer
1642 // `copyfile_state_free` returns -1 if the `to` or `from` files
1643 // cannot be closed. However, this is not considered this an
1645 copyfile_state_free(self.0);
1650 // MacOS prior to 10.12 don't support `fclonefileat`
1651 // We store the availability in a global to avoid unnecessary syscalls
1652 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1656 dst_dirfd: libc::c_int,
1662 let (reader, reader_metadata) = open_from(from)?;
1664 // Opportunistically attempt to create a copy-on-write clone of `from`
1665 // using `fclonefileat`.
1666 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1667 let clonefile_result = run_path_with_cstr(to, |to| {
1668 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
1670 match clonefile_result {
1671 Ok(_) => return Ok(reader_metadata.len()),
1672 Err(err) => match err.raw_os_error() {
1673 // `fclonefileat` will fail on non-APFS volumes, if the
1674 // destination already exists, or if the source and destination
1675 // are on different devices. In all these cases `fcopyfile`
1677 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1678 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1679 _ => return Err(err),
1684 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1685 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1687 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1688 // always safe to call `copyfile_state_free`
1689 let state = unsafe {
1690 let state = copyfile_state_alloc();
1691 if state.is_null() {
1692 return Err(crate::io::Error::last_os_error());
1697 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1699 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1701 let mut bytes_copied: libc::off_t = 0;
1705 COPYFILE_STATE_COPIED,
1706 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1709 Ok(bytes_copied as u64)
1712 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1713 run_path_with_cstr(path, |path| {
1714 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
1719 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1720 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1724 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1725 run_path_with_cstr(path, |path| {
1726 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
1731 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1732 pub fn chroot(dir: &Path) -> io::Result<()> {
1733 run_path_with_cstr(dir, |dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
1736 pub use remove_dir_impl::remove_dir_all;
1738 // Fallback for REDOX, ESP-ID, Horizon, and Miri
1739 #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri))]
1740 mod remove_dir_impl {
1741 pub use crate::sys_common::fs::remove_dir_all;
1744 // Modern implementation using openat(), unlinkat() and fdopendir()
1745 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri)))]
1746 mod remove_dir_impl {
1747 use super::{lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1748 use crate::ffi::CStr;
1750 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1751 use crate::os::unix::prelude::{OwnedFd, RawFd};
1752 use crate::path::{Path, PathBuf};
1753 use crate::sys::common::small_c_string::run_path_with_cstr;
1754 use crate::sys::{cvt, cvt_r};
1757 all(target_os = "linux", target_env = "gnu"),
1758 all(target_os = "macos", not(target_arch = "aarch64"))
1760 use libc::{fdopendir, openat, unlinkat};
1761 #[cfg(all(target_os = "linux", target_env = "gnu"))]
1762 use libc::{fdopendir, openat64 as openat, unlinkat};
1763 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1764 use macos_weak::{fdopendir, openat, unlinkat};
1766 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1768 use crate::sys::weak::weak;
1769 use libc::{c_char, c_int, DIR};
1771 fn get_openat_fn() -> Option<unsafe extern "C" fn(c_int, *const c_char, c_int) -> c_int> {
1772 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1776 pub fn has_openat() -> bool {
1777 get_openat_fn().is_some()
1780 pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1781 get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| {
1782 crate::sys::unix::os::set_errno(libc::ENOSYS);
1787 pub unsafe fn fdopendir(fd: c_int) -> *mut DIR {
1788 #[cfg(all(target_os = "macos", target_arch = "x86"))]
1789 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64$UNIX2003");
1790 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1791 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1792 fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| {
1793 crate::sys::unix::os::set_errno(libc::ENOSYS);
1794 crate::ptr::null_mut()
1798 pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1799 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1800 unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| {
1801 crate::sys::unix::os::set_errno(libc::ENOSYS);
1807 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1808 let fd = cvt_r(|| unsafe {
1810 parent_fd.unwrap_or(libc::AT_FDCWD),
1812 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1815 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1818 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1819 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1821 return Err(io::Error::last_os_error());
1823 let dirp = Dir(ptr);
1824 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1825 let new_parent_fd = dir_fd.into_raw_fd();
1826 // a valid root is not needed because we do not call any functions involving the full path
1827 // of the DirEntrys.
1828 let dummy_root = PathBuf::new();
1829 let inner = InnerReadDir { dirp, root: dummy_root };
1830 Ok((ReadDir::new(inner), new_parent_fd))
1834 target_os = "solaris",
1835 target_os = "illumos",
1836 target_os = "haiku",
1837 target_os = "vxworks",
1839 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1844 target_os = "solaris",
1845 target_os = "illumos",
1846 target_os = "haiku",
1847 target_os = "vxworks",
1849 fn is_dir(ent: &DirEntry) -> Option<bool> {
1850 match ent.entry.d_type {
1851 libc::DT_UNKNOWN => None,
1852 libc::DT_DIR => Some(true),
1857 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
1858 // try opening as directory
1859 let fd = match openat_nofollow_dironly(parent_fd, &path) {
1860 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
1861 // not a directory - don't traverse further
1862 // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
1863 return match parent_fd {
1865 Some(parent_fd) => {
1866 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
1868 // ...unless this was supposed to be the deletion root directory
1875 // open the directory passing ownership of the fd
1876 let (dir, fd) = fdreaddir(fd)?;
1879 let child_name = child.name_cstr();
1880 match is_dir(&child) {
1882 remove_dir_all_recursive(Some(fd), child_name)?;
1885 cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
1888 // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
1889 // if the process has the appropriate privileges. This however can causing orphaned
1890 // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
1891 // into it first instead of trying to unlink() it.
1892 remove_dir_all_recursive(Some(fd), child_name)?;
1897 // unlink the directory after removing its contents
1899 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
1904 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1905 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1906 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1908 let attr = lstat(p)?;
1909 if attr.file_type().is_symlink() {
1910 crate::fs::remove_file(p)
1912 run_path_with_cstr(p, |p| remove_dir_all_recursive(None, &p))
1916 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64"))))]
1917 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1918 remove_dir_all_modern(p)
1921 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1922 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1923 if macos_weak::has_openat() {
1924 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1925 remove_dir_all_modern(p)
1927 // fall back to classic implementation
1928 crate::sys_common::fs::remove_dir_all(p)