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,
116 // With statx, we can overcome 32-bit `time_t` too.
117 #[cfg(target_pointer_width = "32")]
118 stx_atime: libc::statx_timestamp,
119 #[cfg(target_pointer_width = "32")]
120 stx_ctime: libc::statx_timestamp,
121 #[cfg(target_pointer_width = "32")]
122 stx_mtime: libc::statx_timestamp,
126 // We prefer `statx` on Linux if available, which contains file creation time,
127 // as well as 64-bit timestamps of all kinds.
128 // Default `stat64` contains no creation time and may have 32-bit `time_t`.
134 ) -> Option<io::Result<FileAttr>> {
135 use crate::sync::atomic::{AtomicU8, Ordering};
137 // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
138 // We store the availability in global to avoid unnecessary syscalls.
142 static STATX_STATE: AtomicU8 = AtomicU8::new(0);
146 pathname: *const c_char,
149 statxbuf: *mut libc::statx
153 match STATX_STATE.load(Ordering::Relaxed) {
155 // It is a trick to call `statx` with null pointers to check if the syscall
156 // is available. According to the manual, it is expected to fail with EFAULT.
157 // We do this mainly for performance, since it is nearly hundreds times
158 // faster than a normal successful call.
159 let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
161 .and_then(|e| e.raw_os_error());
162 // We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
163 // and returns `EPERM`. Listing all possible errors seems not a good idea.
164 // See: https://github.com/rust-lang/rust/issues/65662
165 if err != Some(libc::EFAULT) {
166 STATX_STATE.store(1, Ordering::Relaxed);
169 STATX_STATE.store(2, Ordering::Relaxed);
175 let mut buf: libc::statx = mem::zeroed();
176 if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
177 return Some(Err(err));
180 // We cannot fill `stat64` exhaustively because of private padding fields.
181 let mut stat: stat64 = mem::zeroed();
182 // `c_ulong` on gnu-mips, `dev_t` otherwise
183 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
184 stat.st_ino = buf.stx_ino as libc::ino64_t;
185 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
186 stat.st_mode = buf.stx_mode as libc::mode_t;
187 stat.st_uid = buf.stx_uid as libc::uid_t;
188 stat.st_gid = buf.stx_gid as libc::gid_t;
189 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
190 stat.st_size = buf.stx_size as off64_t;
191 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
192 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
193 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
194 // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
195 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
196 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
197 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
198 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
199 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
201 let extra = StatxExtraFields {
202 stx_mask: buf.stx_mask,
203 stx_btime: buf.stx_btime,
204 // Store full times to avoid 32-bit `time_t` truncation.
205 #[cfg(target_pointer_width = "32")]
206 stx_atime: buf.stx_atime,
207 #[cfg(target_pointer_width = "32")]
208 stx_ctime: buf.stx_ctime,
209 #[cfg(target_pointer_width = "32")]
210 stx_mtime: buf.stx_mtime,
213 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
218 pub struct FileAttr {
223 // all DirEntry's will have a reference to this struct
224 struct InnerReadDir {
230 inner: Arc<InnerReadDir>,
232 target_os = "android",
234 target_os = "solaris",
235 target_os = "illumos",
236 target_os = "fuchsia",
242 struct Dir(*mut libc::DIR);
244 unsafe impl Send for Dir {}
245 unsafe impl Sync for Dir {}
248 target_os = "android",
250 target_os = "solaris",
251 target_os = "illumos",
252 target_os = "fuchsia",
255 pub struct DirEntry {
256 dir: Arc<InnerReadDir>,
258 // We need to store an owned copy of the entry name on platforms that use
259 // readdir() (not readdir_r()), because a) struct dirent may use a flexible
260 // array to store the name, b) it lives only until the next readdir() call.
264 // Define a minimal subset of fields we need from `dirent64`, especially since
265 // we're not using the immediate `d_name` on these targets. Keeping this as an
266 // `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
268 target_os = "android",
270 target_os = "solaris",
271 target_os = "illumos",
272 target_os = "fuchsia",
275 struct dirent64_min {
277 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
282 target_os = "android",
284 target_os = "solaris",
285 target_os = "illumos",
286 target_os = "fuchsia",
289 pub struct DirEntry {
290 dir: Arc<InnerReadDir>,
291 // The full entry includes a fixed-length `d_name`.
295 #[derive(Clone, Debug)]
296 pub struct OpenOptions {
309 #[derive(Clone, PartialEq, Eq, Debug)]
310 pub struct FilePermissions {
314 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
315 pub struct FileType {
320 pub struct DirBuilder {
326 fn from_stat64(stat: stat64) -> Self {
327 Self { stat, statx_extra_fields: None }
330 #[cfg(target_pointer_width = "32")]
331 pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
332 if let Some(ext) = &self.statx_extra_fields {
333 if (ext.stx_mask & libc::STATX_MTIME) != 0 {
334 return Some(&ext.stx_mtime);
340 #[cfg(target_pointer_width = "32")]
341 pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
342 if let Some(ext) = &self.statx_extra_fields {
343 if (ext.stx_mask & libc::STATX_ATIME) != 0 {
344 return Some(&ext.stx_atime);
350 #[cfg(target_pointer_width = "32")]
351 pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
352 if let Some(ext) = &self.statx_extra_fields {
353 if (ext.stx_mask & libc::STATX_CTIME) != 0 {
354 return Some(&ext.stx_ctime);
362 fn from_stat64(stat: stat64) -> Self {
369 pub fn size(&self) -> u64 {
370 self.stat.st_size as u64
372 pub fn perm(&self) -> FilePermissions {
373 FilePermissions { mode: (self.stat.st_mode as mode_t) }
376 pub fn file_type(&self) -> FileType {
377 FileType { mode: self.stat.st_mode as mode_t }
381 #[cfg(target_os = "netbsd")]
383 pub fn modified(&self) -> io::Result<SystemTime> {
384 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64))
387 pub fn accessed(&self) -> io::Result<SystemTime> {
388 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64))
391 pub fn created(&self) -> io::Result<SystemTime> {
392 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64))
396 #[cfg(not(target_os = "netbsd"))]
398 #[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
399 pub fn modified(&self) -> io::Result<SystemTime> {
400 #[cfg(target_pointer_width = "32")]
402 if let Some(mtime) = self.stx_mtime() {
403 return Ok(SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64));
407 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64))
410 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
411 pub fn modified(&self) -> io::Result<SystemTime> {
412 Ok(SystemTime::new(self.stat.st_mtime as i64, 0))
415 #[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
416 pub fn accessed(&self) -> io::Result<SystemTime> {
417 #[cfg(target_pointer_width = "32")]
419 if let Some(atime) = self.stx_atime() {
420 return Ok(SystemTime::new(atime.tv_sec, atime.tv_nsec as i64));
424 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64))
427 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
428 pub fn accessed(&self) -> io::Result<SystemTime> {
429 Ok(SystemTime::new(self.stat.st_atime as i64, 0))
433 target_os = "freebsd",
434 target_os = "openbsd",
438 pub fn created(&self) -> io::Result<SystemTime> {
439 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64))
443 target_os = "freebsd",
444 target_os = "openbsd",
448 pub fn created(&self) -> io::Result<SystemTime> {
450 if let Some(ext) = &self.statx_extra_fields {
451 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
452 Ok(SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64))
454 Err(io::const_io_error!(
455 io::ErrorKind::Uncategorized,
456 "creation time is not available for the filesystem",
462 Err(io::const_io_error!(
463 io::ErrorKind::Unsupported,
464 "creation time is not available on this platform \
470 impl AsInner<stat64> for FileAttr {
471 fn as_inner(&self) -> &stat64 {
476 impl FilePermissions {
477 pub fn readonly(&self) -> bool {
478 // check if any class (owner, group, others) has write permission
479 self.mode & 0o222 == 0
482 pub fn set_readonly(&mut self, readonly: bool) {
484 // remove write permission for all classes; equivalent to `chmod a-w <file>`
487 // add write permission for all classes; equivalent to `chmod a+w <file>`
491 pub fn mode(&self) -> u32 {
497 pub fn is_dir(&self) -> bool {
498 self.is(libc::S_IFDIR)
500 pub fn is_file(&self) -> bool {
501 self.is(libc::S_IFREG)
503 pub fn is_symlink(&self) -> bool {
504 self.is(libc::S_IFLNK)
507 pub fn is(&self, mode: mode_t) -> bool {
508 self.mode & libc::S_IFMT == mode
512 impl FromInner<u32> for FilePermissions {
513 fn from_inner(mode: u32) -> FilePermissions {
514 FilePermissions { mode: mode as mode_t }
518 impl fmt::Debug for ReadDir {
519 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
521 // Thus the result will be e g 'ReadDir("/home")'
522 fmt::Debug::fmt(&*self.inner.root, f)
526 impl Iterator for ReadDir {
527 type Item = io::Result<DirEntry>;
530 target_os = "android",
532 target_os = "solaris",
533 target_os = "fuchsia",
535 target_os = "illumos"
537 fn next(&mut self) -> Option<io::Result<DirEntry>> {
540 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
541 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
542 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
543 // thread safety for readdir() as long an individual DIR* is not accessed
544 // concurrently, which is sufficient for Rust.
545 super::os::set_errno(0);
546 let entry_ptr = readdir64(self.inner.dirp.0);
547 if entry_ptr.is_null() {
548 // null can mean either the end is reached or an error occurred.
549 // So we had to clear errno beforehand to check for an error now.
550 return match super::os::errno() {
552 e => Some(Err(Error::from_raw_os_error(e))),
556 // Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
557 // whole thing (#93384). Instead, copy everything except the name.
558 let mut copy: dirent64 = mem::zeroed();
559 // Can't dereference entry_ptr, so use the local entry to get
560 // offsetof(struct dirent, d_name)
561 let copy_bytes = &mut copy as *mut _ as *mut u8;
562 let copy_name = &mut copy.d_name as *mut _ as *mut u8;
563 let name_offset = copy_name.offset_from(copy_bytes) as usize;
564 let entry_bytes = entry_ptr as *const u8;
565 let entry_name = entry_bytes.add(name_offset);
566 ptr::copy_nonoverlapping(entry_bytes, copy_bytes, name_offset);
568 let entry = dirent64_min {
569 d_ino: copy.d_ino as u64,
570 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
571 d_type: copy.d_type as u8,
576 // d_name is guaranteed to be null-terminated.
577 name: CStr::from_ptr(entry_name as *const _).to_owned(),
578 dir: Arc::clone(&self.inner),
580 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
581 return Some(Ok(ret));
588 target_os = "android",
590 target_os = "solaris",
591 target_os = "fuchsia",
593 target_os = "illumos"
595 fn next(&mut self) -> Option<io::Result<DirEntry>> {
596 if self.end_of_stream {
601 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
602 let mut entry_ptr = ptr::null_mut();
604 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
606 if entry_ptr.is_null() {
607 // We encountered an error (which will be returned in this iteration), but
608 // we also reached the end of the directory stream. The `end_of_stream`
609 // flag is enabled to make sure that we return `None` in the next iteration
610 // (instead of looping forever)
611 self.end_of_stream = true;
613 return Some(Err(Error::from_raw_os_error(err)));
615 if entry_ptr.is_null() {
618 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
619 return Some(Ok(ret));
628 let r = unsafe { libc::closedir(self.0) };
629 debug_assert_eq!(r, 0);
634 pub fn path(&self) -> PathBuf {
635 self.dir.root.join(self.file_name_os_str())
638 pub fn file_name(&self) -> OsString {
639 self.file_name_os_str().to_os_string()
642 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
643 pub fn metadata(&self) -> io::Result<FileAttr> {
644 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
645 let name = self.name_cstr().as_ptr();
648 if let Some(ret) = unsafe { try_statx(
651 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
658 let mut stat: stat64 = unsafe { mem::zeroed() };
659 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
660 Ok(FileAttr::from_stat64(stat))
663 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
664 pub fn metadata(&self) -> io::Result<FileAttr> {
669 target_os = "solaris",
670 target_os = "illumos",
672 target_os = "vxworks"
674 pub fn file_type(&self) -> io::Result<FileType> {
675 self.metadata().map(|m| m.file_type())
679 target_os = "solaris",
680 target_os = "illumos",
682 target_os = "vxworks"
684 pub fn file_type(&self) -> io::Result<FileType> {
685 match self.entry.d_type {
686 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
687 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
688 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
689 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
690 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
691 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
692 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
693 _ => self.metadata().map(|m| m.file_type()),
701 target_os = "emscripten",
702 target_os = "android",
703 target_os = "solaris",
704 target_os = "illumos",
707 target_os = "fuchsia",
709 target_os = "vxworks",
712 pub fn ino(&self) -> u64 {
713 self.entry.d_ino as u64
717 target_os = "freebsd",
718 target_os = "openbsd",
719 target_os = "netbsd",
720 target_os = "dragonfly"
722 pub fn ino(&self) -> u64 {
723 self.entry.d_fileno as u64
729 target_os = "netbsd",
730 target_os = "openbsd",
731 target_os = "freebsd",
732 target_os = "dragonfly"
734 fn name_bytes(&self) -> &[u8] {
737 slice::from_raw_parts(
738 self.entry.d_name.as_ptr() as *const u8,
739 self.entry.d_namlen as usize,
746 target_os = "netbsd",
747 target_os = "openbsd",
748 target_os = "freebsd",
749 target_os = "dragonfly"
751 fn name_bytes(&self) -> &[u8] {
752 self.name_cstr().to_bytes()
756 target_os = "android",
758 target_os = "solaris",
759 target_os = "illumos",
760 target_os = "fuchsia",
763 fn name_cstr(&self) -> &CStr {
764 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
767 target_os = "android",
769 target_os = "solaris",
770 target_os = "illumos",
771 target_os = "fuchsia",
774 fn name_cstr(&self) -> &CStr {
778 pub fn file_name_os_str(&self) -> &OsStr {
779 OsStr::from_bytes(self.name_bytes())
784 pub fn new() -> OpenOptions {
799 pub fn read(&mut self, read: bool) {
802 pub fn write(&mut self, write: bool) {
805 pub fn append(&mut self, append: bool) {
806 self.append = append;
808 pub fn truncate(&mut self, truncate: bool) {
809 self.truncate = truncate;
811 pub fn create(&mut self, create: bool) {
812 self.create = create;
814 pub fn create_new(&mut self, create_new: bool) {
815 self.create_new = create_new;
818 pub fn custom_flags(&mut self, flags: i32) {
819 self.custom_flags = flags;
821 pub fn mode(&mut self, mode: u32) {
822 self.mode = mode as mode_t;
825 fn get_access_mode(&self) -> io::Result<c_int> {
826 match (self.read, self.write, self.append) {
827 (true, false, false) => Ok(libc::O_RDONLY),
828 (false, true, false) => Ok(libc::O_WRONLY),
829 (true, true, false) => Ok(libc::O_RDWR),
830 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
831 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
832 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
836 fn get_creation_mode(&self) -> io::Result<c_int> {
837 match (self.write, self.append) {
840 if self.truncate || self.create || self.create_new {
841 return Err(Error::from_raw_os_error(libc::EINVAL));
845 if self.truncate && !self.create_new {
846 return Err(Error::from_raw_os_error(libc::EINVAL));
851 Ok(match (self.create, self.truncate, self.create_new) {
852 (false, false, false) => 0,
853 (true, false, false) => libc::O_CREAT,
854 (false, true, false) => libc::O_TRUNC,
855 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
856 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
862 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
863 let path = cstr(path)?;
864 File::open_c(&path, opts)
867 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
868 let flags = libc::O_CLOEXEC
869 | opts.get_access_mode()?
870 | opts.get_creation_mode()?
871 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
872 // The third argument of `open64` is documented to have type `mode_t`. On
873 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
874 // However, since this is a variadic function, C integer promotion rules mean that on
875 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
876 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
877 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
880 pub fn file_attr(&self) -> io::Result<FileAttr> {
881 let fd = self.as_raw_fd();
884 if let Some(ret) = unsafe { try_statx(
886 b"\0" as *const _ as *const c_char,
887 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
894 let mut stat: stat64 = unsafe { mem::zeroed() };
895 cvt(unsafe { fstat64(fd, &mut stat) })?;
896 Ok(FileAttr::from_stat64(stat))
899 pub fn fsync(&self) -> io::Result<()> {
900 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
903 #[cfg(any(target_os = "macos", target_os = "ios"))]
904 unsafe fn os_fsync(fd: c_int) -> c_int {
905 libc::fcntl(fd, libc::F_FULLFSYNC)
907 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
908 unsafe fn os_fsync(fd: c_int) -> c_int {
913 pub fn datasync(&self) -> io::Result<()> {
914 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
917 #[cfg(any(target_os = "macos", target_os = "ios"))]
918 unsafe fn os_datasync(fd: c_int) -> c_int {
919 libc::fcntl(fd, libc::F_FULLFSYNC)
922 target_os = "freebsd",
924 target_os = "android",
925 target_os = "netbsd",
926 target_os = "openbsd"
928 unsafe fn os_datasync(fd: c_int) -> c_int {
932 target_os = "android",
933 target_os = "freebsd",
937 target_os = "netbsd",
938 target_os = "openbsd"
940 unsafe fn os_datasync(fd: c_int) -> c_int {
945 pub fn truncate(&self, size: u64) -> io::Result<()> {
947 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
948 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
951 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
955 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
956 self.0.read_vectored(bufs)
960 pub fn is_read_vectored(&self) -> bool {
961 self.0.is_read_vectored()
964 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
965 self.0.read_at(buf, offset)
968 pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
972 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
976 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
977 self.0.write_vectored(bufs)
981 pub fn is_write_vectored(&self) -> bool {
982 self.0.is_write_vectored()
985 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
986 self.0.write_at(buf, offset)
989 pub fn flush(&self) -> io::Result<()> {
993 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
994 let (whence, pos) = match pos {
995 // Casting to `i64` is fine, too large values will end up as
996 // negative which will cause an error in `lseek64`.
997 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
998 SeekFrom::End(off) => (libc::SEEK_END, off),
999 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1001 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1005 pub fn duplicate(&self) -> io::Result<File> {
1006 self.0.duplicate().map(File)
1009 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1010 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1016 pub fn new() -> DirBuilder {
1017 DirBuilder { mode: 0o777 }
1020 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1022 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
1026 pub fn set_mode(&mut self, mode: u32) {
1027 self.mode = mode as mode_t;
1031 fn cstr(path: &Path) -> io::Result<CString> {
1032 Ok(CString::new(path.as_os_str().as_bytes())?)
1035 impl AsInner<FileDesc> for File {
1036 fn as_inner(&self) -> &FileDesc {
1041 impl AsInnerMut<FileDesc> for File {
1042 fn as_inner_mut(&mut self) -> &mut FileDesc {
1047 impl IntoInner<FileDesc> for File {
1048 fn into_inner(self) -> FileDesc {
1053 impl FromInner<FileDesc> for File {
1054 fn from_inner(file_desc: FileDesc) -> Self {
1059 impl AsFd for File {
1060 fn as_fd(&self) -> BorrowedFd<'_> {
1065 impl AsRawFd for File {
1066 fn as_raw_fd(&self) -> RawFd {
1071 impl IntoRawFd for File {
1072 fn into_raw_fd(self) -> RawFd {
1073 self.0.into_raw_fd()
1077 impl FromRawFd for File {
1078 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1079 Self(FromRawFd::from_raw_fd(raw_fd))
1083 impl fmt::Debug for File {
1084 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1085 #[cfg(any(target_os = "linux", target_os = "netbsd"))]
1086 fn get_path(fd: c_int) -> Option<PathBuf> {
1087 let mut p = PathBuf::from("/proc/self/fd");
1088 p.push(&fd.to_string());
1092 #[cfg(target_os = "macos")]
1093 fn get_path(fd: c_int) -> Option<PathBuf> {
1094 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1095 // is inevitable in this case because macOS defines `fcntl` with
1096 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1097 // alternatives. If a better method is invented, it should be used
1099 let mut buf = vec![0; libc::PATH_MAX as usize];
1100 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1104 let l = buf.iter().position(|&c| c == 0).unwrap();
1105 buf.truncate(l as usize);
1106 buf.shrink_to_fit();
1107 Some(PathBuf::from(OsString::from_vec(buf)))
1110 #[cfg(target_os = "vxworks")]
1111 fn get_path(fd: c_int) -> Option<PathBuf> {
1112 let mut buf = vec![0; libc::PATH_MAX as usize];
1113 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1117 let l = buf.iter().position(|&c| c == 0).unwrap();
1118 buf.truncate(l as usize);
1119 Some(PathBuf::from(OsString::from_vec(buf)))
1123 target_os = "linux",
1124 target_os = "macos",
1125 target_os = "vxworks",
1126 target_os = "netbsd"
1128 fn get_path(_fd: c_int) -> Option<PathBuf> {
1129 // FIXME(#24570): implement this for other Unix platforms
1133 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "vxworks"))]
1134 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1135 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1139 match mode & libc::O_ACCMODE {
1140 libc::O_RDONLY => Some((true, false)),
1141 libc::O_RDWR => Some((true, true)),
1142 libc::O_WRONLY => Some((false, true)),
1147 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
1148 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1149 // FIXME(#24570): implement this for other Unix platforms
1153 let fd = self.as_raw_fd();
1154 let mut b = f.debug_struct("File");
1156 if let Some(path) = get_path(fd) {
1157 b.field("path", &path);
1159 if let Some((read, write)) = get_mode(fd) {
1160 b.field("read", &read).field("write", &write);
1166 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1167 let root = p.to_path_buf();
1170 let ptr = libc::opendir(p.as_ptr());
1172 Err(Error::last_os_error())
1174 let inner = InnerReadDir { dirp: Dir(ptr), root };
1176 inner: Arc::new(inner),
1178 target_os = "android",
1179 target_os = "linux",
1180 target_os = "solaris",
1181 target_os = "illumos",
1182 target_os = "fuchsia",
1183 target_os = "redox",
1185 end_of_stream: false,
1191 pub fn unlink(p: &Path) -> io::Result<()> {
1193 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
1197 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1198 let old = cstr(old)?;
1199 let new = cstr(new)?;
1200 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
1204 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1206 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
1210 pub fn rmdir(p: &Path) -> io::Result<()> {
1212 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
1216 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1217 let c_path = cstr(p)?;
1218 let p = c_path.as_ptr();
1220 let mut buf = Vec::with_capacity(256);
1224 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1227 buf.set_len(buf_read);
1230 if buf_read != buf.capacity() {
1231 buf.shrink_to_fit();
1233 return Ok(PathBuf::from(OsString::from_vec(buf)));
1236 // Trigger the internal buffer resizing logic of `Vec` by requiring
1237 // more space than the current capacity. The length is guaranteed to be
1238 // the same as the capacity due to the if statement above.
1243 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1244 let original = cstr(original)?;
1245 let link = cstr(link)?;
1246 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) })?;
1250 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1251 let original = cstr(original)?;
1252 let link = cstr(link)?;
1254 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf"))] {
1255 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1256 // it implementation-defined whether `link` follows symlinks, so rely on the
1257 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1258 // Android has `linkat` on newer versions, but we happen to know `link`
1259 // always has the correct behavior, so it's here as well.
1260 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1261 } else if #[cfg(target_os = "macos")] {
1262 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1263 // versions have it. We want to use linkat if it is available, so we use weak!
1264 // to check. `linkat` is preferable to `link` because it gives us a flag to
1265 // specify how symlinks should be handled. We pass 0 as the flags argument,
1266 // meaning it shouldn't follow symlinks.
1267 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1269 if let Some(f) = linkat.get() {
1270 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1272 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1275 // Where we can, use `linkat` instead of `link`; see the comment above
1276 // this one for details on why.
1277 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1283 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1287 if let Some(ret) = unsafe { try_statx(
1290 libc::AT_STATX_SYNC_AS_STAT,
1297 let mut stat: stat64 = unsafe { mem::zeroed() };
1298 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1299 Ok(FileAttr::from_stat64(stat))
1302 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1306 if let Some(ret) = unsafe { try_statx(
1309 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1316 let mut stat: stat64 = unsafe { mem::zeroed() };
1317 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1318 Ok(FileAttr::from_stat64(stat))
1321 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1322 let path = CString::new(p.as_os_str().as_bytes())?;
1325 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1327 return Err(io::Error::last_os_error());
1329 buf = CStr::from_ptr(r).to_bytes().to_vec();
1330 libc::free(r as *mut _);
1332 Ok(PathBuf::from(OsString::from_vec(buf)))
1335 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1336 use crate::fs::File;
1337 use crate::sys_common::fs::NOT_FILE_ERROR;
1339 let reader = File::open(from)?;
1340 let metadata = reader.metadata()?;
1341 if !metadata.is_file() {
1342 return Err(NOT_FILE_ERROR);
1344 Ok((reader, metadata))
1347 #[cfg(target_os = "espidf")]
1348 fn open_to_and_set_permissions(
1350 reader_metadata: crate::fs::Metadata,
1351 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1352 use crate::fs::OpenOptions;
1353 let writer = OpenOptions::new().open(to)?;
1354 let writer_metadata = writer.metadata()?;
1355 Ok((writer, writer_metadata))
1358 #[cfg(not(target_os = "espidf"))]
1359 fn open_to_and_set_permissions(
1361 reader_metadata: crate::fs::Metadata,
1362 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1363 use crate::fs::OpenOptions;
1364 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1366 let perm = reader_metadata.permissions();
1367 let writer = OpenOptions::new()
1368 // create the file with the correct mode right away
1374 let writer_metadata = writer.metadata()?;
1375 if writer_metadata.is_file() {
1376 // Set the correct file permissions, in case the file already existed.
1377 // Don't set the permissions on already existing non-files like
1378 // pipes/FIFOs or device nodes.
1379 writer.set_permissions(perm)?;
1381 Ok((writer, writer_metadata))
1385 target_os = "linux",
1386 target_os = "android",
1387 target_os = "macos",
1390 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1391 let (mut reader, reader_metadata) = open_from(from)?;
1392 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1394 io::copy(&mut reader, &mut writer)
1397 #[cfg(any(target_os = "linux", target_os = "android"))]
1398 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1399 let (mut reader, reader_metadata) = open_from(from)?;
1400 let max_len = u64::MAX;
1401 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1403 use super::kernel_copy::{copy_regular_files, CopyResult};
1405 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1406 CopyResult::Ended(bytes) => Ok(bytes),
1407 CopyResult::Error(e, _) => Err(e),
1408 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1409 Ok(bytes) => Ok(bytes + written),
1415 #[cfg(any(target_os = "macos", target_os = "ios"))]
1416 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1417 use crate::sync::atomic::{AtomicBool, Ordering};
1419 const COPYFILE_ACL: u32 = 1 << 0;
1420 const COPYFILE_STAT: u32 = 1 << 1;
1421 const COPYFILE_XATTR: u32 = 1 << 2;
1422 const COPYFILE_DATA: u32 = 1 << 3;
1424 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1425 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1426 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1428 const COPYFILE_STATE_COPIED: u32 = 8;
1430 #[allow(non_camel_case_types)]
1431 type copyfile_state_t = *mut libc::c_void;
1432 #[allow(non_camel_case_types)]
1433 type copyfile_flags_t = u32;
1439 state: copyfile_state_t,
1440 flags: copyfile_flags_t,
1442 fn copyfile_state_alloc() -> copyfile_state_t;
1443 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1444 fn copyfile_state_get(
1445 state: copyfile_state_t,
1447 dst: *mut libc::c_void,
1451 struct FreeOnDrop(copyfile_state_t);
1452 impl Drop for FreeOnDrop {
1453 fn drop(&mut self) {
1454 // The code below ensures that `FreeOnDrop` is never a null pointer
1456 // `copyfile_state_free` returns -1 if the `to` or `from` files
1457 // cannot be closed. However, this is not considered this an
1459 copyfile_state_free(self.0);
1464 // MacOS prior to 10.12 don't support `fclonefileat`
1465 // We store the availability in a global to avoid unnecessary syscalls
1466 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1470 dst_dirfd: libc::c_int,
1476 let (reader, reader_metadata) = open_from(from)?;
1478 // Opportunistically attempt to create a copy-on-write clone of `from`
1479 // using `fclonefileat`.
1480 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1482 let clonefile_result =
1483 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) });
1484 match clonefile_result {
1485 Ok(_) => return Ok(reader_metadata.len()),
1486 Err(err) => match err.raw_os_error() {
1487 // `fclonefileat` will fail on non-APFS volumes, if the
1488 // destination already exists, or if the source and destination
1489 // are on different devices. In all these cases `fcopyfile`
1491 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1492 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1493 _ => return Err(err),
1498 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1499 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1501 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1502 // always safe to call `copyfile_state_free`
1503 let state = unsafe {
1504 let state = copyfile_state_alloc();
1505 if state.is_null() {
1506 return Err(crate::io::Error::last_os_error());
1511 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1513 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1515 let mut bytes_copied: libc::off_t = 0;
1519 COPYFILE_STATE_COPIED,
1520 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1523 Ok(bytes_copied as u64)
1526 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1527 let path = cstr(path)?;
1528 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1532 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1533 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1537 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1538 let path = cstr(path)?;
1539 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1543 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1544 pub fn chroot(dir: &Path) -> io::Result<()> {
1545 let dir = cstr(dir)?;
1546 cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
1550 pub use remove_dir_impl::remove_dir_all;
1552 // Fallback for REDOX and ESP-IDF (and Miri)
1553 #[cfg(any(target_os = "redox", target_os = "espidf", miri))]
1554 mod remove_dir_impl {
1555 pub use crate::sys_common::fs::remove_dir_all;
1558 // Modern implementation using openat(), unlinkat() and fdopendir()
1559 #[cfg(not(any(target_os = "redox", target_os = "espidf", miri)))]
1560 mod remove_dir_impl {
1561 use super::{cstr, lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1562 use crate::ffi::CStr;
1564 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1565 use crate::os::unix::prelude::{OwnedFd, RawFd};
1566 use crate::path::{Path, PathBuf};
1567 use crate::sync::Arc;
1568 use crate::sys::{cvt, cvt_r};
1570 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64")),))]
1571 use libc::{fdopendir, openat, unlinkat};
1572 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1573 use macos_weak::{fdopendir, openat, unlinkat};
1575 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1577 use crate::sys::weak::weak;
1578 use libc::{c_char, c_int, DIR};
1580 fn get_openat_fn() -> Option<unsafe extern "C" fn(c_int, *const c_char, c_int) -> c_int> {
1581 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1585 pub fn has_openat() -> bool {
1586 get_openat_fn().is_some()
1589 pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1590 get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| {
1591 crate::sys::unix::os::set_errno(libc::ENOSYS);
1596 pub unsafe fn fdopendir(fd: c_int) -> *mut DIR {
1597 #[cfg(all(target_os = "macos", target_arch = "x86"))]
1598 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64$UNIX2003");
1599 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1600 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1601 fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| {
1602 crate::sys::unix::os::set_errno(libc::ENOSYS);
1603 crate::ptr::null_mut()
1607 pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1608 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1609 unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| {
1610 crate::sys::unix::os::set_errno(libc::ENOSYS);
1616 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1617 let fd = cvt_r(|| unsafe {
1619 parent_fd.unwrap_or(libc::AT_FDCWD),
1621 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1624 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1627 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1628 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1630 return Err(io::Error::last_os_error());
1632 let dirp = Dir(ptr);
1633 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1634 let new_parent_fd = dir_fd.into_raw_fd();
1635 // a valid root is not needed because we do not call any functions involving the full path
1636 // of the DirEntrys.
1637 let dummy_root = PathBuf::new();
1640 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1642 target_os = "android",
1643 target_os = "linux",
1644 target_os = "solaris",
1645 target_os = "illumos",
1646 target_os = "fuchsia",
1647 target_os = "redox",
1649 end_of_stream: false,
1656 target_os = "solaris",
1657 target_os = "illumos",
1658 target_os = "haiku",
1659 target_os = "vxworks",
1661 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1666 target_os = "solaris",
1667 target_os = "illumos",
1668 target_os = "haiku",
1669 target_os = "vxworks",
1671 fn is_dir(ent: &DirEntry) -> Option<bool> {
1672 match ent.entry.d_type {
1673 libc::DT_UNKNOWN => None,
1674 libc::DT_DIR => Some(true),
1679 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
1680 // try opening as directory
1681 let fd = match openat_nofollow_dironly(parent_fd, &path) {
1682 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
1683 // not a directory - don't traverse further
1684 // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
1685 return match parent_fd {
1687 Some(parent_fd) => {
1688 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
1690 // ...unless this was supposed to be the deletion root directory
1697 // open the directory passing ownership of the fd
1698 let (dir, fd) = fdreaddir(fd)?;
1701 let child_name = child.name_cstr();
1702 match is_dir(&child) {
1704 remove_dir_all_recursive(Some(fd), child_name)?;
1707 cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
1710 // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
1711 // if the process has the appropriate privileges. This however can causing orphaned
1712 // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
1713 // into it first instead of trying to unlink() it.
1714 remove_dir_all_recursive(Some(fd), child_name)?;
1719 // unlink the directory after removing its contents
1721 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
1726 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1727 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1728 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1730 let attr = lstat(p)?;
1731 if attr.file_type().is_symlink() {
1732 crate::fs::remove_file(p)
1734 remove_dir_all_recursive(None, &cstr(p)?)
1738 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64"))))]
1739 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1740 remove_dir_all_modern(p)
1743 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1744 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1745 if macos_weak::has_openat() {
1746 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1747 remove_dir_all_modern(p)
1749 // fall back to classic implementation
1750 crate::sys_common::fs::remove_dir_all(p)