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", target_os = "android"))]
29 use libc::{fstatat, dirfd};
30 #[cfg(target_os = "android")]
31 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, lseek64,
32 dirent as dirent64, open as open64};
33 #[cfg(not(any(target_os = "linux",
34 target_os = "emscripten",
36 target_os = "android")))]
37 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
38 ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
39 #[cfg(not(any(target_os = "linux",
40 target_os = "emscripten",
41 target_os = "solaris",
43 target_os = "fuchsia")))]
44 use libc::{readdir_r as readdir64_r};
46 pub struct File(FileDesc);
53 // all DirEntry's will have a reference to this struct
60 pub struct ReadDir(Arc<InnerReadDir>);
62 struct Dir(*mut libc::DIR);
64 unsafe impl Send for Dir {}
65 unsafe impl Sync for Dir {}
70 // We need to store an owned copy of the entry name
71 // on Solaris and Fuchsia because a) it uses a zero-length
72 // array to store the name, b) its lifetime between readdir
73 // calls is not guaranteed.
74 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
78 #[derive(Clone, Debug)]
79 pub struct OpenOptions {
92 #[derive(Clone, PartialEq, Eq, Debug)]
93 pub struct FilePermissions { mode: mode_t }
95 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
96 pub struct FileType { mode: mode_t }
99 pub struct DirBuilder { mode: mode_t }
102 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
103 pub fn perm(&self) -> FilePermissions {
104 FilePermissions { mode: (self.stat.st_mode as mode_t) }
107 pub fn file_type(&self) -> FileType {
108 FileType { mode: self.stat.st_mode as mode_t }
112 #[cfg(target_os = "netbsd")]
114 pub fn modified(&self) -> io::Result<SystemTime> {
115 Ok(SystemTime::from(libc::timespec {
116 tv_sec: self.stat.st_mtime as libc::time_t,
117 tv_nsec: self.stat.st_mtimensec as libc::c_long,
121 pub fn accessed(&self) -> io::Result<SystemTime> {
122 Ok(SystemTime::from(libc::timespec {
123 tv_sec: self.stat.st_atime as libc::time_t,
124 tv_nsec: self.stat.st_atimensec as libc::c_long,
128 pub fn created(&self) -> io::Result<SystemTime> {
129 Ok(SystemTime::from(libc::timespec {
130 tv_sec: self.stat.st_birthtime as libc::time_t,
131 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
136 #[cfg(not(target_os = "netbsd"))]
138 pub fn modified(&self) -> io::Result<SystemTime> {
139 Ok(SystemTime::from(libc::timespec {
140 tv_sec: self.stat.st_mtime as libc::time_t,
141 tv_nsec: self.stat.st_mtime_nsec as _,
145 pub fn accessed(&self) -> io::Result<SystemTime> {
146 Ok(SystemTime::from(libc::timespec {
147 tv_sec: self.stat.st_atime as libc::time_t,
148 tv_nsec: self.stat.st_atime_nsec as _,
152 #[cfg(any(target_os = "bitrig",
153 target_os = "freebsd",
154 target_os = "openbsd",
157 pub fn created(&self) -> io::Result<SystemTime> {
158 Ok(SystemTime::from(libc::timespec {
159 tv_sec: self.stat.st_birthtime as libc::time_t,
160 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
164 #[cfg(not(any(target_os = "bitrig",
165 target_os = "freebsd",
166 target_os = "openbsd",
168 target_os = "ios")))]
169 pub fn created(&self) -> io::Result<SystemTime> {
170 Err(io::Error::new(io::ErrorKind::Other,
171 "creation time is not available on this platform \
176 impl AsInner<stat64> for FileAttr {
177 fn as_inner(&self) -> &stat64 { &self.stat }
180 impl FilePermissions {
181 pub fn readonly(&self) -> bool {
182 // check if any class (owner, group, others) has write permission
183 self.mode & 0o222 == 0
186 pub fn set_readonly(&mut self, readonly: bool) {
188 // remove write permission for all classes; equivalent to `chmod a-w <file>`
191 // add write permission for all classes; equivalent to `chmod a+w <file>`
195 pub fn mode(&self) -> u32 { self.mode as u32 }
199 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
200 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
201 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
203 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
206 impl FromInner<u32> for FilePermissions {
207 fn from_inner(mode: u32) -> FilePermissions {
208 FilePermissions { mode: mode as mode_t }
212 impl fmt::Debug for ReadDir {
213 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
214 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
215 // Thus the result will be e g 'ReadDir("/home")'
216 fmt::Debug::fmt(&*self.0.root, f)
220 impl Iterator for ReadDir {
221 type Item = io::Result<DirEntry>;
223 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
224 fn next(&mut self) -> Option<io::Result<DirEntry>> {
227 // Although readdir_r(3) would be a correct function to use here because
228 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
229 // is safe to use in threaded applications and it is generally preferred
230 // over the readdir_r(3C) function.
231 super::os::set_errno(0);
232 let entry_ptr = libc::readdir(self.0.dirp.0);
233 if entry_ptr.is_null() {
234 // NULL can mean either the end is reached or an error occurred.
235 // So we had to clear errno beforehand to check for an error now.
236 return match super::os::errno() {
238 e => Some(Err(Error::from_raw_os_error(e))),
242 let name = (*entry_ptr).d_name.as_ptr();
243 let namelen = libc::strlen(name) as usize;
247 name: ::slice::from_raw_parts(name as *const u8,
248 namelen as usize).to_owned().into_boxed_slice(),
251 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
258 #[cfg(not(any(target_os = "solaris", target_os = "fuchsia")))]
259 fn next(&mut self) -> Option<io::Result<DirEntry>> {
261 let mut ret = DirEntry {
262 entry: mem::zeroed(),
265 let mut entry_ptr = ptr::null_mut();
267 if readdir64_r(self.0.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
268 return Some(Err(Error::last_os_error()))
270 if entry_ptr.is_null() {
273 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
283 let r = unsafe { libc::closedir(self.0) };
284 debug_assert_eq!(r, 0);
289 pub fn path(&self) -> PathBuf {
290 self.dir.0.root.join(OsStr::from_bytes(self.name_bytes()))
293 pub fn file_name(&self) -> OsString {
294 OsStr::from_bytes(self.name_bytes()).to_os_string()
297 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
298 pub fn metadata(&self) -> io::Result<FileAttr> {
299 let fd = cvt(unsafe {dirfd(self.dir.0.dirp.0)})?;
300 let mut stat: stat64 = unsafe { mem::zeroed() };
303 self.entry.d_name.as_ptr(),
304 &mut stat as *mut _ as *mut _,
305 libc::AT_SYMLINK_NOFOLLOW)
307 Ok(FileAttr { stat: stat })
310 #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
311 pub fn metadata(&self) -> io::Result<FileAttr> {
315 #[cfg(any(target_os = "solaris", target_os = "haiku"))]
316 pub fn file_type(&self) -> io::Result<FileType> {
317 lstat(&self.path()).map(|m| m.file_type())
320 #[cfg(not(any(target_os = "solaris", target_os = "haiku")))]
321 pub fn file_type(&self) -> io::Result<FileType> {
322 match self.entry.d_type {
323 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
324 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
325 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
326 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
327 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
328 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
329 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
330 _ => lstat(&self.path()).map(|m| m.file_type()),
334 #[cfg(any(target_os = "macos",
337 target_os = "emscripten",
338 target_os = "android",
339 target_os = "solaris",
342 target_os = "fuchsia"))]
343 pub fn ino(&self) -> u64 {
344 self.entry.d_ino as u64
347 #[cfg(any(target_os = "freebsd",
348 target_os = "openbsd",
349 target_os = "bitrig",
350 target_os = "netbsd",
351 target_os = "dragonfly"))]
352 pub fn ino(&self) -> u64 {
353 self.entry.d_fileno as u64
356 #[cfg(any(target_os = "macos",
358 target_os = "netbsd",
359 target_os = "openbsd",
360 target_os = "freebsd",
361 target_os = "dragonfly",
362 target_os = "bitrig"))]
363 fn name_bytes(&self) -> &[u8] {
365 ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
366 self.entry.d_namlen as usize)
369 #[cfg(any(target_os = "android",
371 target_os = "emscripten",
373 target_os = "haiku"))]
374 fn name_bytes(&self) -> &[u8] {
376 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
379 #[cfg(any(target_os = "solaris",
380 target_os = "fuchsia"))]
381 fn name_bytes(&self) -> &[u8] {
387 pub fn new() -> OpenOptions {
402 pub fn read(&mut self, read: bool) { self.read = read; }
403 pub fn write(&mut self, write: bool) { self.write = write; }
404 pub fn append(&mut self, append: bool) { self.append = append; }
405 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
406 pub fn create(&mut self, create: bool) { self.create = create; }
407 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
409 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
410 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
412 fn get_access_mode(&self) -> io::Result<c_int> {
413 match (self.read, self.write, self.append) {
414 (true, false, false) => Ok(libc::O_RDONLY),
415 (false, true, false) => Ok(libc::O_WRONLY),
416 (true, true, false) => Ok(libc::O_RDWR),
417 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
418 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
419 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
423 fn get_creation_mode(&self) -> io::Result<c_int> {
424 match (self.write, self.append) {
427 if self.truncate || self.create || self.create_new {
428 return Err(Error::from_raw_os_error(libc::EINVAL));
431 if self.truncate && !self.create_new {
432 return Err(Error::from_raw_os_error(libc::EINVAL));
436 Ok(match (self.create, self.truncate, self.create_new) {
437 (false, false, false) => 0,
438 (true, false, false) => libc::O_CREAT,
439 (false, true, false) => libc::O_TRUNC,
440 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
441 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
447 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
448 let path = cstr(path)?;
449 File::open_c(&path, opts)
452 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
453 let flags = libc::O_CLOEXEC |
454 opts.get_access_mode()? |
455 opts.get_creation_mode()? |
456 (opts.custom_flags as c_int & !libc::O_ACCMODE);
457 let fd = cvt_r(|| unsafe {
458 open64(path.as_ptr(), flags, opts.mode as c_int)
460 let fd = FileDesc::new(fd);
462 // Currently the standard library supports Linux 2.6.18 which did not
463 // have the O_CLOEXEC flag (passed above). If we're running on an older
464 // Linux kernel then the flag is just ignored by the OS. After we open
465 // the first file, we check whether it has CLOEXEC set. If it doesn't,
466 // we will explicitly ask for a CLOEXEC fd for every further file we
467 // open, if it does, we will skip that step.
469 // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
470 // that we support, so we only do this on Linux currently.
471 #[cfg(target_os = "linux")]
472 fn ensure_cloexec(fd: &FileDesc) -> io::Result<()> {
473 use sync::atomic::{AtomicUsize, Ordering};
475 const OPEN_CLOEXEC_UNKNOWN: usize = 0;
476 const OPEN_CLOEXEC_SUPPORTED: usize = 1;
477 const OPEN_CLOEXEC_NOTSUPPORTED: usize = 2;
478 static OPEN_CLOEXEC: AtomicUsize = AtomicUsize::new(OPEN_CLOEXEC_UNKNOWN);
481 match OPEN_CLOEXEC.load(Ordering::Relaxed) {
482 OPEN_CLOEXEC_UNKNOWN => {
483 need_to_set = !fd.get_cloexec()?;
484 OPEN_CLOEXEC.store(if need_to_set {
485 OPEN_CLOEXEC_NOTSUPPORTED
487 OPEN_CLOEXEC_SUPPORTED
488 }, Ordering::Relaxed);
490 OPEN_CLOEXEC_SUPPORTED => need_to_set = false,
491 OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true,
500 #[cfg(not(target_os = "linux"))]
501 fn ensure_cloexec(_: &FileDesc) -> io::Result<()> {
505 ensure_cloexec(&fd)?;
509 pub fn file_attr(&self) -> io::Result<FileAttr> {
510 let mut stat: stat64 = unsafe { mem::zeroed() };
512 fstat64(self.0.raw(), &mut stat)
514 Ok(FileAttr { stat: stat })
517 pub fn fsync(&self) -> io::Result<()> {
518 cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
522 pub fn datasync(&self) -> io::Result<()> {
523 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
526 #[cfg(any(target_os = "macos", target_os = "ios"))]
527 unsafe fn os_datasync(fd: c_int) -> c_int {
528 libc::fcntl(fd, libc::F_FULLFSYNC)
530 #[cfg(target_os = "linux")]
531 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
532 #[cfg(not(any(target_os = "macos",
534 target_os = "linux")))]
535 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
538 pub fn truncate(&self, size: u64) -> io::Result<()> {
539 #[cfg(target_os = "android")]
540 return ::sys::android::ftruncate64(self.0.raw(), size);
542 #[cfg(not(target_os = "android"))]
543 return cvt_r(|| unsafe {
544 ftruncate64(self.0.raw(), size as off64_t)
548 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
552 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
553 self.0.read_at(buf, offset)
556 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
560 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
561 self.0.write_at(buf, offset)
564 pub fn flush(&self) -> io::Result<()> { Ok(()) }
566 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
567 let (whence, pos) = match pos {
568 // Casting to `i64` is fine, too large values will end up as
569 // negative which will cause an error in `lseek64`.
570 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
571 SeekFrom::End(off) => (libc::SEEK_END, off),
572 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
574 #[cfg(target_os = "emscripten")]
575 let pos = pos as i32;
576 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
580 pub fn duplicate(&self) -> io::Result<File> {
581 self.0.duplicate().map(File)
584 pub fn fd(&self) -> &FileDesc { &self.0 }
586 pub fn into_fd(self) -> FileDesc { self.0 }
588 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
589 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
595 pub fn new() -> DirBuilder {
596 DirBuilder { mode: 0o777 }
599 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
601 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
605 pub fn set_mode(&mut self, mode: u32) {
606 self.mode = mode as mode_t;
610 fn cstr(path: &Path) -> io::Result<CString> {
611 Ok(CString::new(path.as_os_str().as_bytes())?)
614 impl FromInner<c_int> for File {
615 fn from_inner(fd: c_int) -> File {
616 File(FileDesc::new(fd))
620 impl fmt::Debug for File {
621 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
622 #[cfg(target_os = "linux")]
623 fn get_path(fd: c_int) -> Option<PathBuf> {
624 let mut p = PathBuf::from("/proc/self/fd");
625 p.push(&fd.to_string());
629 #[cfg(target_os = "macos")]
630 fn get_path(fd: c_int) -> Option<PathBuf> {
631 // FIXME: The use of PATH_MAX is generally not encouraged, but it
632 // is inevitable in this case because macOS defines `fcntl` with
633 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
634 // alternatives. If a better method is invented, it should be used
636 let mut buf = vec![0;libc::PATH_MAX as usize];
637 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
641 let l = buf.iter().position(|&c| c == 0).unwrap();
642 buf.truncate(l as usize);
644 Some(PathBuf::from(OsString::from_vec(buf)))
647 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
648 fn get_path(_fd: c_int) -> Option<PathBuf> {
649 // FIXME(#24570): implement this for other Unix platforms
653 #[cfg(any(target_os = "linux", target_os = "macos"))]
654 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
655 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
659 match mode & libc::O_ACCMODE {
660 libc::O_RDONLY => Some((true, false)),
661 libc::O_RDWR => Some((true, true)),
662 libc::O_WRONLY => Some((false, true)),
667 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
668 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
669 // FIXME(#24570): implement this for other Unix platforms
673 let fd = self.0.raw();
674 let mut b = f.debug_struct("File");
676 if let Some(path) = get_path(fd) {
677 b.field("path", &path);
679 if let Some((read, write)) = get_mode(fd) {
680 b.field("read", &read).field("write", &write);
686 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
687 let root = p.to_path_buf();
690 let ptr = libc::opendir(p.as_ptr());
692 Err(Error::last_os_error())
694 let inner = InnerReadDir { dirp: Dir(ptr), root };
695 Ok(ReadDir(Arc::new(inner)))
700 pub fn unlink(p: &Path) -> io::Result<()> {
702 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
706 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
707 let old = cstr(old)?;
708 let new = cstr(new)?;
709 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
713 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
715 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
719 pub fn rmdir(p: &Path) -> io::Result<()> {
721 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
725 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
726 let filetype = lstat(path)?.file_type();
727 if filetype.is_symlink() {
730 remove_dir_all_recursive(path)
734 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
735 for child in readdir(path)? {
737 if child.file_type()?.is_dir() {
738 remove_dir_all_recursive(&child.path())?;
740 unlink(&child.path())?;
746 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
747 let c_path = cstr(p)?;
748 let p = c_path.as_ptr();
750 let mut buf = Vec::with_capacity(256);
753 let buf_read = cvt(unsafe {
754 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
757 unsafe { buf.set_len(buf_read); }
759 if buf_read != buf.capacity() {
762 return Ok(PathBuf::from(OsString::from_vec(buf)));
765 // Trigger the internal buffer resizing logic of `Vec` by requiring
766 // more space than the current capacity. The length is guaranteed to be
767 // the same as the capacity due to the if statement above.
772 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
773 let src = cstr(src)?;
774 let dst = cstr(dst)?;
775 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
779 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
780 let src = cstr(src)?;
781 let dst = cstr(dst)?;
782 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
786 pub fn stat(p: &Path) -> io::Result<FileAttr> {
788 let mut stat: stat64 = unsafe { mem::zeroed() };
790 stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
792 Ok(FileAttr { stat: stat })
795 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
797 let mut stat: stat64 = unsafe { mem::zeroed() };
799 lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
801 Ok(FileAttr { stat: stat })
804 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
805 let path = CString::new(p.as_os_str().as_bytes())?;
808 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
810 return Err(io::Error::last_os_error())
812 buf = CStr::from_ptr(r).to_bytes().to_vec();
813 libc::free(r as *mut _);
815 Ok(PathBuf::from(OsString::from_vec(buf)))
818 #[cfg(not(any(target_os = "linux", target_os = "android")))]
819 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
820 use fs::{File, set_permissions};
822 return Err(Error::new(ErrorKind::InvalidInput,
823 "the source path is not an existing regular file"))
826 let mut reader = File::open(from)?;
827 let mut writer = File::create(to)?;
828 let perm = reader.metadata()?.permissions();
830 let ret = io::copy(&mut reader, &mut writer)?;
831 set_permissions(to, perm)?;
835 #[cfg(any(target_os = "linux", target_os = "android"))]
836 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
838 use fs::{File, set_permissions};
839 use sync::atomic::{AtomicBool, Ordering};
841 // Kernel prior to 4.5 don't have copy_file_range
842 // We store the availability in a global to avoid unneccessary syscalls
843 static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
845 unsafe fn copy_file_range(
847 off_in: *mut libc::loff_t,
849 off_out: *mut libc::loff_t,
854 libc::SYS_copy_file_range,
865 return Err(Error::new(ErrorKind::InvalidInput,
866 "the source path is not an existing regular file"))
869 let mut reader = File::open(from)?;
870 let mut writer = File::create(to)?;
872 let metadata = reader.metadata()?;
873 (metadata.permissions(), metadata.size())
876 let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
877 let mut written = 0u64;
878 while written < len {
879 let copy_result = if has_copy_file_range {
880 let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
881 let copy_result = unsafe {
882 // We actually don't have to adjust the offsets,
883 // because copy_file_range adjusts the file offset automatically
884 cvt(copy_file_range(reader.as_raw_fd(),
892 if let Err(ref copy_err) = copy_result {
893 if let Some(libc::ENOSYS) = copy_err.raw_os_error() {
894 HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
899 Err(io::Error::from_raw_os_error(libc::ENOSYS))
902 Ok(ret) => written += ret as u64,
904 match err.raw_os_error() {
905 Some(os_err) if os_err == libc::ENOSYS || os_err == libc::EXDEV => {
906 // Either kernel is too old or the files are not mounted on the same fs.
907 // Try again with fallback method
908 assert_eq!(written, 0);
909 let ret = io::copy(&mut reader, &mut writer)?;
910 set_permissions(to, perm)?;
913 _ => return Err(err),
918 set_permissions(to, perm)?;