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 libc::c_long,
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 #[cfg(target_os = "emscripten")]
789 let pos = pos as i32;
790 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
794 pub fn duplicate(&self) -> io::Result<File> {
795 self.0.duplicate().map(File)
798 pub fn fd(&self) -> &FileDesc { &self.0 }
800 pub fn into_fd(self) -> FileDesc { self.0 }
802 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
803 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
809 pub fn new() -> DirBuilder {
810 DirBuilder { mode: 0o777 }
813 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
815 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
819 pub fn set_mode(&mut self, mode: u32) {
820 self.mode = mode as mode_t;
824 fn cstr(path: &Path) -> io::Result<CString> {
825 Ok(CString::new(path.as_os_str().as_bytes())?)
828 impl FromInner<c_int> for File {
829 fn from_inner(fd: c_int) -> File {
830 File(FileDesc::new(fd))
834 impl fmt::Debug for File {
835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
836 #[cfg(target_os = "linux")]
837 fn get_path(fd: c_int) -> Option<PathBuf> {
838 let mut p = PathBuf::from("/proc/self/fd");
839 p.push(&fd.to_string());
843 #[cfg(target_os = "macos")]
844 fn get_path(fd: c_int) -> Option<PathBuf> {
845 // FIXME: The use of PATH_MAX is generally not encouraged, but it
846 // is inevitable in this case because macOS defines `fcntl` with
847 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
848 // alternatives. If a better method is invented, it should be used
850 let mut buf = vec![0;libc::PATH_MAX as usize];
851 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
855 let l = buf.iter().position(|&c| c == 0).unwrap();
856 buf.truncate(l as usize);
858 Some(PathBuf::from(OsString::from_vec(buf)))
861 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
862 fn get_path(_fd: c_int) -> Option<PathBuf> {
863 // FIXME(#24570): implement this for other Unix platforms
867 #[cfg(any(target_os = "linux", target_os = "macos"))]
868 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
869 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
873 match mode & libc::O_ACCMODE {
874 libc::O_RDONLY => Some((true, false)),
875 libc::O_RDWR => Some((true, true)),
876 libc::O_WRONLY => Some((false, true)),
881 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
882 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
883 // FIXME(#24570): implement this for other Unix platforms
887 let fd = self.0.raw();
888 let mut b = f.debug_struct("File");
890 if let Some(path) = get_path(fd) {
891 b.field("path", &path);
893 if let Some((read, write)) = get_mode(fd) {
894 b.field("read", &read).field("write", &write);
900 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
901 let root = p.to_path_buf();
904 let ptr = libc::opendir(p.as_ptr());
906 Err(Error::last_os_error())
908 let inner = InnerReadDir { dirp: Dir(ptr), root };
910 inner: Arc::new(inner),
911 end_of_stream: false,
917 pub fn unlink(p: &Path) -> io::Result<()> {
919 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
923 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
924 let old = cstr(old)?;
925 let new = cstr(new)?;
926 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
930 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
932 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
936 pub fn rmdir(p: &Path) -> io::Result<()> {
938 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
942 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
943 let c_path = cstr(p)?;
944 let p = c_path.as_ptr();
946 let mut buf = Vec::with_capacity(256);
949 let buf_read = cvt(unsafe {
950 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
953 unsafe { buf.set_len(buf_read); }
955 if buf_read != buf.capacity() {
958 return Ok(PathBuf::from(OsString::from_vec(buf)));
961 // Trigger the internal buffer resizing logic of `Vec` by requiring
962 // more space than the current capacity. The length is guaranteed to be
963 // the same as the capacity due to the if statement above.
968 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
969 let src = cstr(src)?;
970 let dst = cstr(dst)?;
971 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
975 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
976 let src = cstr(src)?;
977 let dst = cstr(dst)?;
978 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
982 pub fn stat(p: &Path) -> io::Result<FileAttr> {
986 if let Some(ret) = unsafe { try_statx(
989 libc::AT_STATX_SYNC_AS_STAT,
996 let mut stat: stat64 = unsafe { mem::zeroed() };
998 stat64(p.as_ptr(), &mut stat)
1000 Ok(FileAttr::from_stat64(stat))
1003 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1007 if let Some(ret) = unsafe { try_statx(
1010 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1017 let mut stat: stat64 = unsafe { mem::zeroed() };
1019 lstat64(p.as_ptr(), &mut stat)
1021 Ok(FileAttr::from_stat64(stat))
1024 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1025 let path = CString::new(p.as_os_str().as_bytes())?;
1028 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1030 return Err(io::Error::last_os_error())
1032 buf = CStr::from_ptr(r).to_bytes().to_vec();
1033 libc::free(r as *mut _);
1035 Ok(PathBuf::from(OsString::from_vec(buf)))
1038 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1039 use crate::fs::File;
1041 let reader = File::open(from)?;
1042 let metadata = reader.metadata()?;
1043 if !metadata.is_file() {
1044 return Err(Error::new(
1045 ErrorKind::InvalidInput,
1046 "the source path is not an existing regular file",
1049 Ok((reader, metadata))
1052 fn open_to_and_set_permissions(
1054 reader_metadata: crate::fs::Metadata,
1055 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1056 use crate::fs::OpenOptions;
1057 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1059 let perm = reader_metadata.permissions();
1060 let writer = OpenOptions::new()
1061 // create the file with the correct mode right away
1067 let writer_metadata = writer.metadata()?;
1068 if writer_metadata.is_file() {
1069 // Set the correct file permissions, in case the file already existed.
1070 // Don't set the permissions on already existing non-files like
1071 // pipes/FIFOs or device nodes.
1072 writer.set_permissions(perm)?;
1074 Ok((writer, writer_metadata))
1077 #[cfg(not(any(target_os = "linux",
1078 target_os = "android",
1079 target_os = "macos",
1080 target_os = "ios")))]
1081 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1082 let (mut reader, reader_metadata) = open_from(from)?;
1083 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1085 io::copy(&mut reader, &mut writer)
1088 #[cfg(any(target_os = "linux", target_os = "android"))]
1089 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1091 use crate::sync::atomic::{AtomicBool, Ordering};
1093 // Kernel prior to 4.5 don't have copy_file_range
1094 // We store the availability in a global to avoid unnecessary syscalls
1095 static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
1097 unsafe fn copy_file_range(
1099 off_in: *mut libc::loff_t,
1100 fd_out: libc::c_int,
1101 off_out: *mut libc::loff_t,
1103 flags: libc::c_uint,
1106 libc::SYS_copy_file_range,
1116 let (mut reader, reader_metadata) = open_from(from)?;
1117 let len = reader_metadata.len();
1118 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1120 let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
1121 let mut written = 0u64;
1122 while written < len {
1123 let copy_result = if has_copy_file_range {
1124 let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
1125 let copy_result = unsafe {
1126 // We actually don't have to adjust the offsets,
1127 // because copy_file_range adjusts the file offset automatically
1128 cvt(copy_file_range(
1137 if let Err(ref copy_err) = copy_result {
1138 match copy_err.raw_os_error() {
1139 Some(libc::ENOSYS) | Some(libc::EPERM) => {
1140 HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
1147 Err(io::Error::from_raw_os_error(libc::ENOSYS))
1150 Ok(ret) => written += ret as u64,
1152 match err.raw_os_error() {
1154 if os_err == libc::ENOSYS
1155 || os_err == libc::EXDEV
1156 || os_err == libc::EINVAL
1157 || os_err == libc::EPERM =>
1159 // Try fallback io::copy if either:
1160 // - Kernel version is < 4.5 (ENOSYS)
1161 // - Files are mounted on different fs (EXDEV)
1162 // - copy_file_range is disallowed, for example by seccomp (EPERM)
1163 // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
1164 assert_eq!(written, 0);
1165 return io::copy(&mut reader, &mut writer);
1167 _ => return Err(err),
1175 #[cfg(any(target_os = "macos", target_os = "ios"))]
1176 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1177 use crate::sync::atomic::{AtomicBool, Ordering};
1179 const COPYFILE_ACL: u32 = 1 << 0;
1180 const COPYFILE_STAT: u32 = 1 << 1;
1181 const COPYFILE_XATTR: u32 = 1 << 2;
1182 const COPYFILE_DATA: u32 = 1 << 3;
1184 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1185 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1186 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1188 const COPYFILE_STATE_COPIED: u32 = 8;
1190 #[allow(non_camel_case_types)]
1191 type copyfile_state_t = *mut libc::c_void;
1192 #[allow(non_camel_case_types)]
1193 type copyfile_flags_t = u32;
1199 state: copyfile_state_t,
1200 flags: copyfile_flags_t,
1202 fn copyfile_state_alloc() -> copyfile_state_t;
1203 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1204 fn copyfile_state_get(
1205 state: copyfile_state_t,
1207 dst: *mut libc::c_void,
1211 struct FreeOnDrop(copyfile_state_t);
1212 impl Drop for FreeOnDrop {
1213 fn drop(&mut self) {
1214 // The code below ensures that `FreeOnDrop` is never a null pointer
1216 // `copyfile_state_free` returns -1 if the `to` or `from` files
1217 // cannot be closed. However, this is not considerd this an
1219 copyfile_state_free(self.0);
1224 // MacOS prior to 10.12 don't support `fclonefileat`
1225 // We store the availability in a global to avoid unnecessary syscalls
1226 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1230 dst_dirfd: libc::c_int,
1231 dst: *const libc::c_char,
1236 let (reader, reader_metadata) = open_from(from)?;
1238 // Opportunistically attempt to create a copy-on-write clone of `from`
1239 // using `fclonefileat`.
1240 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1242 let clonefile_result = cvt(unsafe {
1250 match clonefile_result {
1251 Ok(_) => return Ok(reader_metadata.len()),
1252 Err(err) => match err.raw_os_error() {
1253 // `fclonefileat` will fail on non-APFS volumes, if the
1254 // destination already exists, or if the source and destination
1255 // are on different devices. In all these cases `fcopyfile`
1257 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1258 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1259 _ => return Err(err),
1264 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1265 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1267 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1268 // always safe to call `copyfile_state_free`
1269 let state = unsafe {
1270 let state = copyfile_state_alloc();
1271 if state.is_null() {
1272 return Err(crate::io::Error::last_os_error());
1277 let flags = if writer_metadata.is_file() {
1292 let mut bytes_copied: libc::off_t = 0;
1296 COPYFILE_STATE_COPIED,
1297 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1300 Ok(bytes_copied as u64)