1 use crate::os::unix::prelude::*;
3 use crate::ffi::{CStr, CString, OsStr, OsString};
5 use crate::io::{self, Error, IoSlice, IoSliceMut, ReadBuf, SeekFrom};
7 use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
8 use crate::path::{Path, PathBuf};
11 use crate::sys::fd::FileDesc;
12 use crate::sys::time::SystemTime;
13 use crate::sys::{cvt, cvt_r};
14 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
17 all(target_os = "linux", target_env = "gnu"),
21 use crate::sys::weak::syscall;
22 #[cfg(target_os = "macos")]
23 use crate::sys::weak::weak;
25 use libc::{c_int, mode_t};
30 all(target_os = "linux", target_env = "gnu")
33 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
35 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
38 target_os = "android",
39 target_os = "solaris",
40 target_os = "fuchsia",
44 use libc::readdir as readdir64;
45 #[cfg(target_os = "linux")]
47 #[cfg(any(target_os = "emscripten", target_os = "l4re"))]
48 use libc::readdir64_r;
50 target_os = "android",
52 target_os = "emscripten",
53 target_os = "solaris",
54 target_os = "illumos",
56 target_os = "fuchsia",
59 use libc::readdir_r as readdir64_r;
60 #[cfg(target_os = "android")]
62 dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
63 lstat as lstat64, off64_t, open as open64, stat as stat64,
67 target_os = "emscripten",
72 dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
73 lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
75 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
76 use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
78 pub use crate::sys_common::fs::try_exists;
80 pub struct File(FileDesc);
82 // FIXME: This should be available on Linux with all `target_env`.
83 // But currently only glibc exposes `statx` fn and structs.
84 // We don't want to import unverified raw C structs here directly.
85 // https://github.com/rust-lang/rust/pull/67774
86 macro_rules! cfg_has_statx {
87 ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
89 if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
96 ($($block_inner:tt)*) => {
97 #[cfg(all(target_os = "linux", target_env = "gnu"))]
106 pub struct FileAttr {
108 statx_extra_fields: Option<StatxExtraFields>,
112 struct StatxExtraFields {
113 // This is needed to check if btime is supported by the filesystem.
115 stx_btime: libc::statx_timestamp,
118 // We prefer `statx` on Linux if available, which contains file creation time.
119 // Default `stat64` contains no creation time.
125 ) -> Option<io::Result<FileAttr>> {
126 use crate::sync::atomic::{AtomicU8, Ordering};
128 // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
129 // We store the availability in global to avoid unnecessary syscalls.
133 static STATX_STATE: AtomicU8 = AtomicU8::new(0);
137 pathname: *const c_char,
140 statxbuf: *mut libc::statx
144 match STATX_STATE.load(Ordering::Relaxed) {
146 // It is a trick to call `statx` with null pointers to check if the syscall
147 // is available. According to the manual, it is expected to fail with EFAULT.
148 // We do this mainly for performance, since it is nearly hundreds times
149 // faster than a normal successful call.
150 let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
152 .and_then(|e| e.raw_os_error());
153 // We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
154 // and returns `EPERM`. Listing all possible errors seems not a good idea.
155 // See: https://github.com/rust-lang/rust/issues/65662
156 if err != Some(libc::EFAULT) {
157 STATX_STATE.store(1, Ordering::Relaxed);
160 STATX_STATE.store(2, Ordering::Relaxed);
166 let mut buf: libc::statx = mem::zeroed();
167 if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
168 return Some(Err(err));
171 // We cannot fill `stat64` exhaustively because of private padding fields.
172 let mut stat: stat64 = mem::zeroed();
173 // `c_ulong` on gnu-mips, `dev_t` otherwise
174 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
175 stat.st_ino = buf.stx_ino as libc::ino64_t;
176 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
177 stat.st_mode = buf.stx_mode as libc::mode_t;
178 stat.st_uid = buf.stx_uid as libc::uid_t;
179 stat.st_gid = buf.stx_gid as libc::gid_t;
180 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
181 stat.st_size = buf.stx_size as off64_t;
182 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
183 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
184 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
185 // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
186 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
187 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
188 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
189 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
190 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
192 let extra = StatxExtraFields {
193 stx_mask: buf.stx_mask,
194 stx_btime: buf.stx_btime,
197 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
202 pub struct FileAttr {
207 // all DirEntry's will have a reference to this struct
208 struct InnerReadDir {
214 inner: Arc<InnerReadDir>,
216 target_os = "android",
218 target_os = "solaris",
219 target_os = "illumos",
220 target_os = "fuchsia",
226 struct Dir(*mut libc::DIR);
228 unsafe impl Send for Dir {}
229 unsafe impl Sync for Dir {}
232 target_os = "android",
234 target_os = "solaris",
235 target_os = "illumos",
236 target_os = "fuchsia",
239 pub struct DirEntry {
240 dir: Arc<InnerReadDir>,
242 // We need to store an owned copy of the entry name on platforms that use
243 // readdir() (not readdir_r()), because a) struct dirent may use a flexible
244 // array to store the name, b) it lives only until the next readdir() call.
248 // Define a minimal subset of fields we need from `dirent64`, especially since
249 // we're not using the immediate `d_name` on these targets. Keeping this as an
250 // `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
252 target_os = "android",
254 target_os = "solaris",
255 target_os = "illumos",
256 target_os = "fuchsia",
259 struct dirent64_min {
261 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
266 target_os = "android",
268 target_os = "solaris",
269 target_os = "illumos",
270 target_os = "fuchsia",
273 pub struct DirEntry {
274 dir: Arc<InnerReadDir>,
275 // The full entry includes a fixed-length `d_name`.
279 #[derive(Clone, Debug)]
280 pub struct OpenOptions {
293 #[derive(Clone, PartialEq, Eq, Debug)]
294 pub struct FilePermissions {
298 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
299 pub struct FileType {
304 pub struct DirBuilder {
310 fn from_stat64(stat: stat64) -> Self {
311 Self { stat, statx_extra_fields: None }
316 fn from_stat64(stat: stat64) -> Self {
323 pub fn size(&self) -> u64 {
324 self.stat.st_size as u64
326 pub fn perm(&self) -> FilePermissions {
327 FilePermissions { mode: (self.stat.st_mode as mode_t) }
330 pub fn file_type(&self) -> FileType {
331 FileType { mode: self.stat.st_mode as mode_t }
335 #[cfg(target_os = "netbsd")]
337 pub fn modified(&self) -> io::Result<SystemTime> {
338 Ok(SystemTime::from(libc::timespec {
339 tv_sec: self.stat.st_mtime as libc::time_t,
340 tv_nsec: self.stat.st_mtimensec as libc::c_long,
344 pub fn accessed(&self) -> io::Result<SystemTime> {
345 Ok(SystemTime::from(libc::timespec {
346 tv_sec: self.stat.st_atime as libc::time_t,
347 tv_nsec: self.stat.st_atimensec as libc::c_long,
351 pub fn created(&self) -> io::Result<SystemTime> {
352 Ok(SystemTime::from(libc::timespec {
353 tv_sec: self.stat.st_birthtime as libc::time_t,
354 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
359 #[cfg(not(target_os = "netbsd"))]
361 #[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
362 pub fn modified(&self) -> io::Result<SystemTime> {
363 Ok(SystemTime::from(libc::timespec {
364 tv_sec: self.stat.st_mtime as libc::time_t,
365 tv_nsec: self.stat.st_mtime_nsec as _,
369 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
370 pub fn modified(&self) -> io::Result<SystemTime> {
371 Ok(SystemTime::from(libc::timespec {
372 tv_sec: self.stat.st_mtime as libc::time_t,
377 #[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
378 pub fn accessed(&self) -> io::Result<SystemTime> {
379 Ok(SystemTime::from(libc::timespec {
380 tv_sec: self.stat.st_atime as libc::time_t,
381 tv_nsec: self.stat.st_atime_nsec as _,
385 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
386 pub fn accessed(&self) -> io::Result<SystemTime> {
387 Ok(SystemTime::from(libc::timespec {
388 tv_sec: self.stat.st_atime as libc::time_t,
394 target_os = "freebsd",
395 target_os = "openbsd",
399 pub fn created(&self) -> io::Result<SystemTime> {
400 Ok(SystemTime::from(libc::timespec {
401 tv_sec: self.stat.st_birthtime as libc::time_t,
402 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
407 target_os = "freebsd",
408 target_os = "openbsd",
412 pub fn created(&self) -> io::Result<SystemTime> {
414 if let Some(ext) = &self.statx_extra_fields {
415 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
416 Ok(SystemTime::from(libc::timespec {
417 tv_sec: ext.stx_btime.tv_sec as libc::time_t,
418 tv_nsec: ext.stx_btime.tv_nsec as _,
421 Err(io::const_io_error!(
422 io::ErrorKind::Uncategorized,
423 "creation time is not available for the filesystem",
429 Err(io::const_io_error!(
430 io::ErrorKind::Unsupported,
431 "creation time is not available on this platform \
437 impl AsInner<stat64> for FileAttr {
438 fn as_inner(&self) -> &stat64 {
443 impl FilePermissions {
444 pub fn readonly(&self) -> bool {
445 // check if any class (owner, group, others) has write permission
446 self.mode & 0o222 == 0
449 pub fn set_readonly(&mut self, readonly: bool) {
451 // remove write permission for all classes; equivalent to `chmod a-w <file>`
454 // add write permission for all classes; equivalent to `chmod a+w <file>`
458 pub fn mode(&self) -> u32 {
464 pub fn is_dir(&self) -> bool {
465 self.is(libc::S_IFDIR)
467 pub fn is_file(&self) -> bool {
468 self.is(libc::S_IFREG)
470 pub fn is_symlink(&self) -> bool {
471 self.is(libc::S_IFLNK)
474 pub fn is(&self, mode: mode_t) -> bool {
475 self.mode & libc::S_IFMT == mode
479 impl FromInner<u32> for FilePermissions {
480 fn from_inner(mode: u32) -> FilePermissions {
481 FilePermissions { mode: mode as mode_t }
485 impl fmt::Debug for ReadDir {
486 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
487 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
488 // Thus the result will be e g 'ReadDir("/home")'
489 fmt::Debug::fmt(&*self.inner.root, f)
493 impl Iterator for ReadDir {
494 type Item = io::Result<DirEntry>;
497 target_os = "android",
499 target_os = "solaris",
500 target_os = "fuchsia",
502 target_os = "illumos"
504 fn next(&mut self) -> Option<io::Result<DirEntry>> {
507 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
508 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
509 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
510 // thread safety for readdir() as long an individual DIR* is not accessed
511 // concurrently, which is sufficient for Rust.
512 super::os::set_errno(0);
513 let entry_ptr = readdir64(self.inner.dirp.0);
514 if entry_ptr.is_null() {
515 // null can mean either the end is reached or an error occurred.
516 // So we had to clear errno beforehand to check for an error now.
517 return match super::os::errno() {
519 e => Some(Err(Error::from_raw_os_error(e))),
523 // Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
524 // whole thing (#93384). Instead, copy everything except the name.
525 let mut copy: dirent64 = mem::zeroed();
526 // Can't dereference entry_ptr, so use the local entry to get
527 // offsetof(struct dirent, d_name)
528 let copy_bytes = &mut copy as *mut _ as *mut u8;
529 let copy_name = &mut copy.d_name as *mut _ as *mut u8;
530 let name_offset = copy_name.offset_from(copy_bytes) as usize;
531 let entry_bytes = entry_ptr as *const u8;
532 let entry_name = entry_bytes.add(name_offset);
533 ptr::copy_nonoverlapping(entry_bytes, copy_bytes, name_offset);
535 let entry = dirent64_min {
536 d_ino: copy.d_ino as u64,
537 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
538 d_type: copy.d_type as u8,
543 // d_name is guaranteed to be null-terminated.
544 name: CStr::from_ptr(entry_name as *const _).to_owned(),
545 dir: Arc::clone(&self.inner),
547 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
548 return Some(Ok(ret));
555 target_os = "android",
557 target_os = "solaris",
558 target_os = "fuchsia",
560 target_os = "illumos"
562 fn next(&mut self) -> Option<io::Result<DirEntry>> {
563 if self.end_of_stream {
568 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
569 let mut entry_ptr = ptr::null_mut();
571 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
573 if entry_ptr.is_null() {
574 // We encountered an error (which will be returned in this iteration), but
575 // we also reached the end of the directory stream. The `end_of_stream`
576 // flag is enabled to make sure that we return `None` in the next iteration
577 // (instead of looping forever)
578 self.end_of_stream = true;
580 return Some(Err(Error::from_raw_os_error(err)));
582 if entry_ptr.is_null() {
585 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
586 return Some(Ok(ret));
595 let r = unsafe { libc::closedir(self.0) };
596 debug_assert_eq!(r, 0);
601 pub fn path(&self) -> PathBuf {
602 self.dir.root.join(self.file_name_os_str())
605 pub fn file_name(&self) -> OsString {
606 self.file_name_os_str().to_os_string()
609 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
610 pub fn metadata(&self) -> io::Result<FileAttr> {
611 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
612 let name = self.name_cstr().as_ptr();
615 if let Some(ret) = unsafe { try_statx(
618 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
625 let mut stat: stat64 = unsafe { mem::zeroed() };
626 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
627 Ok(FileAttr::from_stat64(stat))
630 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
631 pub fn metadata(&self) -> io::Result<FileAttr> {
636 target_os = "solaris",
637 target_os = "illumos",
639 target_os = "vxworks"
641 pub fn file_type(&self) -> io::Result<FileType> {
642 self.metadata().map(|m| m.file_type())
646 target_os = "solaris",
647 target_os = "illumos",
649 target_os = "vxworks"
651 pub fn file_type(&self) -> io::Result<FileType> {
652 match self.entry.d_type {
653 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
654 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
655 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
656 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
657 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
658 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
659 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
660 _ => self.metadata().map(|m| m.file_type()),
668 target_os = "emscripten",
669 target_os = "android",
670 target_os = "solaris",
671 target_os = "illumos",
674 target_os = "fuchsia",
676 target_os = "vxworks",
679 pub fn ino(&self) -> u64 {
680 self.entry.d_ino as u64
684 target_os = "freebsd",
685 target_os = "openbsd",
686 target_os = "netbsd",
687 target_os = "dragonfly"
689 pub fn ino(&self) -> u64 {
690 self.entry.d_fileno as u64
696 target_os = "netbsd",
697 target_os = "openbsd",
698 target_os = "freebsd",
699 target_os = "dragonfly"
701 fn name_bytes(&self) -> &[u8] {
704 slice::from_raw_parts(
705 self.entry.d_name.as_ptr() as *const u8,
706 self.entry.d_namlen as usize,
713 target_os = "netbsd",
714 target_os = "openbsd",
715 target_os = "freebsd",
716 target_os = "dragonfly"
718 fn name_bytes(&self) -> &[u8] {
719 self.name_cstr().to_bytes()
723 target_os = "android",
725 target_os = "solaris",
726 target_os = "illumos",
727 target_os = "fuchsia",
730 fn name_cstr(&self) -> &CStr {
731 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
734 target_os = "android",
736 target_os = "solaris",
737 target_os = "illumos",
738 target_os = "fuchsia",
741 fn name_cstr(&self) -> &CStr {
745 pub fn file_name_os_str(&self) -> &OsStr {
746 OsStr::from_bytes(self.name_bytes())
751 pub fn new() -> OpenOptions {
766 pub fn read(&mut self, read: bool) {
769 pub fn write(&mut self, write: bool) {
772 pub fn append(&mut self, append: bool) {
773 self.append = append;
775 pub fn truncate(&mut self, truncate: bool) {
776 self.truncate = truncate;
778 pub fn create(&mut self, create: bool) {
779 self.create = create;
781 pub fn create_new(&mut self, create_new: bool) {
782 self.create_new = create_new;
785 pub fn custom_flags(&mut self, flags: i32) {
786 self.custom_flags = flags;
788 pub fn mode(&mut self, mode: u32) {
789 self.mode = mode as mode_t;
792 fn get_access_mode(&self) -> io::Result<c_int> {
793 match (self.read, self.write, self.append) {
794 (true, false, false) => Ok(libc::O_RDONLY),
795 (false, true, false) => Ok(libc::O_WRONLY),
796 (true, true, false) => Ok(libc::O_RDWR),
797 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
798 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
799 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
803 fn get_creation_mode(&self) -> io::Result<c_int> {
804 match (self.write, self.append) {
807 if self.truncate || self.create || self.create_new {
808 return Err(Error::from_raw_os_error(libc::EINVAL));
812 if self.truncate && !self.create_new {
813 return Err(Error::from_raw_os_error(libc::EINVAL));
818 Ok(match (self.create, self.truncate, self.create_new) {
819 (false, false, false) => 0,
820 (true, false, false) => libc::O_CREAT,
821 (false, true, false) => libc::O_TRUNC,
822 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
823 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
829 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
830 let path = cstr(path)?;
831 File::open_c(&path, opts)
834 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
835 let flags = libc::O_CLOEXEC
836 | opts.get_access_mode()?
837 | opts.get_creation_mode()?
838 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
839 // The third argument of `open64` is documented to have type `mode_t`. On
840 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
841 // However, since this is a variadic function, C integer promotion rules mean that on
842 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
843 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
844 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
847 pub fn file_attr(&self) -> io::Result<FileAttr> {
848 let fd = self.as_raw_fd();
851 if let Some(ret) = unsafe { try_statx(
853 b"\0" as *const _ as *const c_char,
854 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
861 let mut stat: stat64 = unsafe { mem::zeroed() };
862 cvt(unsafe { fstat64(fd, &mut stat) })?;
863 Ok(FileAttr::from_stat64(stat))
866 pub fn fsync(&self) -> io::Result<()> {
867 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
870 #[cfg(any(target_os = "macos", target_os = "ios"))]
871 unsafe fn os_fsync(fd: c_int) -> c_int {
872 libc::fcntl(fd, libc::F_FULLFSYNC)
874 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
875 unsafe fn os_fsync(fd: c_int) -> c_int {
880 pub fn datasync(&self) -> io::Result<()> {
881 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
884 #[cfg(any(target_os = "macos", target_os = "ios"))]
885 unsafe fn os_datasync(fd: c_int) -> c_int {
886 libc::fcntl(fd, libc::F_FULLFSYNC)
889 target_os = "freebsd",
891 target_os = "android",
892 target_os = "netbsd",
893 target_os = "openbsd"
895 unsafe fn os_datasync(fd: c_int) -> c_int {
899 target_os = "android",
900 target_os = "freebsd",
904 target_os = "netbsd",
905 target_os = "openbsd"
907 unsafe fn os_datasync(fd: c_int) -> c_int {
912 pub fn truncate(&self, size: u64) -> io::Result<()> {
913 use crate::convert::TryInto;
915 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
916 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
919 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
923 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
924 self.0.read_vectored(bufs)
928 pub fn is_read_vectored(&self) -> bool {
929 self.0.is_read_vectored()
932 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
933 self.0.read_at(buf, offset)
936 pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
940 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
944 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
945 self.0.write_vectored(bufs)
949 pub fn is_write_vectored(&self) -> bool {
950 self.0.is_write_vectored()
953 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
954 self.0.write_at(buf, offset)
957 pub fn flush(&self) -> io::Result<()> {
961 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
962 let (whence, pos) = match pos {
963 // Casting to `i64` is fine, too large values will end up as
964 // negative which will cause an error in `lseek64`.
965 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
966 SeekFrom::End(off) => (libc::SEEK_END, off),
967 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
969 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos, whence) })?;
973 pub fn duplicate(&self) -> io::Result<File> {
974 self.0.duplicate().map(File)
977 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
978 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
984 pub fn new() -> DirBuilder {
985 DirBuilder { mode: 0o777 }
988 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
990 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
994 pub fn set_mode(&mut self, mode: u32) {
995 self.mode = mode as mode_t;
999 fn cstr(path: &Path) -> io::Result<CString> {
1000 Ok(CString::new(path.as_os_str().as_bytes())?)
1003 impl AsInner<FileDesc> for File {
1004 fn as_inner(&self) -> &FileDesc {
1009 impl AsInnerMut<FileDesc> for File {
1010 fn as_inner_mut(&mut self) -> &mut FileDesc {
1015 impl IntoInner<FileDesc> for File {
1016 fn into_inner(self) -> FileDesc {
1021 impl FromInner<FileDesc> for File {
1022 fn from_inner(file_desc: FileDesc) -> Self {
1027 impl AsFd for File {
1028 fn as_fd(&self) -> BorrowedFd<'_> {
1033 impl AsRawFd for File {
1034 fn as_raw_fd(&self) -> RawFd {
1039 impl IntoRawFd for File {
1040 fn into_raw_fd(self) -> RawFd {
1041 self.0.into_raw_fd()
1045 impl FromRawFd for File {
1046 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1047 Self(FromRawFd::from_raw_fd(raw_fd))
1051 impl fmt::Debug for File {
1052 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1053 #[cfg(any(target_os = "linux", target_os = "netbsd"))]
1054 fn get_path(fd: c_int) -> Option<PathBuf> {
1055 let mut p = PathBuf::from("/proc/self/fd");
1056 p.push(&fd.to_string());
1060 #[cfg(target_os = "macos")]
1061 fn get_path(fd: c_int) -> Option<PathBuf> {
1062 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1063 // is inevitable in this case because macOS defines `fcntl` with
1064 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1065 // alternatives. If a better method is invented, it should be used
1067 let mut buf = vec![0; libc::PATH_MAX as usize];
1068 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1072 let l = buf.iter().position(|&c| c == 0).unwrap();
1073 buf.truncate(l as usize);
1074 buf.shrink_to_fit();
1075 Some(PathBuf::from(OsString::from_vec(buf)))
1078 #[cfg(target_os = "vxworks")]
1079 fn get_path(fd: c_int) -> Option<PathBuf> {
1080 let mut buf = vec![0; libc::PATH_MAX as usize];
1081 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1085 let l = buf.iter().position(|&c| c == 0).unwrap();
1086 buf.truncate(l as usize);
1087 Some(PathBuf::from(OsString::from_vec(buf)))
1091 target_os = "linux",
1092 target_os = "macos",
1093 target_os = "vxworks",
1094 target_os = "netbsd"
1096 fn get_path(_fd: c_int) -> Option<PathBuf> {
1097 // FIXME(#24570): implement this for other Unix platforms
1101 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "vxworks"))]
1102 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1103 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1107 match mode & libc::O_ACCMODE {
1108 libc::O_RDONLY => Some((true, false)),
1109 libc::O_RDWR => Some((true, true)),
1110 libc::O_WRONLY => Some((false, true)),
1115 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
1116 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1117 // FIXME(#24570): implement this for other Unix platforms
1121 let fd = self.as_raw_fd();
1122 let mut b = f.debug_struct("File");
1124 if let Some(path) = get_path(fd) {
1125 b.field("path", &path);
1127 if let Some((read, write)) = get_mode(fd) {
1128 b.field("read", &read).field("write", &write);
1134 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1135 let root = p.to_path_buf();
1138 let ptr = libc::opendir(p.as_ptr());
1140 Err(Error::last_os_error())
1142 let inner = InnerReadDir { dirp: Dir(ptr), root };
1144 inner: Arc::new(inner),
1146 target_os = "android",
1147 target_os = "linux",
1148 target_os = "solaris",
1149 target_os = "illumos",
1150 target_os = "fuchsia",
1151 target_os = "redox",
1153 end_of_stream: false,
1159 pub fn unlink(p: &Path) -> io::Result<()> {
1161 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
1165 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1166 let old = cstr(old)?;
1167 let new = cstr(new)?;
1168 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
1172 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1174 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
1178 pub fn rmdir(p: &Path) -> io::Result<()> {
1180 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
1184 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1185 let c_path = cstr(p)?;
1186 let p = c_path.as_ptr();
1188 let mut buf = Vec::with_capacity(256);
1192 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1195 buf.set_len(buf_read);
1198 if buf_read != buf.capacity() {
1199 buf.shrink_to_fit();
1201 return Ok(PathBuf::from(OsString::from_vec(buf)));
1204 // Trigger the internal buffer resizing logic of `Vec` by requiring
1205 // more space than the current capacity. The length is guaranteed to be
1206 // the same as the capacity due to the if statement above.
1211 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1212 let original = cstr(original)?;
1213 let link = cstr(link)?;
1214 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) })?;
1218 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1219 let original = cstr(original)?;
1220 let link = cstr(link)?;
1222 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf"))] {
1223 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1224 // it implementation-defined whether `link` follows symlinks, so rely on the
1225 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1226 // Android has `linkat` on newer versions, but we happen to know `link`
1227 // always has the correct behavior, so it's here as well.
1228 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1229 } else if #[cfg(target_os = "macos")] {
1230 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1231 // versions have it. We want to use linkat if it is available, so we use weak!
1232 // to check. `linkat` is preferable to `link` because it gives us a flag to
1233 // specify how symlinks should be handled. We pass 0 as the flags argument,
1234 // meaning it shouldn't follow symlinks.
1235 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1237 if let Some(f) = linkat.get() {
1238 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1240 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1243 // Where we can, use `linkat` instead of `link`; see the comment above
1244 // this one for details on why.
1245 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1251 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1255 if let Some(ret) = unsafe { try_statx(
1258 libc::AT_STATX_SYNC_AS_STAT,
1265 let mut stat: stat64 = unsafe { mem::zeroed() };
1266 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1267 Ok(FileAttr::from_stat64(stat))
1270 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1274 if let Some(ret) = unsafe { try_statx(
1277 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1284 let mut stat: stat64 = unsafe { mem::zeroed() };
1285 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1286 Ok(FileAttr::from_stat64(stat))
1289 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1290 let path = CString::new(p.as_os_str().as_bytes())?;
1293 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1295 return Err(io::Error::last_os_error());
1297 buf = CStr::from_ptr(r).to_bytes().to_vec();
1298 libc::free(r as *mut _);
1300 Ok(PathBuf::from(OsString::from_vec(buf)))
1303 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1304 use crate::fs::File;
1305 use crate::sys_common::fs::NOT_FILE_ERROR;
1307 let reader = File::open(from)?;
1308 let metadata = reader.metadata()?;
1309 if !metadata.is_file() {
1310 return Err(NOT_FILE_ERROR);
1312 Ok((reader, metadata))
1315 #[cfg(target_os = "espidf")]
1316 fn open_to_and_set_permissions(
1318 reader_metadata: crate::fs::Metadata,
1319 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1320 use crate::fs::OpenOptions;
1321 let writer = OpenOptions::new().open(to)?;
1322 let writer_metadata = writer.metadata()?;
1323 Ok((writer, writer_metadata))
1326 #[cfg(not(target_os = "espidf"))]
1327 fn open_to_and_set_permissions(
1329 reader_metadata: crate::fs::Metadata,
1330 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1331 use crate::fs::OpenOptions;
1332 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1334 let perm = reader_metadata.permissions();
1335 let writer = OpenOptions::new()
1336 // create the file with the correct mode right away
1342 let writer_metadata = writer.metadata()?;
1343 if writer_metadata.is_file() {
1344 // Set the correct file permissions, in case the file already existed.
1345 // Don't set the permissions on already existing non-files like
1346 // pipes/FIFOs or device nodes.
1347 writer.set_permissions(perm)?;
1349 Ok((writer, writer_metadata))
1353 target_os = "linux",
1354 target_os = "android",
1355 target_os = "macos",
1358 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1359 let (mut reader, reader_metadata) = open_from(from)?;
1360 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1362 io::copy(&mut reader, &mut writer)
1365 #[cfg(any(target_os = "linux", target_os = "android"))]
1366 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1367 let (mut reader, reader_metadata) = open_from(from)?;
1368 let max_len = u64::MAX;
1369 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1371 use super::kernel_copy::{copy_regular_files, CopyResult};
1373 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1374 CopyResult::Ended(bytes) => Ok(bytes),
1375 CopyResult::Error(e, _) => Err(e),
1376 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1377 Ok(bytes) => Ok(bytes + written),
1383 #[cfg(any(target_os = "macos", target_os = "ios"))]
1384 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1385 use crate::sync::atomic::{AtomicBool, Ordering};
1387 const COPYFILE_ACL: u32 = 1 << 0;
1388 const COPYFILE_STAT: u32 = 1 << 1;
1389 const COPYFILE_XATTR: u32 = 1 << 2;
1390 const COPYFILE_DATA: u32 = 1 << 3;
1392 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1393 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1394 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1396 const COPYFILE_STATE_COPIED: u32 = 8;
1398 #[allow(non_camel_case_types)]
1399 type copyfile_state_t = *mut libc::c_void;
1400 #[allow(non_camel_case_types)]
1401 type copyfile_flags_t = u32;
1407 state: copyfile_state_t,
1408 flags: copyfile_flags_t,
1410 fn copyfile_state_alloc() -> copyfile_state_t;
1411 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1412 fn copyfile_state_get(
1413 state: copyfile_state_t,
1415 dst: *mut libc::c_void,
1419 struct FreeOnDrop(copyfile_state_t);
1420 impl Drop for FreeOnDrop {
1421 fn drop(&mut self) {
1422 // The code below ensures that `FreeOnDrop` is never a null pointer
1424 // `copyfile_state_free` returns -1 if the `to` or `from` files
1425 // cannot be closed. However, this is not considered this an
1427 copyfile_state_free(self.0);
1432 // MacOS prior to 10.12 don't support `fclonefileat`
1433 // We store the availability in a global to avoid unnecessary syscalls
1434 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1438 dst_dirfd: libc::c_int,
1444 let (reader, reader_metadata) = open_from(from)?;
1446 // Opportunistically attempt to create a copy-on-write clone of `from`
1447 // using `fclonefileat`.
1448 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1450 let clonefile_result =
1451 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) });
1452 match clonefile_result {
1453 Ok(_) => return Ok(reader_metadata.len()),
1454 Err(err) => match err.raw_os_error() {
1455 // `fclonefileat` will fail on non-APFS volumes, if the
1456 // destination already exists, or if the source and destination
1457 // are on different devices. In all these cases `fcopyfile`
1459 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1460 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1461 _ => return Err(err),
1466 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1467 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1469 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1470 // always safe to call `copyfile_state_free`
1471 let state = unsafe {
1472 let state = copyfile_state_alloc();
1473 if state.is_null() {
1474 return Err(crate::io::Error::last_os_error());
1479 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1481 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1483 let mut bytes_copied: libc::off_t = 0;
1487 COPYFILE_STATE_COPIED,
1488 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1491 Ok(bytes_copied as u64)
1494 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1495 let path = cstr(path)?;
1496 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1500 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1501 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1505 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1506 let path = cstr(path)?;
1507 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1511 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1512 pub fn chroot(dir: &Path) -> io::Result<()> {
1513 let dir = cstr(dir)?;
1514 cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
1518 pub use remove_dir_impl::remove_dir_all;
1520 // Fallback for REDOX and ESP-IDF
1521 #[cfg(any(target_os = "redox", target_os = "espidf"))]
1522 mod remove_dir_impl {
1523 pub use crate::sys_common::fs::remove_dir_all;
1526 // Modern implementation using openat(), unlinkat() and fdopendir()
1527 #[cfg(not(any(target_os = "redox", target_os = "espidf")))]
1528 mod remove_dir_impl {
1529 use super::{cstr, lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1530 use crate::ffi::CStr;
1532 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1533 use crate::os::unix::prelude::{OwnedFd, RawFd};
1534 use crate::path::{Path, PathBuf};
1535 use crate::sync::Arc;
1536 use crate::sys::{cvt, cvt_r};
1538 #[cfg(not(all(target_os = "macos", target_arch = "x86_64"),))]
1539 use libc::{fdopendir, openat, unlinkat};
1540 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1541 use macos_weak::{fdopendir, openat, unlinkat};
1543 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1545 use crate::sys::weak::weak;
1546 use libc::{c_char, c_int, DIR};
1548 fn get_openat_fn() -> Option<unsafe extern "C" fn(c_int, *const c_char, c_int) -> c_int> {
1549 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1553 pub fn has_openat() -> bool {
1554 get_openat_fn().is_some()
1557 pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1558 get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| {
1559 crate::sys::unix::os::set_errno(libc::ENOSYS);
1564 pub unsafe fn fdopendir(fd: c_int) -> *mut DIR {
1565 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1566 fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| {
1567 crate::sys::unix::os::set_errno(libc::ENOSYS);
1568 crate::ptr::null_mut()
1572 pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1573 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1574 unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| {
1575 crate::sys::unix::os::set_errno(libc::ENOSYS);
1581 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1582 let fd = cvt_r(|| unsafe {
1584 parent_fd.unwrap_or(libc::AT_FDCWD),
1586 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1589 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1592 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1593 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1595 return Err(io::Error::last_os_error());
1597 let dirp = Dir(ptr);
1598 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1599 let new_parent_fd = dir_fd.into_raw_fd();
1600 // a valid root is not needed because we do not call any functions involving the full path
1601 // of the DirEntrys.
1602 let dummy_root = PathBuf::new();
1605 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1607 target_os = "android",
1608 target_os = "linux",
1609 target_os = "solaris",
1610 target_os = "illumos",
1611 target_os = "fuchsia",
1612 target_os = "redox",
1614 end_of_stream: false,
1621 target_os = "solaris",
1622 target_os = "illumos",
1623 target_os = "haiku",
1624 target_os = "vxworks",
1626 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1631 target_os = "solaris",
1632 target_os = "illumos",
1633 target_os = "haiku",
1634 target_os = "vxworks",
1636 fn is_dir(ent: &DirEntry) -> Option<bool> {
1637 match ent.entry.d_type {
1638 libc::DT_UNKNOWN => None,
1639 libc::DT_DIR => Some(true),
1644 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
1645 // try opening as directory
1646 let fd = match openat_nofollow_dironly(parent_fd, &path) {
1647 Err(err) if err.raw_os_error() == Some(libc::ENOTDIR) => {
1648 // not a directory - don't traverse further
1649 return match parent_fd {
1651 Some(parent_fd) => {
1652 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
1654 // ...unless this was supposed to be the deletion root directory
1661 // open the directory passing ownership of the fd
1662 let (dir, fd) = fdreaddir(fd)?;
1665 let child_name = child.name_cstr();
1666 match is_dir(&child) {
1668 remove_dir_all_recursive(Some(fd), child_name)?;
1671 cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
1674 // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
1675 // if the process has the appropriate privileges. This however can causing orphaned
1676 // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
1677 // into it first instead of trying to unlink() it.
1678 remove_dir_all_recursive(Some(fd), child_name)?;
1683 // unlink the directory after removing its contents
1685 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
1690 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1691 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1692 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1694 let attr = lstat(p)?;
1695 if attr.file_type().is_symlink() {
1696 crate::fs::remove_file(p)
1698 remove_dir_all_recursive(None, &cstr(p)?)
1702 #[cfg(not(all(target_os = "macos", target_arch = "x86_64")))]
1703 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1704 remove_dir_all_modern(p)
1707 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1708 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1709 if macos_weak::has_openat() {
1710 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1711 remove_dir_all_modern(p)
1713 // fall back to classic implementation
1714 crate::sys_common::fs::remove_dir_all(p)