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::{c_int, c_void};
16 use std::c_str::CString;
19 use std::rt::rtio::IoResult;
21 use io::{retry, keep_going};
24 pub type fd_t = libc::c_int;
36 /// Create a `FileDesc` from an open C file descriptor.
38 /// The `FileDesc` will take ownership of the specified file descriptor and
39 /// close it upon destruction if the `close_on_drop` flag is true, otherwise
40 /// it will not close the file descriptor when this `FileDesc` is dropped.
42 /// Note that all I/O operations done on this object will be *blocking*, but
43 /// they do not require the runtime to be active.
44 pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
45 FileDesc { inner: Arc::new(Inner {
47 close_on_drop: close_on_drop
51 // FIXME(#10465) these functions should not be public, but anything in
52 // native::io wanting to use them is forced to have all the
53 // rtio traits in scope
54 pub fn inner_read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
55 let ret = retry(|| unsafe {
57 buf.as_mut_ptr() as *mut libc::c_void,
58 buf.len() as libc::size_t) as libc::c_int
63 Err(super::last_error())
68 pub fn inner_write(&mut self, buf: &[u8]) -> IoResult<()> {
69 let ret = keep_going(buf, |buf, len| {
71 libc::write(self.fd(), buf as *libc::c_void,
72 len as libc::size_t) as i64
76 Err(super::last_error())
82 pub fn fd(&self) -> fd_t { self.inner.fd }
85 impl rtio::RtioFileStream for FileDesc {
86 fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
87 self.inner_read(buf).map(|i| i as int)
89 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
92 fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
93 match retry(|| unsafe {
94 libc::pread(self.fd(), buf.as_ptr() as *libc::c_void,
95 buf.len() as libc::size_t,
96 offset as libc::off_t) as libc::c_int
98 -1 => Err(super::last_error()),
102 fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
103 super::mkerr_libc(retry(|| unsafe {
104 libc::pwrite(self.fd(), buf.as_ptr() as *libc::c_void,
105 buf.len() as libc::size_t, offset as libc::off_t)
108 fn seek(&mut self, pos: i64, whence: rtio::SeekStyle) -> IoResult<u64> {
109 let whence = match whence {
110 rtio::SeekSet => libc::SEEK_SET,
111 rtio::SeekEnd => libc::SEEK_END,
112 rtio::SeekCur => libc::SEEK_CUR,
114 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
116 Err(super::last_error())
121 fn tell(&self) -> IoResult<u64> {
122 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
124 Err(super::last_error())
129 fn fsync(&mut self) -> IoResult<()> {
130 super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
132 fn datasync(&mut self) -> IoResult<()> {
133 return super::mkerr_libc(os_datasync(self.fd()));
135 #[cfg(target_os = "macos")]
136 #[cfg(target_os = "ios")]
137 fn os_datasync(fd: c_int) -> c_int {
138 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
140 #[cfg(target_os = "linux")]
141 fn os_datasync(fd: c_int) -> c_int {
142 retry(|| unsafe { libc::fdatasync(fd) })
144 #[cfg(not(target_os = "macos"), not(target_os = "ios"), not(target_os = "linux"))]
145 fn os_datasync(fd: c_int) -> c_int {
146 retry(|| unsafe { libc::fsync(fd) })
149 fn truncate(&mut self, offset: i64) -> IoResult<()> {
150 super::mkerr_libc(retry(|| unsafe {
151 libc::ftruncate(self.fd(), offset as libc::off_t)
155 fn fstat(&mut self) -> IoResult<rtio::FileStat> {
156 let mut stat: libc::stat = unsafe { mem::zeroed() };
157 match retry(|| unsafe { libc::fstat(self.fd(), &mut stat) }) {
158 0 => Ok(mkstat(&stat)),
159 _ => Err(super::last_error()),
164 impl rtio::RtioPipe for FileDesc {
165 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
168 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
169 self.inner_write(buf)
171 fn clone(&self) -> Box<rtio::RtioPipe + Send> {
172 box FileDesc { inner: self.inner.clone() } as Box<rtio::RtioPipe + Send>
175 // Only supported on named pipes currently. Note that this doesn't have an
176 // impact on the std::io primitives, this is never called via
177 // std::io::PipeStream. If the functionality is exposed in the future, then
178 // these methods will need to be implemented.
179 fn close_read(&mut self) -> IoResult<()> {
182 fn close_write(&mut self) -> IoResult<()> {
185 fn set_timeout(&mut self, _t: Option<u64>) {}
186 fn set_read_timeout(&mut self, _t: Option<u64>) {}
187 fn set_write_timeout(&mut self, _t: Option<u64>) {}
190 impl rtio::RtioTTY for FileDesc {
191 fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
194 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
195 self.inner_write(buf)
197 fn set_raw(&mut self, _raw: bool) -> IoResult<()> {
200 fn get_winsize(&mut self) -> IoResult<(int, int)> {
203 fn isatty(&self) -> bool { false }
206 impl Drop for Inner {
208 // closing stdio file handles makes no sense, so never do it. Also, note
209 // that errors are ignored when closing a file descriptor. The reason
210 // for this is that if an error occurs we don't actually know if the
211 // file descriptor was closed or not, and if we retried (for something
212 // like EINTR), we might close another valid file descriptor (opened
213 // after we closed ours.
214 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
215 let n = unsafe { libc::close(self.fd) };
217 println!("error {} when closing file descriptor {}", n,
230 /// Create a `CFile` from an open `FILE` pointer.
232 /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
234 pub fn new(file: *libc::FILE) -> CFile {
237 fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
241 pub fn flush(&mut self) -> IoResult<()> {
242 super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
246 impl rtio::RtioFileStream for CFile {
247 fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
248 let ret = keep_going(buf, |buf, len| {
250 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
257 Err(super::last_error())
263 fn write(&mut self, buf: &[u8]) -> IoResult<()> {
264 let ret = keep_going(buf, |buf, len| {
266 libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
271 Err(super::last_error())
277 fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
278 self.flush().and_then(|()| self.fd.pread(buf, offset))
280 fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
281 self.flush().and_then(|()| self.fd.pwrite(buf, offset))
283 fn seek(&mut self, pos: i64, style: rtio::SeekStyle) -> IoResult<u64> {
284 let whence = match style {
285 rtio::SeekSet => libc::SEEK_SET,
286 rtio::SeekEnd => libc::SEEK_END,
287 rtio::SeekCur => libc::SEEK_CUR,
289 let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
291 Err(super::last_error())
296 fn tell(&self) -> IoResult<u64> {
297 let ret = unsafe { libc::ftell(self.file) };
299 Err(super::last_error())
304 fn fsync(&mut self) -> IoResult<()> {
305 self.flush().and_then(|()| self.fd.fsync())
307 fn datasync(&mut self) -> IoResult<()> {
308 self.flush().and_then(|()| self.fd.fsync())
310 fn truncate(&mut self, offset: i64) -> IoResult<()> {
311 self.flush().and_then(|()| self.fd.truncate(offset))
314 fn fstat(&mut self) -> IoResult<rtio::FileStat> {
315 self.flush().and_then(|()| self.fd.fstat())
319 impl Drop for CFile {
321 unsafe { let _ = libc::fclose(self.file); }
325 pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess)
326 -> IoResult<FileDesc>
328 let flags = match fm {
330 rtio::Append => libc::O_APPEND,
331 rtio::Truncate => libc::O_TRUNC,
333 // Opening with a write permission must silently create the file.
334 let (flags, mode) = match fa {
335 rtio::Read => (flags | libc::O_RDONLY, 0),
336 rtio::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
337 libc::S_IRUSR | libc::S_IWUSR),
338 rtio::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
339 libc::S_IRUSR | libc::S_IWUSR),
342 match retry(|| unsafe { libc::open(path.with_ref(|p| p), flags, mode) }) {
343 -1 => Err(super::last_error()),
344 fd => Ok(FileDesc::new(fd, true)),
348 pub fn mkdir(p: &CString, mode: uint) -> IoResult<()> {
349 super::mkerr_libc(retry(|| unsafe {
350 libc::mkdir(p.with_ref(|p| p), mode as libc::mode_t)
354 pub fn readdir(p: &CString) -> IoResult<Vec<CString>> {
355 use libc::{dirent_t};
356 use libc::{opendir, readdir_r, closedir};
358 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<CString> {
359 let root = unsafe { CString::new(root.with_ref(|p| p), false) };
360 let root = Path::new(root);
362 dirs.move_iter().filter(|path| {
363 path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
364 }).map(|path| root.join(path).to_c_str()).collect()
368 fn rust_dirent_t_size() -> libc::c_int;
369 fn rust_list_dir_val(ptr: *mut dirent_t) -> *libc::c_char;
372 let size = unsafe { rust_dirent_t_size() };
373 let mut buf = Vec::<u8>::with_capacity(size as uint);
374 let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
376 let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) });
378 if dir_ptr as uint != 0 {
379 let mut paths = vec!();
380 let mut entry_ptr = 0 as *mut dirent_t;
381 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
382 if entry_ptr.is_null() { break }
384 CString::new(rust_list_dir_val(entry_ptr), false)
386 paths.push(Path::new(cstr));
388 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
391 Err(super::last_error())
395 pub fn unlink(p: &CString) -> IoResult<()> {
396 super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) }))
399 pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
400 super::mkerr_libc(retry(|| unsafe {
401 libc::rename(old.with_ref(|p| p), new.with_ref(|p| p))
405 pub fn chmod(p: &CString, mode: uint) -> IoResult<()> {
406 super::mkerr_libc(retry(|| unsafe {
407 libc::chmod(p.with_ref(|p| p), mode as libc::mode_t)
411 pub fn rmdir(p: &CString) -> IoResult<()> {
412 super::mkerr_libc(retry(|| unsafe {
413 libc::rmdir(p.with_ref(|p| p))
417 pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
418 super::mkerr_libc(retry(|| unsafe {
419 libc::chown(p.with_ref(|p| p), uid as libc::uid_t,
424 pub fn readlink(p: &CString) -> IoResult<CString> {
425 let p = p.with_ref(|p| p);
426 let mut len = unsafe { libc::pathconf(p, libc::_PC_NAME_MAX) };
428 len = 1024; // FIXME: read PATH_MAX from C ffi?
430 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
431 match retry(|| unsafe {
432 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
433 len as libc::size_t) as libc::c_int
435 -1 => Err(super::last_error()),
438 unsafe { buf.set_len(n as uint); }
439 Ok(buf.as_slice().to_c_str())
444 pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
445 super::mkerr_libc(retry(|| unsafe {
446 libc::symlink(src.with_ref(|p| p), dst.with_ref(|p| p))
450 pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
451 super::mkerr_libc(retry(|| unsafe {
452 libc::link(src.with_ref(|p| p), dst.with_ref(|p| p))
456 fn mkstat(stat: &libc::stat) -> rtio::FileStat {
457 // FileStat times are in milliseconds
458 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
460 #[cfg(not(target_os = "linux"), not(target_os = "android"))]
461 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
462 #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
463 fn flags(_stat: &libc::stat) -> u64 { 0 }
465 #[cfg(not(target_os = "linux"), not(target_os = "android"))]
466 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
467 #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
468 fn gen(_stat: &libc::stat) -> u64 { 0 }
471 size: stat.st_size as u64,
472 kind: stat.st_mode as u64,
473 perm: stat.st_mode as u64,
474 created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
475 modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
476 accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
477 device: stat.st_dev as u64,
478 inode: stat.st_ino as u64,
479 rdev: stat.st_rdev as u64,
480 nlink: stat.st_nlink as u64,
481 uid: stat.st_uid as u64,
482 gid: stat.st_gid as u64,
483 blksize: stat.st_blksize as u64,
484 blocks: stat.st_blocks as u64,
490 pub fn stat(p: &CString) -> IoResult<rtio::FileStat> {
491 let mut stat: libc::stat = unsafe { mem::zeroed() };
492 match retry(|| unsafe { libc::stat(p.with_ref(|p| p), &mut stat) }) {
493 0 => Ok(mkstat(&stat)),
494 _ => Err(super::last_error()),
498 pub fn lstat(p: &CString) -> IoResult<rtio::FileStat> {
499 let mut stat: libc::stat = unsafe { mem::zeroed() };
500 match retry(|| unsafe { libc::lstat(p.with_ref(|p| p), &mut stat) }) {
501 0 => Ok(mkstat(&stat)),
502 _ => Err(super::last_error()),
506 pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
507 let buf = libc::utimbuf {
508 actime: (atime / 1000) as libc::time_t,
509 modtime: (mtime / 1000) as libc::time_t,
511 super::mkerr_libc(retry(|| unsafe {
512 libc::utime(p.with_ref(|p| p), &buf)
518 use super::{CFile, FileDesc};
521 use std::rt::rtio::{RtioFileStream, SeekSet};
523 #[ignore(cfg(target_os = "freebsd"))] // hmm, maybe pipes have a tiny buffer
525 fn test_file_desc() {
526 // Run this test with some pipes so we don't have to mess around with
527 // opening or closing files.
528 let os::Pipe { input, out } = os::pipe();
529 let mut reader = FileDesc::new(input, true);
530 let mut writer = FileDesc::new(out, true);
532 writer.inner_write(bytes!("test")).ok().unwrap();
533 let mut buf = [0u8, ..4];
534 match reader.inner_read(buf) {
536 assert_eq!(buf[0], 't' as u8);
537 assert_eq!(buf[1], 'e' as u8);
538 assert_eq!(buf[2], 's' as u8);
539 assert_eq!(buf[3], 't' as u8);
541 r => fail!("invalid read: {:?}", r)
544 assert!(writer.inner_read(buf).is_err());
545 assert!(reader.inner_write(buf).is_err());
551 let f = libc::tmpfile();
552 assert!(!f.is_null());
553 let mut file = CFile::new(f);
555 file.write(bytes!("test")).ok().unwrap();
556 let mut buf = [0u8, ..4];
557 let _ = file.seek(0, SeekSet).ok().unwrap();
558 match file.read(buf) {
560 assert_eq!(buf[0], 't' as u8);
561 assert_eq!(buf[1], 'e' as u8);
562 assert_eq!(buf[2], 's' as u8);
563 assert_eq!(buf[3], 't' as u8);
565 r => fail!("invalid read: {:?}", r)