1 use crate::os::unix::prelude::*;
3 use crate::ffi::{CString, CStr, OsString, OsStr};
5 use crate::io::{self, Error, ErrorKind, SeekFrom, IoSlice, IoSliceMut};
7 use crate::path::{Path, PathBuf};
10 use crate::sys::fd::FileDesc;
11 use crate::sys::time::SystemTime;
12 use crate::sys::{cvt, cvt_r};
13 use crate::sys_common::{AsInner, FromInner};
15 use libc::{c_int, mode_t};
17 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
18 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64};
19 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
21 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
23 #[cfg(target_os = "android")]
24 use libc::{stat as stat64, fstat as fstat64, fstatat as fstatat64, lstat as lstat64, lseek64,
25 dirent as dirent64, open as open64};
26 #[cfg(not(any(target_os = "linux",
27 target_os = "emscripten",
29 target_os = "android")))]
30 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
31 ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
32 #[cfg(not(any(target_os = "linux",
33 target_os = "emscripten",
34 target_os = "solaris",
36 target_os = "fuchsia",
37 target_os = "redox")))]
38 use libc::{readdir_r as readdir64_r};
40 pub use crate::sys_common::fs::remove_dir_all;
42 pub struct File(FileDesc);
44 // FIXME: This should be available on Linux with all `target_arch` and `target_env`.
45 // https://github.com/rust-lang/libc/issues/1545
46 macro_rules! cfg_has_statx {
47 ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
49 if #[cfg(all(target_os = "linux", target_env = "gnu", any(
52 // target_arch = "mips",
53 target_arch = "powerpc",
54 target_arch = "x86_64",
55 // target_arch = "aarch64",
56 target_arch = "powerpc64",
57 // target_arch = "mips64",
58 // target_arch = "s390x",
59 target_arch = "sparc64",
67 ($($block_inner:tt)*) => {
68 #[cfg(all(target_os = "linux", target_env = "gnu", any(
71 // target_arch = "mips",
72 target_arch = "powerpc",
73 target_arch = "x86_64",
74 // target_arch = "aarch64",
75 target_arch = "powerpc64",
76 // target_arch = "mips64",
77 // target_arch = "s390x",
78 target_arch = "sparc64",
90 statx_extra_fields: Option<StatxExtraFields>,
94 struct StatxExtraFields {
95 // This is needed to check if btime is supported by the filesystem.
97 stx_btime: libc::statx_timestamp,
100 // We prefer `statx` on Linux if available, which contains file creation time.
101 // Default `stat64` contains no creation time.
104 path: *const libc::c_char,
107 ) -> Option<io::Result<FileAttr>> {
108 use crate::sync::atomic::{AtomicBool, Ordering};
110 // Linux kernel prior to 4.11 or glibc prior to glibc 2.28 don't support `statx`
111 // We store the availability in a global to avoid unnecessary syscalls
112 static HAS_STATX: AtomicBool = AtomicBool::new(true);
116 pathname: *const libc::c_char,
119 statxbuf: *mut libc::statx
123 if !HAS_STATX.load(Ordering::Relaxed) {
127 let mut buf: libc::statx = mem::zeroed();
128 let ret = cvt(statx(fd, path, flags, mask, &mut buf));
130 Err(err) => match err.raw_os_error() {
131 Some(libc::ENOSYS) => {
132 HAS_STATX.store(false, Ordering::Relaxed);
135 _ => return Some(Err(err)),
138 // We cannot fill `stat64` exhaustively because of private padding fields.
139 let mut stat: stat64 = mem::zeroed();
140 // `c_ulong` on gnu-mips, `dev_t` otherwise
141 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
142 stat.st_ino = buf.stx_ino as libc::ino64_t;
143 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
144 stat.st_mode = buf.stx_mode as libc::mode_t;
145 stat.st_uid = buf.stx_uid as libc::uid_t;
146 stat.st_gid = buf.stx_gid as libc::gid_t;
147 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
148 stat.st_size = buf.stx_size as off64_t;
149 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
150 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
151 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
152 // `i64` on gnu-x86_64-x32, `c_ulong` otherwise.
153 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
154 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
155 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
156 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
157 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
159 let extra = StatxExtraFields {
160 stx_mask: buf.stx_mask,
161 stx_btime: buf.stx_btime,
164 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
171 pub struct FileAttr {
176 // all DirEntry's will have a reference to this struct
177 struct InnerReadDir {
184 inner: Arc<InnerReadDir>,
188 struct Dir(*mut libc::DIR);
190 unsafe impl Send for Dir {}
191 unsafe impl Sync for Dir {}
193 pub struct DirEntry {
196 // We need to store an owned copy of the entry name
197 // on Solaris and Fuchsia because a) it uses a zero-length
198 // array to store the name, b) its lifetime between readdir
199 // calls is not guaranteed.
200 #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))]
204 #[derive(Clone, Debug)]
205 pub struct OpenOptions {
218 #[derive(Clone, PartialEq, Eq, Debug)]
219 pub struct FilePermissions { mode: mode_t }
221 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
222 pub struct FileType { mode: mode_t }
225 pub struct DirBuilder { mode: mode_t }
229 fn from_stat64(stat: stat64) -> Self {
230 Self { stat, statx_extra_fields: None }
235 fn from_stat64(stat: stat64) -> Self {
242 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
243 pub fn perm(&self) -> FilePermissions {
244 FilePermissions { mode: (self.stat.st_mode as mode_t) }
247 pub fn file_type(&self) -> FileType {
248 FileType { mode: self.stat.st_mode as mode_t }
252 #[cfg(target_os = "netbsd")]
254 pub fn modified(&self) -> io::Result<SystemTime> {
255 Ok(SystemTime::from(libc::timespec {
256 tv_sec: self.stat.st_mtime as libc::time_t,
257 tv_nsec: self.stat.st_mtimensec as libc::c_long,
261 pub fn accessed(&self) -> io::Result<SystemTime> {
262 Ok(SystemTime::from(libc::timespec {
263 tv_sec: self.stat.st_atime as libc::time_t,
264 tv_nsec: self.stat.st_atimensec as libc::c_long,
268 pub fn created(&self) -> io::Result<SystemTime> {
269 Ok(SystemTime::from(libc::timespec {
270 tv_sec: self.stat.st_birthtime as libc::time_t,
271 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
276 #[cfg(not(target_os = "netbsd"))]
278 pub fn modified(&self) -> io::Result<SystemTime> {
279 Ok(SystemTime::from(libc::timespec {
280 tv_sec: self.stat.st_mtime as libc::time_t,
281 tv_nsec: self.stat.st_mtime_nsec as _,
285 pub fn accessed(&self) -> io::Result<SystemTime> {
286 Ok(SystemTime::from(libc::timespec {
287 tv_sec: self.stat.st_atime as libc::time_t,
288 tv_nsec: self.stat.st_atime_nsec as _,
292 #[cfg(any(target_os = "freebsd",
293 target_os = "openbsd",
296 pub fn created(&self) -> io::Result<SystemTime> {
297 Ok(SystemTime::from(libc::timespec {
298 tv_sec: self.stat.st_birthtime as libc::time_t,
299 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
303 #[cfg(not(any(target_os = "freebsd",
304 target_os = "openbsd",
306 target_os = "ios")))]
307 pub fn created(&self) -> io::Result<SystemTime> {
309 if let Some(ext) = &self.statx_extra_fields {
310 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
311 Ok(SystemTime::from(libc::timespec {
312 tv_sec: ext.stx_btime.tv_sec as libc::time_t,
313 tv_nsec: ext.stx_btime.tv_nsec as _,
317 io::ErrorKind::Other,
318 "creation time is not available for the filesystem",
324 Err(io::Error::new(io::ErrorKind::Other,
325 "creation time is not available on this platform \
330 impl AsInner<stat64> for FileAttr {
331 fn as_inner(&self) -> &stat64 { &self.stat }
334 impl FilePermissions {
335 pub fn readonly(&self) -> bool {
336 // check if any class (owner, group, others) has write permission
337 self.mode & 0o222 == 0
340 pub fn set_readonly(&mut self, readonly: bool) {
342 // remove write permission for all classes; equivalent to `chmod a-w <file>`
345 // add write permission for all classes; equivalent to `chmod a+w <file>`
349 pub fn mode(&self) -> u32 { self.mode as u32 }
353 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
354 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
355 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
357 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
360 impl FromInner<u32> for FilePermissions {
361 fn from_inner(mode: u32) -> FilePermissions {
362 FilePermissions { mode: mode as mode_t }
366 impl fmt::Debug for ReadDir {
367 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
369 // Thus the result will be e g 'ReadDir("/home")'
370 fmt::Debug::fmt(&*self.inner.root, f)
374 impl Iterator for ReadDir {
375 type Item = io::Result<DirEntry>;
377 #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))]
378 fn next(&mut self) -> Option<io::Result<DirEntry>> {
383 // Although readdir_r(3) would be a correct function to use here because
384 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
385 // is safe to use in threaded applications and it is generally preferred
386 // over the readdir_r(3C) function.
387 super::os::set_errno(0);
388 let entry_ptr = libc::readdir(self.inner.dirp.0);
389 if entry_ptr.is_null() {
390 // NULL can mean either the end is reached or an error occurred.
391 // So we had to clear errno beforehand to check for an error now.
392 return match super::os::errno() {
394 e => Some(Err(Error::from_raw_os_error(e))),
398 let name = (*entry_ptr).d_name.as_ptr();
399 let namelen = libc::strlen(name) as usize;
403 name: slice::from_raw_parts(name as *const u8,
404 namelen as usize).to_owned().into_boxed_slice(),
407 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
414 #[cfg(not(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox")))]
415 fn next(&mut self) -> Option<io::Result<DirEntry>> {
416 if self.end_of_stream {
421 let mut ret = DirEntry {
422 entry: mem::zeroed(),
425 let mut entry_ptr = ptr::null_mut();
427 if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
428 if entry_ptr.is_null() {
429 // We encountered an error (which will be returned in this iteration), but
430 // we also reached the end of the directory stream. The `end_of_stream`
431 // flag is enabled to make sure that we return `None` in the next iteration
432 // (instead of looping forever)
433 self.end_of_stream = true;
435 return Some(Err(Error::last_os_error()))
437 if entry_ptr.is_null() {
440 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
450 let r = unsafe { libc::closedir(self.0) };
451 debug_assert_eq!(r, 0);
456 pub fn path(&self) -> PathBuf {
457 self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
460 pub fn file_name(&self) -> OsString {
461 OsStr::from_bytes(self.name_bytes()).to_os_string()
464 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
465 pub fn metadata(&self) -> io::Result<FileAttr> {
466 let fd = cvt(unsafe { dirfd(self.dir.inner.dirp.0) })?;
467 let name = self.entry.d_name.as_ptr();
470 if let Some(ret) = unsafe { try_statx(
473 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
480 let mut stat: stat64 = unsafe { mem::zeroed() };
482 fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW)
484 Ok(FileAttr::from_stat64(stat))
487 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
488 pub fn metadata(&self) -> io::Result<FileAttr> {
492 #[cfg(any(target_os = "solaris", target_os = "haiku", target_os = "hermit"))]
493 pub fn file_type(&self) -> io::Result<FileType> {
494 lstat(&self.path()).map(|m| m.file_type())
497 #[cfg(not(any(target_os = "solaris", target_os = "haiku", target_os = "hermit")))]
498 pub fn file_type(&self) -> io::Result<FileType> {
499 match self.entry.d_type {
500 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
501 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
502 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
503 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
504 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
505 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
506 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
507 _ => lstat(&self.path()).map(|m| m.file_type()),
511 #[cfg(any(target_os = "macos",
514 target_os = "emscripten",
515 target_os = "android",
516 target_os = "solaris",
519 target_os = "fuchsia",
520 target_os = "hermit",
521 target_os = "redox"))]
522 pub fn ino(&self) -> u64 {
523 self.entry.d_ino as u64
526 #[cfg(any(target_os = "freebsd",
527 target_os = "openbsd",
528 target_os = "netbsd",
529 target_os = "dragonfly"))]
530 pub fn ino(&self) -> u64 {
531 self.entry.d_fileno as u64
534 #[cfg(any(target_os = "macos",
536 target_os = "netbsd",
537 target_os = "openbsd",
538 target_os = "freebsd",
539 target_os = "dragonfly"))]
540 fn name_bytes(&self) -> &[u8] {
543 slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
544 self.entry.d_namlen as usize)
547 #[cfg(any(target_os = "android",
549 target_os = "emscripten",
552 target_os = "hermit"))]
553 fn name_bytes(&self) -> &[u8] {
555 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
558 #[cfg(any(target_os = "solaris",
559 target_os = "fuchsia",
560 target_os = "redox"))]
561 fn name_bytes(&self) -> &[u8] {
567 pub fn new() -> OpenOptions {
582 pub fn read(&mut self, read: bool) { self.read = read; }
583 pub fn write(&mut self, write: bool) { self.write = write; }
584 pub fn append(&mut self, append: bool) { self.append = append; }
585 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
586 pub fn create(&mut self, create: bool) { self.create = create; }
587 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
589 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
590 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
592 fn get_access_mode(&self) -> io::Result<c_int> {
593 match (self.read, self.write, self.append) {
594 (true, false, false) => Ok(libc::O_RDONLY),
595 (false, true, false) => Ok(libc::O_WRONLY),
596 (true, true, false) => Ok(libc::O_RDWR),
597 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
598 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
599 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
603 fn get_creation_mode(&self) -> io::Result<c_int> {
604 match (self.write, self.append) {
607 if self.truncate || self.create || self.create_new {
608 return Err(Error::from_raw_os_error(libc::EINVAL));
611 if self.truncate && !self.create_new {
612 return Err(Error::from_raw_os_error(libc::EINVAL));
616 Ok(match (self.create, self.truncate, self.create_new) {
617 (false, false, false) => 0,
618 (true, false, false) => libc::O_CREAT,
619 (false, true, false) => libc::O_TRUNC,
620 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
621 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
627 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
628 let path = cstr(path)?;
629 File::open_c(&path, opts)
632 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
633 let flags = libc::O_CLOEXEC |
634 opts.get_access_mode()? |
635 opts.get_creation_mode()? |
636 (opts.custom_flags as c_int & !libc::O_ACCMODE);
637 let fd = cvt_r(|| unsafe {
638 open64(path.as_ptr(), flags, opts.mode as c_int)
640 let fd = FileDesc::new(fd);
642 // Currently the standard library supports Linux 2.6.18 which did not
643 // have the O_CLOEXEC flag (passed above). If we're running on an older
644 // Linux kernel then the flag is just ignored by the OS. After we open
645 // the first file, we check whether it has CLOEXEC set. If it doesn't,
646 // we will explicitly ask for a CLOEXEC fd for every further file we
647 // open, if it does, we will skip that step.
649 // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
650 // that we support, so we only do this on Linux currently.
651 #[cfg(target_os = "linux")]
652 fn ensure_cloexec(fd: &FileDesc) -> io::Result<()> {
653 use crate::sync::atomic::{AtomicUsize, Ordering};
655 const OPEN_CLOEXEC_UNKNOWN: usize = 0;
656 const OPEN_CLOEXEC_SUPPORTED: usize = 1;
657 const OPEN_CLOEXEC_NOTSUPPORTED: usize = 2;
658 static OPEN_CLOEXEC: AtomicUsize = AtomicUsize::new(OPEN_CLOEXEC_UNKNOWN);
661 match OPEN_CLOEXEC.load(Ordering::Relaxed) {
662 OPEN_CLOEXEC_UNKNOWN => {
663 need_to_set = !fd.get_cloexec()?;
664 OPEN_CLOEXEC.store(if need_to_set {
665 OPEN_CLOEXEC_NOTSUPPORTED
667 OPEN_CLOEXEC_SUPPORTED
668 }, Ordering::Relaxed);
670 OPEN_CLOEXEC_SUPPORTED => need_to_set = false,
671 OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true,
680 #[cfg(not(target_os = "linux"))]
681 fn ensure_cloexec(_: &FileDesc) -> io::Result<()> {
685 ensure_cloexec(&fd)?;
689 pub fn file_attr(&self) -> io::Result<FileAttr> {
690 let fd = self.0.raw();
693 if let Some(ret) = unsafe { try_statx(
695 b"\0" as *const _ as *const libc::c_char,
696 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
703 let mut stat: stat64 = unsafe { mem::zeroed() };
705 fstat64(fd, &mut stat)
707 Ok(FileAttr::from_stat64(stat))
710 pub fn fsync(&self) -> io::Result<()> {
711 cvt_r(|| unsafe { os_fsync(self.0.raw()) })?;
714 #[cfg(any(target_os = "macos", target_os = "ios"))]
715 unsafe fn os_fsync(fd: c_int) -> c_int {
716 libc::fcntl(fd, libc::F_FULLFSYNC)
718 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
719 unsafe fn os_fsync(fd: c_int) -> c_int { libc::fsync(fd) }
722 pub fn datasync(&self) -> io::Result<()> {
723 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
726 #[cfg(any(target_os = "macos", target_os = "ios"))]
727 unsafe fn os_datasync(fd: c_int) -> c_int {
728 libc::fcntl(fd, libc::F_FULLFSYNC)
730 #[cfg(target_os = "linux")]
731 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
732 #[cfg(not(any(target_os = "macos",
734 target_os = "linux")))]
735 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
738 pub fn truncate(&self, size: u64) -> io::Result<()> {
739 #[cfg(target_os = "android")]
740 return crate::sys::android::ftruncate64(self.0.raw(), size);
742 #[cfg(not(target_os = "android"))]
744 use crate::convert::TryInto;
745 let size: off64_t = size
747 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
749 ftruncate64(self.0.raw(), size)
754 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
758 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
759 self.0.read_vectored(bufs)
762 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
763 self.0.read_at(buf, offset)
766 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
770 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
771 self.0.write_vectored(bufs)
774 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
775 self.0.write_at(buf, offset)
778 pub fn flush(&self) -> io::Result<()> { Ok(()) }
780 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
781 let (whence, pos) = match pos {
782 // Casting to `i64` is fine, too large values will end up as
783 // negative which will cause an error in `lseek64`.
784 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
785 SeekFrom::End(off) => (libc::SEEK_END, off),
786 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
788 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
792 pub fn duplicate(&self) -> io::Result<File> {
793 self.0.duplicate().map(File)
796 pub fn fd(&self) -> &FileDesc { &self.0 }
798 pub fn into_fd(self) -> FileDesc { self.0 }
800 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
801 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
807 pub fn new() -> DirBuilder {
808 DirBuilder { mode: 0o777 }
811 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
813 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
817 pub fn set_mode(&mut self, mode: u32) {
818 self.mode = mode as mode_t;
822 fn cstr(path: &Path) -> io::Result<CString> {
823 Ok(CString::new(path.as_os_str().as_bytes())?)
826 impl FromInner<c_int> for File {
827 fn from_inner(fd: c_int) -> File {
828 File(FileDesc::new(fd))
832 impl fmt::Debug for File {
833 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834 #[cfg(target_os = "linux")]
835 fn get_path(fd: c_int) -> Option<PathBuf> {
836 let mut p = PathBuf::from("/proc/self/fd");
837 p.push(&fd.to_string());
841 #[cfg(target_os = "macos")]
842 fn get_path(fd: c_int) -> Option<PathBuf> {
843 // FIXME: The use of PATH_MAX is generally not encouraged, but it
844 // is inevitable in this case because macOS defines `fcntl` with
845 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
846 // alternatives. If a better method is invented, it should be used
848 let mut buf = vec![0;libc::PATH_MAX as usize];
849 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
853 let l = buf.iter().position(|&c| c == 0).unwrap();
854 buf.truncate(l as usize);
856 Some(PathBuf::from(OsString::from_vec(buf)))
859 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
860 fn get_path(_fd: c_int) -> Option<PathBuf> {
861 // FIXME(#24570): implement this for other Unix platforms
865 #[cfg(any(target_os = "linux", target_os = "macos"))]
866 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
867 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
871 match mode & libc::O_ACCMODE {
872 libc::O_RDONLY => Some((true, false)),
873 libc::O_RDWR => Some((true, true)),
874 libc::O_WRONLY => Some((false, true)),
879 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
880 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
881 // FIXME(#24570): implement this for other Unix platforms
885 let fd = self.0.raw();
886 let mut b = f.debug_struct("File");
888 if let Some(path) = get_path(fd) {
889 b.field("path", &path);
891 if let Some((read, write)) = get_mode(fd) {
892 b.field("read", &read).field("write", &write);
898 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
899 let root = p.to_path_buf();
902 let ptr = libc::opendir(p.as_ptr());
904 Err(Error::last_os_error())
906 let inner = InnerReadDir { dirp: Dir(ptr), root };
908 inner: Arc::new(inner),
909 end_of_stream: false,
915 pub fn unlink(p: &Path) -> io::Result<()> {
917 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
921 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
922 let old = cstr(old)?;
923 let new = cstr(new)?;
924 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
928 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
930 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
934 pub fn rmdir(p: &Path) -> io::Result<()> {
936 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
940 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
941 let c_path = cstr(p)?;
942 let p = c_path.as_ptr();
944 let mut buf = Vec::with_capacity(256);
947 let buf_read = cvt(unsafe {
948 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
951 unsafe { buf.set_len(buf_read); }
953 if buf_read != buf.capacity() {
956 return Ok(PathBuf::from(OsString::from_vec(buf)));
959 // Trigger the internal buffer resizing logic of `Vec` by requiring
960 // more space than the current capacity. The length is guaranteed to be
961 // the same as the capacity due to the if statement above.
966 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
967 let src = cstr(src)?;
968 let dst = cstr(dst)?;
969 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
973 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
974 let src = cstr(src)?;
975 let dst = cstr(dst)?;
976 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
980 pub fn stat(p: &Path) -> io::Result<FileAttr> {
984 if let Some(ret) = unsafe { try_statx(
987 libc::AT_STATX_SYNC_AS_STAT,
994 let mut stat: stat64 = unsafe { mem::zeroed() };
996 stat64(p.as_ptr(), &mut stat)
998 Ok(FileAttr::from_stat64(stat))
1001 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1005 if let Some(ret) = unsafe { try_statx(
1008 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1015 let mut stat: stat64 = unsafe { mem::zeroed() };
1017 lstat64(p.as_ptr(), &mut stat)
1019 Ok(FileAttr::from_stat64(stat))
1022 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1023 let path = CString::new(p.as_os_str().as_bytes())?;
1026 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1028 return Err(io::Error::last_os_error())
1030 buf = CStr::from_ptr(r).to_bytes().to_vec();
1031 libc::free(r as *mut _);
1033 Ok(PathBuf::from(OsString::from_vec(buf)))
1036 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1037 use crate::fs::File;
1039 let reader = File::open(from)?;
1040 let metadata = reader.metadata()?;
1041 if !metadata.is_file() {
1042 return Err(Error::new(
1043 ErrorKind::InvalidInput,
1044 "the source path is not an existing regular file",
1047 Ok((reader, metadata))
1050 fn open_to_and_set_permissions(
1052 reader_metadata: crate::fs::Metadata,
1053 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1054 use crate::fs::OpenOptions;
1055 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1057 let perm = reader_metadata.permissions();
1058 let writer = OpenOptions::new()
1059 // create the file with the correct mode right away
1065 let writer_metadata = writer.metadata()?;
1066 if writer_metadata.is_file() {
1067 // Set the correct file permissions, in case the file already existed.
1068 // Don't set the permissions on already existing non-files like
1069 // pipes/FIFOs or device nodes.
1070 writer.set_permissions(perm)?;
1072 Ok((writer, writer_metadata))
1075 #[cfg(not(any(target_os = "linux",
1076 target_os = "android",
1077 target_os = "macos",
1078 target_os = "ios")))]
1079 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1080 let (mut reader, reader_metadata) = open_from(from)?;
1081 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1083 io::copy(&mut reader, &mut writer)
1086 #[cfg(any(target_os = "linux", target_os = "android"))]
1087 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1089 use crate::sync::atomic::{AtomicBool, Ordering};
1091 // Kernel prior to 4.5 don't have copy_file_range
1092 // We store the availability in a global to avoid unnecessary syscalls
1093 static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
1095 unsafe fn copy_file_range(
1097 off_in: *mut libc::loff_t,
1098 fd_out: libc::c_int,
1099 off_out: *mut libc::loff_t,
1101 flags: libc::c_uint,
1104 libc::SYS_copy_file_range,
1114 let (mut reader, reader_metadata) = open_from(from)?;
1115 let len = reader_metadata.len();
1116 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1118 let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
1119 let mut written = 0u64;
1120 while written < len {
1121 let copy_result = if has_copy_file_range {
1122 let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
1123 let copy_result = unsafe {
1124 // We actually don't have to adjust the offsets,
1125 // because copy_file_range adjusts the file offset automatically
1126 cvt(copy_file_range(
1135 if let Err(ref copy_err) = copy_result {
1136 match copy_err.raw_os_error() {
1137 Some(libc::ENOSYS) | Some(libc::EPERM) => {
1138 HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
1145 Err(io::Error::from_raw_os_error(libc::ENOSYS))
1148 Ok(ret) => written += ret as u64,
1150 match err.raw_os_error() {
1152 if os_err == libc::ENOSYS
1153 || os_err == libc::EXDEV
1154 || os_err == libc::EINVAL
1155 || os_err == libc::EPERM =>
1157 // Try fallback io::copy if either:
1158 // - Kernel version is < 4.5 (ENOSYS)
1159 // - Files are mounted on different fs (EXDEV)
1160 // - copy_file_range is disallowed, for example by seccomp (EPERM)
1161 // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
1162 assert_eq!(written, 0);
1163 return io::copy(&mut reader, &mut writer);
1165 _ => return Err(err),
1173 #[cfg(any(target_os = "macos", target_os = "ios"))]
1174 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1175 use crate::sync::atomic::{AtomicBool, Ordering};
1177 const COPYFILE_ACL: u32 = 1 << 0;
1178 const COPYFILE_STAT: u32 = 1 << 1;
1179 const COPYFILE_XATTR: u32 = 1 << 2;
1180 const COPYFILE_DATA: u32 = 1 << 3;
1182 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1183 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1184 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1186 const COPYFILE_STATE_COPIED: u32 = 8;
1188 #[allow(non_camel_case_types)]
1189 type copyfile_state_t = *mut libc::c_void;
1190 #[allow(non_camel_case_types)]
1191 type copyfile_flags_t = u32;
1197 state: copyfile_state_t,
1198 flags: copyfile_flags_t,
1200 fn copyfile_state_alloc() -> copyfile_state_t;
1201 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1202 fn copyfile_state_get(
1203 state: copyfile_state_t,
1205 dst: *mut libc::c_void,
1209 struct FreeOnDrop(copyfile_state_t);
1210 impl Drop for FreeOnDrop {
1211 fn drop(&mut self) {
1212 // The code below ensures that `FreeOnDrop` is never a null pointer
1214 // `copyfile_state_free` returns -1 if the `to` or `from` files
1215 // cannot be closed. However, this is not considerd this an
1217 copyfile_state_free(self.0);
1222 // MacOS prior to 10.12 don't support `fclonefileat`
1223 // We store the availability in a global to avoid unnecessary syscalls
1224 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1228 dst_dirfd: libc::c_int,
1229 dst: *const libc::c_char,
1234 let (reader, reader_metadata) = open_from(from)?;
1236 // Opportunistically attempt to create a copy-on-write clone of `from`
1237 // using `fclonefileat`.
1238 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1240 let clonefile_result = cvt(unsafe {
1248 match clonefile_result {
1249 Ok(_) => return Ok(reader_metadata.len()),
1250 Err(err) => match err.raw_os_error() {
1251 // `fclonefileat` will fail on non-APFS volumes, if the
1252 // destination already exists, or if the source and destination
1253 // are on different devices. In all these cases `fcopyfile`
1255 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1256 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1257 _ => return Err(err),
1262 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1263 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1265 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1266 // always safe to call `copyfile_state_free`
1267 let state = unsafe {
1268 let state = copyfile_state_alloc();
1269 if state.is_null() {
1270 return Err(crate::io::Error::last_os_error());
1275 let flags = if writer_metadata.is_file() {
1290 let mut bytes_copied: libc::off_t = 0;
1294 COPYFILE_STATE_COPIED,
1295 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1298 Ok(bytes_copied as u64)