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 //! Blocking posix-based file I/O
14 use libc::{mod, c_int, c_void};
15 use std::c_str::CString;
17 use std::rt::rtio::{mod, IoResult};
19 use io::{retry, keep_going};
22 pub type fd_t = libc::c_int;
34 /// Create a `FileDesc` from an open C file descriptor.
36 /// The `FileDesc` will take ownership of the specified file descriptor and
37 /// close it upon destruction if the `close_on_drop` flag is true, otherwise
38 /// it will not close the file descriptor when this `FileDesc` is dropped.
40 /// Note that all I/O operations done on this object will be *blocking*, but
41 /// they do not require the runtime to be active.
42 pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
43 FileDesc { inner: Arc::new(Inner {
45 close_on_drop: close_on_drop
49 // FIXME(#10465) these functions should not be public, but anything in
50 // native::io wanting to use them is forced to have all the
51 // rtio traits in scope
52 pub fn inner_read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
53 let ret = retry(|| unsafe {
55 buf.as_mut_ptr() as *mut libc::c_void,
56 buf.len() as libc::size_t)
61 Err(super::last_error())
66 pub fn inner_write(&mut self, buf: &[u8]) -> IoResult<()> {
67 let ret = keep_going(buf, |buf, len| {
69 libc::write(self.fd(), buf as *const libc::c_void,
70 len as libc::size_t) as i64
74 Err(super::last_error())
80 pub fn fd(&self) -> fd_t { self.inner.fd }
83 impl rtio::RtioFileStream for FileDesc {
84 fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
85 self.inner_read(buf).map(|i| i as int)
87 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
90 fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
91 match retry(|| unsafe {
92 libc::pread(self.fd(), buf.as_ptr() as *mut _,
93 buf.len() as libc::size_t,
94 offset as libc::off_t)
96 -1 => Err(super::last_error()),
100 fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
101 super::mkerr_libc(retry(|| unsafe {
102 libc::pwrite(self.fd(), buf.as_ptr() as *const _,
103 buf.len() as libc::size_t, offset as libc::off_t)
106 fn seek(&mut self, pos: i64, whence: rtio::SeekStyle) -> IoResult<u64> {
107 let whence = match whence {
108 rtio::SeekSet => libc::SEEK_SET,
109 rtio::SeekEnd => libc::SEEK_END,
110 rtio::SeekCur => libc::SEEK_CUR,
112 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
114 Err(super::last_error())
119 fn tell(&self) -> IoResult<u64> {
120 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
122 Err(super::last_error())
127 fn fsync(&mut self) -> IoResult<()> {
128 super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
130 fn datasync(&mut self) -> IoResult<()> {
131 return super::mkerr_libc(os_datasync(self.fd()));
133 #[cfg(any(target_os = "macos", target_os = "ios"))]
134 fn os_datasync(fd: c_int) -> c_int {
135 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
137 #[cfg(target_os = "linux")]
138 fn os_datasync(fd: c_int) -> c_int {
139 retry(|| unsafe { libc::fdatasync(fd) })
141 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
142 fn os_datasync(fd: c_int) -> c_int {
143 retry(|| unsafe { libc::fsync(fd) })
146 fn truncate(&mut self, offset: i64) -> IoResult<()> {
147 super::mkerr_libc(retry(|| unsafe {
148 libc::ftruncate(self.fd(), offset as libc::off_t)
152 fn fstat(&mut self) -> IoResult<rtio::FileStat> {
153 let mut stat: libc::stat = unsafe { mem::zeroed() };
154 match unsafe { libc::fstat(self.fd(), &mut stat) } {
155 0 => Ok(mkstat(&stat)),
156 _ => Err(super::last_error()),
161 impl rtio::RtioPipe for FileDesc {
162 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
165 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
166 self.inner_write(buf)
168 fn clone(&self) -> Box<rtio::RtioPipe + Send> {
169 box FileDesc { inner: self.inner.clone() } as Box<rtio::RtioPipe + Send>
172 // Only supported on named pipes currently. Note that this doesn't have an
173 // impact on the std::io primitives, this is never called via
174 // std::io::PipeStream. If the functionality is exposed in the future, then
175 // these methods will need to be implemented.
176 fn close_read(&mut self) -> IoResult<()> {
179 fn close_write(&mut self) -> IoResult<()> {
182 fn set_timeout(&mut self, _t: Option<u64>) {}
183 fn set_read_timeout(&mut self, _t: Option<u64>) {}
184 fn set_write_timeout(&mut self, _t: Option<u64>) {}
187 impl rtio::RtioTTY for FileDesc {
188 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
191 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
192 self.inner_write(buf)
194 fn set_raw(&mut self, _raw: bool) -> IoResult<()> {
197 fn get_winsize(&mut self) -> IoResult<(int, int)> {
200 fn isatty(&self) -> bool { false }
203 impl Drop for Inner {
205 // closing stdio file handles makes no sense, so never do it. Also, note
206 // that errors are ignored when closing a file descriptor. The reason
207 // for this is that if an error occurs we don't actually know if the
208 // file descriptor was closed or not, and if we retried (for something
209 // like EINTR), we might close another valid file descriptor (opened
210 // after we closed ours.
211 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
212 let n = unsafe { libc::close(self.fd) };
214 println!("error {} when closing file descriptor {}", n,
222 file: *mut libc::FILE,
227 /// Create a `CFile` from an open `FILE` pointer.
229 /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
231 pub fn new(file: *mut libc::FILE) -> CFile {
234 fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
238 pub fn flush(&mut self) -> IoResult<()> {
239 super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
243 impl rtio::RtioFileStream for CFile {
244 fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
245 let ret = keep_going(buf, |buf, len| {
247 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
254 Err(super::last_error())
260 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
261 let ret = keep_going(buf, |buf, len| {
263 libc::fwrite(buf as *const libc::c_void, 1, len as libc::size_t,
268 Err(super::last_error())
274 fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
275 self.flush().and_then(|()| self.fd.pread(buf, offset))
277 fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
278 self.flush().and_then(|()| self.fd.pwrite(buf, offset))
280 fn seek(&mut self, pos: i64, style: rtio::SeekStyle) -> IoResult<u64> {
281 let whence = match style {
282 rtio::SeekSet => libc::SEEK_SET,
283 rtio::SeekEnd => libc::SEEK_END,
284 rtio::SeekCur => libc::SEEK_CUR,
286 let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
288 Err(super::last_error())
293 fn tell(&self) -> IoResult<u64> {
294 let ret = unsafe { libc::ftell(self.file) };
296 Err(super::last_error())
301 fn fsync(&mut self) -> IoResult<()> {
302 self.flush().and_then(|()| self.fd.fsync())
304 fn datasync(&mut self) -> IoResult<()> {
305 self.flush().and_then(|()| self.fd.datasync())
307 fn truncate(&mut self, offset: i64) -> IoResult<()> {
308 self.flush().and_then(|()| self.fd.truncate(offset))
311 fn fstat(&mut self) -> IoResult<rtio::FileStat> {
312 self.flush().and_then(|()| self.fd.fstat())
316 impl Drop for CFile {
318 unsafe { let _ = libc::fclose(self.file); }
322 pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess)
323 -> IoResult<FileDesc>
325 let flags = match fm {
327 rtio::Append => libc::O_APPEND,
328 rtio::Truncate => libc::O_TRUNC,
330 // Opening with a write permission must silently create the file.
331 let (flags, mode) = match fa {
332 rtio::Read => (flags | libc::O_RDONLY, 0),
333 rtio::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
334 libc::S_IRUSR | libc::S_IWUSR),
335 rtio::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
336 libc::S_IRUSR | libc::S_IWUSR),
339 match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
340 -1 => Err(super::last_error()),
341 fd => Ok(FileDesc::new(fd, true)),
345 pub fn mkdir(p: &CString, mode: uint) -> IoResult<()> {
346 super::mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
349 pub fn readdir(p: &CString) -> IoResult<Vec<CString>> {
350 use libc::{dirent_t};
351 use libc::{opendir, readdir_r, closedir};
353 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<CString> {
354 let root = unsafe { CString::new(root.as_ptr(), false) };
355 let root = Path::new(root);
357 dirs.into_iter().filter(|path| {
358 path.as_vec() != b"." && path.as_vec() != b".."
359 }).map(|path| root.join(path).to_c_str()).collect()
363 fn rust_dirent_t_size() -> libc::c_int;
364 fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
367 let size = unsafe { rust_dirent_t_size() };
368 let mut buf = Vec::<u8>::with_capacity(size as uint);
369 let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
371 let dir_ptr = unsafe {opendir(p.as_ptr())};
373 if dir_ptr as uint != 0 {
374 let mut paths = vec!();
375 let mut entry_ptr = 0 as *mut dirent_t;
376 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
377 if entry_ptr.is_null() { break }
379 CString::new(rust_list_dir_val(entry_ptr), false)
381 paths.push(Path::new(cstr));
383 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
386 Err(super::last_error())
390 pub fn unlink(p: &CString) -> IoResult<()> {
391 super::mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
394 pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
395 super::mkerr_libc(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })
398 pub fn chmod(p: &CString, mode: uint) -> IoResult<()> {
399 super::mkerr_libc(retry(|| unsafe {
400 libc::chmod(p.as_ptr(), mode as libc::mode_t)
404 pub fn rmdir(p: &CString) -> IoResult<()> {
405 super::mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
408 pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
409 super::mkerr_libc(retry(|| unsafe {
410 libc::chown(p.as_ptr(), uid as libc::uid_t,
415 pub fn readlink(p: &CString) -> IoResult<CString> {
417 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
419 len = 1024; // FIXME: read PATH_MAX from C ffi?
421 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
423 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
424 len as libc::size_t) as libc::c_int
426 -1 => Err(super::last_error()),
429 unsafe { buf.set_len(n as uint); }
430 Ok(buf.as_slice().to_c_str())
435 pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
436 super::mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
439 pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
440 super::mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
443 fn mkstat(stat: &libc::stat) -> rtio::FileStat {
444 // FileStat times are in milliseconds
445 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
447 #[cfg(not(any(target_os = "linux", target_os = "android")))]
448 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
449 #[cfg(any(target_os = "linux", target_os = "android"))]
450 fn flags(_stat: &libc::stat) -> u64 { 0 }
452 #[cfg(not(any(target_os = "linux", target_os = "android")))]
453 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
454 #[cfg(any(target_os = "linux", target_os = "android"))]
455 fn gen(_stat: &libc::stat) -> u64 { 0 }
458 size: stat.st_size as u64,
459 kind: stat.st_mode as u64,
460 perm: stat.st_mode as u64,
461 created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
462 modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
463 accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
464 device: stat.st_dev as u64,
465 inode: stat.st_ino as u64,
466 rdev: stat.st_rdev as u64,
467 nlink: stat.st_nlink as u64,
468 uid: stat.st_uid as u64,
469 gid: stat.st_gid as u64,
470 blksize: stat.st_blksize as u64,
471 blocks: stat.st_blocks as u64,
477 pub fn stat(p: &CString) -> IoResult<rtio::FileStat> {
478 let mut stat: libc::stat = unsafe { mem::zeroed() };
479 match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
480 0 => Ok(mkstat(&stat)),
481 _ => Err(super::last_error()),
485 pub fn lstat(p: &CString) -> IoResult<rtio::FileStat> {
486 let mut stat: libc::stat = unsafe { mem::zeroed() };
487 match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
488 0 => Ok(mkstat(&stat)),
489 _ => Err(super::last_error()),
493 pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
494 let buf = libc::utimbuf {
495 actime: (atime / 1000) as libc::time_t,
496 modtime: (mtime / 1000) as libc::time_t,
498 super::mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
503 use super::{CFile, FileDesc};
506 use std::rt::rtio::{RtioFileStream, SeekSet};
508 #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
510 fn test_file_desc() {
511 // Run this test with some pipes so we don't have to mess around with
512 // opening or closing files.
513 let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
514 let mut reader = FileDesc::new(reader, true);
515 let mut writer = FileDesc::new(writer, true);
517 writer.inner_write(b"test").ok().unwrap();
518 let mut buf = [0u8, ..4];
519 match reader.inner_read(buf) {
521 assert_eq!(buf[0], 't' as u8);
522 assert_eq!(buf[1], 'e' as u8);
523 assert_eq!(buf[2], 's' as u8);
524 assert_eq!(buf[3], 't' as u8);
526 r => fail!("invalid read: {:?}", r)
529 assert!(writer.inner_read(buf).is_err());
530 assert!(reader.inner_write(buf).is_err());
536 let f = libc::tmpfile();
537 assert!(!f.is_null());
538 let mut file = CFile::new(f);
540 file.write(b"test").ok().unwrap();
541 let mut buf = [0u8, ..4];
542 let _ = file.seek(0, SeekSet).ok().unwrap();
543 match file.read(buf) {
545 assert_eq!(buf[0], 't' as u8);
546 assert_eq!(buf[1], 'e' as u8);
547 assert_eq!(buf[2], 's' as u8);
548 assert_eq!(buf[3], 't' as u8);
550 r => fail!("invalid read: {:?}", r)