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.
13 use os::unix::prelude::*;
15 use ffi::{CString, CStr, OsString, OsStr};
17 use io::{self, Error, ErrorKind, SeekFrom};
18 use libc::{self, c_int, mode_t};
20 use path::{Path, PathBuf};
23 use sys::fd::FileDesc;
24 use sys::time::SystemTime;
25 use sys::{cvt, cvt_r};
26 use sys_common::{AsInner, FromInner};
28 #[cfg(target_os = "linux")]
29 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r};
30 #[cfg(not(target_os = "linux"))]
31 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
32 ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64};
33 #[cfg(not(any(target_os = "linux", target_os = "solaris")))]
34 use libc::{readdir_r as readdir64_r};
36 pub struct File(FileDesc);
48 struct Dir(*mut libc::DIR);
50 unsafe impl Send for Dir {}
51 unsafe impl Sync for Dir {}
56 // We need to store an owned copy of the directory name
57 // on Solaris because a) it uses a zero-length array to
58 // store the name, b) its lifetime between readdir calls
60 #[cfg(target_os = "solaris")]
65 pub struct OpenOptions {
78 #[derive(Clone, PartialEq, Eq, Debug)]
79 pub struct FilePermissions { mode: mode_t }
81 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
82 pub struct FileType { mode: mode_t }
84 pub struct DirBuilder { mode: mode_t }
87 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
88 pub fn perm(&self) -> FilePermissions {
89 FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
92 pub fn file_type(&self) -> FileType {
93 FileType { mode: self.stat.st_mode as mode_t }
97 #[cfg(any(target_os = "ios", target_os = "macos"))]
98 // FIXME: update SystemTime to store a timespec and don't lose precision
100 pub fn modified(&self) -> io::Result<SystemTime> {
101 Ok(SystemTime::from(libc::timeval {
102 tv_sec: self.stat.st_mtime,
103 tv_usec: (self.stat.st_mtime_nsec / 1000) as libc::suseconds_t,
107 pub fn accessed(&self) -> io::Result<SystemTime> {
108 Ok(SystemTime::from(libc::timeval {
109 tv_sec: self.stat.st_atime,
110 tv_usec: (self.stat.st_atime_nsec / 1000) as libc::suseconds_t,
114 pub fn created(&self) -> io::Result<SystemTime> {
115 Ok(SystemTime::from(libc::timeval {
116 tv_sec: self.stat.st_birthtime,
117 tv_usec: (self.stat.st_birthtime_nsec / 1000) as libc::suseconds_t,
122 #[cfg(not(any(target_os = "ios", target_os = "macos")))]
124 pub fn modified(&self) -> io::Result<SystemTime> {
125 Ok(SystemTime::from(libc::timespec {
126 tv_sec: self.stat.st_mtime as libc::time_t,
127 tv_nsec: self.stat.st_mtime_nsec as libc::c_long,
131 pub fn accessed(&self) -> io::Result<SystemTime> {
132 Ok(SystemTime::from(libc::timespec {
133 tv_sec: self.stat.st_atime as libc::time_t,
134 tv_nsec: self.stat.st_atime_nsec as libc::c_long,
138 #[cfg(any(target_os = "bitrig",
139 target_os = "freebsd",
140 target_os = "openbsd"))]
141 pub fn created(&self) -> io::Result<SystemTime> {
142 Ok(SystemTime::from(libc::timespec {
143 tv_sec: self.stat.st_birthtime as libc::time_t,
144 tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
148 #[cfg(not(any(target_os = "bitrig",
149 target_os = "freebsd",
150 target_os = "openbsd")))]
151 pub fn created(&self) -> io::Result<SystemTime> {
152 Err(io::Error::new(io::ErrorKind::Other,
153 "creation time is not available on this platform \
158 impl AsInner<stat64> for FileAttr {
159 fn as_inner(&self) -> &stat64 { &self.stat }
162 impl FilePermissions {
163 pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
164 pub fn set_readonly(&mut self, readonly: bool) {
171 pub fn mode(&self) -> u32 { self.mode as u32 }
175 pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
176 pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
177 pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
179 pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
182 impl FromInner<u32> for FilePermissions {
183 fn from_inner(mode: u32) -> FilePermissions {
184 FilePermissions { mode: mode as mode_t }
188 impl Iterator for ReadDir {
189 type Item = io::Result<DirEntry>;
191 #[cfg(target_os = "solaris")]
192 fn next(&mut self) -> Option<io::Result<DirEntry>> {
195 // Although readdir_r(3) would be a correct function to use here because
196 // of the thread safety, on Illumos the readdir(3C) function is safe to use
197 // in threaded applications and it is generally preferred over the
198 // readdir_r(3C) function.
199 let entry_ptr = libc::readdir(self.dirp.0);
200 if entry_ptr.is_null() {
204 let name = (*entry_ptr).d_name.as_ptr();
205 let namelen = libc::strlen(name) as usize;
209 name: ::slice::from_raw_parts(name as *const u8,
210 namelen as usize).to_owned().into_boxed_slice(),
211 root: self.root.clone()
213 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
220 #[cfg(not(target_os = "solaris"))]
221 fn next(&mut self) -> Option<io::Result<DirEntry>> {
223 let mut ret = DirEntry {
224 entry: mem::zeroed(),
225 root: self.root.clone()
227 let mut entry_ptr = ptr::null_mut();
229 if readdir64_r(self.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
230 return Some(Err(Error::last_os_error()))
232 if entry_ptr.is_null() {
235 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
245 let r = unsafe { libc::closedir(self.0) };
246 debug_assert_eq!(r, 0);
251 pub fn path(&self) -> PathBuf {
252 self.root.join(OsStr::from_bytes(self.name_bytes()))
255 pub fn file_name(&self) -> OsString {
256 OsStr::from_bytes(self.name_bytes()).to_os_string()
259 pub fn metadata(&self) -> io::Result<FileAttr> {
263 #[cfg(target_os = "solaris")]
264 pub fn file_type(&self) -> io::Result<FileType> {
265 stat(&self.path()).map(|m| m.file_type())
268 #[cfg(not(target_os = "solaris"))]
269 pub fn file_type(&self) -> io::Result<FileType> {
270 match self.entry.d_type {
271 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
272 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
273 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
274 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
275 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
276 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
277 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
278 _ => lstat(&self.path()).map(|m| m.file_type()),
282 #[cfg(any(target_os = "macos",
285 target_os = "emscripten",
286 target_os = "android",
287 target_os = "solaris"))]
288 pub fn ino(&self) -> u64 {
289 self.entry.d_ino as u64
292 #[cfg(any(target_os = "freebsd",
293 target_os = "openbsd",
294 target_os = "bitrig",
295 target_os = "netbsd",
296 target_os = "dragonfly"))]
297 pub fn ino(&self) -> u64 {
298 self.entry.d_fileno as u64
301 #[cfg(any(target_os = "macos",
303 target_os = "netbsd",
304 target_os = "openbsd",
305 target_os = "freebsd",
306 target_os = "dragonfly",
307 target_os = "bitrig"))]
308 fn name_bytes(&self) -> &[u8] {
310 ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
311 self.entry.d_namlen as usize)
314 #[cfg(any(target_os = "android",
316 target_os = "emscripten"))]
317 fn name_bytes(&self) -> &[u8] {
319 CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
322 #[cfg(target_os = "solaris")]
323 fn name_bytes(&self) -> &[u8] {
329 pub fn new() -> OpenOptions {
344 pub fn read(&mut self, read: bool) { self.read = read; }
345 pub fn write(&mut self, write: bool) { self.write = write; }
346 pub fn append(&mut self, append: bool) { self.append = append; }
347 pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
348 pub fn create(&mut self, create: bool) { self.create = create; }
349 pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
351 pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
352 pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
354 fn get_access_mode(&self) -> io::Result<c_int> {
355 match (self.read, self.write, self.append) {
356 (true, false, false) => Ok(libc::O_RDONLY),
357 (false, true, false) => Ok(libc::O_WRONLY),
358 (true, true, false) => Ok(libc::O_RDWR),
359 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
360 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
361 (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
365 fn get_creation_mode(&self) -> io::Result<c_int> {
366 match (self.write, self.append) {
369 if self.truncate || self.create || self.create_new {
370 return Err(Error::from_raw_os_error(libc::EINVAL));
373 if self.truncate && !self.create_new {
374 return Err(Error::from_raw_os_error(libc::EINVAL));
378 Ok(match (self.create, self.truncate, self.create_new) {
379 (false, false, false) => 0,
380 (true, false, false) => libc::O_CREAT,
381 (false, true, false) => libc::O_TRUNC,
382 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
383 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
389 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
390 let path = try!(cstr(path));
391 File::open_c(&path, opts)
394 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
395 let flags = libc::O_CLOEXEC |
396 try!(opts.get_access_mode()) |
397 try!(opts.get_creation_mode()) |
398 (opts.custom_flags as c_int & !libc::O_ACCMODE);
399 let fd = try!(cvt_r(|| unsafe {
400 libc::open(path.as_ptr(), flags, opts.mode as c_int)
402 let fd = FileDesc::new(fd);
404 // Currently the standard library supports Linux 2.6.18 which did not
405 // have the O_CLOEXEC flag (passed above). If we're running on an older
406 // Linux kernel then the flag is just ignored by the OS, so we continue
407 // to explicitly ask for a CLOEXEC fd here.
409 // The CLOEXEC flag, however, is supported on versions of OSX/BSD/etc
410 // that we support, so we only do this on Linux currently.
411 if cfg!(target_os = "linux") {
418 pub fn file_attr(&self) -> io::Result<FileAttr> {
419 let mut stat: stat64 = unsafe { mem::zeroed() };
421 fstat64(self.0.raw(), &mut stat)
423 Ok(FileAttr { stat: stat })
426 pub fn fsync(&self) -> io::Result<()> {
427 try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
431 pub fn datasync(&self) -> io::Result<()> {
432 try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
435 #[cfg(any(target_os = "macos", target_os = "ios"))]
436 unsafe fn os_datasync(fd: c_int) -> c_int {
437 libc::fcntl(fd, libc::F_FULLFSYNC)
439 #[cfg(target_os = "linux")]
440 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
441 #[cfg(not(any(target_os = "macos",
443 target_os = "linux")))]
444 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
447 pub fn truncate(&self, size: u64) -> io::Result<()> {
448 try!(cvt_r(|| unsafe {
449 ftruncate64(self.0.raw(), size as off64_t)
454 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
458 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
462 pub fn flush(&self) -> io::Result<()> { Ok(()) }
464 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
465 let (whence, pos) = match pos {
466 SeekFrom::Start(off) => (libc::SEEK_SET, off as off64_t),
467 SeekFrom::End(off) => (libc::SEEK_END, off as off64_t),
468 SeekFrom::Current(off) => (libc::SEEK_CUR, off as off64_t),
470 let n = try!(cvt(unsafe { lseek64(self.0.raw(), pos, whence) }));
474 pub fn duplicate(&self) -> io::Result<File> {
475 self.0.duplicate().map(File)
478 pub fn fd(&self) -> &FileDesc { &self.0 }
480 pub fn into_fd(self) -> FileDesc { self.0 }
484 pub fn new() -> DirBuilder {
485 DirBuilder { mode: 0o777 }
488 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
489 let p = try!(cstr(p));
490 try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }));
494 pub fn set_mode(&mut self, mode: u32) {
495 self.mode = mode as mode_t;
499 fn cstr(path: &Path) -> io::Result<CString> {
500 Ok(try!(CString::new(path.as_os_str().as_bytes())))
503 impl FromInner<c_int> for File {
504 fn from_inner(fd: c_int) -> File {
505 File(FileDesc::new(fd))
509 impl fmt::Debug for File {
510 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
511 #[cfg(target_os = "linux")]
512 fn get_path(fd: c_int) -> Option<PathBuf> {
513 use string::ToString;
514 let mut p = PathBuf::from("/proc/self/fd");
515 p.push(&fd.to_string());
519 #[cfg(target_os = "macos")]
520 fn get_path(fd: c_int) -> Option<PathBuf> {
521 // FIXME: The use of PATH_MAX is generally not encouraged, but it
522 // is inevitable in this case because OS X defines `fcntl` with
523 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
524 // alternatives. If a better method is invented, it should be used
526 let mut buf = vec![0;libc::PATH_MAX as usize];
527 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
531 let l = buf.iter().position(|&c| c == 0).unwrap();
532 buf.truncate(l as usize);
534 Some(PathBuf::from(OsString::from_vec(buf)))
537 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
538 fn get_path(_fd: c_int) -> Option<PathBuf> {
539 // FIXME(#24570): implement this for other Unix platforms
543 #[cfg(any(target_os = "linux", target_os = "macos"))]
544 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
545 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
549 match mode & libc::O_ACCMODE {
550 libc::O_RDONLY => Some((true, false)),
551 libc::O_RDWR => Some((true, true)),
552 libc::O_WRONLY => Some((false, true)),
557 #[cfg(not(any(target_os = "linux", target_os = "macos")))]
558 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
559 // FIXME(#24570): implement this for other Unix platforms
563 let fd = self.0.raw();
564 let mut b = f.debug_struct("File");
566 if let Some(path) = get_path(fd) {
567 b.field("path", &path);
569 if let Some((read, write)) = get_mode(fd) {
570 b.field("read", &read).field("write", &write);
576 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
577 let root = Arc::new(p.to_path_buf());
578 let p = try!(cstr(p));
580 let ptr = libc::opendir(p.as_ptr());
582 Err(Error::last_os_error())
584 Ok(ReadDir { dirp: Dir(ptr), root: root })
589 pub fn unlink(p: &Path) -> io::Result<()> {
590 let p = try!(cstr(p));
591 try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
595 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
596 let old = try!(cstr(old));
597 let new = try!(cstr(new));
598 try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
602 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
603 let p = try!(cstr(p));
604 try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
608 pub fn rmdir(p: &Path) -> io::Result<()> {
609 let p = try!(cstr(p));
610 try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
614 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
615 let filetype = try!(lstat(path)).file_type();
616 if filetype.is_symlink() {
619 remove_dir_all_recursive(path)
623 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
624 for child in try!(readdir(path)) {
625 let child = try!(child);
626 if try!(child.file_type()).is_dir() {
627 try!(remove_dir_all_recursive(&child.path()));
629 try!(unlink(&child.path()));
635 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
636 let c_path = try!(cstr(p));
637 let p = c_path.as_ptr();
639 let mut buf = Vec::with_capacity(256);
642 let buf_read = try!(cvt(unsafe {
643 libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity() as libc::size_t)
646 unsafe { buf.set_len(buf_read); }
648 if buf_read != buf.capacity() {
651 return Ok(PathBuf::from(OsString::from_vec(buf)));
654 // Trigger the internal buffer resizing logic of `Vec` by requiring
655 // more space than the current capacity. The length is guaranteed to be
656 // the same as the capacity due to the if statement above.
661 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
662 let src = try!(cstr(src));
663 let dst = try!(cstr(dst));
664 try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
668 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
669 let src = try!(cstr(src));
670 let dst = try!(cstr(dst));
671 try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
675 pub fn stat(p: &Path) -> io::Result<FileAttr> {
676 let p = try!(cstr(p));
677 let mut stat: stat64 = unsafe { mem::zeroed() };
679 stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
681 Ok(FileAttr { stat: stat })
684 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
685 let p = try!(cstr(p));
686 let mut stat: stat64 = unsafe { mem::zeroed() };
688 lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
690 Ok(FileAttr { stat: stat })
693 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
694 let path = try!(CString::new(p.as_os_str().as_bytes()));
697 let r = libc::realpath(path.as_ptr(), ptr::null_mut());
699 return Err(io::Error::last_os_error())
701 buf = CStr::from_ptr(r).to_bytes().to_vec();
702 libc::free(r as *mut _);
704 Ok(PathBuf::from(OsString::from_vec(buf)))
707 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
708 use fs::{File, set_permissions};
710 return Err(Error::new(ErrorKind::InvalidInput,
711 "the source path is not an existing regular file"))
714 let mut reader = try!(File::open(from));
715 let mut writer = try!(File::create(to));
716 let perm = try!(reader.metadata()).permissions();
718 let ret = try!(io::copy(&mut reader, &mut writer));
719 try!(set_permissions(to, perm));