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(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
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(target_os = "horizon")]
416 pub fn modified(&self) -> io::Result<SystemTime> {
417 Ok(SystemTime::from(self.stat.st_mtim))
420 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
421 pub fn accessed(&self) -> io::Result<SystemTime> {
422 #[cfg(target_pointer_width = "32")]
424 if let Some(atime) = self.stx_atime() {
425 return Ok(SystemTime::new(atime.tv_sec, atime.tv_nsec as i64));
429 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64))
432 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
433 pub fn accessed(&self) -> io::Result<SystemTime> {
434 Ok(SystemTime::new(self.stat.st_atime as i64, 0))
437 #[cfg(target_os = "horizon")]
438 pub fn accessed(&self) -> io::Result<SystemTime> {
439 Ok(SystemTime::from(self.stat.st_atim))
443 target_os = "freebsd",
444 target_os = "openbsd",
448 pub fn created(&self) -> io::Result<SystemTime> {
449 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64))
453 target_os = "freebsd",
454 target_os = "openbsd",
458 pub fn created(&self) -> io::Result<SystemTime> {
460 if let Some(ext) = &self.statx_extra_fields {
461 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
462 Ok(SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64))
464 Err(io::const_io_error!(
465 io::ErrorKind::Uncategorized,
466 "creation time is not available for the filesystem",
472 Err(io::const_io_error!(
473 io::ErrorKind::Unsupported,
474 "creation time is not available on this platform \
480 impl AsInner<stat64> for FileAttr {
481 fn as_inner(&self) -> &stat64 {
486 impl FilePermissions {
487 pub fn readonly(&self) -> bool {
488 // check if any class (owner, group, others) has write permission
489 self.mode & 0o222 == 0
492 pub fn set_readonly(&mut self, readonly: bool) {
494 // remove write permission for all classes; equivalent to `chmod a-w <file>`
497 // add write permission for all classes; equivalent to `chmod a+w <file>`
501 pub fn mode(&self) -> u32 {
507 pub fn is_dir(&self) -> bool {
508 self.is(libc::S_IFDIR)
510 pub fn is_file(&self) -> bool {
511 self.is(libc::S_IFREG)
513 pub fn is_symlink(&self) -> bool {
514 self.is(libc::S_IFLNK)
517 pub fn is(&self, mode: mode_t) -> bool {
518 self.mode & libc::S_IFMT == mode
522 impl FromInner<u32> for FilePermissions {
523 fn from_inner(mode: u32) -> FilePermissions {
524 FilePermissions { mode: mode as mode_t }
528 impl fmt::Debug for ReadDir {
529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
531 // Thus the result will be e g 'ReadDir("/home")'
532 fmt::Debug::fmt(&*self.inner.root, f)
536 impl Iterator for ReadDir {
537 type Item = io::Result<DirEntry>;
540 target_os = "android",
542 target_os = "solaris",
543 target_os = "fuchsia",
545 target_os = "illumos"
547 fn next(&mut self) -> Option<io::Result<DirEntry>> {
550 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
551 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
552 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
553 // thread safety for readdir() as long an individual DIR* is not accessed
554 // concurrently, which is sufficient for Rust.
555 super::os::set_errno(0);
556 let entry_ptr = readdir64(self.inner.dirp.0);
557 if entry_ptr.is_null() {
558 // null can mean either the end is reached or an error occurred.
559 // So we had to clear errno beforehand to check for an error now.
560 return match super::os::errno() {
562 e => Some(Err(Error::from_raw_os_error(e))),
566 // Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
567 // whole thing (#93384). Instead, copy everything except the name.
568 let mut copy: dirent64 = mem::zeroed();
569 // Can't dereference entry_ptr, so use the local entry to get
570 // offsetof(struct dirent, d_name)
571 let copy_bytes = &mut copy as *mut _ as *mut u8;
572 let copy_name = &mut copy.d_name as *mut _ as *mut u8;
573 let name_offset = copy_name.offset_from(copy_bytes) as usize;
574 let entry_bytes = entry_ptr as *const u8;
575 let entry_name = entry_bytes.add(name_offset);
576 ptr::copy_nonoverlapping(entry_bytes, copy_bytes, name_offset);
578 let entry = dirent64_min {
579 d_ino: copy.d_ino as u64,
580 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
581 d_type: copy.d_type as u8,
586 // d_name is guaranteed to be null-terminated.
587 name: CStr::from_ptr(entry_name as *const _).to_owned(),
588 dir: Arc::clone(&self.inner),
590 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
591 return Some(Ok(ret));
598 target_os = "android",
600 target_os = "solaris",
601 target_os = "fuchsia",
603 target_os = "illumos"
605 fn next(&mut self) -> Option<io::Result<DirEntry>> {
606 if self.end_of_stream {
611 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
612 let mut entry_ptr = ptr::null_mut();
614 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
616 if entry_ptr.is_null() {
617 // We encountered an error (which will be returned in this iteration), but
618 // we also reached the end of the directory stream. The `end_of_stream`
619 // flag is enabled to make sure that we return `None` in the next iteration
620 // (instead of looping forever)
621 self.end_of_stream = true;
623 return Some(Err(Error::from_raw_os_error(err)));
625 if entry_ptr.is_null() {
628 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
629 return Some(Ok(ret));
638 let r = unsafe { libc::closedir(self.0) };
639 debug_assert_eq!(r, 0);
644 pub fn path(&self) -> PathBuf {
645 self.dir.root.join(self.file_name_os_str())
648 pub fn file_name(&self) -> OsString {
649 self.file_name_os_str().to_os_string()
652 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
653 pub fn metadata(&self) -> io::Result<FileAttr> {
654 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
655 let name = self.name_cstr().as_ptr();
658 if let Some(ret) = unsafe { try_statx(
661 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
668 let mut stat: stat64 = unsafe { mem::zeroed() };
669 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
670 Ok(FileAttr::from_stat64(stat))
673 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
674 pub fn metadata(&self) -> io::Result<FileAttr> {
679 target_os = "solaris",
680 target_os = "illumos",
682 target_os = "vxworks"
684 pub fn file_type(&self) -> io::Result<FileType> {
685 self.metadata().map(|m| m.file_type())
689 target_os = "solaris",
690 target_os = "illumos",
692 target_os = "vxworks"
694 pub fn file_type(&self) -> io::Result<FileType> {
695 match self.entry.d_type {
696 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
697 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
698 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
699 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
700 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
701 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
702 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
703 _ => self.metadata().map(|m| m.file_type()),
711 target_os = "emscripten",
712 target_os = "android",
713 target_os = "solaris",
714 target_os = "illumos",
717 target_os = "fuchsia",
719 target_os = "vxworks",
720 target_os = "espidf",
721 target_os = "horizon"
723 pub fn ino(&self) -> u64 {
724 self.entry.d_ino as u64
728 target_os = "freebsd",
729 target_os = "openbsd",
730 target_os = "netbsd",
731 target_os = "dragonfly"
733 pub fn ino(&self) -> u64 {
734 self.entry.d_fileno as u64
740 target_os = "netbsd",
741 target_os = "openbsd",
742 target_os = "freebsd",
743 target_os = "dragonfly"
745 fn name_bytes(&self) -> &[u8] {
748 slice::from_raw_parts(
749 self.entry.d_name.as_ptr() as *const u8,
750 self.entry.d_namlen as usize,
757 target_os = "netbsd",
758 target_os = "openbsd",
759 target_os = "freebsd",
760 target_os = "dragonfly"
762 fn name_bytes(&self) -> &[u8] {
763 self.name_cstr().to_bytes()
767 target_os = "android",
769 target_os = "solaris",
770 target_os = "illumos",
771 target_os = "fuchsia",
774 fn name_cstr(&self) -> &CStr {
775 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
778 target_os = "android",
780 target_os = "solaris",
781 target_os = "illumos",
782 target_os = "fuchsia",
785 fn name_cstr(&self) -> &CStr {
789 pub fn file_name_os_str(&self) -> &OsStr {
790 OsStr::from_bytes(self.name_bytes())
795 pub fn new() -> OpenOptions {
810 pub fn read(&mut self, read: bool) {
813 pub fn write(&mut self, write: bool) {
816 pub fn append(&mut self, append: bool) {
817 self.append = append;
819 pub fn truncate(&mut self, truncate: bool) {
820 self.truncate = truncate;
822 pub fn create(&mut self, create: bool) {
823 self.create = create;
825 pub fn create_new(&mut self, create_new: bool) {
826 self.create_new = create_new;
829 pub fn custom_flags(&mut self, flags: i32) {
830 self.custom_flags = flags;
832 pub fn mode(&mut self, mode: u32) {
833 self.mode = mode as mode_t;
836 fn get_access_mode(&self) -> io::Result<c_int> {
837 match (self.read, self.write, self.append) {
838 (true, false, false) => Ok(libc::O_RDONLY),
839 (false, true, false) => Ok(libc::O_WRONLY),
840 (true, true, false) => Ok(libc::O_RDWR),
841 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
842 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
843 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
847 fn get_creation_mode(&self) -> io::Result<c_int> {
848 match (self.write, self.append) {
851 if self.truncate || self.create || self.create_new {
852 return Err(Error::from_raw_os_error(libc::EINVAL));
856 if self.truncate && !self.create_new {
857 return Err(Error::from_raw_os_error(libc::EINVAL));
862 Ok(match (self.create, self.truncate, self.create_new) {
863 (false, false, false) => 0,
864 (true, false, false) => libc::O_CREAT,
865 (false, true, false) => libc::O_TRUNC,
866 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
867 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
873 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
874 let path = cstr(path)?;
875 File::open_c(&path, opts)
878 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
879 let flags = libc::O_CLOEXEC
880 | opts.get_access_mode()?
881 | opts.get_creation_mode()?
882 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
883 // The third argument of `open64` is documented to have type `mode_t`. On
884 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
885 // However, since this is a variadic function, C integer promotion rules mean that on
886 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
887 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
888 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
891 pub fn file_attr(&self) -> io::Result<FileAttr> {
892 let fd = self.as_raw_fd();
895 if let Some(ret) = unsafe { try_statx(
897 b"\0" as *const _ as *const c_char,
898 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
905 let mut stat: stat64 = unsafe { mem::zeroed() };
906 cvt(unsafe { fstat64(fd, &mut stat) })?;
907 Ok(FileAttr::from_stat64(stat))
910 pub fn fsync(&self) -> io::Result<()> {
911 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
914 #[cfg(any(target_os = "macos", target_os = "ios"))]
915 unsafe fn os_fsync(fd: c_int) -> c_int {
916 libc::fcntl(fd, libc::F_FULLFSYNC)
918 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
919 unsafe fn os_fsync(fd: c_int) -> c_int {
924 pub fn datasync(&self) -> io::Result<()> {
925 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
928 #[cfg(any(target_os = "macos", target_os = "ios"))]
929 unsafe fn os_datasync(fd: c_int) -> c_int {
930 libc::fcntl(fd, libc::F_FULLFSYNC)
933 target_os = "freebsd",
935 target_os = "android",
936 target_os = "netbsd",
937 target_os = "openbsd"
939 unsafe fn os_datasync(fd: c_int) -> c_int {
943 target_os = "android",
944 target_os = "freebsd",
948 target_os = "netbsd",
949 target_os = "openbsd"
951 unsafe fn os_datasync(fd: c_int) -> c_int {
956 pub fn truncate(&self, size: u64) -> io::Result<()> {
958 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
959 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
962 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
966 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
967 self.0.read_vectored(bufs)
971 pub fn is_read_vectored(&self) -> bool {
972 self.0.is_read_vectored()
975 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
976 self.0.read_at(buf, offset)
979 pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
983 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
987 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
988 self.0.write_vectored(bufs)
992 pub fn is_write_vectored(&self) -> bool {
993 self.0.is_write_vectored()
996 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
997 self.0.write_at(buf, offset)
1000 pub fn flush(&self) -> io::Result<()> {
1004 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1005 let (whence, pos) = match pos {
1006 // Casting to `i64` is fine, too large values will end up as
1007 // negative which will cause an error in `lseek64`.
1008 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1009 SeekFrom::End(off) => (libc::SEEK_END, off),
1010 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1012 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1016 pub fn duplicate(&self) -> io::Result<File> {
1017 self.0.duplicate().map(File)
1020 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1021 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1027 pub fn new() -> DirBuilder {
1028 DirBuilder { mode: 0o777 }
1031 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1033 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
1037 pub fn set_mode(&mut self, mode: u32) {
1038 self.mode = mode as mode_t;
1042 fn cstr(path: &Path) -> io::Result<CString> {
1043 Ok(CString::new(path.as_os_str().as_bytes())?)
1046 impl AsInner<FileDesc> for File {
1047 fn as_inner(&self) -> &FileDesc {
1052 impl AsInnerMut<FileDesc> for File {
1053 fn as_inner_mut(&mut self) -> &mut FileDesc {
1058 impl IntoInner<FileDesc> for File {
1059 fn into_inner(self) -> FileDesc {
1064 impl FromInner<FileDesc> for File {
1065 fn from_inner(file_desc: FileDesc) -> Self {
1070 impl AsFd for File {
1071 fn as_fd(&self) -> BorrowedFd<'_> {
1076 impl AsRawFd for File {
1077 fn as_raw_fd(&self) -> RawFd {
1082 impl IntoRawFd for File {
1083 fn into_raw_fd(self) -> RawFd {
1084 self.0.into_raw_fd()
1088 impl FromRawFd for File {
1089 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1090 Self(FromRawFd::from_raw_fd(raw_fd))
1094 impl fmt::Debug for File {
1095 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1096 #[cfg(any(target_os = "linux", target_os = "netbsd"))]
1097 fn get_path(fd: c_int) -> Option<PathBuf> {
1098 let mut p = PathBuf::from("/proc/self/fd");
1099 p.push(&fd.to_string());
1103 #[cfg(target_os = "macos")]
1104 fn get_path(fd: c_int) -> Option<PathBuf> {
1105 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1106 // is inevitable in this case because macOS defines `fcntl` with
1107 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1108 // alternatives. If a better method is invented, it should be used
1110 let mut buf = vec![0; libc::PATH_MAX as usize];
1111 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1115 let l = buf.iter().position(|&c| c == 0).unwrap();
1116 buf.truncate(l as usize);
1117 buf.shrink_to_fit();
1118 Some(PathBuf::from(OsString::from_vec(buf)))
1121 #[cfg(target_os = "vxworks")]
1122 fn get_path(fd: c_int) -> Option<PathBuf> {
1123 let mut buf = vec![0; libc::PATH_MAX as usize];
1124 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1128 let l = buf.iter().position(|&c| c == 0).unwrap();
1129 buf.truncate(l as usize);
1130 Some(PathBuf::from(OsString::from_vec(buf)))
1134 target_os = "linux",
1135 target_os = "macos",
1136 target_os = "vxworks",
1137 target_os = "netbsd"
1139 fn get_path(_fd: c_int) -> Option<PathBuf> {
1140 // FIXME(#24570): implement this for other Unix platforms
1144 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "vxworks"))]
1145 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1146 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1150 match mode & libc::O_ACCMODE {
1151 libc::O_RDONLY => Some((true, false)),
1152 libc::O_RDWR => Some((true, true)),
1153 libc::O_WRONLY => Some((false, true)),
1158 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
1159 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1160 // FIXME(#24570): implement this for other Unix platforms
1164 let fd = self.as_raw_fd();
1165 let mut b = f.debug_struct("File");
1167 if let Some(path) = get_path(fd) {
1168 b.field("path", &path);
1170 if let Some((read, write)) = get_mode(fd) {
1171 b.field("read", &read).field("write", &write);
1177 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1178 let root = p.to_path_buf();
1181 let ptr = libc::opendir(p.as_ptr());
1183 Err(Error::last_os_error())
1185 let inner = InnerReadDir { dirp: Dir(ptr), root };
1187 inner: Arc::new(inner),
1189 target_os = "android",
1190 target_os = "linux",
1191 target_os = "solaris",
1192 target_os = "illumos",
1193 target_os = "fuchsia",
1194 target_os = "redox",
1196 end_of_stream: false,
1202 pub fn unlink(p: &Path) -> io::Result<()> {
1204 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
1208 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1209 let old = cstr(old)?;
1210 let new = cstr(new)?;
1211 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
1215 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1217 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
1221 pub fn rmdir(p: &Path) -> io::Result<()> {
1223 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
1227 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1228 let c_path = cstr(p)?;
1229 let p = c_path.as_ptr();
1231 let mut buf = Vec::with_capacity(256);
1235 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1238 buf.set_len(buf_read);
1241 if buf_read != buf.capacity() {
1242 buf.shrink_to_fit();
1244 return Ok(PathBuf::from(OsString::from_vec(buf)));
1247 // Trigger the internal buffer resizing logic of `Vec` by requiring
1248 // more space than the current capacity. The length is guaranteed to be
1249 // the same as the capacity due to the if statement above.
1254 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1255 let original = cstr(original)?;
1256 let link = cstr(link)?;
1257 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) })?;
1261 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1262 let original = cstr(original)?;
1263 let link = cstr(link)?;
1265 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon"))] {
1266 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1267 // it implementation-defined whether `link` follows symlinks, so rely on the
1268 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1269 // Android has `linkat` on newer versions, but we happen to know `link`
1270 // always has the correct behavior, so it's here as well.
1271 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1272 } else if #[cfg(target_os = "macos")] {
1273 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1274 // versions have it. We want to use linkat if it is available, so we use weak!
1275 // to check. `linkat` is preferable to `link` because it gives us a flag to
1276 // specify how symlinks should be handled. We pass 0 as the flags argument,
1277 // meaning it shouldn't follow symlinks.
1278 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1280 if let Some(f) = linkat.get() {
1281 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1283 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1286 // Where we can, use `linkat` instead of `link`; see the comment above
1287 // this one for details on why.
1288 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1294 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1298 if let Some(ret) = unsafe { try_statx(
1301 libc::AT_STATX_SYNC_AS_STAT,
1308 let mut stat: stat64 = unsafe { mem::zeroed() };
1309 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1310 Ok(FileAttr::from_stat64(stat))
1313 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1317 if let Some(ret) = unsafe { try_statx(
1320 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1327 let mut stat: stat64 = unsafe { mem::zeroed() };
1328 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1329 Ok(FileAttr::from_stat64(stat))
1332 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1333 let path = CString::new(p.as_os_str().as_bytes())?;
1336 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1338 return Err(io::Error::last_os_error());
1340 buf = CStr::from_ptr(r).to_bytes().to_vec();
1341 libc::free(r as *mut _);
1343 Ok(PathBuf::from(OsString::from_vec(buf)))
1346 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1347 use crate::fs::File;
1348 use crate::sys_common::fs::NOT_FILE_ERROR;
1350 let reader = File::open(from)?;
1351 let metadata = reader.metadata()?;
1352 if !metadata.is_file() {
1353 return Err(NOT_FILE_ERROR);
1355 Ok((reader, metadata))
1358 #[cfg(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 let writer = OpenOptions::new().open(to)?;
1365 let writer_metadata = writer.metadata()?;
1366 Ok((writer, writer_metadata))
1369 #[cfg(not(target_os = "espidf"))]
1370 fn open_to_and_set_permissions(
1372 reader_metadata: crate::fs::Metadata,
1373 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1374 use crate::fs::OpenOptions;
1375 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1377 let perm = reader_metadata.permissions();
1378 let writer = OpenOptions::new()
1379 // create the file with the correct mode right away
1385 let writer_metadata = writer.metadata()?;
1386 if writer_metadata.is_file() {
1387 // Set the correct file permissions, in case the file already existed.
1388 // Don't set the permissions on already existing non-files like
1389 // pipes/FIFOs or device nodes.
1390 writer.set_permissions(perm)?;
1392 Ok((writer, writer_metadata))
1396 target_os = "linux",
1397 target_os = "android",
1398 target_os = "macos",
1401 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1402 let (mut reader, reader_metadata) = open_from(from)?;
1403 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1405 io::copy(&mut reader, &mut writer)
1408 #[cfg(any(target_os = "linux", target_os = "android"))]
1409 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1410 let (mut reader, reader_metadata) = open_from(from)?;
1411 let max_len = u64::MAX;
1412 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1414 use super::kernel_copy::{copy_regular_files, CopyResult};
1416 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1417 CopyResult::Ended(bytes) => Ok(bytes),
1418 CopyResult::Error(e, _) => Err(e),
1419 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1420 Ok(bytes) => Ok(bytes + written),
1426 #[cfg(any(target_os = "macos", target_os = "ios"))]
1427 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1428 use crate::sync::atomic::{AtomicBool, Ordering};
1430 const COPYFILE_ACL: u32 = 1 << 0;
1431 const COPYFILE_STAT: u32 = 1 << 1;
1432 const COPYFILE_XATTR: u32 = 1 << 2;
1433 const COPYFILE_DATA: u32 = 1 << 3;
1435 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1436 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1437 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1439 const COPYFILE_STATE_COPIED: u32 = 8;
1441 #[allow(non_camel_case_types)]
1442 type copyfile_state_t = *mut libc::c_void;
1443 #[allow(non_camel_case_types)]
1444 type copyfile_flags_t = u32;
1450 state: copyfile_state_t,
1451 flags: copyfile_flags_t,
1453 fn copyfile_state_alloc() -> copyfile_state_t;
1454 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1455 fn copyfile_state_get(
1456 state: copyfile_state_t,
1458 dst: *mut libc::c_void,
1462 struct FreeOnDrop(copyfile_state_t);
1463 impl Drop for FreeOnDrop {
1464 fn drop(&mut self) {
1465 // The code below ensures that `FreeOnDrop` is never a null pointer
1467 // `copyfile_state_free` returns -1 if the `to` or `from` files
1468 // cannot be closed. However, this is not considered this an
1470 copyfile_state_free(self.0);
1475 // MacOS prior to 10.12 don't support `fclonefileat`
1476 // We store the availability in a global to avoid unnecessary syscalls
1477 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1481 dst_dirfd: libc::c_int,
1487 let (reader, reader_metadata) = open_from(from)?;
1489 // Opportunistically attempt to create a copy-on-write clone of `from`
1490 // using `fclonefileat`.
1491 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1493 let clonefile_result =
1494 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) });
1495 match clonefile_result {
1496 Ok(_) => return Ok(reader_metadata.len()),
1497 Err(err) => match err.raw_os_error() {
1498 // `fclonefileat` will fail on non-APFS volumes, if the
1499 // destination already exists, or if the source and destination
1500 // are on different devices. In all these cases `fcopyfile`
1502 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1503 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1504 _ => return Err(err),
1509 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1510 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1512 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1513 // always safe to call `copyfile_state_free`
1514 let state = unsafe {
1515 let state = copyfile_state_alloc();
1516 if state.is_null() {
1517 return Err(crate::io::Error::last_os_error());
1522 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1524 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1526 let mut bytes_copied: libc::off_t = 0;
1530 COPYFILE_STATE_COPIED,
1531 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1534 Ok(bytes_copied as u64)
1537 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1538 let path = cstr(path)?;
1539 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1543 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1544 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1548 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1549 let path = cstr(path)?;
1550 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1554 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1555 pub fn chroot(dir: &Path) -> io::Result<()> {
1556 let dir = cstr(dir)?;
1557 cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
1561 pub use remove_dir_impl::remove_dir_all;
1563 // Fallback for REDOX, ESP-ID, Horizon, and Miri
1564 #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri))]
1565 mod remove_dir_impl {
1566 pub use crate::sys_common::fs::remove_dir_all;
1569 // Modern implementation using openat(), unlinkat() and fdopendir()
1570 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri)))]
1571 mod remove_dir_impl {
1572 use super::{cstr, lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1573 use crate::ffi::CStr;
1575 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1576 use crate::os::unix::prelude::{OwnedFd, RawFd};
1577 use crate::path::{Path, PathBuf};
1578 use crate::sync::Arc;
1579 use crate::sys::{cvt, cvt_r};
1581 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64")),))]
1582 use libc::{fdopendir, openat, unlinkat};
1583 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1584 use macos_weak::{fdopendir, openat, unlinkat};
1586 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1588 use crate::sys::weak::weak;
1589 use libc::{c_char, c_int, DIR};
1591 fn get_openat_fn() -> Option<unsafe extern "C" fn(c_int, *const c_char, c_int) -> c_int> {
1592 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1596 pub fn has_openat() -> bool {
1597 get_openat_fn().is_some()
1600 pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1601 get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| {
1602 crate::sys::unix::os::set_errno(libc::ENOSYS);
1607 pub unsafe fn fdopendir(fd: c_int) -> *mut DIR {
1608 #[cfg(all(target_os = "macos", target_arch = "x86"))]
1609 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64$UNIX2003");
1610 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1611 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1612 fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| {
1613 crate::sys::unix::os::set_errno(libc::ENOSYS);
1614 crate::ptr::null_mut()
1618 pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1619 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1620 unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| {
1621 crate::sys::unix::os::set_errno(libc::ENOSYS);
1627 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1628 let fd = cvt_r(|| unsafe {
1630 parent_fd.unwrap_or(libc::AT_FDCWD),
1632 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1635 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1638 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1639 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1641 return Err(io::Error::last_os_error());
1643 let dirp = Dir(ptr);
1644 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1645 let new_parent_fd = dir_fd.into_raw_fd();
1646 // a valid root is not needed because we do not call any functions involving the full path
1647 // of the DirEntrys.
1648 let dummy_root = PathBuf::new();
1651 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1653 target_os = "android",
1654 target_os = "linux",
1655 target_os = "solaris",
1656 target_os = "illumos",
1657 target_os = "fuchsia",
1658 target_os = "redox",
1660 end_of_stream: false,
1667 target_os = "solaris",
1668 target_os = "illumos",
1669 target_os = "haiku",
1670 target_os = "vxworks",
1672 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1677 target_os = "solaris",
1678 target_os = "illumos",
1679 target_os = "haiku",
1680 target_os = "vxworks",
1682 fn is_dir(ent: &DirEntry) -> Option<bool> {
1683 match ent.entry.d_type {
1684 libc::DT_UNKNOWN => None,
1685 libc::DT_DIR => Some(true),
1690 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
1691 // try opening as directory
1692 let fd = match openat_nofollow_dironly(parent_fd, &path) {
1693 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
1694 // not a directory - don't traverse further
1695 // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
1696 return match parent_fd {
1698 Some(parent_fd) => {
1699 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
1701 // ...unless this was supposed to be the deletion root directory
1708 // open the directory passing ownership of the fd
1709 let (dir, fd) = fdreaddir(fd)?;
1712 let child_name = child.name_cstr();
1713 match is_dir(&child) {
1715 remove_dir_all_recursive(Some(fd), child_name)?;
1718 cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
1721 // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
1722 // if the process has the appropriate privileges. This however can causing orphaned
1723 // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
1724 // into it first instead of trying to unlink() it.
1725 remove_dir_all_recursive(Some(fd), child_name)?;
1730 // unlink the directory after removing its contents
1732 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
1737 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1738 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1739 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1741 let attr = lstat(p)?;
1742 if attr.file_type().is_symlink() {
1743 crate::fs::remove_file(p)
1745 remove_dir_all_recursive(None, &cstr(p)?)
1749 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64"))))]
1750 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1751 remove_dir_all_modern(p)
1754 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1755 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1756 if macos_weak::has_openat() {
1757 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1758 remove_dir_all_modern(p)
1760 // fall back to classic implementation
1761 crate::sys_common::fs::remove_dir_all(p)