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 {}
231 pub struct DirEntry {
233 dir: Arc<InnerReadDir>,
234 // We need to store an owned copy of the entry name on platforms that use
235 // readdir() (not readdir_r()), because a) struct dirent may use a flexible
236 // array to store the name, b) it lives only until the next readdir() call.
238 target_os = "android",
240 target_os = "solaris",
241 target_os = "illumos",
242 target_os = "fuchsia",
248 #[derive(Clone, Debug)]
249 pub struct OpenOptions {
262 #[derive(Clone, PartialEq, Eq, Debug)]
263 pub struct FilePermissions {
267 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
268 pub struct FileType {
273 pub struct DirBuilder {
279 fn from_stat64(stat: stat64) -> Self {
280 Self { stat, statx_extra_fields: None }
285 fn from_stat64(stat: stat64) -> Self {
292 pub fn size(&self) -> u64 {
293 self.stat.st_size as u64
295 pub fn perm(&self) -> FilePermissions {
296 FilePermissions { mode: (self.stat.st_mode as mode_t) }
299 pub fn file_type(&self) -> FileType {
300 FileType { mode: self.stat.st_mode as mode_t }
304 #[cfg(target_os = "netbsd")]
306 pub fn modified(&self) -> io::Result<SystemTime> {
307 Ok(SystemTime::from(libc::timespec {
308 tv_sec: self.stat.st_mtime as libc::time_t,
309 tv_nsec: self.stat.st_mtimensec as libc::c_long,
313 pub fn accessed(&self) -> io::Result<SystemTime> {
314 Ok(SystemTime::from(libc::timespec {
315 tv_sec: self.stat.st_atime as libc::time_t,
316 tv_nsec: self.stat.st_atimensec as libc::c_long,
320 pub fn created(&self) -> io::Result<SystemTime> {
321 Ok(SystemTime::from(libc::timespec {
322 tv_sec: self.stat.st_birthtime as libc::time_t,
323 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
328 #[cfg(not(target_os = "netbsd"))]
330 #[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
331 pub fn modified(&self) -> io::Result<SystemTime> {
332 Ok(SystemTime::from(libc::timespec {
333 tv_sec: self.stat.st_mtime as libc::time_t,
334 tv_nsec: self.stat.st_mtime_nsec as _,
338 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
339 pub fn modified(&self) -> io::Result<SystemTime> {
340 Ok(SystemTime::from(libc::timespec {
341 tv_sec: self.stat.st_mtime as libc::time_t,
346 #[cfg(all(not(target_os = "vxworks"), not(target_os = "espidf")))]
347 pub fn accessed(&self) -> io::Result<SystemTime> {
348 Ok(SystemTime::from(libc::timespec {
349 tv_sec: self.stat.st_atime as libc::time_t,
350 tv_nsec: self.stat.st_atime_nsec as _,
354 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
355 pub fn accessed(&self) -> io::Result<SystemTime> {
356 Ok(SystemTime::from(libc::timespec {
357 tv_sec: self.stat.st_atime as libc::time_t,
363 target_os = "freebsd",
364 target_os = "openbsd",
368 pub fn created(&self) -> io::Result<SystemTime> {
369 Ok(SystemTime::from(libc::timespec {
370 tv_sec: self.stat.st_birthtime as libc::time_t,
371 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
376 target_os = "freebsd",
377 target_os = "openbsd",
381 pub fn created(&self) -> io::Result<SystemTime> {
383 if let Some(ext) = &self.statx_extra_fields {
384 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
385 Ok(SystemTime::from(libc::timespec {
386 tv_sec: ext.stx_btime.tv_sec as libc::time_t,
387 tv_nsec: ext.stx_btime.tv_nsec as _,
390 Err(io::Error::new_const(
391 io::ErrorKind::Uncategorized,
392 &"creation time is not available for the filesystem",
398 Err(io::Error::new_const(
399 io::ErrorKind::Unsupported,
400 &"creation time is not available on this platform \
406 impl AsInner<stat64> for FileAttr {
407 fn as_inner(&self) -> &stat64 {
412 impl FilePermissions {
413 pub fn readonly(&self) -> bool {
414 // check if any class (owner, group, others) has write permission
415 self.mode & 0o222 == 0
418 pub fn set_readonly(&mut self, readonly: bool) {
420 // remove write permission for all classes; equivalent to `chmod a-w <file>`
423 // add write permission for all classes; equivalent to `chmod a+w <file>`
427 pub fn mode(&self) -> u32 {
433 pub fn is_dir(&self) -> bool {
434 self.is(libc::S_IFDIR)
436 pub fn is_file(&self) -> bool {
437 self.is(libc::S_IFREG)
439 pub fn is_symlink(&self) -> bool {
440 self.is(libc::S_IFLNK)
443 pub fn is(&self, mode: mode_t) -> bool {
444 self.mode & libc::S_IFMT == mode
448 impl FromInner<u32> for FilePermissions {
449 fn from_inner(mode: u32) -> FilePermissions {
450 FilePermissions { mode: mode as mode_t }
454 impl fmt::Debug for ReadDir {
455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
456 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
457 // Thus the result will be e g 'ReadDir("/home")'
458 fmt::Debug::fmt(&*self.inner.root, f)
462 impl Iterator for ReadDir {
463 type Item = io::Result<DirEntry>;
466 target_os = "android",
468 target_os = "solaris",
469 target_os = "fuchsia",
471 target_os = "illumos"
473 fn next(&mut self) -> Option<io::Result<DirEntry>> {
476 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
477 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
478 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
479 // thread safety for readdir() as long an individual DIR* is not accessed
480 // concurrently, which is sufficient for Rust.
481 super::os::set_errno(0);
482 let entry_ptr = readdir64(self.inner.dirp.0);
483 if entry_ptr.is_null() {
484 // null can mean either the end is reached or an error occurred.
485 // So we had to clear errno beforehand to check for an error now.
486 return match super::os::errno() {
488 e => Some(Err(Error::from_raw_os_error(e))),
492 // Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
493 // whole thing (#93384). Instead, copy everything except the name.
494 let entry_bytes = entry_ptr as *const u8;
495 let entry_name = ptr::addr_of!((*entry_ptr).d_name) as *const u8;
496 let name_offset = entry_name.offset_from(entry_bytes) as usize;
497 let mut entry: dirent64 = mem::zeroed();
498 ptr::copy_nonoverlapping(entry_bytes, &mut entry as *mut _ as *mut u8, name_offset);
502 // d_name is guaranteed to be null-terminated.
503 name: CStr::from_ptr(entry_name as *const _).to_owned(),
504 dir: Arc::clone(&self.inner),
506 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
507 return Some(Ok(ret));
514 target_os = "android",
516 target_os = "solaris",
517 target_os = "fuchsia",
519 target_os = "illumos"
521 fn next(&mut self) -> Option<io::Result<DirEntry>> {
522 if self.end_of_stream {
527 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
528 let mut entry_ptr = ptr::null_mut();
530 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
532 if entry_ptr.is_null() {
533 // We encountered an error (which will be returned in this iteration), but
534 // we also reached the end of the directory stream. The `end_of_stream`
535 // flag is enabled to make sure that we return `None` in the next iteration
536 // (instead of looping forever)
537 self.end_of_stream = true;
539 return Some(Err(Error::from_raw_os_error(err)));
541 if entry_ptr.is_null() {
544 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
545 return Some(Ok(ret));
554 let r = unsafe { libc::closedir(self.0) };
555 debug_assert_eq!(r, 0);
560 pub fn path(&self) -> PathBuf {
561 self.dir.root.join(self.file_name_os_str())
564 pub fn file_name(&self) -> OsString {
565 self.file_name_os_str().to_os_string()
568 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
569 pub fn metadata(&self) -> io::Result<FileAttr> {
570 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
571 let name = self.name_cstr().as_ptr();
574 if let Some(ret) = unsafe { try_statx(
577 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
584 let mut stat: stat64 = unsafe { mem::zeroed() };
585 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
586 Ok(FileAttr::from_stat64(stat))
589 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
590 pub fn metadata(&self) -> io::Result<FileAttr> {
595 target_os = "solaris",
596 target_os = "illumos",
598 target_os = "vxworks"
600 pub fn file_type(&self) -> io::Result<FileType> {
601 self.metadata().map(|m| m.file_type())
605 target_os = "solaris",
606 target_os = "illumos",
608 target_os = "vxworks"
610 pub fn file_type(&self) -> io::Result<FileType> {
611 match self.entry.d_type {
612 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
613 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
614 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
615 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
616 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
617 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
618 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
619 _ => self.metadata().map(|m| m.file_type()),
627 target_os = "emscripten",
628 target_os = "android",
629 target_os = "solaris",
630 target_os = "illumos",
633 target_os = "fuchsia",
635 target_os = "vxworks",
638 pub fn ino(&self) -> u64 {
639 self.entry.d_ino as u64
643 target_os = "freebsd",
644 target_os = "openbsd",
645 target_os = "netbsd",
646 target_os = "dragonfly"
648 pub fn ino(&self) -> u64 {
649 self.entry.d_fileno as u64
655 target_os = "netbsd",
656 target_os = "openbsd",
657 target_os = "freebsd",
658 target_os = "dragonfly"
660 fn name_bytes(&self) -> &[u8] {
663 slice::from_raw_parts(
664 self.entry.d_name.as_ptr() as *const u8,
665 self.entry.d_namlen as usize,
672 target_os = "netbsd",
673 target_os = "openbsd",
674 target_os = "freebsd",
675 target_os = "dragonfly"
677 fn name_bytes(&self) -> &[u8] {
678 self.name_cstr().to_bytes()
682 target_os = "android",
684 target_os = "solaris",
685 target_os = "illumos",
686 target_os = "fuchsia",
689 fn name_cstr(&self) -> &CStr {
690 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
693 target_os = "android",
695 target_os = "solaris",
696 target_os = "illumos",
697 target_os = "fuchsia",
700 fn name_cstr(&self) -> &CStr {
704 pub fn file_name_os_str(&self) -> &OsStr {
705 OsStr::from_bytes(self.name_bytes())
710 pub fn new() -> OpenOptions {
725 pub fn read(&mut self, read: bool) {
728 pub fn write(&mut self, write: bool) {
731 pub fn append(&mut self, append: bool) {
732 self.append = append;
734 pub fn truncate(&mut self, truncate: bool) {
735 self.truncate = truncate;
737 pub fn create(&mut self, create: bool) {
738 self.create = create;
740 pub fn create_new(&mut self, create_new: bool) {
741 self.create_new = create_new;
744 pub fn custom_flags(&mut self, flags: i32) {
745 self.custom_flags = flags;
747 pub fn mode(&mut self, mode: u32) {
748 self.mode = mode as mode_t;
751 fn get_access_mode(&self) -> io::Result<c_int> {
752 match (self.read, self.write, self.append) {
753 (true, false, false) => Ok(libc::O_RDONLY),
754 (false, true, false) => Ok(libc::O_WRONLY),
755 (true, true, false) => Ok(libc::O_RDWR),
756 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
757 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
758 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
762 fn get_creation_mode(&self) -> io::Result<c_int> {
763 match (self.write, self.append) {
766 if self.truncate || self.create || self.create_new {
767 return Err(Error::from_raw_os_error(libc::EINVAL));
771 if self.truncate && !self.create_new {
772 return Err(Error::from_raw_os_error(libc::EINVAL));
777 Ok(match (self.create, self.truncate, self.create_new) {
778 (false, false, false) => 0,
779 (true, false, false) => libc::O_CREAT,
780 (false, true, false) => libc::O_TRUNC,
781 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
782 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
788 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
789 let path = cstr(path)?;
790 File::open_c(&path, opts)
793 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
794 let flags = libc::O_CLOEXEC
795 | opts.get_access_mode()?
796 | opts.get_creation_mode()?
797 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
798 // The third argument of `open64` is documented to have type `mode_t`. On
799 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
800 // However, since this is a variadic function, C integer promotion rules mean that on
801 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
802 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
803 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
806 pub fn file_attr(&self) -> io::Result<FileAttr> {
807 let fd = self.as_raw_fd();
810 if let Some(ret) = unsafe { try_statx(
812 b"\0" as *const _ as *const c_char,
813 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
820 let mut stat: stat64 = unsafe { mem::zeroed() };
821 cvt(unsafe { fstat64(fd, &mut stat) })?;
822 Ok(FileAttr::from_stat64(stat))
825 pub fn fsync(&self) -> io::Result<()> {
826 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
829 #[cfg(any(target_os = "macos", target_os = "ios"))]
830 unsafe fn os_fsync(fd: c_int) -> c_int {
831 libc::fcntl(fd, libc::F_FULLFSYNC)
833 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
834 unsafe fn os_fsync(fd: c_int) -> c_int {
839 pub fn datasync(&self) -> io::Result<()> {
840 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
843 #[cfg(any(target_os = "macos", target_os = "ios"))]
844 unsafe fn os_datasync(fd: c_int) -> c_int {
845 libc::fcntl(fd, libc::F_FULLFSYNC)
848 target_os = "freebsd",
850 target_os = "android",
851 target_os = "netbsd",
852 target_os = "openbsd"
854 unsafe fn os_datasync(fd: c_int) -> c_int {
858 target_os = "android",
859 target_os = "freebsd",
863 target_os = "netbsd",
864 target_os = "openbsd"
866 unsafe fn os_datasync(fd: c_int) -> c_int {
871 pub fn truncate(&self, size: u64) -> io::Result<()> {
872 use crate::convert::TryInto;
874 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
875 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
878 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
882 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
883 self.0.read_vectored(bufs)
887 pub fn is_read_vectored(&self) -> bool {
888 self.0.is_read_vectored()
891 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
892 self.0.read_at(buf, offset)
895 pub fn read_buf(&self, buf: &mut ReadBuf<'_>) -> io::Result<()> {
899 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
903 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
904 self.0.write_vectored(bufs)
908 pub fn is_write_vectored(&self) -> bool {
909 self.0.is_write_vectored()
912 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
913 self.0.write_at(buf, offset)
916 pub fn flush(&self) -> io::Result<()> {
920 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
921 let (whence, pos) = match pos {
922 // Casting to `i64` is fine, too large values will end up as
923 // negative which will cause an error in `lseek64`.
924 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
925 SeekFrom::End(off) => (libc::SEEK_END, off),
926 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
928 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos, whence) })?;
932 pub fn duplicate(&self) -> io::Result<File> {
933 self.0.duplicate().map(File)
936 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
937 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
943 pub fn new() -> DirBuilder {
944 DirBuilder { mode: 0o777 }
947 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
949 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
953 pub fn set_mode(&mut self, mode: u32) {
954 self.mode = mode as mode_t;
958 fn cstr(path: &Path) -> io::Result<CString> {
959 Ok(CString::new(path.as_os_str().as_bytes())?)
962 impl AsInner<FileDesc> for File {
963 fn as_inner(&self) -> &FileDesc {
968 impl AsInnerMut<FileDesc> for File {
969 fn as_inner_mut(&mut self) -> &mut FileDesc {
974 impl IntoInner<FileDesc> for File {
975 fn into_inner(self) -> FileDesc {
980 impl FromInner<FileDesc> for File {
981 fn from_inner(file_desc: FileDesc) -> Self {
987 fn as_fd(&self) -> BorrowedFd<'_> {
992 impl AsRawFd for File {
993 fn as_raw_fd(&self) -> RawFd {
998 impl IntoRawFd for File {
999 fn into_raw_fd(self) -> RawFd {
1000 self.0.into_raw_fd()
1004 impl FromRawFd for File {
1005 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1006 Self(FromRawFd::from_raw_fd(raw_fd))
1010 impl fmt::Debug for File {
1011 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1012 #[cfg(any(target_os = "linux", target_os = "netbsd"))]
1013 fn get_path(fd: c_int) -> Option<PathBuf> {
1014 let mut p = PathBuf::from("/proc/self/fd");
1015 p.push(&fd.to_string());
1019 #[cfg(target_os = "macos")]
1020 fn get_path(fd: c_int) -> Option<PathBuf> {
1021 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1022 // is inevitable in this case because macOS defines `fcntl` with
1023 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1024 // alternatives. If a better method is invented, it should be used
1026 let mut buf = vec![0; libc::PATH_MAX as usize];
1027 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1031 let l = buf.iter().position(|&c| c == 0).unwrap();
1032 buf.truncate(l as usize);
1033 buf.shrink_to_fit();
1034 Some(PathBuf::from(OsString::from_vec(buf)))
1037 #[cfg(target_os = "vxworks")]
1038 fn get_path(fd: c_int) -> Option<PathBuf> {
1039 let mut buf = vec![0; libc::PATH_MAX as usize];
1040 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1044 let l = buf.iter().position(|&c| c == 0).unwrap();
1045 buf.truncate(l as usize);
1046 Some(PathBuf::from(OsString::from_vec(buf)))
1050 target_os = "linux",
1051 target_os = "macos",
1052 target_os = "vxworks",
1053 target_os = "netbsd"
1055 fn get_path(_fd: c_int) -> Option<PathBuf> {
1056 // FIXME(#24570): implement this for other Unix platforms
1060 #[cfg(any(target_os = "linux", target_os = "macos", target_os = "vxworks"))]
1061 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1062 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1066 match mode & libc::O_ACCMODE {
1067 libc::O_RDONLY => Some((true, false)),
1068 libc::O_RDWR => Some((true, true)),
1069 libc::O_WRONLY => Some((false, true)),
1074 #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "vxworks")))]
1075 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1076 // FIXME(#24570): implement this for other Unix platforms
1080 let fd = self.as_raw_fd();
1081 let mut b = f.debug_struct("File");
1083 if let Some(path) = get_path(fd) {
1084 b.field("path", &path);
1086 if let Some((read, write)) = get_mode(fd) {
1087 b.field("read", &read).field("write", &write);
1093 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
1094 let root = p.to_path_buf();
1097 let ptr = libc::opendir(p.as_ptr());
1099 Err(Error::last_os_error())
1101 let inner = InnerReadDir { dirp: Dir(ptr), root };
1103 inner: Arc::new(inner),
1105 target_os = "android",
1106 target_os = "linux",
1107 target_os = "solaris",
1108 target_os = "illumos",
1109 target_os = "fuchsia",
1110 target_os = "redox",
1112 end_of_stream: false,
1118 pub fn unlink(p: &Path) -> io::Result<()> {
1120 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
1124 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1125 let old = cstr(old)?;
1126 let new = cstr(new)?;
1127 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
1131 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1133 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
1137 pub fn rmdir(p: &Path) -> io::Result<()> {
1139 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
1143 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1144 let c_path = cstr(p)?;
1145 let p = c_path.as_ptr();
1147 let mut buf = Vec::with_capacity(256);
1151 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1154 buf.set_len(buf_read);
1157 if buf_read != buf.capacity() {
1158 buf.shrink_to_fit();
1160 return Ok(PathBuf::from(OsString::from_vec(buf)));
1163 // Trigger the internal buffer resizing logic of `Vec` by requiring
1164 // more space than the current capacity. The length is guaranteed to be
1165 // the same as the capacity due to the if statement above.
1170 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1171 let original = cstr(original)?;
1172 let link = cstr(link)?;
1173 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) })?;
1177 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1178 let original = cstr(original)?;
1179 let link = cstr(link)?;
1181 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf"))] {
1182 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1183 // it implementation-defined whether `link` follows symlinks, so rely on the
1184 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1185 // Android has `linkat` on newer versions, but we happen to know `link`
1186 // always has the correct behavior, so it's here as well.
1187 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1188 } else if #[cfg(target_os = "macos")] {
1189 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1190 // versions have it. We want to use linkat if it is available, so we use weak!
1191 // to check. `linkat` is preferable to `link` because it gives us a flag to
1192 // specify how symlinks should be handled. We pass 0 as the flags argument,
1193 // meaning it shouldn't follow symlinks.
1194 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1196 if let Some(f) = linkat.get() {
1197 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1199 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1202 // Where we can, use `linkat` instead of `link`; see the comment above
1203 // this one for details on why.
1204 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1210 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1214 if let Some(ret) = unsafe { try_statx(
1217 libc::AT_STATX_SYNC_AS_STAT,
1224 let mut stat: stat64 = unsafe { mem::zeroed() };
1225 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1226 Ok(FileAttr::from_stat64(stat))
1229 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1233 if let Some(ret) = unsafe { try_statx(
1236 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1243 let mut stat: stat64 = unsafe { mem::zeroed() };
1244 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1245 Ok(FileAttr::from_stat64(stat))
1248 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1249 let path = CString::new(p.as_os_str().as_bytes())?;
1252 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1254 return Err(io::Error::last_os_error());
1256 buf = CStr::from_ptr(r).to_bytes().to_vec();
1257 libc::free(r as *mut _);
1259 Ok(PathBuf::from(OsString::from_vec(buf)))
1262 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1263 use crate::fs::File;
1264 use crate::sys_common::fs::NOT_FILE_ERROR;
1266 let reader = File::open(from)?;
1267 let metadata = reader.metadata()?;
1268 if !metadata.is_file() {
1269 return Err(NOT_FILE_ERROR);
1271 Ok((reader, metadata))
1274 #[cfg(target_os = "espidf")]
1275 fn open_to_and_set_permissions(
1277 reader_metadata: crate::fs::Metadata,
1278 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1279 use crate::fs::OpenOptions;
1280 let writer = OpenOptions::new().open(to)?;
1281 let writer_metadata = writer.metadata()?;
1282 Ok((writer, writer_metadata))
1285 #[cfg(not(target_os = "espidf"))]
1286 fn open_to_and_set_permissions(
1288 reader_metadata: crate::fs::Metadata,
1289 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1290 use crate::fs::OpenOptions;
1291 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1293 let perm = reader_metadata.permissions();
1294 let writer = OpenOptions::new()
1295 // create the file with the correct mode right away
1301 let writer_metadata = writer.metadata()?;
1302 if writer_metadata.is_file() {
1303 // Set the correct file permissions, in case the file already existed.
1304 // Don't set the permissions on already existing non-files like
1305 // pipes/FIFOs or device nodes.
1306 writer.set_permissions(perm)?;
1308 Ok((writer, writer_metadata))
1312 target_os = "linux",
1313 target_os = "android",
1314 target_os = "macos",
1317 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1318 let (mut reader, reader_metadata) = open_from(from)?;
1319 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1321 io::copy(&mut reader, &mut writer)
1324 #[cfg(any(target_os = "linux", target_os = "android"))]
1325 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1326 let (mut reader, reader_metadata) = open_from(from)?;
1327 let max_len = u64::MAX;
1328 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1330 use super::kernel_copy::{copy_regular_files, CopyResult};
1332 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1333 CopyResult::Ended(bytes) => Ok(bytes),
1334 CopyResult::Error(e, _) => Err(e),
1335 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1336 Ok(bytes) => Ok(bytes + written),
1342 #[cfg(any(target_os = "macos", target_os = "ios"))]
1343 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1344 use crate::sync::atomic::{AtomicBool, Ordering};
1346 const COPYFILE_ACL: u32 = 1 << 0;
1347 const COPYFILE_STAT: u32 = 1 << 1;
1348 const COPYFILE_XATTR: u32 = 1 << 2;
1349 const COPYFILE_DATA: u32 = 1 << 3;
1351 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1352 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1353 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1355 const COPYFILE_STATE_COPIED: u32 = 8;
1357 #[allow(non_camel_case_types)]
1358 type copyfile_state_t = *mut libc::c_void;
1359 #[allow(non_camel_case_types)]
1360 type copyfile_flags_t = u32;
1366 state: copyfile_state_t,
1367 flags: copyfile_flags_t,
1369 fn copyfile_state_alloc() -> copyfile_state_t;
1370 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1371 fn copyfile_state_get(
1372 state: copyfile_state_t,
1374 dst: *mut libc::c_void,
1378 struct FreeOnDrop(copyfile_state_t);
1379 impl Drop for FreeOnDrop {
1380 fn drop(&mut self) {
1381 // The code below ensures that `FreeOnDrop` is never a null pointer
1383 // `copyfile_state_free` returns -1 if the `to` or `from` files
1384 // cannot be closed. However, this is not considered this an
1386 copyfile_state_free(self.0);
1391 // MacOS prior to 10.12 don't support `fclonefileat`
1392 // We store the availability in a global to avoid unnecessary syscalls
1393 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1397 dst_dirfd: libc::c_int,
1403 let (reader, reader_metadata) = open_from(from)?;
1405 // Opportunistically attempt to create a copy-on-write clone of `from`
1406 // using `fclonefileat`.
1407 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1409 let clonefile_result =
1410 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) });
1411 match clonefile_result {
1412 Ok(_) => return Ok(reader_metadata.len()),
1413 Err(err) => match err.raw_os_error() {
1414 // `fclonefileat` will fail on non-APFS volumes, if the
1415 // destination already exists, or if the source and destination
1416 // are on different devices. In all these cases `fcopyfile`
1418 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1419 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1420 _ => return Err(err),
1425 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1426 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1428 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1429 // always safe to call `copyfile_state_free`
1430 let state = unsafe {
1431 let state = copyfile_state_alloc();
1432 if state.is_null() {
1433 return Err(crate::io::Error::last_os_error());
1438 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1440 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1442 let mut bytes_copied: libc::off_t = 0;
1446 COPYFILE_STATE_COPIED,
1447 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1450 Ok(bytes_copied as u64)
1453 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1454 let path = cstr(path)?;
1455 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1459 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1460 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1464 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1465 let path = cstr(path)?;
1466 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
1470 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1471 pub fn chroot(dir: &Path) -> io::Result<()> {
1472 let dir = cstr(dir)?;
1473 cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
1477 pub use remove_dir_impl::remove_dir_all;
1479 // Fallback for REDOX and ESP-IDF
1480 #[cfg(any(target_os = "redox", target_os = "espidf"))]
1481 mod remove_dir_impl {
1482 pub use crate::sys_common::fs::remove_dir_all;
1485 // Dynamically choose implementation Macos x86-64: modern for 10.10+, fallback for older versions
1486 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1487 mod remove_dir_impl {
1488 use super::{cstr, lstat, Dir, InnerReadDir, ReadDir};
1489 use crate::ffi::CStr;
1491 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1492 use crate::os::unix::prelude::{OwnedFd, RawFd};
1493 use crate::path::{Path, PathBuf};
1494 use crate::sync::Arc;
1495 use crate::sys::weak::weak;
1496 use crate::sys::{cvt, cvt_r};
1497 use libc::{c_char, c_int, DIR};
1499 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1500 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1501 let fd = cvt_r(|| unsafe {
1502 openat.get().unwrap()(
1503 parent_fd.unwrap_or(libc::AT_FDCWD),
1505 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1508 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1511 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1512 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1513 let ptr = unsafe { fdopendir.get().unwrap()(dir_fd.as_raw_fd()) };
1515 return Err(io::Error::last_os_error());
1517 let dirp = Dir(ptr);
1518 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1519 let new_parent_fd = dir_fd.into_raw_fd();
1520 // a valid root is not needed because we do not call any functions involving the full path
1521 // of the DirEntrys.
1522 let dummy_root = PathBuf::new();
1525 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1526 end_of_stream: false,
1532 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, p: &Path) -> io::Result<()> {
1533 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1535 let pcstr = cstr(p)?;
1537 // entry is expected to be a directory, open as such
1538 let fd = openat_nofollow_dironly(parent_fd, &pcstr)?;
1540 // open the directory passing ownership of the fd
1541 let (dir, fd) = fdreaddir(fd)?;
1544 match child.entry.d_type {
1546 remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?;
1548 libc::DT_UNKNOWN => {
1549 match cvt(unsafe { unlinkat.get().unwrap()(fd, child.name_cstr().as_ptr(), 0) })
1551 // type unknown - try to unlink
1552 Err(err) if err.raw_os_error() == Some(libc::EPERM) => {
1553 // if the file is a directory unlink fails with EPERM
1554 remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?;
1562 // not a directory -> unlink
1563 cvt(unsafe { unlinkat.get().unwrap()(fd, child.name_cstr().as_ptr(), 0) })?;
1568 // unlink the directory after removing its contents
1570 unlinkat.get().unwrap()(
1571 parent_fd.unwrap_or(libc::AT_FDCWD),
1579 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1580 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1581 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1583 let attr = lstat(p)?;
1584 if attr.file_type().is_symlink() {
1585 crate::fs::remove_file(p)
1587 remove_dir_all_recursive(None, p)
1591 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1592 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1593 if openat.get().is_some() {
1594 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1595 remove_dir_all_modern(p)
1597 // fall back to classic implementation
1598 crate::sys_common::fs::remove_dir_all(p)
1603 // Modern implementation using openat(), unlinkat() and fdopendir()
1605 all(target_os = "macos", target_arch = "x86_64"),
1606 target_os = "redox",
1607 target_os = "espidf"
1609 mod remove_dir_impl {
1610 use super::{cstr, lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1611 use crate::ffi::CStr;
1613 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1614 use crate::os::unix::prelude::{OwnedFd, RawFd};
1615 use crate::path::{Path, PathBuf};
1616 use crate::sync::Arc;
1617 use crate::sys::{cvt, cvt_r};
1618 use libc::{fdopendir, openat, unlinkat};
1620 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1621 let fd = cvt_r(|| unsafe {
1623 parent_fd.unwrap_or(libc::AT_FDCWD),
1625 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1628 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1631 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1632 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1634 return Err(io::Error::last_os_error());
1636 let dirp = Dir(ptr);
1637 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1638 let new_parent_fd = dir_fd.into_raw_fd();
1639 // a valid root is not needed because we do not call any functions involving the full path
1640 // of the DirEntrys.
1641 let dummy_root = PathBuf::new();
1644 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1646 target_os = "android",
1647 target_os = "linux",
1648 target_os = "solaris",
1649 target_os = "illumos",
1650 target_os = "fuchsia",
1651 target_os = "redox",
1653 end_of_stream: false,
1660 target_os = "solaris",
1661 target_os = "illumos",
1662 target_os = "haiku",
1663 target_os = "vxworks",
1665 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1670 target_os = "solaris",
1671 target_os = "illumos",
1672 target_os = "haiku",
1673 target_os = "vxworks",
1675 fn is_dir(ent: &DirEntry) -> Option<bool> {
1676 match ent.entry.d_type {
1677 libc::DT_UNKNOWN => None,
1678 libc::DT_DIR => Some(true),
1683 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, p: &Path) -> io::Result<()> {
1684 let pcstr = cstr(p)?;
1686 // entry is expected to be a directory, open as such
1687 let fd = openat_nofollow_dironly(parent_fd, &pcstr)?;
1689 // open the directory passing ownership of the fd
1690 let (dir, fd) = fdreaddir(fd)?;
1693 match is_dir(&child) {
1695 remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?;
1698 cvt(unsafe { unlinkat(fd, child.name_cstr().as_ptr(), 0) })?;
1700 None => match cvt(unsafe { unlinkat(fd, child.name_cstr().as_ptr(), 0) }) {
1701 // type unknown - try to unlink
1703 if err.raw_os_error() == Some(libc::EISDIR)
1704 || err.raw_os_error() == Some(libc::EPERM) =>
1706 // if the file is a directory unlink fails with EISDIR on Linux and EPERM everyhwere else
1707 remove_dir_all_recursive(Some(fd), Path::new(&child.file_name()))?;
1716 // unlink the directory after removing its contents
1718 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), pcstr.as_ptr(), libc::AT_REMOVEDIR)
1723 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1724 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1725 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1727 let attr = lstat(p)?;
1728 if attr.file_type().is_symlink() {
1729 crate::fs::remove_file(p)
1731 remove_dir_all_recursive(None, p)