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(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",
34 target_os = "android")))]
35 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
36 ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
37 #[cfg(not(any(target_os = "linux",
38 target_os = "emscripten",
39 target_os = "solaris",
41 target_os = "fuchsia")))]
42 use libc::{readdir_r as readdir64_r};
44 pub struct File(FileDesc);
56 struct Dir(*mut libc::DIR);
58 unsafe impl Send for Dir {}
59 unsafe impl Sync for Dir {}
64 // We need to store an owned copy of the directory name
65 // on Solaris and Fuchsia because a) it uses a zero-length
66 // array to store the name, b) its lifetime between readdir
67 // calls is not guaranteed.
68 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
72 #[derive(Clone, Debug)]
73 pub struct OpenOptions {
86 #[derive(Clone, PartialEq, Eq, Debug)]
87 pub struct FilePermissions { mode: mode_t }
89 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
90 pub struct FileType { mode: mode_t }
93 pub struct DirBuilder { mode: mode_t }
96 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
97 pub fn perm(&self) -> FilePermissions {
98 FilePermissions { mode: (self.stat.st_mode as mode_t) }
101 pub fn file_type(&self) -> FileType {
102 FileType { mode: self.stat.st_mode as mode_t }
106 #[cfg(target_os = "netbsd")]
108 pub fn modified(&self) -> io::Result<SystemTime> {
109 Ok(SystemTime::from(libc::timespec {
110 tv_sec: self.stat.st_mtime as libc::time_t,
111 tv_nsec: self.stat.st_mtimensec as libc::c_long,
115 pub fn accessed(&self) -> io::Result<SystemTime> {
116 Ok(SystemTime::from(libc::timespec {
117 tv_sec: self.stat.st_atime as libc::time_t,
118 tv_nsec: self.stat.st_atimensec as libc::c_long,
122 pub fn created(&self) -> io::Result<SystemTime> {
123 Ok(SystemTime::from(libc::timespec {
124 tv_sec: self.stat.st_birthtime as libc::time_t,
125 tv_nsec: self.stat.st_birthtimensec as libc::c_long,
130 #[cfg(not(target_os = "netbsd"))]
132 pub fn modified(&self) -> io::Result<SystemTime> {
133 Ok(SystemTime::from(libc::timespec {
134 tv_sec: self.stat.st_mtime as libc::time_t,
135 tv_nsec: self.stat.st_mtime_nsec as _,
139 pub fn accessed(&self) -> io::Result<SystemTime> {
140 Ok(SystemTime::from(libc::timespec {
141 tv_sec: self.stat.st_atime as libc::time_t,
142 tv_nsec: self.stat.st_atime_nsec as _,
146 #[cfg(any(target_os = "bitrig",
147 target_os = "freebsd",
148 target_os = "openbsd",
151 pub fn created(&self) -> io::Result<SystemTime> {
152 Ok(SystemTime::from(libc::timespec {
153 tv_sec: self.stat.st_birthtime as libc::time_t,
154 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
158 #[cfg(not(any(target_os = "bitrig",
159 target_os = "freebsd",
160 target_os = "openbsd",
162 target_os = "ios")))]
163 pub fn created(&self) -> io::Result<SystemTime> {
164 Err(io::Error::new(io::ErrorKind::Other,
165 "creation time is not available on this platform \
170 impl AsInner<stat64> for FileAttr {
171 fn as_inner(&self) -> &stat64 { &self.stat }
174 impl FilePermissions {
175 pub fn readonly(&self) -> bool {
176 // check if any class (owner, group, others) has write permission
177 self.mode & 0o222 == 0
180 pub fn set_readonly(&mut self, readonly: bool) {
182 // remove write permission for all classes; equivalent to `chmod a-w <file>`
185 // add write permission for all classes; equivalent to `chmod a+w <file>`
189 pub fn mode(&self) -> u32 { self.mode as u32 }
193 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
194 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
195 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
197 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
200 impl FromInner<u32> for FilePermissions {
201 fn from_inner(mode: u32) -> FilePermissions {
202 FilePermissions { mode: mode as mode_t }
206 impl fmt::Debug for ReadDir {
207 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208 // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
209 // Thus the result will be e g 'ReadDir("/home")'
210 fmt::Debug::fmt(&*self.root, f)
214 impl Iterator for ReadDir {
215 type Item = io::Result<DirEntry>;
217 #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
218 fn next(&mut self) -> Option<io::Result<DirEntry>> {
221 // Although readdir_r(3) would be a correct function to use here because
222 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
223 // is safe to use in threaded applications and it is generally preferred
224 // over the readdir_r(3C) function.
225 super::os::set_errno(0);
226 let entry_ptr = libc::readdir(self.dirp.0);
227 if entry_ptr.is_null() {
228 // NULL can mean either the end is reached or an error occurred.
229 // So we had to clear errno beforehand to check for an error now.
230 return match super::os::errno() {
232 e => Some(Err(Error::from_raw_os_error(e))),
236 let name = (*entry_ptr).d_name.as_ptr();
237 let namelen = libc::strlen(name) as usize;
241 name: ::slice::from_raw_parts(name as *const u8,
242 namelen as usize).to_owned().into_boxed_slice(),
243 root: self.root.clone()
245 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
252 #[cfg(not(any(target_os = "solaris", target_os = "fuchsia")))]
253 fn next(&mut self) -> Option<io::Result<DirEntry>> {
255 let mut ret = DirEntry {
256 entry: mem::zeroed(),
257 root: self.root.clone()
259 let mut entry_ptr = ptr::null_mut();
261 if readdir64_r(self.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
262 return Some(Err(Error::last_os_error()))
264 if entry_ptr.is_null() {
267 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
277 let r = unsafe { libc::closedir(self.0) };
278 debug_assert_eq!(r, 0);
283 pub fn path(&self) -> PathBuf {
284 self.root.join(OsStr::from_bytes(self.name_bytes()))
287 pub fn file_name(&self) -> OsString {
288 OsStr::from_bytes(self.name_bytes()).to_os_string()
291 pub fn metadata(&self) -> io::Result<FileAttr> {
295 #[cfg(any(target_os = "solaris", target_os = "haiku"))]
296 pub fn file_type(&self) -> io::Result<FileType> {
297 lstat(&self.path()).map(|m| m.file_type())
300 #[cfg(not(any(target_os = "solaris", target_os = "haiku")))]
301 pub fn file_type(&self) -> io::Result<FileType> {
302 match self.entry.d_type {
303 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
304 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
305 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
306 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
307 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
308 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
309 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
310 _ => lstat(&self.path()).map(|m| m.file_type()),
314 #[cfg(any(target_os = "macos",
317 target_os = "emscripten",
318 target_os = "android",
319 target_os = "solaris",
322 target_os = "fuchsia"))]
323 pub fn ino(&self) -> u64 {
324 self.entry.d_ino as u64
327 #[cfg(any(target_os = "freebsd",
328 target_os = "openbsd",
329 target_os = "bitrig",
330 target_os = "netbsd",
331 target_os = "dragonfly"))]
332 pub fn ino(&self) -> u64 {
333 self.entry.d_fileno as u64
336 #[cfg(any(target_os = "macos",
338 target_os = "netbsd",
339 target_os = "openbsd",
340 target_os = "freebsd",
341 target_os = "dragonfly",
342 target_os = "bitrig"))]
343 fn name_bytes(&self) -> &[u8] {
345 ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
346 self.entry.d_namlen as usize)
349 #[cfg(any(target_os = "android",
351 target_os = "emscripten",
353 target_os = "haiku"))]
354 fn name_bytes(&self) -> &[u8] {
356 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
359 #[cfg(any(target_os = "solaris",
360 target_os = "fuchsia"))]
361 fn name_bytes(&self) -> &[u8] {
367 pub fn new() -> OpenOptions {
382 pub fn read(&mut self, read: bool) { self.read = read; }
383 pub fn write(&mut self, write: bool) { self.write = write; }
384 pub fn append(&mut self, append: bool) { self.append = append; }
385 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
386 pub fn create(&mut self, create: bool) { self.create = create; }
387 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
389 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
390 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
392 fn get_access_mode(&self) -> io::Result<c_int> {
393 match (self.read, self.write, self.append) {
394 (true, false, false) => Ok(libc::O_RDONLY),
395 (false, true, false) => Ok(libc::O_WRONLY),
396 (true, true, false) => Ok(libc::O_RDWR),
397 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
398 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
399 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
403 fn get_creation_mode(&self) -> io::Result<c_int> {
404 match (self.write, self.append) {
407 if self.truncate || self.create || self.create_new {
408 return Err(Error::from_raw_os_error(libc::EINVAL));
411 if self.truncate && !self.create_new {
412 return Err(Error::from_raw_os_error(libc::EINVAL));
416 Ok(match (self.create, self.truncate, self.create_new) {
417 (false, false, false) => 0,
418 (true, false, false) => libc::O_CREAT,
419 (false, true, false) => libc::O_TRUNC,
420 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
421 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
427 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
428 let path = cstr(path)?;
429 File::open_c(&path, opts)
432 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
433 let flags = libc::O_CLOEXEC |
434 opts.get_access_mode()? |
435 opts.get_creation_mode()? |
436 (opts.custom_flags as c_int & !libc::O_ACCMODE);
437 let fd = cvt_r(|| unsafe {
438 open64(path.as_ptr(), flags, opts.mode as c_int)
440 let fd = FileDesc::new(fd);
442 // Currently the standard library supports Linux 2.6.18 which did not
443 // have the O_CLOEXEC flag (passed above). If we're running on an older
444 // Linux kernel then the flag is just ignored by the OS, so we continue
445 // to explicitly ask for a CLOEXEC fd here.
447 // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
448 // that we support, so we only do this on Linux currently.
449 if cfg!(target_os = "linux") {
456 pub fn file_attr(&self) -> io::Result<FileAttr> {
457 let mut stat: stat64 = unsafe { mem::zeroed() };
459 fstat64(self.0.raw(), &mut stat)
461 Ok(FileAttr { stat: stat })
464 pub fn fsync(&self) -> io::Result<()> {
465 cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
469 pub fn datasync(&self) -> io::Result<()> {
470 cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
473 #[cfg(any(target_os = "macos", target_os = "ios"))]
474 unsafe fn os_datasync(fd: c_int) -> c_int {
475 libc::fcntl(fd, libc::F_FULLFSYNC)
477 #[cfg(target_os = "linux")]
478 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
479 #[cfg(not(any(target_os = "macos",
481 target_os = "linux")))]
482 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
485 pub fn truncate(&self, size: u64) -> io::Result<()> {
486 #[cfg(target_os = "android")]
487 return ::sys::android::ftruncate64(self.0.raw(), size);
489 #[cfg(not(target_os = "android"))]
490 return cvt_r(|| unsafe {
491 ftruncate64(self.0.raw(), size as off64_t)
495 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
499 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
500 self.0.read_at(buf, offset)
503 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
507 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
508 self.0.write_at(buf, offset)
511 pub fn flush(&self) -> io::Result<()> { Ok(()) }
513 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
514 let (whence, pos) = match pos {
515 // Casting to `i64` is fine, too large values will end up as
516 // negative which will cause an error in `lseek64`.
517 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
518 SeekFrom::End(off) => (libc::SEEK_END, off),
519 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
521 #[cfg(target_os = "emscripten")]
522 let pos = pos as i32;
523 let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
527 pub fn duplicate(&self) -> io::Result<File> {
528 self.0.duplicate().map(File)
531 pub fn fd(&self) -> &FileDesc { &self.0 }
533 pub fn into_fd(self) -> FileDesc { self.0 }
535 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
536 cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
542 pub fn new() -> DirBuilder {
543 DirBuilder { mode: 0o777 }
546 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
548 cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
552 pub fn set_mode(&mut self, mode: u32) {
553 self.mode = mode as mode_t;
557 fn cstr(path: &Path) -> io::Result<CString> {
558 Ok(CString::new(path.as_os_str().as_bytes())?)
561 impl FromInner<c_int> for File {
562 fn from_inner(fd: c_int) -> File {
563 File(FileDesc::new(fd))
567 impl fmt::Debug for File {
568 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
569 #[cfg(target_os = "linux")]
570 fn get_path(fd: c_int) -> Option<PathBuf> {
571 let mut p = PathBuf::from("/proc/self/fd");
572 p.push(&fd.to_string());
576 #[cfg(target_os = "macos")]
577 fn get_path(fd: c_int) -> Option<PathBuf> {
578 // FIXME: The use of PATH_MAX is generally not encouraged, but it
579 // is inevitable in this case because macOS defines `fcntl` with
580 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
581 // alternatives. If a better method is invented, it should be used
583 let mut buf = vec![0;libc::PATH_MAX as usize];
584 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
588 let l = buf.iter().position(|&c| c == 0).unwrap();
589 buf.truncate(l as usize);
591 Some(PathBuf::from(OsString::from_vec(buf)))
594 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
595 fn get_path(_fd: c_int) -> Option<PathBuf> {
596 // FIXME(#24570): implement this for other Unix platforms
600 #[cfg(any(target_os = "linux", target_os = "macos"))]
601 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
602 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
606 match mode & libc::O_ACCMODE {
607 libc::O_RDONLY => Some((true, false)),
608 libc::O_RDWR => Some((true, true)),
609 libc::O_WRONLY => Some((false, true)),
614 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
615 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
616 // FIXME(#24570): implement this for other Unix platforms
620 let fd = self.0.raw();
621 let mut b = f.debug_struct("File");
623 if let Some(path) = get_path(fd) {
624 b.field("path", &path);
626 if let Some((read, write)) = get_mode(fd) {
627 b.field("read", &read).field("write", &write);
633 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
634 let root = Arc::new(p.to_path_buf());
637 let ptr = libc::opendir(p.as_ptr());
639 Err(Error::last_os_error())
641 Ok(ReadDir { dirp: Dir(ptr), root: root })
646 pub fn unlink(p: &Path) -> io::Result<()> {
648 cvt(unsafe { libc::unlink(p.as_ptr()) })?;
652 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
653 let old = cstr(old)?;
654 let new = cstr(new)?;
655 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
659 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
661 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
665 pub fn rmdir(p: &Path) -> io::Result<()> {
667 cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
671 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
672 let filetype = lstat(path)?.file_type();
673 if filetype.is_symlink() {
676 remove_dir_all_recursive(path)
680 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
681 for child in readdir(path)? {
683 if child.file_type()?.is_dir() {
684 remove_dir_all_recursive(&child.path())?;
686 unlink(&child.path())?;
692 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
693 let c_path = cstr(p)?;
694 let p = c_path.as_ptr();
696 let mut buf = Vec::with_capacity(256);
699 let buf_read = cvt(unsafe {
700 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
703 unsafe { buf.set_len(buf_read); }
705 if buf_read != buf.capacity() {
708 return Ok(PathBuf::from(OsString::from_vec(buf)));
711 // Trigger the internal buffer resizing logic of `Vec` by requiring
712 // more space than the current capacity. The length is guaranteed to be
713 // the same as the capacity due to the if statement above.
718 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
719 let src = cstr(src)?;
720 let dst = cstr(dst)?;
721 cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
725 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
726 let src = cstr(src)?;
727 let dst = cstr(dst)?;
728 cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
732 pub fn stat(p: &Path) -> io::Result<FileAttr> {
734 let mut stat: stat64 = unsafe { mem::zeroed() };
736 stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
738 Ok(FileAttr { stat: stat })
741 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
743 let mut stat: stat64 = unsafe { mem::zeroed() };
745 lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
747 Ok(FileAttr { stat: stat })
750 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
751 let path = CString::new(p.as_os_str().as_bytes())?;
754 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
756 return Err(io::Error::last_os_error())
758 buf = CStr::from_ptr(r).to_bytes().to_vec();
759 libc::free(r as *mut _);
761 Ok(PathBuf::from(OsString::from_vec(buf)))
764 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
765 use fs::{File, set_permissions};
767 return Err(Error::new(ErrorKind::InvalidInput,
768 "the source path is not an existing regular file"))
771 let mut reader = File::open(from)?;
772 let mut writer = File::create(to)?;
773 let perm = reader.metadata()?.permissions();
775 let ret = io::copy(&mut reader, &mut writer)?;
776 set_permissions(to, perm)?;