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
13 use std::sync::arc::UnsafeArc;
14 use std::c_str::CString;
17 use libc::{c_int, c_void};
22 use io::{IoResult, retry, keep_going};
24 pub type fd_t = libc::c_int;
32 inner: UnsafeArc<Inner>
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: UnsafeArc::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 {
83 // This unsafety is fine because we're just reading off the file
84 // descriptor, no one is modifying this.
85 unsafe { (*self.inner.get()).fd }
89 impl io::Reader for FileDesc {
90 fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
95 impl io::Writer for FileDesc {
96 fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
101 impl rtio::RtioFileStream for FileDesc {
102 fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
103 self.inner_read(buf).map(|i| i as int)
105 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
106 self.inner_write(buf)
108 fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
109 match retry(|| unsafe {
110 libc::pread(self.fd(), buf.as_ptr() as *libc::c_void,
111 buf.len() as libc::size_t,
112 offset as libc::off_t) as libc::c_int
114 -1 => Err(super::last_error()),
118 fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
119 super::mkerr_libc(retry(|| unsafe {
120 libc::pwrite(self.fd(), buf.as_ptr() as *libc::c_void,
121 buf.len() as libc::size_t, offset as libc::off_t)
124 fn seek(&mut self, pos: i64, whence: io::SeekStyle) -> Result<u64, IoError> {
125 let whence = match whence {
126 io::SeekSet => libc::SEEK_SET,
127 io::SeekEnd => libc::SEEK_END,
128 io::SeekCur => libc::SEEK_CUR,
130 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
132 Err(super::last_error())
137 fn tell(&self) -> Result<u64, IoError> {
138 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
140 Err(super::last_error())
145 fn fsync(&mut self) -> Result<(), IoError> {
146 super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
148 fn datasync(&mut self) -> Result<(), IoError> {
149 return super::mkerr_libc(os_datasync(self.fd()));
151 #[cfg(target_os = "macos")]
152 fn os_datasync(fd: c_int) -> c_int {
153 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
155 #[cfg(target_os = "linux")]
156 fn os_datasync(fd: c_int) -> c_int {
157 retry(|| unsafe { libc::fdatasync(fd) })
159 #[cfg(not(target_os = "macos"), not(target_os = "linux"))]
160 fn os_datasync(fd: c_int) -> c_int {
161 retry(|| unsafe { libc::fsync(fd) })
164 fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
165 super::mkerr_libc(retry(|| unsafe {
166 libc::ftruncate(self.fd(), offset as libc::off_t)
171 impl rtio::RtioPipe for FileDesc {
172 fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
175 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
176 self.inner_write(buf)
178 fn clone(&self) -> ~rtio::RtioPipe:Send {
179 box FileDesc { inner: self.inner.clone() } as ~rtio::RtioPipe:Send
183 impl rtio::RtioTTY for FileDesc {
184 fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
187 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
188 self.inner_write(buf)
190 fn set_raw(&mut self, _raw: bool) -> Result<(), IoError> {
193 fn get_winsize(&mut self) -> Result<(int, int), IoError> {
196 fn isatty(&self) -> bool { false }
199 impl Drop for Inner {
201 // closing stdio file handles makes no sense, so never do it. Also, note
202 // that errors are ignored when closing a file descriptor. The reason
203 // for this is that if an error occurs we don't actually know if the
204 // file descriptor was closed or not, and if we retried (for something
205 // like EINTR), we might close another valid file descriptor (opened
206 // after we closed ours.
207 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
208 let n = unsafe { libc::close(self.fd) };
210 println!("error {} when closing file descriptor {}", n,
223 /// Create a `CFile` from an open `FILE` pointer.
225 /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
227 pub fn new(file: *libc::FILE) -> CFile {
230 fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
234 pub fn flush(&mut self) -> Result<(), IoError> {
235 super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
239 impl rtio::RtioFileStream for CFile {
240 fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError> {
241 let ret = keep_going(buf, |buf, len| {
243 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
248 Err(io::standard_error(io::EndOfFile))
250 Err(super::last_error())
256 fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
257 let ret = keep_going(buf, |buf, len| {
259 libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
264 Err(super::last_error())
270 fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
271 self.flush().and_then(|()| self.fd.pread(buf, offset))
273 fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
274 self.flush().and_then(|()| self.fd.pwrite(buf, offset))
276 fn seek(&mut self, pos: i64, style: io::SeekStyle) -> Result<u64, IoError> {
277 let whence = match style {
278 io::SeekSet => libc::SEEK_SET,
279 io::SeekEnd => libc::SEEK_END,
280 io::SeekCur => libc::SEEK_CUR,
282 let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
284 Err(super::last_error())
289 fn tell(&self) -> Result<u64, IoError> {
290 let ret = unsafe { libc::ftell(self.file) };
292 Err(super::last_error())
297 fn fsync(&mut self) -> Result<(), IoError> {
298 self.flush().and_then(|()| self.fd.fsync())
300 fn datasync(&mut self) -> Result<(), IoError> {
301 self.flush().and_then(|()| self.fd.fsync())
303 fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
304 self.flush().and_then(|()| self.fd.truncate(offset))
308 impl Drop for CFile {
310 unsafe { let _ = libc::fclose(self.file); }
314 pub fn open(path: &CString, fm: io::FileMode, fa: io::FileAccess)
315 -> IoResult<FileDesc> {
316 let flags = match fm {
318 io::Append => libc::O_APPEND,
319 io::Truncate => libc::O_TRUNC,
321 // Opening with a write permission must silently create the file.
322 let (flags, mode) = match fa {
323 io::Read => (flags | libc::O_RDONLY, 0),
324 io::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
325 libc::S_IRUSR | libc::S_IWUSR),
326 io::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
327 libc::S_IRUSR | libc::S_IWUSR),
330 match retry(|| unsafe { libc::open(path.with_ref(|p| p), flags, mode) }) {
331 -1 => Err(super::last_error()),
332 fd => Ok(FileDesc::new(fd, true)),
336 pub fn mkdir(p: &CString, mode: io::FilePermission) -> IoResult<()> {
337 super::mkerr_libc(retry(|| unsafe {
338 libc::mkdir(p.with_ref(|p| p), mode as libc::mode_t)
342 pub fn readdir(p: &CString) -> IoResult<Vec<Path>> {
343 use libc::{dirent_t};
344 use libc::{opendir, readdir_r, closedir};
346 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
347 let root = unsafe { CString::new(root.with_ref(|p| p), false) };
348 let root = Path::new(root);
350 dirs.move_iter().filter(|path| {
351 path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
352 }).map(|path| root.join(path)).collect()
356 fn rust_dirent_t_size() -> libc::c_int;
357 fn rust_list_dir_val(ptr: *mut dirent_t) -> *libc::c_char;
360 let size = unsafe { rust_dirent_t_size() };
361 let mut buf = Vec::<u8>::with_capacity(size as uint);
362 let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
364 let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) });
366 if dir_ptr as uint != 0 {
367 let mut paths = vec!();
368 let mut entry_ptr = 0 as *mut dirent_t;
369 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
370 if entry_ptr.is_null() { break }
372 CString::new(rust_list_dir_val(entry_ptr), false)
374 paths.push(Path::new(cstr));
376 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
379 Err(super::last_error())
383 pub fn unlink(p: &CString) -> IoResult<()> {
384 super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) }))
387 pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
388 super::mkerr_libc(retry(|| unsafe {
389 libc::rename(old.with_ref(|p| p), new.with_ref(|p| p))
393 pub fn chmod(p: &CString, mode: io::FilePermission) -> IoResult<()> {
394 super::mkerr_libc(retry(|| unsafe {
395 libc::chmod(p.with_ref(|p| p), mode as libc::mode_t)
399 pub fn rmdir(p: &CString) -> IoResult<()> {
400 super::mkerr_libc(retry(|| unsafe {
401 libc::rmdir(p.with_ref(|p| p))
405 pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
406 super::mkerr_libc(retry(|| unsafe {
407 libc::chown(p.with_ref(|p| p), uid as libc::uid_t,
412 pub fn readlink(p: &CString) -> IoResult<Path> {
413 let p = p.with_ref(|p| p);
414 let mut len = unsafe { libc::pathconf(p, libc::_PC_NAME_MAX) };
416 len = 1024; // FIXME: read PATH_MAX from C ffi?
418 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
419 match retry(|| unsafe {
420 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
421 len as libc::size_t) as libc::c_int
423 -1 => Err(super::last_error()),
426 unsafe { buf.set_len(n as uint); }
432 pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
433 super::mkerr_libc(retry(|| unsafe {
434 libc::symlink(src.with_ref(|p| p), dst.with_ref(|p| p))
438 pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
439 super::mkerr_libc(retry(|| unsafe {
440 libc::link(src.with_ref(|p| p), dst.with_ref(|p| p))
444 fn mkstat(stat: &libc::stat, path: &CString) -> io::FileStat {
445 let path = unsafe { CString::new(path.with_ref(|p| p), false) };
447 // FileStat times are in milliseconds
448 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
450 let kind = match (stat.st_mode as c_int) & libc::S_IFMT {
451 libc::S_IFREG => io::TypeFile,
452 libc::S_IFDIR => io::TypeDirectory,
453 libc::S_IFIFO => io::TypeNamedPipe,
454 libc::S_IFBLK => io::TypeBlockSpecial,
455 libc::S_IFLNK => io::TypeSymlink,
456 _ => io::TypeUnknown,
459 #[cfg(not(target_os = "linux"), not(target_os = "android"))]
460 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
461 #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
462 fn flags(_stat: &libc::stat) -> u64 { 0 }
464 #[cfg(not(target_os = "linux"), not(target_os = "android"))]
465 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
466 #[cfg(target_os = "linux")] #[cfg(target_os = "android")]
467 fn gen(_stat: &libc::stat) -> u64 { 0 }
470 path: Path::new(path),
471 size: stat.st_size as u64,
473 perm: (stat.st_mode) as io::FilePermission & io::AllPermissions,
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 unstable: io::UnstableFileStat {
478 device: stat.st_dev as u64,
479 inode: stat.st_ino as u64,
480 rdev: stat.st_rdev as u64,
481 nlink: stat.st_nlink as u64,
482 uid: stat.st_uid as u64,
483 gid: stat.st_gid as u64,
484 blksize: stat.st_blksize as u64,
485 blocks: stat.st_blocks as u64,
492 pub fn stat(p: &CString) -> IoResult<io::FileStat> {
493 let mut stat: libc::stat = unsafe { mem::uninit() };
494 match retry(|| unsafe { libc::stat(p.with_ref(|p| p), &mut stat) }) {
495 0 => Ok(mkstat(&stat, p)),
496 _ => Err(super::last_error()),
500 pub fn lstat(p: &CString) -> IoResult<io::FileStat> {
501 let mut stat: libc::stat = unsafe { mem::uninit() };
502 match retry(|| unsafe { libc::lstat(p.with_ref(|p| p), &mut stat) }) {
503 0 => Ok(mkstat(&stat, p)),
504 _ => Err(super::last_error()),
508 pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
509 let buf = libc::utimbuf {
510 actime: (atime / 1000) as libc::time_t,
511 modtime: (mtime / 1000) as libc::time_t,
513 super::mkerr_libc(retry(|| unsafe {
514 libc::utime(p.with_ref(|p| p), &buf)
520 use super::{CFile, FileDesc};
524 use std::rt::rtio::RtioFileStream;
526 #[ignore(cfg(target_os = "freebsd"))] // hmm, maybe pipes have a tiny buffer
528 fn test_file_desc() {
529 // Run this test with some pipes so we don't have to mess around with
530 // opening or closing files.
531 let os::Pipe { input, out } = os::pipe();
532 let mut reader = FileDesc::new(input, true);
533 let mut writer = FileDesc::new(out, true);
535 writer.inner_write(bytes!("test")).unwrap();
536 let mut buf = [0u8, ..4];
537 match reader.inner_read(buf) {
539 assert_eq!(buf[0], 't' as u8);
540 assert_eq!(buf[1], 'e' as u8);
541 assert_eq!(buf[2], 's' as u8);
542 assert_eq!(buf[3], 't' as u8);
544 r => fail!("invalid read: {:?}", r)
547 assert!(writer.inner_read(buf).is_err());
548 assert!(reader.inner_write(buf).is_err());
554 let f = libc::tmpfile();
555 assert!(!f.is_null());
556 let mut file = CFile::new(f);
558 file.write(bytes!("test")).unwrap();
559 let mut buf = [0u8, ..4];
560 let _ = file.seek(0, io::SeekSet).unwrap();
561 match file.read(buf) {
563 assert_eq!(buf[0], 't' as u8);
564 assert_eq!(buf[1], 'e' as u8);
565 assert_eq!(buf[2], 's' as u8);
566 assert_eq!(buf[3], 't' as u8);
568 r => fail!("invalid read: {:?}", r)