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"))]
27 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64};
28 #[cfg(target_os = "android")]
29 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, lseek64,
30 dirent as dirent64, open as open64};
31 #[cfg(not(any(target_os = "linux",
32 target_os = "emscripten",
33 target_os = "android")))]
34 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
35 ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
36 #[cfg(not(any(target_os = "linux",
37 target_os = "emscripten",
38 target_os = "solaris",
39 target_os = "fuchsia")))]
40 use libc::{readdir_r as readdir64_r};
42 pub struct File(FileDesc);
54 struct Dir(*mut libc::DIR);
56 unsafe impl Send for Dir {}
57 unsafe impl Sync for Dir {}
62 // We need to store an owned copy of the directory name
63 // on Solaris and Fuchsia because a) it uses a zero-length
64 // array to store the name, b) its lifetime between readdir
65 // calls is not guaranteed.
66 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
70 #[derive(Clone, Debug)]
71 pub struct OpenOptions {
84 #[derive(Clone, PartialEq, Eq, Debug)]
85 pub struct FilePermissions { mode: mode_t }
87 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
88 pub struct FileType { mode: mode_t }
91 pub struct DirBuilder { mode: mode_t }
94 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
95 pub fn perm(&self) -> FilePermissions {
96 FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
99 pub fn file_type(&self) -> FileType {
100 FileType { mode: self.stat.st_mode as mode_t }
104 #[cfg(target_os = "netbsd")]
106 pub fn modified(&self) -> io::Result<SystemTime> {
107 Ok(SystemTime::from(libc::timespec {
108 tv_sec: self.stat.st_mtime as libc::time_t,
109 tv_nsec: self.stat.st_mtimensec as libc::c_long,
113 pub fn accessed(&self) -> io::Result<SystemTime> {
114 Ok(SystemTime::from(libc::timespec {
115 tv_sec: self.stat.st_atime as libc::time_t,
116 tv_nsec: self.stat.st_atimensec as libc::c_long,
120 pub fn created(&self) -> io::Result<SystemTime> {
121 Ok(SystemTime::from(libc::timespec {
122 tv_sec: self.stat.st_birthtime as libc::time_t,
123 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
128 #[cfg(not(target_os = "netbsd"))]
130 pub fn modified(&self) -> io::Result<SystemTime> {
131 Ok(SystemTime::from(libc::timespec {
132 tv_sec: self.stat.st_mtime as libc::time_t,
133 tv_nsec: self.stat.st_mtime_nsec as libc::c_long,
137 pub fn accessed(&self) -> io::Result<SystemTime> {
138 Ok(SystemTime::from(libc::timespec {
139 tv_sec: self.stat.st_atime as libc::time_t,
140 tv_nsec: self.stat.st_atime_nsec as libc::c_long,
144 #[cfg(any(target_os = "bitrig",
145 target_os = "freebsd",
146 target_os = "openbsd",
149 pub fn created(&self) -> io::Result<SystemTime> {
150 Ok(SystemTime::from(libc::timespec {
151 tv_sec: self.stat.st_birthtime as libc::time_t,
152 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
156 #[cfg(not(any(target_os = "bitrig",
157 target_os = "freebsd",
158 target_os = "openbsd",
160 target_os = "ios")))]
161 pub fn created(&self) -> io::Result<SystemTime> {
162 Err(io::Error::new(io::ErrorKind::Other,
163 "creation time is not available on this platform \
168 impl AsInner<stat64> for FileAttr {
169 fn as_inner(&self) -> &stat64 { &self.stat }
172 impl FilePermissions {
173 pub fn readonly(&self) -> bool {
174 // check if any class (owner, group, others) has write permission
175 self.mode & 0o222 == 0
178 pub fn set_readonly(&mut self, readonly: bool) {
180 // remove write permission for all classes; equivalent to `chmod a-w <file>`
183 // add write permission for all classes; equivalent to `chmod a+w <file>`
187 pub fn mode(&self) -> u32 { self.mode as u32 }
191 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
192 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
193 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
195 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
198 impl FromInner<u32> for FilePermissions {
199 fn from_inner(mode: u32) -> FilePermissions {
200 FilePermissions { mode: mode as mode_t }
204 impl fmt::Debug for ReadDir {
205 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
206 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
207 // Thus the result will be e g 'ReadDir("/home")'
208 fmt::Debug::fmt(&*self.root, f)
212 impl Iterator for ReadDir {
213 type Item = io::Result<DirEntry>;
215 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
216 fn next(&mut self) -> Option<io::Result<DirEntry>> {
219 // Although readdir_r(3) would be a correct function to use here because
220 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
221 // is safe to use in threaded applications and it is generally preferred
222 // over the readdir_r(3C) function.
223 super::os::set_errno(0);
224 let entry_ptr = libc::readdir(self.dirp.0);
225 if entry_ptr.is_null() {
226 // NULL can mean either the end is reached or an error occurred.
227 // So we had to clear errno beforehand to check for an error now.
228 return match super::os::errno() {
230 e => Some(Err(Error::from_raw_os_error(e))),
234 let name = (*entry_ptr).d_name.as_ptr();
235 let namelen = libc::strlen(name) as usize;
239 name: ::slice::from_raw_parts(name as *const u8,
240 namelen as usize).to_owned().into_boxed_slice(),
241 root: self.root.clone()
243 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
250 #[cfg(not(any(target_os = "solaris", target_os = "fuchsia")))]
251 fn next(&mut self) -> Option<io::Result<DirEntry>> {
253 let mut ret = DirEntry {
254 entry: mem::zeroed(),
255 root: self.root.clone()
257 let mut entry_ptr = ptr::null_mut();
259 if readdir64_r(self.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
260 return Some(Err(Error::last_os_error()))
262 if entry_ptr.is_null() {
265 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
275 let r = unsafe { libc::closedir(self.0) };
276 debug_assert_eq!(r, 0);
281 pub fn path(&self) -> PathBuf {
282 self.root.join(OsStr::from_bytes(self.name_bytes()))
285 pub fn file_name(&self) -> OsString {
286 OsStr::from_bytes(self.name_bytes()).to_os_string()
289 pub fn metadata(&self) -> io::Result<FileAttr> {
293 #[cfg(any(target_os = "solaris", target_os = "haiku"))]
294 pub fn file_type(&self) -> io::Result<FileType> {
295 lstat(&self.path()).map(|m| m.file_type())
298 #[cfg(not(any(target_os = "solaris", target_os = "haiku")))]
299 pub fn file_type(&self) -> io::Result<FileType> {
300 match self.entry.d_type {
301 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
302 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
303 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
304 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
305 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
306 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
307 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
308 _ => lstat(&self.path()).map(|m| m.file_type()),
312 #[cfg(any(target_os = "macos",
315 target_os = "emscripten",
316 target_os = "android",
317 target_os = "solaris",
319 target_os = "fuchsia"))]
320 pub fn ino(&self) -> u64 {
321 self.entry.d_ino as u64
324 #[cfg(any(target_os = "freebsd",
325 target_os = "openbsd",
326 target_os = "bitrig",
327 target_os = "netbsd",
328 target_os = "dragonfly"))]
329 pub fn ino(&self) -> u64 {
330 self.entry.d_fileno as u64
333 #[cfg(any(target_os = "macos",
335 target_os = "netbsd",
336 target_os = "openbsd",
337 target_os = "freebsd",
338 target_os = "dragonfly",
339 target_os = "bitrig"))]
340 fn name_bytes(&self) -> &[u8] {
342 ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
343 self.entry.d_namlen as usize)
346 #[cfg(any(target_os = "android",
348 target_os = "emscripten",
349 target_os = "haiku"))]
350 fn name_bytes(&self) -> &[u8] {
352 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
355 #[cfg(any(target_os = "solaris",
356 target_os = "fuchsia"))]
357 fn name_bytes(&self) -> &[u8] {
363 pub fn new() -> OpenOptions {
378 pub fn read(&mut self, read: bool) { self.read = read; }
379 pub fn write(&mut self, write: bool) { self.write = write; }
380 pub fn append(&mut self, append: bool) { self.append = append; }
381 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
382 pub fn create(&mut self, create: bool) { self.create = create; }
383 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
385 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
386 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
388 fn get_access_mode(&self) -> io::Result<c_int> {
389 match (self.read, self.write, self.append) {
390 (true, false, false) => Ok(libc::O_RDONLY),
391 (false, true, false) => Ok(libc::O_WRONLY),
392 (true, true, false) => Ok(libc::O_RDWR),
393 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
394 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
395 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
399 fn get_creation_mode(&self) -> io::Result<c_int> {
400 match (self.write, self.append) {
403 if self.truncate || self.create || self.create_new {
404 return Err(Error::from_raw_os_error(libc::EINVAL));
407 if self.truncate && !self.create_new {
408 return Err(Error::from_raw_os_error(libc::EINVAL));
412 Ok(match (self.create, self.truncate, self.create_new) {
413 (false, false, false) => 0,
414 (true, false, false) => libc::O_CREAT,
415 (false, true, false) => libc::O_TRUNC,
416 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
417 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
423 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
424 let path = cstr(path)?;
425 File::open_c(&path, opts)
428 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
429 let flags = libc::O_CLOEXEC |
430 opts.get_access_mode()? |
431 opts.get_creation_mode()? |
432 (opts.custom_flags as c_int & !libc::O_ACCMODE);
433 let fd = cvt_r(|| unsafe {
434 open64(path.as_ptr(), flags, opts.mode as c_int)
436 let fd = FileDesc::new(fd);
438 // Currently the standard library supports Linux 2.6.18 which did not
439 // have the O_CLOEXEC flag (passed above). If we're running on an older
440 // Linux kernel then the flag is just ignored by the OS, so we continue
441 // to explicitly ask for a CLOEXEC fd here.
443 // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
444 // that we support, so we only do this on Linux currently.
445 if cfg!(target_os = "linux") {
452 pub fn file_attr(&self) -> io::Result<FileAttr> {
453 let mut stat: stat64 = unsafe { mem::zeroed() };
455 fstat64(self.0.raw(), &mut stat)
457 Ok(FileAttr { stat: stat })
460 pub fn fsync(&self) -> io::Result<()> {
461 cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
465 pub fn datasync(&self) -> io::Result<()> {
466 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
469 #[cfg(any(target_os = "macos", target_os = "ios"))]
470 unsafe fn os_datasync(fd: c_int) -> c_int {
471 libc::fcntl(fd, libc::F_FULLFSYNC)
473 #[cfg(target_os = "linux")]
474 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
475 #[cfg(not(any(target_os = "macos",
477 target_os = "linux")))]
478 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
481 pub fn truncate(&self, size: u64) -> io::Result<()> {
482 #[cfg(target_os = "android")]
483 return ::sys::android::ftruncate64(self.0.raw(), size);
485 #[cfg(not(target_os = "android"))]
486 return cvt_r(|| unsafe {
487 ftruncate64(self.0.raw(), size as off64_t)
491 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
495 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
496 self.0.read_at(buf, offset)
499 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
503 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
504 self.0.write_at(buf, offset)
507 pub fn flush(&self) -> io::Result<()> { Ok(()) }
509 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
510 let (whence, pos) = match pos {
511 // Casting to `i64` is fine, too large values will end up as
512 // negative which will cause an error in `lseek64`.
513 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
514 SeekFrom::End(off) => (libc::SEEK_END, off),
515 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
517 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
521 pub fn duplicate(&self) -> io::Result<File> {
522 self.0.duplicate().map(File)
525 pub fn fd(&self) -> &FileDesc { &self.0 }
527 pub fn into_fd(self) -> FileDesc { self.0 }
529 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
530 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
536 pub fn new() -> DirBuilder {
537 DirBuilder { mode: 0o777 }
540 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
542 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
546 pub fn set_mode(&mut self, mode: u32) {
547 self.mode = mode as mode_t;
551 fn cstr(path: &Path) -> io::Result<CString> {
552 Ok(CString::new(path.as_os_str().as_bytes())?)
555 impl FromInner<c_int> for File {
556 fn from_inner(fd: c_int) -> File {
557 File(FileDesc::new(fd))
561 impl fmt::Debug for File {
562 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
563 #[cfg(target_os = "linux")]
564 fn get_path(fd: c_int) -> Option<PathBuf> {
565 let mut p = PathBuf::from("/proc/self/fd");
566 p.push(&fd.to_string());
570 #[cfg(target_os = "macos")]
571 fn get_path(fd: c_int) -> Option<PathBuf> {
572 // FIXME: The use of PATH_MAX is generally not encouraged, but it
573 // is inevitable in this case because macOS defines `fcntl` with
574 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
575 // alternatives. If a better method is invented, it should be used
577 let mut buf = vec![0;libc::PATH_MAX as usize];
578 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
582 let l = buf.iter().position(|&c| c == 0).unwrap();
583 buf.truncate(l as usize);
585 Some(PathBuf::from(OsString::from_vec(buf)))
588 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
589 fn get_path(_fd: c_int) -> Option<PathBuf> {
590 // FIXME(#24570): implement this for other Unix platforms
594 #[cfg(any(target_os = "linux", target_os = "macos"))]
595 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
596 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
600 match mode & libc::O_ACCMODE {
601 libc::O_RDONLY => Some((true, false)),
602 libc::O_RDWR => Some((true, true)),
603 libc::O_WRONLY => Some((false, true)),
608 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
609 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
610 // FIXME(#24570): implement this for other Unix platforms
614 let fd = self.0.raw();
615 let mut b = f.debug_struct("File");
617 if let Some(path) = get_path(fd) {
618 b.field("path", &path);
620 if let Some((read, write)) = get_mode(fd) {
621 b.field("read", &read).field("write", &write);
627 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
628 let root = Arc::new(p.to_path_buf());
631 let ptr = libc::opendir(p.as_ptr());
633 Err(Error::last_os_error())
635 Ok(ReadDir { dirp: Dir(ptr), root: root })
640 pub fn unlink(p: &Path) -> io::Result<()> {
642 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
646 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
647 let old = cstr(old)?;
648 let new = cstr(new)?;
649 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
653 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
655 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
659 pub fn rmdir(p: &Path) -> io::Result<()> {
661 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
665 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
666 let filetype = lstat(path)?.file_type();
667 if filetype.is_symlink() {
670 remove_dir_all_recursive(path)
674 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
675 for child in readdir(path)? {
677 if child.file_type()?.is_dir() {
678 remove_dir_all_recursive(&child.path())?;
680 unlink(&child.path())?;
686 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
687 let c_path = cstr(p)?;
688 let p = c_path.as_ptr();
690 let mut buf = Vec::with_capacity(256);
693 let buf_read = cvt(unsafe {
694 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
697 unsafe { buf.set_len(buf_read); }
699 if buf_read != buf.capacity() {
702 return Ok(PathBuf::from(OsString::from_vec(buf)));
705 // Trigger the internal buffer resizing logic of `Vec` by requiring
706 // more space than the current capacity. The length is guaranteed to be
707 // the same as the capacity due to the if statement above.
712 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
713 let src = cstr(src)?;
714 let dst = cstr(dst)?;
715 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
719 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
720 let src = cstr(src)?;
721 let dst = cstr(dst)?;
722 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
726 pub fn stat(p: &Path) -> io::Result<FileAttr> {
728 let mut stat: stat64 = unsafe { mem::zeroed() };
730 stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
732 Ok(FileAttr { stat: stat })
735 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
737 let mut stat: stat64 = unsafe { mem::zeroed() };
739 lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
741 Ok(FileAttr { stat: stat })
744 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
745 let path = CString::new(p.as_os_str().as_bytes())?;
748 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
750 return Err(io::Error::last_os_error())
752 buf = CStr::from_ptr(r).to_bytes().to_vec();
753 libc::free(r as *mut _);
755 Ok(PathBuf::from(OsString::from_vec(buf)))
758 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
759 use fs::{File, set_permissions};
761 return Err(Error::new(ErrorKind::InvalidInput,
762 "the source path is not an existing regular file"))
765 let mut reader = File::open(from)?;
766 let mut writer = File::create(to)?;
767 let perm = reader.metadata()?.permissions();
769 let ret = io::copy(&mut reader, &mut writer)?;
770 set_permissions(to, perm)?;