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;
22 use io::{IoResult, 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]) -> Result<uint, IoError> {
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
61 Err(io::standard_error(io::EndOfFile))
63 Err(super::last_error())
68 pub fn inner_write(&mut self, buf: &[u8]) -> Result<(), IoError> {
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 io::Reader for FileDesc {
86 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
91 impl io::Writer for FileDesc {
92 fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
97 impl rtio::RtioFileStream for FileDesc {
98 fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
99 self.inner_read(buf).map(|i| i as int)
101 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
102 self.inner_write(buf)
104 fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
105 match retry(|| unsafe {
106 libc::pread(self.fd(), buf.as_ptr() as *libc::c_void,
107 buf.len() as libc::size_t,
108 offset as libc::off_t) as libc::c_int
110 -1 => Err(super::last_error()),
114 fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
115 super::mkerr_libc(retry(|| unsafe {
116 libc::pwrite(self.fd(), buf.as_ptr() as *libc::c_void,
117 buf.len() as libc::size_t, offset as libc::off_t)
120 fn seek(&mut self, pos: i64, whence: io::SeekStyle) -> Result<u64, IoError> {
121 let whence = match whence {
122 io::SeekSet => libc::SEEK_SET,
123 io::SeekEnd => libc::SEEK_END,
124 io::SeekCur => libc::SEEK_CUR,
126 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
128 Err(super::last_error())
133 fn tell(&self) -> Result<u64, IoError> {
134 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
136 Err(super::last_error())
141 fn fsync(&mut self) -> Result<(), IoError> {
142 super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
144 fn datasync(&mut self) -> Result<(), IoError> {
145 return super::mkerr_libc(os_datasync(self.fd()));
147 #[cfg(target_os = "macos")]
148 fn os_datasync(fd: c_int) -> c_int {
149 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
151 #[cfg(target_os = "linux")]
152 fn os_datasync(fd: c_int) -> c_int {
153 retry(|| unsafe { libc::fdatasync(fd) })
155 #[cfg(not(target_os = "macos"), not(target_os = "linux"))]
156 fn os_datasync(fd: c_int) -> c_int {
157 retry(|| unsafe { libc::fsync(fd) })
160 fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
161 super::mkerr_libc(retry(|| unsafe {
162 libc::ftruncate(self.fd(), offset as libc::off_t)
166 fn fstat(&mut self) -> IoResult<io::FileStat> {
167 let mut stat: libc::stat = unsafe { mem::uninit() };
168 match retry(|| unsafe { libc::fstat(self.fd(), &mut stat) }) {
169 0 => Ok(mkstat(&stat)),
170 _ => Err(super::last_error()),
175 impl rtio::RtioPipe for FileDesc {
176 fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
179 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
180 self.inner_write(buf)
182 fn clone(&self) -> Box<rtio::RtioPipe:Send> {
183 box FileDesc { inner: self.inner.clone() } as Box<rtio::RtioPipe:Send>
186 // Only supported on named pipes currently. Note that this doesn't have an
187 // impact on the std::io primitives, this is never called via
188 // std::io::PipeStream. If the functionality is exposed in the future, then
189 // these methods will need to be implemented.
190 fn close_read(&mut self) -> Result<(), IoError> {
191 Err(io::standard_error(io::InvalidInput))
193 fn close_write(&mut self) -> Result<(), IoError> {
194 Err(io::standard_error(io::InvalidInput))
196 fn set_timeout(&mut self, _t: Option<u64>) {}
197 fn set_read_timeout(&mut self, _t: Option<u64>) {}
198 fn set_write_timeout(&mut self, _t: Option<u64>) {}
201 impl rtio::RtioTTY for FileDesc {
202 fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
205 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
206 self.inner_write(buf)
208 fn set_raw(&mut self, _raw: bool) -> Result<(), IoError> {
211 fn get_winsize(&mut self) -> Result<(int, int), IoError> {
214 fn isatty(&self) -> bool { false }
217 impl Drop for Inner {
219 // closing stdio file handles makes no sense, so never do it. Also, note
220 // that errors are ignored when closing a file descriptor. The reason
221 // for this is that if an error occurs we don't actually know if the
222 // file descriptor was closed or not, and if we retried (for something
223 // like EINTR), we might close another valid file descriptor (opened
224 // after we closed ours.
225 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
226 let n = unsafe { libc::close(self.fd) };
228 println!("error {} when closing file descriptor {}", n,
241 /// Create a `CFile` from an open `FILE` pointer.
243 /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
245 pub fn new(file: *libc::FILE) -> CFile {
248 fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
252 pub fn flush(&mut self) -> Result<(), IoError> {
253 super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
257 impl rtio::RtioFileStream for CFile {
258 fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
259 let ret = keep_going(buf, |buf, len| {
261 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
266 Err(io::standard_error(io::EndOfFile))
268 Err(super::last_error())
274 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
275 let ret = keep_going(buf, |buf, len| {
277 libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
282 Err(super::last_error())
288 fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
289 self.flush().and_then(|()| self.fd.pread(buf, offset))
291 fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
292 self.flush().and_then(|()| self.fd.pwrite(buf, offset))
294 fn seek(&mut self, pos: i64, style: io::SeekStyle) -> Result<u64, IoError> {
295 let whence = match style {
296 io::SeekSet => libc::SEEK_SET,
297 io::SeekEnd => libc::SEEK_END,
298 io::SeekCur => libc::SEEK_CUR,
300 let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
302 Err(super::last_error())
307 fn tell(&self) -> Result<u64, IoError> {
308 let ret = unsafe { libc::ftell(self.file) };
310 Err(super::last_error())
315 fn fsync(&mut self) -> Result<(), IoError> {
316 self.flush().and_then(|()| self.fd.fsync())
318 fn datasync(&mut self) -> Result<(), IoError> {
319 self.flush().and_then(|()| self.fd.fsync())
321 fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
322 self.flush().and_then(|()| self.fd.truncate(offset))
325 fn fstat(&mut self) -> IoResult<io::FileStat> {
326 self.flush().and_then(|()| self.fd.fstat())
330 impl Drop for CFile {
332 unsafe { let _ = libc::fclose(self.file); }
336 pub fn open(path: &CString, fm: io::FileMode, fa: io::FileAccess)
337 -> IoResult<FileDesc> {
338 let flags = match fm {
340 io::Append => libc::O_APPEND,
341 io::Truncate => libc::O_TRUNC,
343 // Opening with a write permission must silently create the file.
344 let (flags, mode) = match fa {
345 io::Read => (flags | libc::O_RDONLY, 0),
346 io::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
347 libc::S_IRUSR | libc::S_IWUSR),
348 io::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
349 libc::S_IRUSR | libc::S_IWUSR),
352 match retry(|| unsafe { libc::open(path.with_ref(|p| p), flags, mode) }) {
353 -1 => Err(super::last_error()),
354 fd => Ok(FileDesc::new(fd, true)),
358 pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> {
359 super::mkerr_libc(retry(|| unsafe {
360 libc::mkdir(p.with_ref(|p| p), mode.bits() as libc::mode_t)
364 pub fn readdir(p: &CString) -> IoResult<Vec<Path>> {
365 use libc::{dirent_t};
366 use libc::{opendir, readdir_r, closedir};
368 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
369 let root = unsafe { CString::new(root.with_ref(|p| p), false) };
370 let root = Path::new(root);
372 dirs.move_iter().filter(|path| {
373 path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
374 }).map(|path| root.join(path)).collect()
378 fn rust_dirent_t_size() -> libc::c_int;
379 fn rust_list_dir_val(ptr: *mut dirent_t) -> *libc::c_char;
382 let size = unsafe { rust_dirent_t_size() };
383 let mut buf = Vec::<u8>::with_capacity(size as uint);
384 let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
386 let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) });
388 if dir_ptr as uint != 0 {
389 let mut paths = vec!();
390 let mut entry_ptr = 0 as *mut dirent_t;
391 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
392 if entry_ptr.is_null() { break }
394 CString::new(rust_list_dir_val(entry_ptr), false)
396 paths.push(Path::new(cstr));
398 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
401 Err(super::last_error())
405 pub fn unlink(p: &CString) -> IoResult<()> {
406 super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) }))
409 pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
410 super::mkerr_libc(retry(|| unsafe {
411 libc::rename(old.with_ref(|p| p), new.with_ref(|p| p))
415 pub fn chmod(p: &CString, mode: io::FilePermission) -> IoResult<()> {
416 super::mkerr_libc(retry(|| unsafe {
417 libc::chmod(p.with_ref(|p| p), mode.bits() as libc::mode_t)
421 pub fn rmdir(p: &CString) -> IoResult<()> {
422 super::mkerr_libc(retry(|| unsafe {
423 libc::rmdir(p.with_ref(|p| p))
427 pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
428 super::mkerr_libc(retry(|| unsafe {
429 libc::chown(p.with_ref(|p| p), uid as libc::uid_t,
434 pub fn readlink(p: &CString) -> IoResult<Path> {
435 let p = p.with_ref(|p| p);
436 let mut len = unsafe { libc::pathconf(p, libc::_PC_NAME_MAX) };
438 len = 1024; // FIXME: read PATH_MAX from C ffi?
440 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
441 match retry(|| unsafe {
442 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
443 len as libc::size_t) as libc::c_int
445 -1 => Err(super::last_error()),
448 unsafe { buf.set_len(n as uint); }
454 pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
455 super::mkerr_libc(retry(|| unsafe {
456 libc::symlink(src.with_ref(|p| p), dst.with_ref(|p| p))
460 pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
461 super::mkerr_libc(retry(|| unsafe {
462 libc::link(src.with_ref(|p| p), dst.with_ref(|p| p))
466 fn mkstat(stat: &libc::stat) -> io::FileStat {
467 // FileStat times are in milliseconds
468 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
470 let kind = match (stat.st_mode as c_int) & libc::S_IFMT {
471 libc::S_IFREG => io::TypeFile,
472 libc::S_IFDIR => io::TypeDirectory,
473 libc::S_IFIFO => io::TypeNamedPipe,
474 libc::S_IFBLK => io::TypeBlockSpecial,
475 libc::S_IFLNK => io::TypeSymlink,
476 _ => io::TypeUnknown,
479 #[cfg(not(target_os = "linux"), not(target_os = "android"))]
480 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
481 #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
482 fn flags(_stat: &libc::stat) -> u64 { 0 }
484 #[cfg(not(target_os = "linux"), not(target_os = "android"))]
485 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
486 #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
487 fn gen(_stat: &libc::stat) -> u64 { 0 }
490 size: stat.st_size as u64,
492 perm: io::FilePermission::from_bits_truncate(stat.st_mode as u32),
493 created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
494 modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
495 accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
496 unstable: io::UnstableFileStat {
497 device: stat.st_dev as u64,
498 inode: stat.st_ino as u64,
499 rdev: stat.st_rdev as u64,
500 nlink: stat.st_nlink as u64,
501 uid: stat.st_uid as u64,
502 gid: stat.st_gid as u64,
503 blksize: stat.st_blksize as u64,
504 blocks: stat.st_blocks as u64,
511 pub fn stat(p: &CString) -> IoResult<io::FileStat> {
512 let mut stat: libc::stat = unsafe { mem::uninit() };
513 match retry(|| unsafe { libc::stat(p.with_ref(|p| p), &mut stat) }) {
514 0 => Ok(mkstat(&stat)),
515 _ => Err(super::last_error()),
519 pub fn lstat(p: &CString) -> IoResult<io::FileStat> {
520 let mut stat: libc::stat = unsafe { mem::uninit() };
521 match retry(|| unsafe { libc::lstat(p.with_ref(|p| p), &mut stat) }) {
522 0 => Ok(mkstat(&stat)),
523 _ => Err(super::last_error()),
527 pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
528 let buf = libc::utimbuf {
529 actime: (atime / 1000) as libc::time_t,
530 modtime: (mtime / 1000) as libc::time_t,
532 super::mkerr_libc(retry(|| unsafe {
533 libc::utime(p.with_ref(|p| p), &buf)
539 use super::{CFile, FileDesc};
543 use std::rt::rtio::RtioFileStream;
545 #[ignore(cfg(target_os = "freebsd"))] // hmm, maybe pipes have a tiny buffer
547 fn test_file_desc() {
548 // Run this test with some pipes so we don't have to mess around with
549 // opening or closing files.
550 let os::Pipe { input, out } = os::pipe();
551 let mut reader = FileDesc::new(input, true);
552 let mut writer = FileDesc::new(out, true);
554 writer.inner_write(bytes!("test")).unwrap();
555 let mut buf = [0u8, ..4];
556 match reader.inner_read(buf) {
558 assert_eq!(buf[0], 't' as u8);
559 assert_eq!(buf[1], 'e' as u8);
560 assert_eq!(buf[2], 's' as u8);
561 assert_eq!(buf[3], 't' as u8);
563 r => fail!("invalid read: {:?}", r)
566 assert!(writer.inner_read(buf).is_err());
567 assert!(reader.inner_write(buf).is_err());
573 let f = libc::tmpfile();
574 assert!(!f.is_null());
575 let mut file = CFile::new(f);
577 file.write(bytes!("test")).unwrap();
578 let mut buf = [0u8, ..4];
579 let _ = file.seek(0, io::SeekSet).unwrap();
580 match file.read(buf) {
582 assert_eq!(buf[0], 't' as u8);
583 assert_eq!(buf[1], 'e' as u8);
584 assert_eq!(buf[2], 's' as u8);
585 assert_eq!(buf[3], 't' as u8);
587 r => fail!("invalid read: {:?}", r)