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, SeekFrom};
18 use libc::{self, c_int, size_t, off_t, c_char, mode_t};
20 use path::{Path, PathBuf};
23 use sys::fd::FileDesc;
24 use sys::{c, cvt, cvt_r};
25 use sys_common::FromInner;
28 pub struct File(FileDesc);
39 struct Dir(*mut libc::DIR);
41 unsafe impl Send for Dir {}
42 unsafe impl Sync for Dir {}
45 buf: Vec<u8>, // actually *mut libc::dirent_t
50 pub struct OpenOptions {
57 #[derive(Clone, PartialEq, Eq, Debug)]
58 pub struct FilePermissions { mode: mode_t }
61 pub fn is_dir(&self) -> bool {
62 (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFDIR
64 pub fn is_file(&self) -> bool {
65 (self.stat.st_mode as mode_t) & libc::S_IFMT == libc::S_IFREG
67 pub fn size(&self) -> u64 { self.stat.st_size as u64 }
68 pub fn perm(&self) -> FilePermissions {
69 FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
72 pub fn accessed(&self) -> u64 {
73 self.mktime(self.stat.st_atime as u64, self.stat.st_atime_nsec as u64)
75 pub fn modified(&self) -> u64 {
76 self.mktime(self.stat.st_mtime as u64, self.stat.st_mtime_nsec as u64)
79 // times are in milliseconds (currently)
80 fn mktime(&self, secs: u64, nsecs: u64) -> u64 {
81 secs * 1000 + nsecs / 1000000
85 impl FilePermissions {
86 pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
87 pub fn set_readonly(&mut self, readonly: bool) {
94 pub fn mode(&self) -> i32 { self.mode as i32 }
97 impl FromInner<i32> for FilePermissions {
98 fn from_inner(mode: i32) -> FilePermissions {
99 FilePermissions { mode: mode as mode_t }
103 impl Iterator for ReadDir {
104 type Item = io::Result<DirEntry>;
106 fn next(&mut self) -> Option<io::Result<DirEntry>> {
108 fn rust_dirent_t_size() -> c_int;
111 let mut buf: Vec<u8> = Vec::with_capacity(unsafe {
112 rust_dirent_t_size() as usize
114 let ptr = buf.as_mut_ptr() as *mut libc::dirent_t;
116 let mut entry_ptr = ptr::null_mut();
118 if unsafe { libc::readdir_r(self.dirp.0, ptr, &mut entry_ptr) != 0 } {
119 return Some(Err(Error::last_os_error()))
121 if entry_ptr.is_null() {
125 let entry = DirEntry {
127 root: self.root.clone()
129 if entry.name_bytes() == b"." || entry.name_bytes() == b".." {
132 return Some(Ok(entry))
140 let r = unsafe { libc::closedir(self.0) };
141 debug_assert_eq!(r, 0);
146 pub fn path(&self) -> PathBuf {
147 self.root.join(<OsStr as OsStrExt>::from_bytes(self.name_bytes()))
150 fn name_bytes(&self) -> &[u8] {
152 fn rust_list_dir_val(ptr: *mut libc::dirent_t) -> *const c_char;
155 CStr::from_ptr(rust_list_dir_val(self.dirent())).to_bytes()
159 fn dirent(&self) -> *mut libc::dirent_t {
160 self.buf.as_ptr() as *mut _
165 pub fn new() -> OpenOptions {
174 pub fn read(&mut self, read: bool) {
178 pub fn write(&mut self, write: bool) {
182 pub fn append(&mut self, append: bool) {
183 self.flag(libc::O_APPEND, append);
186 pub fn truncate(&mut self, truncate: bool) {
187 self.flag(libc::O_TRUNC, truncate);
190 pub fn create(&mut self, create: bool) {
191 self.flag(libc::O_CREAT, create);
194 pub fn mode(&mut self, mode: i32) {
195 self.mode = mode as mode_t;
198 fn flag(&mut self, bit: c_int, on: bool) {
208 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
209 let path = try!(cstr(path));
210 File::open_c(&path, opts)
213 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
214 let flags = opts.flags | match (opts.read, opts.write) {
215 (true, true) => libc::O_RDWR,
216 (false, true) => libc::O_WRONLY,
218 (false, false) => libc::O_RDONLY,
220 let fd = try!(cvt_r(|| unsafe {
221 libc::open(path.as_ptr(), flags, opts.mode)
223 let fd = FileDesc::new(fd);
228 pub fn into_fd(self) -> FileDesc { self.0 }
230 pub fn file_attr(&self) -> io::Result<FileAttr> {
231 let mut stat: libc::stat = unsafe { mem::zeroed() };
232 try!(cvt(unsafe { libc::fstat(self.0.raw(), &mut stat) }));
233 Ok(FileAttr { stat: stat })
236 pub fn fsync(&self) -> io::Result<()> {
237 try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
241 pub fn datasync(&self) -> io::Result<()> {
242 try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
245 #[cfg(any(target_os = "macos", target_os = "ios"))]
246 unsafe fn os_datasync(fd: c_int) -> c_int {
247 libc::fcntl(fd, libc::F_FULLFSYNC)
249 #[cfg(target_os = "linux")]
250 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
251 #[cfg(not(any(target_os = "macos",
253 target_os = "linux")))]
254 unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
257 pub fn truncate(&self, size: u64) -> io::Result<()> {
258 try!(cvt_r(|| unsafe {
259 libc::ftruncate(self.0.raw(), size as libc::off_t)
264 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
268 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
272 pub fn flush(&self) -> io::Result<()> { Ok(()) }
274 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
275 let (whence, pos) = match pos {
276 SeekFrom::Start(off) => (libc::SEEK_SET, off as off_t),
277 SeekFrom::End(off) => (libc::SEEK_END, off as off_t),
278 SeekFrom::Current(off) => (libc::SEEK_CUR, off as off_t),
280 let n = try!(cvt(unsafe { libc::lseek(self.0.raw(), pos, whence) }));
284 pub fn fd(&self) -> &FileDesc { &self.0 }
287 fn cstr(path: &Path) -> io::Result<CString> {
288 path.as_os_str().to_cstring().ok_or(
289 io::Error::new(io::ErrorKind::InvalidInput, "path contained a null"))
292 impl FromInner<c_int> for File {
293 fn from_inner(fd: c_int) -> File {
294 File(FileDesc::new(fd))
298 impl fmt::Debug for File {
299 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
300 #[cfg(target_os = "linux")]
301 fn get_path(fd: c_int) -> Option<PathBuf> {
302 use string::ToString;
303 let mut p = PathBuf::from("/proc/self/fd");
304 p.push(&fd.to_string());
308 #[cfg(not(target_os = "linux"))]
309 fn get_path(_fd: c_int) -> Option<PathBuf> {
310 // FIXME(#24570): implement this for other Unix platforms
314 #[cfg(target_os = "linux")]
315 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
316 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
320 match mode & libc::O_ACCMODE {
321 libc::O_RDONLY => Some((true, false)),
322 libc::O_RDWR => Some((true, true)),
323 libc::O_WRONLY => Some((false, true)),
328 #[cfg(not(target_os = "linux"))]
329 fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
330 // FIXME(#24570): implement this for other Unix platforms
334 let fd = self.0.raw();
335 let mut b = f.debug_struct("File").field("fd", &fd);
336 if let Some(path) = get_path(fd) {
337 b = b.field("path", &path);
339 if let Some((read, write)) = get_mode(fd) {
340 b = b.field("read", &read).field("write", &write);
346 pub fn mkdir(p: &Path) -> io::Result<()> {
347 let p = try!(cstr(p));
348 try!(cvt(unsafe { libc::mkdir(p.as_ptr(), 0o777) }));
352 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
353 let root = Arc::new(p.to_path_buf());
354 let p = try!(cstr(p));
356 let ptr = libc::opendir(p.as_ptr());
358 Err(Error::last_os_error())
360 Ok(ReadDir { dirp: Dir(ptr), root: root })
365 pub fn unlink(p: &Path) -> io::Result<()> {
366 let p = try!(cstr(p));
367 try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
371 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
372 let old = try!(cstr(old));
373 let new = try!(cstr(new));
374 try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
378 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
379 let p = try!(cstr(p));
380 try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
384 pub fn rmdir(p: &Path) -> io::Result<()> {
385 let p = try!(cstr(p));
386 try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
390 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
391 let c_path = try!(cstr(p));
392 let p = c_path.as_ptr();
393 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
395 len = 1024; // FIXME: read PATH_MAX from C ffi?
397 let mut buf: Vec<u8> = Vec::with_capacity(len as usize);
400 libc::readlink(p, buf.as_ptr() as *mut c_char, len as size_t)
402 buf.set_len(n as usize);
404 Ok(PathBuf::from(OsString::from_vec(buf)))
407 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
408 let src = try!(cstr(src));
409 let dst = try!(cstr(dst));
410 try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
414 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
415 let src = try!(cstr(src));
416 let dst = try!(cstr(dst));
417 try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
421 pub fn stat(p: &Path) -> io::Result<FileAttr> {
422 let p = try!(cstr(p));
423 let mut stat: libc::stat = unsafe { mem::zeroed() };
424 try!(cvt(unsafe { libc::stat(p.as_ptr(), &mut stat) }));
425 Ok(FileAttr { stat: stat })
428 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
429 let p = try!(cstr(p));
430 let mut stat: libc::stat = unsafe { mem::zeroed() };
431 try!(cvt(unsafe { libc::lstat(p.as_ptr(), &mut stat) }));
432 Ok(FileAttr { stat: stat })
435 pub fn utimes(p: &Path, atime: u64, mtime: u64) -> io::Result<()> {
436 let p = try!(cstr(p));
437 let buf = [super::ms_to_timeval(atime), super::ms_to_timeval(mtime)];
438 try!(cvt(unsafe { c::utimes(p.as_ptr(), buf.as_ptr()) }));