1 use crate::os::unix::prelude::*;
3 use crate::ffi::{CStr, OsStr, OsString};
5 use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
7 use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
8 use crate::path::{Path, PathBuf};
11 use crate::sys::common::small_c_string::run_path_with_cstr;
12 use crate::sys::fd::FileDesc;
13 use crate::sys::time::SystemTime;
14 use crate::sys::{cvt, cvt_r};
15 use crate::sys_common::{AsInner, AsInnerMut, FromInner, IntoInner};
18 all(target_os = "linux", target_env = "gnu"),
21 target_os = "watchos",
23 use crate::sys::weak::syscall;
24 #[cfg(any(target_os = "android", target_os = "macos"))]
25 use crate::sys::weak::weak;
27 use libc::{c_int, mode_t};
32 target_os = "watchos",
33 all(target_os = "linux", target_env = "gnu")
36 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
38 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
41 target_os = "android",
42 target_os = "solaris",
43 target_os = "fuchsia",
47 use libc::readdir as readdir64;
48 #[cfg(target_os = "linux")]
50 #[cfg(any(target_os = "emscripten", target_os = "l4re"))]
51 use libc::readdir64_r;
53 target_os = "android",
55 target_os = "emscripten",
56 target_os = "solaris",
57 target_os = "illumos",
59 target_os = "fuchsia",
62 use libc::readdir_r as readdir64_r;
63 #[cfg(target_os = "android")]
65 dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
66 lstat as lstat64, off64_t, open as open64, stat as stat64,
70 target_os = "emscripten",
75 dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
76 lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
78 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
79 use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
81 pub use crate::sys_common::fs::try_exists;
83 pub struct File(FileDesc);
85 // FIXME: This should be available on Linux with all `target_env`.
86 // But currently only glibc exposes `statx` fn and structs.
87 // We don't want to import unverified raw C structs here directly.
88 // https://github.com/rust-lang/rust/pull/67774
89 macro_rules! cfg_has_statx {
90 ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
92 if #[cfg(all(target_os = "linux", target_env = "gnu"))] {
99 ($($block_inner:tt)*) => {
100 #[cfg(all(target_os = "linux", target_env = "gnu"))]
109 pub struct FileAttr {
111 statx_extra_fields: Option<StatxExtraFields>,
115 struct StatxExtraFields {
116 // This is needed to check if btime is supported by the filesystem.
118 stx_btime: libc::statx_timestamp,
119 // With statx, we can overcome 32-bit `time_t` too.
120 #[cfg(target_pointer_width = "32")]
121 stx_atime: libc::statx_timestamp,
122 #[cfg(target_pointer_width = "32")]
123 stx_ctime: libc::statx_timestamp,
124 #[cfg(target_pointer_width = "32")]
125 stx_mtime: libc::statx_timestamp,
129 // We prefer `statx` on Linux if available, which contains file creation time,
130 // as well as 64-bit timestamps of all kinds.
131 // Default `stat64` contains no creation time and may have 32-bit `time_t`.
137 ) -> Option<io::Result<FileAttr>> {
138 use crate::sync::atomic::{AtomicU8, Ordering};
140 // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
141 // We store the availability in global to avoid unnecessary syscalls.
145 static STATX_STATE: AtomicU8 = AtomicU8::new(0);
149 pathname: *const c_char,
152 statxbuf: *mut libc::statx
156 match STATX_STATE.load(Ordering::Relaxed) {
158 // It is a trick to call `statx` with null pointers to check if the syscall
159 // is available. According to the manual, it is expected to fail with EFAULT.
160 // We do this mainly for performance, since it is nearly hundreds times
161 // faster than a normal successful call.
162 let err = cvt(statx(0, ptr::null(), 0, libc::STATX_ALL, ptr::null_mut()))
164 .and_then(|e| e.raw_os_error());
165 // We don't check `err == Some(libc::ENOSYS)` because the syscall may be limited
166 // and returns `EPERM`. Listing all possible errors seems not a good idea.
167 // See: https://github.com/rust-lang/rust/issues/65662
168 if err != Some(libc::EFAULT) {
169 STATX_STATE.store(1, Ordering::Relaxed);
172 STATX_STATE.store(2, Ordering::Relaxed);
178 let mut buf: libc::statx = mem::zeroed();
179 if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
180 return Some(Err(err));
183 // We cannot fill `stat64` exhaustively because of private padding fields.
184 let mut stat: stat64 = mem::zeroed();
185 // `c_ulong` on gnu-mips, `dev_t` otherwise
186 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
187 stat.st_ino = buf.stx_ino as libc::ino64_t;
188 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
189 stat.st_mode = buf.stx_mode as libc::mode_t;
190 stat.st_uid = buf.stx_uid as libc::uid_t;
191 stat.st_gid = buf.stx_gid as libc::gid_t;
192 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
193 stat.st_size = buf.stx_size as off64_t;
194 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
195 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
196 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
197 // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
198 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
199 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
200 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
201 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
202 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
204 let extra = StatxExtraFields {
205 stx_mask: buf.stx_mask,
206 stx_btime: buf.stx_btime,
207 // Store full times to avoid 32-bit `time_t` truncation.
208 #[cfg(target_pointer_width = "32")]
209 stx_atime: buf.stx_atime,
210 #[cfg(target_pointer_width = "32")]
211 stx_ctime: buf.stx_ctime,
212 #[cfg(target_pointer_width = "32")]
213 stx_mtime: buf.stx_mtime,
216 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
221 pub struct FileAttr {
226 // all DirEntry's will have a reference to this struct
227 struct InnerReadDir {
233 inner: Arc<InnerReadDir>,
235 target_os = "android",
237 target_os = "solaris",
238 target_os = "illumos",
239 target_os = "fuchsia",
245 struct Dir(*mut libc::DIR);
247 unsafe impl Send for Dir {}
248 unsafe impl Sync for Dir {}
251 target_os = "android",
253 target_os = "solaris",
254 target_os = "illumos",
255 target_os = "fuchsia",
258 pub struct DirEntry {
259 dir: Arc<InnerReadDir>,
261 // We need to store an owned copy of the entry name on platforms that use
262 // readdir() (not readdir_r()), because a) struct dirent may use a flexible
263 // array to store the name, b) it lives only until the next readdir() call.
264 name: crate::ffi::CString,
267 // Define a minimal subset of fields we need from `dirent64`, especially since
268 // we're not using the immediate `d_name` on these targets. Keeping this as an
269 // `entry` field in `DirEntry` helps reduce the `cfg` boilerplate elsewhere.
271 target_os = "android",
273 target_os = "solaris",
274 target_os = "illumos",
275 target_os = "fuchsia",
278 struct dirent64_min {
280 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
285 target_os = "android",
287 target_os = "solaris",
288 target_os = "illumos",
289 target_os = "fuchsia",
292 pub struct DirEntry {
293 dir: Arc<InnerReadDir>,
294 // The full entry includes a fixed-length `d_name`.
298 #[derive(Clone, Debug)]
299 pub struct OpenOptions {
312 #[derive(Clone, PartialEq, Eq, Debug)]
313 pub struct FilePermissions {
317 #[derive(Copy, Clone, Debug, Default)]
318 pub struct FileTimes {
319 accessed: Option<SystemTime>,
320 modified: Option<SystemTime>,
323 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
324 pub struct FileType {
329 pub struct DirBuilder {
335 fn from_stat64(stat: stat64) -> Self {
336 Self { stat, statx_extra_fields: None }
339 #[cfg(target_pointer_width = "32")]
340 pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
341 if let Some(ext) = &self.statx_extra_fields {
342 if (ext.stx_mask & libc::STATX_MTIME) != 0 {
343 return Some(&ext.stx_mtime);
349 #[cfg(target_pointer_width = "32")]
350 pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
351 if let Some(ext) = &self.statx_extra_fields {
352 if (ext.stx_mask & libc::STATX_ATIME) != 0 {
353 return Some(&ext.stx_atime);
359 #[cfg(target_pointer_width = "32")]
360 pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
361 if let Some(ext) = &self.statx_extra_fields {
362 if (ext.stx_mask & libc::STATX_CTIME) != 0 {
363 return Some(&ext.stx_ctime);
371 fn from_stat64(stat: stat64) -> Self {
378 pub fn size(&self) -> u64 {
379 self.stat.st_size as u64
381 pub fn perm(&self) -> FilePermissions {
382 FilePermissions { mode: (self.stat.st_mode as mode_t) }
385 pub fn file_type(&self) -> FileType {
386 FileType { mode: self.stat.st_mode as mode_t }
390 #[cfg(target_os = "netbsd")]
392 pub fn modified(&self) -> io::Result<SystemTime> {
393 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64))
396 pub fn accessed(&self) -> io::Result<SystemTime> {
397 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64))
400 pub fn created(&self) -> io::Result<SystemTime> {
401 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64))
405 #[cfg(not(target_os = "netbsd"))]
407 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
408 pub fn modified(&self) -> io::Result<SystemTime> {
409 #[cfg(target_pointer_width = "32")]
411 if let Some(mtime) = self.stx_mtime() {
412 return Ok(SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64));
416 Ok(SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64))
419 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
420 pub fn modified(&self) -> io::Result<SystemTime> {
421 Ok(SystemTime::new(self.stat.st_mtime as i64, 0))
424 #[cfg(target_os = "horizon")]
425 pub fn modified(&self) -> io::Result<SystemTime> {
426 Ok(SystemTime::from(self.stat.st_mtim))
429 #[cfg(not(any(target_os = "vxworks", target_os = "espidf", target_os = "horizon")))]
430 pub fn accessed(&self) -> io::Result<SystemTime> {
431 #[cfg(target_pointer_width = "32")]
433 if let Some(atime) = self.stx_atime() {
434 return Ok(SystemTime::new(atime.tv_sec, atime.tv_nsec as i64));
438 Ok(SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64))
441 #[cfg(any(target_os = "vxworks", target_os = "espidf"))]
442 pub fn accessed(&self) -> io::Result<SystemTime> {
443 Ok(SystemTime::new(self.stat.st_atime as i64, 0))
446 #[cfg(target_os = "horizon")]
447 pub fn accessed(&self) -> io::Result<SystemTime> {
448 Ok(SystemTime::from(self.stat.st_atim))
452 target_os = "freebsd",
453 target_os = "openbsd",
456 target_os = "watchos",
458 pub fn created(&self) -> io::Result<SystemTime> {
459 Ok(SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64))
463 target_os = "freebsd",
464 target_os = "openbsd",
467 target_os = "watchos",
469 pub fn created(&self) -> io::Result<SystemTime> {
471 if let Some(ext) = &self.statx_extra_fields {
472 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
473 Ok(SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64))
475 Err(io::const_io_error!(
476 io::ErrorKind::Uncategorized,
477 "creation time is not available for the filesystem",
483 Err(io::const_io_error!(
484 io::ErrorKind::Unsupported,
485 "creation time is not available on this platform \
491 impl AsInner<stat64> for FileAttr {
492 fn as_inner(&self) -> &stat64 {
497 impl FilePermissions {
498 pub fn readonly(&self) -> bool {
499 // check if any class (owner, group, others) has write permission
500 self.mode & 0o222 == 0
503 pub fn set_readonly(&mut self, readonly: bool) {
505 // remove write permission for all classes; equivalent to `chmod a-w <file>`
508 // add write permission for all classes; equivalent to `chmod a+w <file>`
512 pub fn mode(&self) -> u32 {
518 pub fn set_accessed(&mut self, t: SystemTime) {
519 self.accessed = Some(t);
522 pub fn set_modified(&mut self, t: SystemTime) {
523 self.modified = Some(t);
528 pub fn is_dir(&self) -> bool {
529 self.is(libc::S_IFDIR)
531 pub fn is_file(&self) -> bool {
532 self.is(libc::S_IFREG)
534 pub fn is_symlink(&self) -> bool {
535 self.is(libc::S_IFLNK)
538 pub fn is(&self, mode: mode_t) -> bool {
539 self.mode & libc::S_IFMT == mode
543 impl FromInner<u32> for FilePermissions {
544 fn from_inner(mode: u32) -> FilePermissions {
545 FilePermissions { mode: mode as mode_t }
549 impl fmt::Debug for ReadDir {
550 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
551 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
552 // Thus the result will be e g 'ReadDir("/home")'
553 fmt::Debug::fmt(&*self.inner.root, f)
557 impl Iterator for ReadDir {
558 type Item = io::Result<DirEntry>;
561 target_os = "android",
563 target_os = "solaris",
564 target_os = "fuchsia",
566 target_os = "illumos"
568 fn next(&mut self) -> Option<io::Result<DirEntry>> {
571 // As of POSIX.1-2017, readdir() is not required to be thread safe; only
572 // readdir_r() is. However, readdir_r() cannot correctly handle platforms
573 // with unlimited or variable NAME_MAX. Many modern platforms guarantee
574 // thread safety for readdir() as long an individual DIR* is not accessed
575 // concurrently, which is sufficient for Rust.
576 super::os::set_errno(0);
577 let entry_ptr = readdir64(self.inner.dirp.0);
578 if entry_ptr.is_null() {
579 // null can mean either the end is reached or an error occurred.
580 // So we had to clear errno beforehand to check for an error now.
581 return match super::os::errno() {
583 e => Some(Err(Error::from_raw_os_error(e))),
587 // Only d_reclen bytes of *entry_ptr are valid, so we can't just copy the
588 // whole thing (#93384). Instead, copy everything except the name.
589 let mut copy: dirent64 = mem::zeroed();
590 // Can't dereference entry_ptr, so use the local entry to get
591 // offsetof(struct dirent, d_name)
592 let copy_bytes = &mut copy as *mut _ as *mut u8;
593 let copy_name = &mut copy.d_name as *mut _ as *mut u8;
594 let name_offset = copy_name.offset_from(copy_bytes) as usize;
595 let entry_bytes = entry_ptr as *const u8;
596 let entry_name = entry_bytes.add(name_offset);
597 ptr::copy_nonoverlapping(entry_bytes, copy_bytes, name_offset);
599 let entry = dirent64_min {
600 d_ino: copy.d_ino as u64,
601 #[cfg(not(any(target_os = "solaris", target_os = "illumos")))]
602 d_type: copy.d_type as u8,
607 // d_name is guaranteed to be null-terminated.
608 name: CStr::from_ptr(entry_name as *const _).to_owned(),
609 dir: Arc::clone(&self.inner),
611 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
612 return Some(Ok(ret));
619 target_os = "android",
621 target_os = "solaris",
622 target_os = "fuchsia",
624 target_os = "illumos"
626 fn next(&mut self) -> Option<io::Result<DirEntry>> {
627 if self.end_of_stream {
632 let mut ret = DirEntry { entry: mem::zeroed(), dir: Arc::clone(&self.inner) };
633 let mut entry_ptr = ptr::null_mut();
635 let err = readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr);
637 if entry_ptr.is_null() {
638 // We encountered an error (which will be returned in this iteration), but
639 // we also reached the end of the directory stream. The `end_of_stream`
640 // flag is enabled to make sure that we return `None` in the next iteration
641 // (instead of looping forever)
642 self.end_of_stream = true;
644 return Some(Err(Error::from_raw_os_error(err)));
646 if entry_ptr.is_null() {
649 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
650 return Some(Ok(ret));
659 let r = unsafe { libc::closedir(self.0) };
661 r == 0 || crate::io::Error::last_os_error().kind() == crate::io::ErrorKind::Interrupted,
662 "unexpected error during closedir: {:?}",
663 crate::io::Error::last_os_error()
669 pub fn path(&self) -> PathBuf {
670 self.dir.root.join(self.file_name_os_str())
673 pub fn file_name(&self) -> OsString {
674 self.file_name_os_str().to_os_string()
677 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
678 pub fn metadata(&self) -> io::Result<FileAttr> {
679 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
680 let name = self.name_cstr().as_ptr();
683 if let Some(ret) = unsafe { try_statx(
686 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
693 let mut stat: stat64 = unsafe { mem::zeroed() };
694 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
695 Ok(FileAttr::from_stat64(stat))
698 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
699 pub fn metadata(&self) -> io::Result<FileAttr> {
704 target_os = "solaris",
705 target_os = "illumos",
707 target_os = "vxworks"
709 pub fn file_type(&self) -> io::Result<FileType> {
710 self.metadata().map(|m| m.file_type())
714 target_os = "solaris",
715 target_os = "illumos",
717 target_os = "vxworks"
719 pub fn file_type(&self) -> io::Result<FileType> {
720 match self.entry.d_type {
721 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
722 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
723 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
724 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
725 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
726 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
727 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
728 _ => self.metadata().map(|m| m.file_type()),
735 target_os = "watchos",
737 target_os = "emscripten",
738 target_os = "android",
739 target_os = "solaris",
740 target_os = "illumos",
743 target_os = "fuchsia",
745 target_os = "vxworks",
746 target_os = "espidf",
747 target_os = "horizon"
749 pub fn ino(&self) -> u64 {
750 self.entry.d_ino as u64
754 target_os = "freebsd",
755 target_os = "openbsd",
756 target_os = "netbsd",
757 target_os = "dragonfly"
759 pub fn ino(&self) -> u64 {
760 self.entry.d_fileno as u64
766 target_os = "watchos",
767 target_os = "netbsd",
768 target_os = "openbsd",
769 target_os = "freebsd",
770 target_os = "dragonfly"
772 fn name_bytes(&self) -> &[u8] {
775 slice::from_raw_parts(
776 self.entry.d_name.as_ptr() as *const u8,
777 self.entry.d_namlen as usize,
784 target_os = "watchos",
785 target_os = "netbsd",
786 target_os = "openbsd",
787 target_os = "freebsd",
788 target_os = "dragonfly"
790 fn name_bytes(&self) -> &[u8] {
791 self.name_cstr().to_bytes()
795 target_os = "android",
797 target_os = "solaris",
798 target_os = "illumos",
799 target_os = "fuchsia",
802 #[cfg_attr(miri, allow(unused))]
803 fn name_cstr(&self) -> &CStr {
804 unsafe { CStr::from_ptr(self.entry.d_name.as_ptr()) }
807 target_os = "android",
809 target_os = "solaris",
810 target_os = "illumos",
811 target_os = "fuchsia",
814 #[cfg_attr(miri, allow(unused))]
815 fn name_cstr(&self) -> &CStr {
819 pub fn file_name_os_str(&self) -> &OsStr {
820 OsStr::from_bytes(self.name_bytes())
825 pub fn new() -> OpenOptions {
840 pub fn read(&mut self, read: bool) {
843 pub fn write(&mut self, write: bool) {
846 pub fn append(&mut self, append: bool) {
847 self.append = append;
849 pub fn truncate(&mut self, truncate: bool) {
850 self.truncate = truncate;
852 pub fn create(&mut self, create: bool) {
853 self.create = create;
855 pub fn create_new(&mut self, create_new: bool) {
856 self.create_new = create_new;
859 pub fn custom_flags(&mut self, flags: i32) {
860 self.custom_flags = flags;
862 pub fn mode(&mut self, mode: u32) {
863 self.mode = mode as mode_t;
866 fn get_access_mode(&self) -> io::Result<c_int> {
867 match (self.read, self.write, self.append) {
868 (true, false, false) => Ok(libc::O_RDONLY),
869 (false, true, false) => Ok(libc::O_WRONLY),
870 (true, true, false) => Ok(libc::O_RDWR),
871 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
872 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
873 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
877 fn get_creation_mode(&self) -> io::Result<c_int> {
878 match (self.write, self.append) {
881 if self.truncate || self.create || self.create_new {
882 return Err(Error::from_raw_os_error(libc::EINVAL));
886 if self.truncate && !self.create_new {
887 return Err(Error::from_raw_os_error(libc::EINVAL));
892 Ok(match (self.create, self.truncate, self.create_new) {
893 (false, false, false) => 0,
894 (true, false, false) => libc::O_CREAT,
895 (false, true, false) => libc::O_TRUNC,
896 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
897 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
903 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
904 run_path_with_cstr(path, |path| File::open_c(path, opts))
907 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
908 let flags = libc::O_CLOEXEC
909 | opts.get_access_mode()?
910 | opts.get_creation_mode()?
911 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
912 // The third argument of `open64` is documented to have type `mode_t`. On
913 // some platforms (like macOS, where `open64` is actually `open`), `mode_t` is `u16`.
914 // However, since this is a variadic function, C integer promotion rules mean that on
915 // the ABI level, this still gets passed as `c_int` (aka `u32` on Unix platforms).
916 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
917 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
920 pub fn file_attr(&self) -> io::Result<FileAttr> {
921 let fd = self.as_raw_fd();
924 if let Some(ret) = unsafe { try_statx(
926 b"\0" as *const _ as *const c_char,
927 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
934 let mut stat: stat64 = unsafe { mem::zeroed() };
935 cvt(unsafe { fstat64(fd, &mut stat) })?;
936 Ok(FileAttr::from_stat64(stat))
939 pub fn fsync(&self) -> io::Result<()> {
940 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
943 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
944 unsafe fn os_fsync(fd: c_int) -> c_int {
945 libc::fcntl(fd, libc::F_FULLFSYNC)
947 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "watchos")))]
948 unsafe fn os_fsync(fd: c_int) -> c_int {
953 pub fn datasync(&self) -> io::Result<()> {
954 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
957 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
958 unsafe fn os_datasync(fd: c_int) -> c_int {
959 libc::fcntl(fd, libc::F_FULLFSYNC)
962 target_os = "freebsd",
964 target_os = "android",
965 target_os = "netbsd",
966 target_os = "openbsd"
968 unsafe fn os_datasync(fd: c_int) -> c_int {
972 target_os = "android",
973 target_os = "freebsd",
977 target_os = "netbsd",
978 target_os = "openbsd",
979 target_os = "watchos",
981 unsafe fn os_datasync(fd: c_int) -> c_int {
986 pub fn truncate(&self, size: u64) -> io::Result<()> {
988 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
989 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
992 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
996 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
997 self.0.read_vectored(bufs)
1001 pub fn is_read_vectored(&self) -> bool {
1002 self.0.is_read_vectored()
1005 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1006 self.0.read_at(buf, offset)
1009 pub fn read_buf(&self, cursor: BorrowedCursor<'_>) -> io::Result<()> {
1010 self.0.read_buf(cursor)
1013 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1017 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1018 self.0.write_vectored(bufs)
1022 pub fn is_write_vectored(&self) -> bool {
1023 self.0.is_write_vectored()
1026 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1027 self.0.write_at(buf, offset)
1030 pub fn flush(&self) -> io::Result<()> {
1034 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1035 let (whence, pos) = match pos {
1036 // Casting to `i64` is fine, too large values will end up as
1037 // negative which will cause an error in `lseek64`.
1038 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1039 SeekFrom::End(off) => (libc::SEEK_END, off),
1040 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1042 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1046 pub fn duplicate(&self) -> io::Result<File> {
1047 self.0.duplicate().map(File)
1050 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1051 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1055 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1056 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))]
1057 let to_timespec = |time: Option<SystemTime>| {
1059 Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1060 Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_io_error!(io::ErrorKind::InvalidInput, "timestamp is too large to set as a file time")),
1061 Some(_) => Err(io::const_io_error!(io::ErrorKind::InvalidInput, "timestamp is too small to set as a file time")),
1062 None => Ok(libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT as _ }),
1065 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon")))]
1066 let times = [to_timespec(times.accessed)?, to_timespec(times.modified)?];
1068 if #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon"))] {
1069 // Redox doesn't appear to support `UTIME_OMIT`.
1070 // ESP-IDF and HorizonOS do not support `futimens` at all and the behavior for those OS is therefore
1071 // the same as for Redox.
1073 Err(io::const_io_error!(
1074 io::ErrorKind::Unsupported,
1075 "setting file times not supported",
1077 } else if #[cfg(any(target_os = "android", target_os = "macos"))] {
1078 // futimens requires macOS 10.13, and Android API level 19
1080 weak!(fn futimens(c_int, *const libc::timespec) -> c_int);
1081 match futimens.get() {
1082 Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1083 #[cfg(target_os = "macos")]
1085 fn ts_to_tv(ts: &libc::timespec) -> libc::timeval {
1088 tv_usec: (ts.tv_nsec / 1000) as _
1091 let timevals = [ts_to_tv(×[0]), ts_to_tv(×[1])];
1092 libc::futimes(self.as_raw_fd(), timevals.as_ptr())
1094 // futimes requires even newer Android.
1095 #[cfg(target_os = "android")]
1096 None => return Err(io::const_io_error!(
1097 io::ErrorKind::Unsupported,
1098 "setting file times requires Android API level >= 19",
1104 cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1112 pub fn new() -> DirBuilder {
1113 DirBuilder { mode: 0o777 }
1116 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1117 run_path_with_cstr(p, |p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1120 pub fn set_mode(&mut self, mode: u32) {
1121 self.mode = mode as mode_t;
1125 impl AsInner<FileDesc> for File {
1126 fn as_inner(&self) -> &FileDesc {
1131 impl AsInnerMut<FileDesc> for File {
1132 fn as_inner_mut(&mut self) -> &mut FileDesc {
1137 impl IntoInner<FileDesc> for File {
1138 fn into_inner(self) -> FileDesc {
1143 impl FromInner<FileDesc> for File {
1144 fn from_inner(file_desc: FileDesc) -> Self {
1149 impl AsFd for File {
1150 fn as_fd(&self) -> BorrowedFd<'_> {
1155 impl AsRawFd for File {
1156 fn as_raw_fd(&self) -> RawFd {
1161 impl IntoRawFd for File {
1162 fn into_raw_fd(self) -> RawFd {
1163 self.0.into_raw_fd()
1167 impl FromRawFd for File {
1168 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1169 Self(FromRawFd::from_raw_fd(raw_fd))
1173 impl fmt::Debug for File {
1174 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1176 target_os = "linux",
1177 target_os = "netbsd",
1178 target_os = "illumos",
1179 target_os = "solaris"
1181 fn get_path(fd: c_int) -> Option<PathBuf> {
1182 let mut p = PathBuf::from("/proc/self/fd");
1183 p.push(&fd.to_string());
1187 #[cfg(target_os = "macos")]
1188 fn get_path(fd: c_int) -> Option<PathBuf> {
1189 // FIXME: The use of PATH_MAX is generally not encouraged, but it
1190 // is inevitable in this case because macOS defines `fcntl` with
1191 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
1192 // alternatives. If a better method is invented, it should be used
1194 let mut buf = vec![0; libc::PATH_MAX as usize];
1195 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
1199 let l = buf.iter().position(|&c| c == 0).unwrap();
1200 buf.truncate(l as usize);
1201 buf.shrink_to_fit();
1202 Some(PathBuf::from(OsString::from_vec(buf)))
1205 #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))]
1206 fn get_path(fd: c_int) -> Option<PathBuf> {
1207 let info = Box::<libc::kinfo_file>::new_zeroed();
1208 let mut info = unsafe { info.assume_init() };
1209 info.kf_structsize = mem::size_of::<libc::kinfo_file>() as libc::c_int;
1210 let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
1214 let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
1215 Some(PathBuf::from(OsString::from_vec(buf)))
1218 #[cfg(target_os = "vxworks")]
1219 fn get_path(fd: c_int) -> Option<PathBuf> {
1220 let mut buf = vec![0; libc::PATH_MAX as usize];
1221 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_ptr()) };
1225 let l = buf.iter().position(|&c| c == 0).unwrap();
1226 buf.truncate(l as usize);
1227 Some(PathBuf::from(OsString::from_vec(buf)))
1231 target_os = "linux",
1232 target_os = "macos",
1233 target_os = "vxworks",
1234 all(target_os = "freebsd", target_arch = "x86_64"),
1235 target_os = "netbsd",
1236 target_os = "illumos",
1237 target_os = "solaris"
1239 fn get_path(_fd: c_int) -> Option<PathBuf> {
1240 // FIXME(#24570): implement this for other Unix platforms
1245 target_os = "linux",
1246 target_os = "macos",
1247 target_os = "freebsd",
1248 target_os = "netbsd",
1249 target_os = "openbsd",
1250 target_os = "vxworks"
1252 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
1253 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
1257 match mode & libc::O_ACCMODE {
1258 libc::O_RDONLY => Some((true, false)),
1259 libc::O_RDWR => Some((true, true)),
1260 libc::O_WRONLY => Some((false, true)),
1266 target_os = "linux",
1267 target_os = "macos",
1268 target_os = "freebsd",
1269 target_os = "netbsd",
1270 target_os = "openbsd",
1271 target_os = "vxworks"
1273 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
1274 // FIXME(#24570): implement this for other Unix platforms
1278 let fd = self.as_raw_fd();
1279 let mut b = f.debug_struct("File");
1281 if let Some(path) = get_path(fd) {
1282 b.field("path", &path);
1284 if let Some((read, write)) = get_mode(fd) {
1285 b.field("read", &read).field("write", &write);
1291 pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1292 let ptr = run_path_with_cstr(path, |p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1294 Err(Error::last_os_error())
1296 let root = path.to_path_buf();
1297 let inner = InnerReadDir { dirp: Dir(ptr), root };
1299 inner: Arc::new(inner),
1301 target_os = "android",
1302 target_os = "linux",
1303 target_os = "solaris",
1304 target_os = "illumos",
1305 target_os = "fuchsia",
1306 target_os = "redox",
1308 end_of_stream: false,
1313 pub fn unlink(p: &Path) -> io::Result<()> {
1314 run_path_with_cstr(p, |p| cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ()))
1317 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
1318 run_path_with_cstr(old, |old| {
1319 run_path_with_cstr(new, |new| {
1320 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1325 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
1326 run_path_with_cstr(p, |p| cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ()))
1329 pub fn rmdir(p: &Path) -> io::Result<()> {
1330 run_path_with_cstr(p, |p| cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ()))
1333 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
1334 run_path_with_cstr(p, |c_path| {
1335 let p = c_path.as_ptr();
1337 let mut buf = Vec::with_capacity(256);
1341 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })?
1345 buf.set_len(buf_read);
1348 if buf_read != buf.capacity() {
1349 buf.shrink_to_fit();
1351 return Ok(PathBuf::from(OsString::from_vec(buf)));
1354 // Trigger the internal buffer resizing logic of `Vec` by requiring
1355 // more space than the current capacity. The length is guaranteed to be
1356 // the same as the capacity due to the if statement above.
1362 pub fn symlink(original: &Path, link: &Path) -> io::Result<()> {
1363 run_path_with_cstr(original, |original| {
1364 run_path_with_cstr(link, |link| {
1365 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
1370 pub fn link(original: &Path, link: &Path) -> io::Result<()> {
1371 run_path_with_cstr(original, |original| {
1372 run_path_with_cstr(link, |link| {
1374 if #[cfg(any(target_os = "vxworks", target_os = "redox", target_os = "android", target_os = "espidf", target_os = "horizon"))] {
1375 // VxWorks, Redox and ESP-IDF lack `linkat`, so use `link` instead. POSIX leaves
1376 // it implementation-defined whether `link` follows symlinks, so rely on the
1377 // `symlink_hard_link` test in library/std/src/fs/tests.rs to check the behavior.
1378 // Android has `linkat` on newer versions, but we happen to know `link`
1379 // always has the correct behavior, so it's here as well.
1380 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1381 } else if #[cfg(target_os = "macos")] {
1382 // On MacOS, older versions (<=10.9) lack support for linkat while newer
1383 // versions have it. We want to use linkat if it is available, so we use weak!
1384 // to check. `linkat` is preferable to `link` because it gives us a flag to
1385 // specify how symlinks should be handled. We pass 0 as the flags argument,
1386 // meaning it shouldn't follow symlinks.
1387 weak!(fn linkat(c_int, *const c_char, c_int, *const c_char, c_int) -> c_int);
1389 if let Some(f) = linkat.get() {
1390 cvt(unsafe { f(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1392 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
1395 // Where we can, use `linkat` instead of `link`; see the comment above
1396 // this one for details on why.
1397 cvt(unsafe { libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0) })?;
1405 pub fn stat(p: &Path) -> io::Result<FileAttr> {
1406 run_path_with_cstr(p, |p| {
1408 if let Some(ret) = unsafe { try_statx(
1411 libc::AT_STATX_SYNC_AS_STAT,
1418 let mut stat: stat64 = unsafe { mem::zeroed() };
1419 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
1420 Ok(FileAttr::from_stat64(stat))
1424 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1425 run_path_with_cstr(p, |p| {
1427 if let Some(ret) = unsafe { try_statx(
1430 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1437 let mut stat: stat64 = unsafe { mem::zeroed() };
1438 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
1439 Ok(FileAttr::from_stat64(stat))
1443 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1444 let r = run_path_with_cstr(p, |path| unsafe {
1445 Ok(libc::realpath(path.as_ptr(), ptr::null_mut()))
1448 return Err(io::Error::last_os_error());
1450 Ok(PathBuf::from(OsString::from_vec(unsafe {
1451 let buf = CStr::from_ptr(r).to_bytes().to_vec();
1452 libc::free(r as *mut _);
1457 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1458 use crate::fs::File;
1459 use crate::sys_common::fs::NOT_FILE_ERROR;
1461 let reader = File::open(from)?;
1462 let metadata = reader.metadata()?;
1463 if !metadata.is_file() {
1464 return Err(NOT_FILE_ERROR);
1466 Ok((reader, metadata))
1469 #[cfg(target_os = "espidf")]
1470 fn open_to_and_set_permissions(
1472 reader_metadata: crate::fs::Metadata,
1473 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1474 use crate::fs::OpenOptions;
1475 let writer = OpenOptions::new().open(to)?;
1476 let writer_metadata = writer.metadata()?;
1477 Ok((writer, writer_metadata))
1480 #[cfg(not(target_os = "espidf"))]
1481 fn open_to_and_set_permissions(
1483 reader_metadata: crate::fs::Metadata,
1484 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1485 use crate::fs::OpenOptions;
1486 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1488 let perm = reader_metadata.permissions();
1489 let writer = OpenOptions::new()
1490 // create the file with the correct mode right away
1496 let writer_metadata = writer.metadata()?;
1497 if writer_metadata.is_file() {
1498 // Set the correct file permissions, in case the file already existed.
1499 // Don't set the permissions on already existing non-files like
1500 // pipes/FIFOs or device nodes.
1501 writer.set_permissions(perm)?;
1503 Ok((writer, writer_metadata))
1507 target_os = "linux",
1508 target_os = "android",
1509 target_os = "macos",
1511 target_os = "watchos",
1513 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1514 let (mut reader, reader_metadata) = open_from(from)?;
1515 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1517 io::copy(&mut reader, &mut writer)
1520 #[cfg(any(target_os = "linux", target_os = "android"))]
1521 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1522 let (mut reader, reader_metadata) = open_from(from)?;
1523 let max_len = u64::MAX;
1524 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1526 use super::kernel_copy::{copy_regular_files, CopyResult};
1528 match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) {
1529 CopyResult::Ended(bytes) => Ok(bytes),
1530 CopyResult::Error(e, _) => Err(e),
1531 CopyResult::Fallback(written) => match io::copy::generic_copy(&mut reader, &mut writer) {
1532 Ok(bytes) => Ok(bytes + written),
1538 #[cfg(any(target_os = "macos", target_os = "ios", target_os = "watchos"))]
1539 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1540 use crate::sync::atomic::{AtomicBool, Ordering};
1542 const COPYFILE_ACL: u32 = 1 << 0;
1543 const COPYFILE_STAT: u32 = 1 << 1;
1544 const COPYFILE_XATTR: u32 = 1 << 2;
1545 const COPYFILE_DATA: u32 = 1 << 3;
1547 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1548 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1549 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1551 const COPYFILE_STATE_COPIED: u32 = 8;
1553 #[allow(non_camel_case_types)]
1554 type copyfile_state_t = *mut libc::c_void;
1555 #[allow(non_camel_case_types)]
1556 type copyfile_flags_t = u32;
1562 state: copyfile_state_t,
1563 flags: copyfile_flags_t,
1565 fn copyfile_state_alloc() -> copyfile_state_t;
1566 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1567 fn copyfile_state_get(
1568 state: copyfile_state_t,
1570 dst: *mut libc::c_void,
1574 struct FreeOnDrop(copyfile_state_t);
1575 impl Drop for FreeOnDrop {
1576 fn drop(&mut self) {
1577 // The code below ensures that `FreeOnDrop` is never a null pointer
1579 // `copyfile_state_free` returns -1 if the `to` or `from` files
1580 // cannot be closed. However, this is not considered this an
1582 copyfile_state_free(self.0);
1587 // MacOS prior to 10.12 don't support `fclonefileat`
1588 // We store the availability in a global to avoid unnecessary syscalls
1589 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1593 dst_dirfd: libc::c_int,
1599 let (reader, reader_metadata) = open_from(from)?;
1601 // Opportunistically attempt to create a copy-on-write clone of `from`
1602 // using `fclonefileat`.
1603 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1604 let clonefile_result = run_path_with_cstr(to, |to| {
1605 cvt(unsafe { fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
1607 match clonefile_result {
1608 Ok(_) => return Ok(reader_metadata.len()),
1609 Err(err) => match err.raw_os_error() {
1610 // `fclonefileat` will fail on non-APFS volumes, if the
1611 // destination already exists, or if the source and destination
1612 // are on different devices. In all these cases `fcopyfile`
1614 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1615 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1616 _ => return Err(err),
1621 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1622 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1624 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1625 // always safe to call `copyfile_state_free`
1626 let state = unsafe {
1627 let state = copyfile_state_alloc();
1628 if state.is_null() {
1629 return Err(crate::io::Error::last_os_error());
1634 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { COPYFILE_DATA };
1636 cvt(unsafe { fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
1638 let mut bytes_copied: libc::off_t = 0;
1642 COPYFILE_STATE_COPIED,
1643 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1646 Ok(bytes_copied as u64)
1649 pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1650 run_path_with_cstr(path, |path| {
1651 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
1656 pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
1657 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
1661 pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
1662 run_path_with_cstr(path, |path| {
1663 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
1668 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
1669 pub fn chroot(dir: &Path) -> io::Result<()> {
1670 run_path_with_cstr(dir, |dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
1673 pub use remove_dir_impl::remove_dir_all;
1675 // Fallback for REDOX, ESP-ID, Horizon, and Miri
1676 #[cfg(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri))]
1677 mod remove_dir_impl {
1678 pub use crate::sys_common::fs::remove_dir_all;
1681 // Modern implementation using openat(), unlinkat() and fdopendir()
1682 #[cfg(not(any(target_os = "redox", target_os = "espidf", target_os = "horizon", miri)))]
1683 mod remove_dir_impl {
1684 use super::{lstat, Dir, DirEntry, InnerReadDir, ReadDir};
1685 use crate::ffi::CStr;
1687 use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
1688 use crate::os::unix::prelude::{OwnedFd, RawFd};
1689 use crate::path::{Path, PathBuf};
1690 use crate::sync::Arc;
1691 use crate::sys::common::small_c_string::run_path_with_cstr;
1692 use crate::sys::{cvt, cvt_r};
1694 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64")),))]
1695 use libc::{fdopendir, openat, unlinkat};
1696 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1697 use macos_weak::{fdopendir, openat, unlinkat};
1699 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1701 use crate::sys::weak::weak;
1702 use libc::{c_char, c_int, DIR};
1704 fn get_openat_fn() -> Option<unsafe extern "C" fn(c_int, *const c_char, c_int) -> c_int> {
1705 weak!(fn openat(c_int, *const c_char, c_int) -> c_int);
1709 pub fn has_openat() -> bool {
1710 get_openat_fn().is_some()
1713 pub unsafe fn openat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1714 get_openat_fn().map(|openat| openat(dirfd, pathname, flags)).unwrap_or_else(|| {
1715 crate::sys::unix::os::set_errno(libc::ENOSYS);
1720 pub unsafe fn fdopendir(fd: c_int) -> *mut DIR {
1721 #[cfg(all(target_os = "macos", target_arch = "x86"))]
1722 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64$UNIX2003");
1723 #[cfg(all(target_os = "macos", target_arch = "x86_64"))]
1724 weak!(fn fdopendir(c_int) -> *mut DIR, "fdopendir$INODE64");
1725 fdopendir.get().map(|fdopendir| fdopendir(fd)).unwrap_or_else(|| {
1726 crate::sys::unix::os::set_errno(libc::ENOSYS);
1727 crate::ptr::null_mut()
1731 pub unsafe fn unlinkat(dirfd: c_int, pathname: *const c_char, flags: c_int) -> c_int {
1732 weak!(fn unlinkat(c_int, *const c_char, c_int) -> c_int);
1733 unlinkat.get().map(|unlinkat| unlinkat(dirfd, pathname, flags)).unwrap_or_else(|| {
1734 crate::sys::unix::os::set_errno(libc::ENOSYS);
1740 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
1741 let fd = cvt_r(|| unsafe {
1743 parent_fd.unwrap_or(libc::AT_FDCWD),
1745 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
1748 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
1751 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
1752 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
1754 return Err(io::Error::last_os_error());
1756 let dirp = Dir(ptr);
1757 // file descriptor is automatically closed by libc::closedir() now, so give up ownership
1758 let new_parent_fd = dir_fd.into_raw_fd();
1759 // a valid root is not needed because we do not call any functions involving the full path
1760 // of the DirEntrys.
1761 let dummy_root = PathBuf::new();
1764 inner: Arc::new(InnerReadDir { dirp, root: dummy_root }),
1766 target_os = "android",
1767 target_os = "linux",
1768 target_os = "solaris",
1769 target_os = "illumos",
1770 target_os = "fuchsia",
1771 target_os = "redox",
1773 end_of_stream: false,
1780 target_os = "solaris",
1781 target_os = "illumos",
1782 target_os = "haiku",
1783 target_os = "vxworks",
1785 fn is_dir(_ent: &DirEntry) -> Option<bool> {
1790 target_os = "solaris",
1791 target_os = "illumos",
1792 target_os = "haiku",
1793 target_os = "vxworks",
1795 fn is_dir(ent: &DirEntry) -> Option<bool> {
1796 match ent.entry.d_type {
1797 libc::DT_UNKNOWN => None,
1798 libc::DT_DIR => Some(true),
1803 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
1804 // try opening as directory
1805 let fd = match openat_nofollow_dironly(parent_fd, &path) {
1806 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
1807 // not a directory - don't traverse further
1808 // (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
1809 return match parent_fd {
1811 Some(parent_fd) => {
1812 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
1814 // ...unless this was supposed to be the deletion root directory
1821 // open the directory passing ownership of the fd
1822 let (dir, fd) = fdreaddir(fd)?;
1825 let child_name = child.name_cstr();
1826 match is_dir(&child) {
1828 remove_dir_all_recursive(Some(fd), child_name)?;
1831 cvt(unsafe { unlinkat(fd, child_name.as_ptr(), 0) })?;
1834 // POSIX specifies that calling unlink()/unlinkat(..., 0) on a directory can succeed
1835 // if the process has the appropriate privileges. This however can causing orphaned
1836 // directories requiring an fsck e.g. on Solaris and Illumos. So we try recursing
1837 // into it first instead of trying to unlink() it.
1838 remove_dir_all_recursive(Some(fd), child_name)?;
1843 // unlink the directory after removing its contents
1845 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
1850 fn remove_dir_all_modern(p: &Path) -> io::Result<()> {
1851 // We cannot just call remove_dir_all_recursive() here because that would not delete a passed
1852 // symlink. No need to worry about races, because remove_dir_all_recursive() does not recurse
1854 let attr = lstat(p)?;
1855 if attr.file_type().is_symlink() {
1856 crate::fs::remove_file(p)
1858 run_path_with_cstr(p, |p| remove_dir_all_recursive(None, &p))
1862 #[cfg(not(all(target_os = "macos", not(target_arch = "aarch64"))))]
1863 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1864 remove_dir_all_modern(p)
1867 #[cfg(all(target_os = "macos", not(target_arch = "aarch64")))]
1868 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
1869 if macos_weak::has_openat() {
1870 // openat() is available with macOS 10.10+, just like unlinkat() and fdopendir()
1871 remove_dir_all_modern(p)
1873 // fall back to classic implementation
1874 crate::sys_common::fs::remove_dir_all(p)