1 // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use os::unix::prelude::*;
13 use ffi::{CString, CStr, OsString, OsStr};
15 use io::{self, Error, ErrorKind, SeekFrom};
16 use libc::{self, c_int, mode_t};
18 use path::{Path, PathBuf};
21 use sys::fd::FileDesc;
22 use sys::time::SystemTime;
23 use sys::{cvt, cvt_r};
24 use sys_common::{AsInner, FromInner};
26 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "l4re"))]
27 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64};
28 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
30 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
32 #[cfg(target_os = "android")]
33 use libc::{stat as stat64, fstat as fstat64, fstatat as fstatat64, lstat as lstat64, lseek64,
34 dirent as dirent64, open as open64};
35 #[cfg(not(any(target_os = "linux",
36 target_os = "emscripten",
38 target_os = "android")))]
39 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
40 ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
41 #[cfg(not(any(target_os = "linux",
42 target_os = "emscripten",
43 target_os = "solaris",
45 target_os = "fuchsia")))]
46 use libc::{readdir_r as readdir64_r};
48 pub struct File(FileDesc);
55 // all DirEntry's will have a reference to this struct
63 inner: Arc<InnerReadDir>,
67 struct Dir(*mut libc::DIR);
69 unsafe impl Send for Dir {}
70 unsafe impl Sync for Dir {}
75 // We need to store an owned copy of the entry name
76 // on Solaris and Fuchsia because a) it uses a zero-length
77 // array to store the name, b) its lifetime between readdir
78 // calls is not guaranteed.
79 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
83 #[derive(Clone, Debug)]
84 pub struct OpenOptions {
97 #[derive(Clone, PartialEq, Eq, Debug)]
98 pub struct FilePermissions { mode: mode_t }
100 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
101 pub struct FileType { mode: mode_t }
104 pub struct DirBuilder { mode: mode_t }
107 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
108 pub fn perm(&self) -> FilePermissions {
109 FilePermissions { mode: (self.stat.st_mode as mode_t) }
112 pub fn file_type(&self) -> FileType {
113 FileType { mode: self.stat.st_mode as mode_t }
117 #[cfg(target_os = "netbsd")]
119 pub fn modified(&self) -> io::Result<SystemTime> {
120 Ok(SystemTime::from(libc::timespec {
121 tv_sec: self.stat.st_mtime as libc::time_t,
122 tv_nsec: self.stat.st_mtimensec as libc::c_long,
126 pub fn accessed(&self) -> io::Result<SystemTime> {
127 Ok(SystemTime::from(libc::timespec {
128 tv_sec: self.stat.st_atime as libc::time_t,
129 tv_nsec: self.stat.st_atimensec as libc::c_long,
133 pub fn created(&self) -> io::Result<SystemTime> {
134 Ok(SystemTime::from(libc::timespec {
135 tv_sec: self.stat.st_birthtime as libc::time_t,
136 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
141 #[cfg(not(target_os = "netbsd"))]
143 pub fn modified(&self) -> io::Result<SystemTime> {
144 Ok(SystemTime::from(libc::timespec {
145 tv_sec: self.stat.st_mtime as libc::time_t,
146 tv_nsec: self.stat.st_mtime_nsec as _,
150 pub fn accessed(&self) -> io::Result<SystemTime> {
151 Ok(SystemTime::from(libc::timespec {
152 tv_sec: self.stat.st_atime as libc::time_t,
153 tv_nsec: self.stat.st_atime_nsec as _,
157 #[cfg(any(target_os = "bitrig",
158 target_os = "freebsd",
159 target_os = "openbsd",
162 pub fn created(&self) -> io::Result<SystemTime> {
163 Ok(SystemTime::from(libc::timespec {
164 tv_sec: self.stat.st_birthtime as libc::time_t,
165 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
169 #[cfg(not(any(target_os = "bitrig",
170 target_os = "freebsd",
171 target_os = "openbsd",
173 target_os = "ios")))]
174 pub fn created(&self) -> io::Result<SystemTime> {
175 Err(io::Error::new(io::ErrorKind::Other,
176 "creation time is not available on this platform \
181 impl AsInner<stat64> for FileAttr {
182 fn as_inner(&self) -> &stat64 { &self.stat }
185 impl FilePermissions {
186 pub fn readonly(&self) -> bool {
187 // check if any class (owner, group, others) has write permission
188 self.mode & 0o222 == 0
191 pub fn set_readonly(&mut self, readonly: bool) {
193 // remove write permission for all classes; equivalent to `chmod a-w <file>`
196 // add write permission for all classes; equivalent to `chmod a+w <file>`
200 pub fn mode(&self) -> u32 { self.mode as u32 }
204 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
205 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
206 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
208 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
211 impl FromInner<u32> for FilePermissions {
212 fn from_inner(mode: u32) -> FilePermissions {
213 FilePermissions { mode: mode as mode_t }
217 impl fmt::Debug for ReadDir {
218 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
220 // Thus the result will be e g 'ReadDir("/home")'
221 fmt::Debug::fmt(&*self.inner.root, f)
225 impl Iterator for ReadDir {
226 type Item = io::Result<DirEntry>;
228 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
229 fn next(&mut self) -> Option<io::Result<DirEntry>> {
232 // Although readdir_r(3) would be a correct function to use here because
233 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
234 // is safe to use in threaded applications and it is generally preferred
235 // over the readdir_r(3C) function.
236 super::os::set_errno(0);
237 let entry_ptr = libc::readdir(self.inner.dirp.0);
238 if entry_ptr.is_null() {
239 // NULL can mean either the end is reached or an error occurred.
240 // So we had to clear errno beforehand to check for an error now.
241 return match super::os::errno() {
243 e => Some(Err(Error::from_raw_os_error(e))),
247 let name = (*entry_ptr).d_name.as_ptr();
248 let namelen = libc::strlen(name) as usize;
252 name: ::slice::from_raw_parts(name as *const u8,
253 namelen as usize).to_owned().into_boxed_slice(),
256 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
263 #[cfg(not(any(target_os = "solaris", target_os = "fuchsia")))]
264 fn next(&mut self) -> Option<io::Result<DirEntry>> {
265 if self.end_of_stream {
270 let mut ret = DirEntry {
271 entry: mem::zeroed(),
274 let mut entry_ptr = ptr::null_mut();
276 if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
277 if entry_ptr.is_null() {
278 // We encountered an error (which will be returned in this iteration), but
279 // we also reached the end of the directory stream. The `end_of_stream`
280 // flag is enabled to make sure that we return `None` in the next iteration
281 // (instead of looping forever)
282 self.end_of_stream = true;
284 return Some(Err(Error::last_os_error()))
286 if entry_ptr.is_null() {
289 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
299 let r = unsafe { libc::closedir(self.0) };
300 debug_assert_eq!(r, 0);
305 pub fn path(&self) -> PathBuf {
306 self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
309 pub fn file_name(&self) -> OsString {
310 OsStr::from_bytes(self.name_bytes()).to_os_string()
313 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
314 pub fn metadata(&self) -> io::Result<FileAttr> {
315 let fd = cvt(unsafe {dirfd(self.dir.inner.dirp.0)})?;
316 let mut stat: stat64 = unsafe { mem::zeroed() };
318 fstatat64(fd, self.entry.d_name.as_ptr(), &mut stat, libc::AT_SYMLINK_NOFOLLOW)
320 Ok(FileAttr { stat: stat })
323 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
324 pub fn metadata(&self) -> io::Result<FileAttr> {
328 #[cfg(any(target_os = "solaris", target_os = "haiku"))]
329 pub fn file_type(&self) -> io::Result<FileType> {
330 lstat(&self.path()).map(|m| m.file_type())
333 #[cfg(not(any(target_os = "solaris", target_os = "haiku")))]
334 pub fn file_type(&self) -> io::Result<FileType> {
335 match self.entry.d_type {
336 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
337 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
338 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
339 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
340 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
341 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
342 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
343 _ => lstat(&self.path()).map(|m| m.file_type()),
347 #[cfg(any(target_os = "macos",
350 target_os = "emscripten",
351 target_os = "android",
352 target_os = "solaris",
355 target_os = "fuchsia"))]
356 pub fn ino(&self) -> u64 {
357 self.entry.d_ino as u64
360 #[cfg(any(target_os = "freebsd",
361 target_os = "openbsd",
362 target_os = "bitrig",
363 target_os = "netbsd",
364 target_os = "dragonfly"))]
365 pub fn ino(&self) -> u64 {
366 self.entry.d_fileno as u64
369 #[cfg(any(target_os = "macos",
371 target_os = "netbsd",
372 target_os = "openbsd",
373 target_os = "freebsd",
374 target_os = "dragonfly",
375 target_os = "bitrig"))]
376 fn name_bytes(&self) -> &[u8] {
378 ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
379 self.entry.d_namlen as usize)
382 #[cfg(any(target_os = "android",
384 target_os = "emscripten",
386 target_os = "haiku"))]
387 fn name_bytes(&self) -> &[u8] {
389 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
392 #[cfg(any(target_os = "solaris",
393 target_os = "fuchsia"))]
394 fn name_bytes(&self) -> &[u8] {
400 pub fn new() -> OpenOptions {
415 pub fn read(&mut self, read: bool) { self.read = read; }
416 pub fn write(&mut self, write: bool) { self.write = write; }
417 pub fn append(&mut self, append: bool) { self.append = append; }
418 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
419 pub fn create(&mut self, create: bool) { self.create = create; }
420 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
422 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
423 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
425 fn get_access_mode(&self) -> io::Result<c_int> {
426 match (self.read, self.write, self.append) {
427 (true, false, false) => Ok(libc::O_RDONLY),
428 (false, true, false) => Ok(libc::O_WRONLY),
429 (true, true, false) => Ok(libc::O_RDWR),
430 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
431 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
432 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
436 fn get_creation_mode(&self) -> io::Result<c_int> {
437 match (self.write, self.append) {
440 if self.truncate || self.create || self.create_new {
441 return Err(Error::from_raw_os_error(libc::EINVAL));
444 if self.truncate && !self.create_new {
445 return Err(Error::from_raw_os_error(libc::EINVAL));
449 Ok(match (self.create, self.truncate, self.create_new) {
450 (false, false, false) => 0,
451 (true, false, false) => libc::O_CREAT,
452 (false, true, false) => libc::O_TRUNC,
453 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
454 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
460 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
461 let path = cstr(path)?;
462 File::open_c(&path, opts)
465 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
466 let flags = libc::O_CLOEXEC |
467 opts.get_access_mode()? |
468 opts.get_creation_mode()? |
469 (opts.custom_flags as c_int & !libc::O_ACCMODE);
470 let fd = cvt_r(|| unsafe {
471 open64(path.as_ptr(), flags, opts.mode as c_int)
473 let fd = FileDesc::new(fd);
475 // Currently the standard library supports Linux 2.6.18 which did not
476 // have the O_CLOEXEC flag (passed above). If we're running on an older
477 // Linux kernel then the flag is just ignored by the OS. After we open
478 // the first file, we check whether it has CLOEXEC set. If it doesn't,
479 // we will explicitly ask for a CLOEXEC fd for every further file we
480 // open, if it does, we will skip that step.
482 // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
483 // that we support, so we only do this on Linux currently.
484 #[cfg(target_os = "linux")]
485 fn ensure_cloexec(fd: &FileDesc) -> io::Result<()> {
486 use sync::atomic::{AtomicUsize, Ordering};
488 const OPEN_CLOEXEC_UNKNOWN: usize = 0;
489 const OPEN_CLOEXEC_SUPPORTED: usize = 1;
490 const OPEN_CLOEXEC_NOTSUPPORTED: usize = 2;
491 static OPEN_CLOEXEC: AtomicUsize = AtomicUsize::new(OPEN_CLOEXEC_UNKNOWN);
494 match OPEN_CLOEXEC.load(Ordering::Relaxed) {
495 OPEN_CLOEXEC_UNKNOWN => {
496 need_to_set = !fd.get_cloexec()?;
497 OPEN_CLOEXEC.store(if need_to_set {
498 OPEN_CLOEXEC_NOTSUPPORTED
500 OPEN_CLOEXEC_SUPPORTED
501 }, Ordering::Relaxed);
503 OPEN_CLOEXEC_SUPPORTED => need_to_set = false,
504 OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true,
513 #[cfg(not(target_os = "linux"))]
514 fn ensure_cloexec(_: &FileDesc) -> io::Result<()> {
518 ensure_cloexec(&fd)?;
522 pub fn file_attr(&self) -> io::Result<FileAttr> {
523 let mut stat: stat64 = unsafe { mem::zeroed() };
525 fstat64(self.0.raw(), &mut stat)
527 Ok(FileAttr { stat: stat })
530 pub fn fsync(&self) -> io::Result<()> {
531 cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
535 pub fn datasync(&self) -> io::Result<()> {
536 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
539 #[cfg(any(target_os = "macos", target_os = "ios"))]
540 unsafe fn os_datasync(fd: c_int) -> c_int {
541 libc::fcntl(fd, libc::F_FULLFSYNC)
543 #[cfg(target_os = "linux")]
544 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
545 #[cfg(not(any(target_os = "macos",
547 target_os = "linux")))]
548 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
551 pub fn truncate(&self, size: u64) -> io::Result<()> {
552 #[cfg(target_os = "android")]
553 return ::sys::android::ftruncate64(self.0.raw(), size);
555 #[cfg(not(target_os = "android"))]
556 return cvt_r(|| unsafe {
557 ftruncate64(self.0.raw(), size as off64_t)
561 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
565 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
566 self.0.read_at(buf, offset)
569 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
573 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
574 self.0.write_at(buf, offset)
577 pub fn flush(&self) -> io::Result<()> { Ok(()) }
579 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
580 let (whence, pos) = match pos {
581 // Casting to `i64` is fine, too large values will end up as
582 // negative which will cause an error in `lseek64`.
583 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
584 SeekFrom::End(off) => (libc::SEEK_END, off),
585 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
587 #[cfg(target_os = "emscripten")]
588 let pos = pos as i32;
589 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
593 pub fn duplicate(&self) -> io::Result<File> {
594 self.0.duplicate().map(File)
597 pub fn fd(&self) -> &FileDesc { &self.0 }
599 pub fn into_fd(self) -> FileDesc { self.0 }
601 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
602 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
608 pub fn new() -> DirBuilder {
609 DirBuilder { mode: 0o777 }
612 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
614 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
618 pub fn set_mode(&mut self, mode: u32) {
619 self.mode = mode as mode_t;
623 fn cstr(path: &Path) -> io::Result<CString> {
624 Ok(CString::new(path.as_os_str().as_bytes())?)
627 impl FromInner<c_int> for File {
628 fn from_inner(fd: c_int) -> File {
629 File(FileDesc::new(fd))
633 impl fmt::Debug for File {
634 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
635 #[cfg(target_os = "linux")]
636 fn get_path(fd: c_int) -> Option<PathBuf> {
637 let mut p = PathBuf::from("/proc/self/fd");
638 p.push(&fd.to_string());
642 #[cfg(target_os = "macos")]
643 fn get_path(fd: c_int) -> Option<PathBuf> {
644 // FIXME: The use of PATH_MAX is generally not encouraged, but it
645 // is inevitable in this case because macOS defines `fcntl` with
646 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
647 // alternatives. If a better method is invented, it should be used
649 let mut buf = vec![0;libc::PATH_MAX as usize];
650 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
654 let l = buf.iter().position(|&c| c == 0).unwrap();
655 buf.truncate(l as usize);
657 Some(PathBuf::from(OsString::from_vec(buf)))
660 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
661 fn get_path(_fd: c_int) -> Option<PathBuf> {
662 // FIXME(#24570): implement this for other Unix platforms
666 #[cfg(any(target_os = "linux", target_os = "macos"))]
667 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
668 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
672 match mode & libc::O_ACCMODE {
673 libc::O_RDONLY => Some((true, false)),
674 libc::O_RDWR => Some((true, true)),
675 libc::O_WRONLY => Some((false, true)),
680 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
681 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
682 // FIXME(#24570): implement this for other Unix platforms
686 let fd = self.0.raw();
687 let mut b = f.debug_struct("File");
689 if let Some(path) = get_path(fd) {
690 b.field("path", &path);
692 if let Some((read, write)) = get_mode(fd) {
693 b.field("read", &read).field("write", &write);
699 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
700 let root = p.to_path_buf();
703 let ptr = libc::opendir(p.as_ptr());
705 Err(Error::last_os_error())
707 let inner = InnerReadDir { dirp: Dir(ptr), root };
709 inner: Arc::new(inner),
710 end_of_stream: false,
716 pub fn unlink(p: &Path) -> io::Result<()> {
718 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
722 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
723 let old = cstr(old)?;
724 let new = cstr(new)?;
725 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
729 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
731 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
735 pub fn rmdir(p: &Path) -> io::Result<()> {
737 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
741 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
742 let filetype = lstat(path)?.file_type();
743 if filetype.is_symlink() {
746 remove_dir_all_recursive(path)
750 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
751 for child in readdir(path)? {
753 if child.file_type()?.is_dir() {
754 remove_dir_all_recursive(&child.path())?;
756 unlink(&child.path())?;
762 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
763 let c_path = cstr(p)?;
764 let p = c_path.as_ptr();
766 let mut buf = Vec::with_capacity(256);
769 let buf_read = cvt(unsafe {
770 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
773 unsafe { buf.set_len(buf_read); }
775 if buf_read != buf.capacity() {
778 return Ok(PathBuf::from(OsString::from_vec(buf)));
781 // Trigger the internal buffer resizing logic of `Vec` by requiring
782 // more space than the current capacity. The length is guaranteed to be
783 // the same as the capacity due to the if statement above.
788 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
789 let src = cstr(src)?;
790 let dst = cstr(dst)?;
791 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
795 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
796 let src = cstr(src)?;
797 let dst = cstr(dst)?;
798 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
802 pub fn stat(p: &Path) -> io::Result<FileAttr> {
804 let mut stat: stat64 = unsafe { mem::zeroed() };
806 stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
808 Ok(FileAttr { stat: stat })
811 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
813 let mut stat: stat64 = unsafe { mem::zeroed() };
815 lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
817 Ok(FileAttr { stat: stat })
820 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
821 let path = CString::new(p.as_os_str().as_bytes())?;
824 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
826 return Err(io::Error::last_os_error())
828 buf = CStr::from_ptr(r).to_bytes().to_vec();
829 libc::free(r as *mut _);
831 Ok(PathBuf::from(OsString::from_vec(buf)))
834 #[cfg(not(any(target_os = "linux", target_os = "android")))]
835 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
838 return Err(Error::new(ErrorKind::InvalidInput,
839 "the source path is not an existing regular file"))
842 let mut reader = File::open(from)?;
843 let mut writer = File::create(to)?;
844 let perm = reader.metadata()?.permissions();
846 let ret = io::copy(&mut reader, &mut writer)?;
847 writer.set_permissions(perm)?;
851 #[cfg(any(target_os = "linux", target_os = "android"))]
852 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
855 use sync::atomic::{AtomicBool, Ordering};
857 // Kernel prior to 4.5 don't have copy_file_range
858 // We store the availability in a global to avoid unneccessary syscalls
859 static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
861 unsafe fn copy_file_range(
863 off_in: *mut libc::loff_t,
865 off_out: *mut libc::loff_t,
870 libc::SYS_copy_file_range,
881 return Err(Error::new(ErrorKind::InvalidInput,
882 "the source path is not an existing regular file"))
885 let mut reader = File::open(from)?;
886 let mut writer = File::create(to)?;
888 let metadata = reader.metadata()?;
889 (metadata.permissions(), metadata.size())
892 let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
893 let mut written = 0u64;
894 while written < len {
895 let copy_result = if has_copy_file_range {
896 let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
897 let copy_result = unsafe {
898 // We actually don't have to adjust the offsets,
899 // because copy_file_range adjusts the file offset automatically
900 cvt(copy_file_range(reader.as_raw_fd(),
908 if let Err(ref copy_err) = copy_result {
909 match copy_err.raw_os_error() {
910 Some(libc::ENOSYS) | Some(libc::EPERM) => {
911 HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
918 Err(io::Error::from_raw_os_error(libc::ENOSYS))
921 Ok(ret) => written += ret as u64,
923 match err.raw_os_error() {
924 Some(os_err) if os_err == libc::ENOSYS
925 || os_err == libc::EXDEV
926 || os_err == libc::EPERM => {
927 // Try fallback io::copy if either:
928 // - Kernel version is < 4.5 (ENOSYS)
929 // - Files are mounted on different fs (EXDEV)
930 // - copy_file_range is disallowed, for example by seccomp (EPERM)
931 assert_eq!(written, 0);
932 let ret = io::copy(&mut reader, &mut writer)?;
933 writer.set_permissions(perm)?;
936 _ => return Err(err),
941 writer.set_permissions(perm)?;