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);
49 // all DirEntry's will have a reference to this struct
57 inner: Arc<InnerReadDir>,
61 struct Dir(*mut libc::DIR);
63 unsafe impl Send for Dir {}
64 unsafe impl Sync for Dir {}
69 // We need to store an owned copy of the entry name
70 // on Solaris and Fuchsia because a) it uses a zero-length
71 // array to store the name, b) its lifetime between readdir
72 // calls is not guaranteed.
73 #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))]
77 #[derive(Clone, Debug)]
78 pub struct OpenOptions {
91 #[derive(Clone, PartialEq, Eq, Debug)]
92 pub struct FilePermissions { mode: mode_t }
94 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
95 pub struct FileType { mode: mode_t }
98 pub struct DirBuilder { mode: mode_t }
101 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
102 pub fn perm(&self) -> FilePermissions {
103 FilePermissions { mode: (self.stat.st_mode as mode_t) }
106 pub fn file_type(&self) -> FileType {
107 FileType { mode: self.stat.st_mode as mode_t }
111 #[cfg(target_os = "netbsd")]
113 pub fn modified(&self) -> io::Result<SystemTime> {
114 Ok(SystemTime::from(libc::timespec {
115 tv_sec: self.stat.st_mtime as libc::time_t,
116 tv_nsec: self.stat.st_mtimensec as libc::c_long,
120 pub fn accessed(&self) -> io::Result<SystemTime> {
121 Ok(SystemTime::from(libc::timespec {
122 tv_sec: self.stat.st_atime as libc::time_t,
123 tv_nsec: self.stat.st_atimensec as libc::c_long,
127 pub fn created(&self) -> io::Result<SystemTime> {
128 Ok(SystemTime::from(libc::timespec {
129 tv_sec: self.stat.st_birthtime as libc::time_t,
130 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
135 #[cfg(not(target_os = "netbsd"))]
137 pub fn modified(&self) -> io::Result<SystemTime> {
138 Ok(SystemTime::from(libc::timespec {
139 tv_sec: self.stat.st_mtime as libc::time_t,
140 tv_nsec: self.stat.st_mtime_nsec as _,
144 pub fn accessed(&self) -> io::Result<SystemTime> {
145 Ok(SystemTime::from(libc::timespec {
146 tv_sec: self.stat.st_atime as libc::time_t,
147 tv_nsec: self.stat.st_atime_nsec as _,
151 #[cfg(any(target_os = "freebsd",
152 target_os = "openbsd",
155 pub fn created(&self) -> io::Result<SystemTime> {
156 Ok(SystemTime::from(libc::timespec {
157 tv_sec: self.stat.st_birthtime as libc::time_t,
158 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
162 #[cfg(not(any(target_os = "freebsd",
163 target_os = "openbsd",
165 target_os = "ios")))]
166 pub fn created(&self) -> io::Result<SystemTime> {
167 Err(io::Error::new(io::ErrorKind::Other,
168 "creation time is not available on this platform \
173 impl AsInner<stat64> for FileAttr {
174 fn as_inner(&self) -> &stat64 { &self.stat }
177 impl FilePermissions {
178 pub fn readonly(&self) -> bool {
179 // check if any class (owner, group, others) has write permission
180 self.mode & 0o222 == 0
183 pub fn set_readonly(&mut self, readonly: bool) {
185 // remove write permission for all classes; equivalent to `chmod a-w <file>`
188 // add write permission for all classes; equivalent to `chmod a+w <file>`
192 pub fn mode(&self) -> u32 { self.mode as u32 }
196 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
197 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
198 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
200 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
203 impl FromInner<u32> for FilePermissions {
204 fn from_inner(mode: u32) -> FilePermissions {
205 FilePermissions { mode: mode as mode_t }
209 impl fmt::Debug for ReadDir {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
212 // Thus the result will be e g 'ReadDir("/home")'
213 fmt::Debug::fmt(&*self.inner.root, f)
217 impl Iterator for ReadDir {
218 type Item = io::Result<DirEntry>;
220 #[cfg(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox"))]
221 fn next(&mut self) -> Option<io::Result<DirEntry>> {
226 // Although readdir_r(3) would be a correct function to use here because
227 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
228 // is safe to use in threaded applications and it is generally preferred
229 // over the readdir_r(3C) function.
230 super::os::set_errno(0);
231 let entry_ptr = libc::readdir(self.inner.dirp.0);
232 if entry_ptr.is_null() {
233 // NULL can mean either the end is reached or an error occurred.
234 // So we had to clear errno beforehand to check for an error now.
235 return match super::os::errno() {
237 e => Some(Err(Error::from_raw_os_error(e))),
241 let name = (*entry_ptr).d_name.as_ptr();
242 let namelen = libc::strlen(name) as usize;
246 name: slice::from_raw_parts(name as *const u8,
247 namelen as usize).to_owned().into_boxed_slice(),
250 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
257 #[cfg(not(any(target_os = "solaris", target_os = "fuchsia", target_os = "redox")))]
258 fn next(&mut self) -> Option<io::Result<DirEntry>> {
259 if self.end_of_stream {
264 let mut ret = DirEntry {
265 entry: mem::zeroed(),
268 let mut entry_ptr = ptr::null_mut();
270 if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
271 if entry_ptr.is_null() {
272 // We encountered an error (which will be returned in this iteration), but
273 // we also reached the end of the directory stream. The `end_of_stream`
274 // flag is enabled to make sure that we return `None` in the next iteration
275 // (instead of looping forever)
276 self.end_of_stream = true;
278 return Some(Err(Error::last_os_error()))
280 if entry_ptr.is_null() {
283 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
293 let r = unsafe { libc::closedir(self.0) };
294 debug_assert_eq!(r, 0);
299 pub fn path(&self) -> PathBuf {
300 self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
303 pub fn file_name(&self) -> OsString {
304 OsStr::from_bytes(self.name_bytes()).to_os_string()
307 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
308 pub fn metadata(&self) -> io::Result<FileAttr> {
309 let fd = cvt(unsafe {dirfd(self.dir.inner.dirp.0)})?;
310 let mut stat: stat64 = unsafe { mem::zeroed() };
312 fstatat64(fd, self.entry.d_name.as_ptr(), &mut stat, libc::AT_SYMLINK_NOFOLLOW)
314 Ok(FileAttr { stat })
317 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
318 pub fn metadata(&self) -> io::Result<FileAttr> {
322 #[cfg(any(target_os = "solaris", target_os = "haiku", target_os = "hermit"))]
323 pub fn file_type(&self) -> io::Result<FileType> {
324 lstat(&self.path()).map(|m| m.file_type())
327 #[cfg(not(any(target_os = "solaris", target_os = "haiku", target_os = "hermit")))]
328 pub fn file_type(&self) -> io::Result<FileType> {
329 match self.entry.d_type {
330 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
331 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
332 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
333 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
334 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
335 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
336 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
337 _ => lstat(&self.path()).map(|m| m.file_type()),
341 #[cfg(any(target_os = "macos",
344 target_os = "emscripten",
345 target_os = "android",
346 target_os = "solaris",
349 target_os = "fuchsia",
350 target_os = "hermit",
351 target_os = "redox"))]
352 pub fn ino(&self) -> u64 {
353 self.entry.d_ino as u64
356 #[cfg(any(target_os = "freebsd",
357 target_os = "openbsd",
358 target_os = "netbsd",
359 target_os = "dragonfly"))]
360 pub fn ino(&self) -> u64 {
361 self.entry.d_fileno as u64
364 #[cfg(any(target_os = "macos",
366 target_os = "netbsd",
367 target_os = "openbsd",
368 target_os = "freebsd",
369 target_os = "dragonfly"))]
370 fn name_bytes(&self) -> &[u8] {
373 slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
374 self.entry.d_namlen as usize)
377 #[cfg(any(target_os = "android",
379 target_os = "emscripten",
382 target_os = "hermit"))]
383 fn name_bytes(&self) -> &[u8] {
385 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
388 #[cfg(any(target_os = "solaris",
389 target_os = "fuchsia",
390 target_os = "redox"))]
391 fn name_bytes(&self) -> &[u8] {
397 pub fn new() -> OpenOptions {
412 pub fn read(&mut self, read: bool) { self.read = read; }
413 pub fn write(&mut self, write: bool) { self.write = write; }
414 pub fn append(&mut self, append: bool) { self.append = append; }
415 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
416 pub fn create(&mut self, create: bool) { self.create = create; }
417 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
419 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
420 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
422 fn get_access_mode(&self) -> io::Result<c_int> {
423 match (self.read, self.write, self.append) {
424 (true, false, false) => Ok(libc::O_RDONLY),
425 (false, true, false) => Ok(libc::O_WRONLY),
426 (true, true, false) => Ok(libc::O_RDWR),
427 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
428 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
429 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
433 fn get_creation_mode(&self) -> io::Result<c_int> {
434 match (self.write, self.append) {
437 if self.truncate || self.create || self.create_new {
438 return Err(Error::from_raw_os_error(libc::EINVAL));
441 if self.truncate && !self.create_new {
442 return Err(Error::from_raw_os_error(libc::EINVAL));
446 Ok(match (self.create, self.truncate, self.create_new) {
447 (false, false, false) => 0,
448 (true, false, false) => libc::O_CREAT,
449 (false, true, false) => libc::O_TRUNC,
450 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
451 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
457 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
458 let path = cstr(path)?;
459 File::open_c(&path, opts)
462 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
463 let flags = libc::O_CLOEXEC |
464 opts.get_access_mode()? |
465 opts.get_creation_mode()? |
466 (opts.custom_flags as c_int & !libc::O_ACCMODE);
467 let fd = cvt_r(|| unsafe {
468 open64(path.as_ptr(), flags, opts.mode as c_int)
470 let fd = FileDesc::new(fd);
472 // Currently the standard library supports Linux 2.6.18 which did not
473 // have the O_CLOEXEC flag (passed above). If we're running on an older
474 // Linux kernel then the flag is just ignored by the OS. After we open
475 // the first file, we check whether it has CLOEXEC set. If it doesn't,
476 // we will explicitly ask for a CLOEXEC fd for every further file we
477 // open, if it does, we will skip that step.
479 // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
480 // that we support, so we only do this on Linux currently.
481 #[cfg(target_os = "linux")]
482 fn ensure_cloexec(fd: &FileDesc) -> io::Result<()> {
483 use crate::sync::atomic::{AtomicUsize, Ordering};
485 const OPEN_CLOEXEC_UNKNOWN: usize = 0;
486 const OPEN_CLOEXEC_SUPPORTED: usize = 1;
487 const OPEN_CLOEXEC_NOTSUPPORTED: usize = 2;
488 static OPEN_CLOEXEC: AtomicUsize = AtomicUsize::new(OPEN_CLOEXEC_UNKNOWN);
491 match OPEN_CLOEXEC.load(Ordering::Relaxed) {
492 OPEN_CLOEXEC_UNKNOWN => {
493 need_to_set = !fd.get_cloexec()?;
494 OPEN_CLOEXEC.store(if need_to_set {
495 OPEN_CLOEXEC_NOTSUPPORTED
497 OPEN_CLOEXEC_SUPPORTED
498 }, Ordering::Relaxed);
500 OPEN_CLOEXEC_SUPPORTED => need_to_set = false,
501 OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true,
510 #[cfg(not(target_os = "linux"))]
511 fn ensure_cloexec(_: &FileDesc) -> io::Result<()> {
515 ensure_cloexec(&fd)?;
519 pub fn file_attr(&self) -> io::Result<FileAttr> {
520 let mut stat: stat64 = unsafe { mem::zeroed() };
522 fstat64(self.0.raw(), &mut stat)
524 Ok(FileAttr { stat })
527 pub fn fsync(&self) -> io::Result<()> {
528 cvt_r(|| unsafe { os_fsync(self.0.raw()) })?;
531 #[cfg(any(target_os = "macos", target_os = "ios"))]
532 unsafe fn os_fsync(fd: c_int) -> c_int {
533 libc::fcntl(fd, libc::F_FULLFSYNC)
535 #[cfg(not(any(target_os = "macos", target_os = "ios")))]
536 unsafe fn os_fsync(fd: c_int) -> c_int { libc::fsync(fd) }
539 pub fn datasync(&self) -> io::Result<()> {
540 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
543 #[cfg(any(target_os = "macos", target_os = "ios"))]
544 unsafe fn os_datasync(fd: c_int) -> c_int {
545 libc::fcntl(fd, libc::F_FULLFSYNC)
547 #[cfg(target_os = "linux")]
548 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
549 #[cfg(not(any(target_os = "macos",
551 target_os = "linux")))]
552 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
555 pub fn truncate(&self, size: u64) -> io::Result<()> {
556 #[cfg(target_os = "android")]
557 return crate::sys::android::ftruncate64(self.0.raw(), size);
559 #[cfg(not(target_os = "android"))]
560 return cvt_r(|| unsafe {
561 ftruncate64(self.0.raw(), size as off64_t)
565 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
569 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
570 self.0.read_vectored(bufs)
573 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
574 self.0.read_at(buf, offset)
577 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
581 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
582 self.0.write_vectored(bufs)
585 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
586 self.0.write_at(buf, offset)
589 pub fn flush(&self) -> io::Result<()> { Ok(()) }
591 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
592 let (whence, pos) = match pos {
593 // Casting to `i64` is fine, too large values will end up as
594 // negative which will cause an error in `lseek64`.
595 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
596 SeekFrom::End(off) => (libc::SEEK_END, off),
597 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
599 #[cfg(target_os = "emscripten")]
600 let pos = pos as i32;
601 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
605 pub fn duplicate(&self) -> io::Result<File> {
606 self.0.duplicate().map(File)
609 pub fn fd(&self) -> &FileDesc { &self.0 }
611 pub fn into_fd(self) -> FileDesc { self.0 }
613 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
614 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
620 pub fn new() -> DirBuilder {
621 DirBuilder { mode: 0o777 }
624 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
626 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
630 pub fn set_mode(&mut self, mode: u32) {
631 self.mode = mode as mode_t;
635 fn cstr(path: &Path) -> io::Result<CString> {
636 Ok(CString::new(path.as_os_str().as_bytes())?)
639 impl FromInner<c_int> for File {
640 fn from_inner(fd: c_int) -> File {
641 File(FileDesc::new(fd))
645 impl fmt::Debug for File {
646 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647 #[cfg(target_os = "linux")]
648 fn get_path(fd: c_int) -> Option<PathBuf> {
649 let mut p = PathBuf::from("/proc/self/fd");
650 p.push(&fd.to_string());
654 #[cfg(target_os = "macos")]
655 fn get_path(fd: c_int) -> Option<PathBuf> {
656 // FIXME: The use of PATH_MAX is generally not encouraged, but it
657 // is inevitable in this case because macOS defines `fcntl` with
658 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
659 // alternatives. If a better method is invented, it should be used
661 let mut buf = vec![0;libc::PATH_MAX as usize];
662 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
666 let l = buf.iter().position(|&c| c == 0).unwrap();
667 buf.truncate(l as usize);
669 Some(PathBuf::from(OsString::from_vec(buf)))
672 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
673 fn get_path(_fd: c_int) -> Option<PathBuf> {
674 // FIXME(#24570): implement this for other Unix platforms
678 #[cfg(any(target_os = "linux", target_os = "macos"))]
679 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
680 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
684 match mode & libc::O_ACCMODE {
685 libc::O_RDONLY => Some((true, false)),
686 libc::O_RDWR => Some((true, true)),
687 libc::O_WRONLY => Some((false, true)),
692 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
693 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
694 // FIXME(#24570): implement this for other Unix platforms
698 let fd = self.0.raw();
699 let mut b = f.debug_struct("File");
701 if let Some(path) = get_path(fd) {
702 b.field("path", &path);
704 if let Some((read, write)) = get_mode(fd) {
705 b.field("read", &read).field("write", &write);
711 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
712 let root = p.to_path_buf();
715 let ptr = libc::opendir(p.as_ptr());
717 Err(Error::last_os_error())
719 let inner = InnerReadDir { dirp: Dir(ptr), root };
721 inner: Arc::new(inner),
722 end_of_stream: false,
728 pub fn unlink(p: &Path) -> io::Result<()> {
730 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
734 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
735 let old = cstr(old)?;
736 let new = cstr(new)?;
737 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
741 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
743 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
747 pub fn rmdir(p: &Path) -> io::Result<()> {
749 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
753 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
754 let c_path = cstr(p)?;
755 let p = c_path.as_ptr();
757 let mut buf = Vec::with_capacity(256);
760 let buf_read = cvt(unsafe {
761 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
764 unsafe { buf.set_len(buf_read); }
766 if buf_read != buf.capacity() {
769 return Ok(PathBuf::from(OsString::from_vec(buf)));
772 // Trigger the internal buffer resizing logic of `Vec` by requiring
773 // more space than the current capacity. The length is guaranteed to be
774 // the same as the capacity due to the if statement above.
779 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
780 let src = cstr(src)?;
781 let dst = cstr(dst)?;
782 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
786 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
787 let src = cstr(src)?;
788 let dst = cstr(dst)?;
789 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
793 pub fn stat(p: &Path) -> io::Result<FileAttr> {
795 let mut stat: stat64 = unsafe { mem::zeroed() };
797 stat64(p.as_ptr(), &mut stat)
799 Ok(FileAttr { stat })
802 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
804 let mut stat: stat64 = unsafe { mem::zeroed() };
806 lstat64(p.as_ptr(), &mut stat)
808 Ok(FileAttr { stat })
811 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
812 let path = CString::new(p.as_os_str().as_bytes())?;
815 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
817 return Err(io::Error::last_os_error())
819 buf = CStr::from_ptr(r).to_bytes().to_vec();
820 libc::free(r as *mut _);
822 Ok(PathBuf::from(OsString::from_vec(buf)))
825 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
828 let reader = File::open(from)?;
829 let metadata = reader.metadata()?;
830 if !metadata.is_file() {
831 return Err(Error::new(
832 ErrorKind::InvalidInput,
833 "the source path is not an existing regular file",
836 Ok((reader, metadata))
839 fn open_to_and_set_permissions(
841 reader_metadata: crate::fs::Metadata,
842 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
843 use crate::fs::OpenOptions;
844 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
846 let perm = reader_metadata.permissions();
847 let writer = OpenOptions::new()
848 // create the file with the correct mode right away
854 let writer_metadata = writer.metadata()?;
855 if writer_metadata.is_file() {
856 // Set the correct file permissions, in case the file already existed.
857 // Don't set the permissions on already existing non-files like
858 // pipes/FIFOs or device nodes.
859 writer.set_permissions(perm)?;
861 Ok((writer, writer_metadata))
864 #[cfg(not(any(target_os = "linux",
865 target_os = "android",
867 target_os = "ios")))]
868 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
869 let (mut reader, reader_metadata) = open_from(from)?;
870 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
872 io::copy(&mut reader, &mut writer)
875 #[cfg(any(target_os = "linux", target_os = "android"))]
876 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
878 use crate::sync::atomic::{AtomicBool, Ordering};
880 // Kernel prior to 4.5 don't have copy_file_range
881 // We store the availability in a global to avoid unnecessary syscalls
882 static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
884 unsafe fn copy_file_range(
886 off_in: *mut libc::loff_t,
888 off_out: *mut libc::loff_t,
893 libc::SYS_copy_file_range,
903 let (mut reader, reader_metadata) = open_from(from)?;
904 let len = reader_metadata.len();
905 let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
907 let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
908 let mut written = 0u64;
909 while written < len {
910 let copy_result = if has_copy_file_range {
911 let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
912 let copy_result = unsafe {
913 // We actually don't have to adjust the offsets,
914 // because copy_file_range adjusts the file offset automatically
924 if let Err(ref copy_err) = copy_result {
925 match copy_err.raw_os_error() {
926 Some(libc::ENOSYS) | Some(libc::EPERM) => {
927 HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
934 Err(io::Error::from_raw_os_error(libc::ENOSYS))
937 Ok(ret) => written += ret as u64,
939 match err.raw_os_error() {
941 if os_err == libc::ENOSYS
942 || os_err == libc::EXDEV
943 || os_err == libc::EINVAL
944 || os_err == libc::EPERM =>
946 // Try fallback io::copy if either:
947 // - Kernel version is < 4.5 (ENOSYS)
948 // - Files are mounted on different fs (EXDEV)
949 // - copy_file_range is disallowed, for example by seccomp (EPERM)
950 // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
951 assert_eq!(written, 0);
952 return io::copy(&mut reader, &mut writer);
954 _ => return Err(err),
962 #[cfg(any(target_os = "macos", target_os = "ios"))]
963 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
964 use crate::sync::atomic::{AtomicBool, Ordering};
966 const COPYFILE_ACL: u32 = 1 << 0;
967 const COPYFILE_STAT: u32 = 1 << 1;
968 const COPYFILE_XATTR: u32 = 1 << 2;
969 const COPYFILE_DATA: u32 = 1 << 3;
971 const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
972 const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
973 const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
975 const COPYFILE_STATE_COPIED: u32 = 8;
977 #[allow(non_camel_case_types)]
978 type copyfile_state_t = *mut libc::c_void;
979 #[allow(non_camel_case_types)]
980 type copyfile_flags_t = u32;
986 state: copyfile_state_t,
987 flags: copyfile_flags_t,
989 fn copyfile_state_alloc() -> copyfile_state_t;
990 fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
991 fn copyfile_state_get(
992 state: copyfile_state_t,
994 dst: *mut libc::c_void,
998 struct FreeOnDrop(copyfile_state_t);
999 impl Drop for FreeOnDrop {
1000 fn drop(&mut self) {
1001 // The code below ensures that `FreeOnDrop` is never a null pointer
1003 // `copyfile_state_free` returns -1 if the `to` or `from` files
1004 // cannot be closed. However, this is not considerd this an
1006 copyfile_state_free(self.0);
1011 // MacOS prior to 10.12 don't support `fclonefileat`
1012 // We store the availability in a global to avoid unnecessary syscalls
1013 static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1017 dst_dirfd: libc::c_int,
1018 dst: *const libc::c_char,
1023 let (reader, reader_metadata) = open_from(from)?;
1025 // Opportunistically attempt to create a copy-on-write clone of `from`
1026 // using `fclonefileat`.
1027 if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1029 let clonefile_result = cvt(unsafe {
1037 match clonefile_result {
1038 Ok(_) => return Ok(reader_metadata.len()),
1039 Err(err) => match err.raw_os_error() {
1040 // `fclonefileat` will fail on non-APFS volumes, if the
1041 // destination already exists, or if the source and destination
1042 // are on different devices. In all these cases `fcopyfile`
1044 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1045 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1046 _ => return Err(err),
1051 // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1052 let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1054 // We ensure that `FreeOnDrop` never contains a null pointer so it is
1055 // always safe to call `copyfile_state_free`
1056 let state = unsafe {
1057 let state = copyfile_state_alloc();
1058 if state.is_null() {
1059 return Err(crate::io::Error::last_os_error());
1064 let flags = if writer_metadata.is_file() {
1079 let mut bytes_copied: libc::off_t = 0;
1083 COPYFILE_STATE_COPIED,
1084 &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1087 Ok(bytes_copied as u64)