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 #![allow(deprecated)] // this module itself is essentially deprecated
17 use ffi::{CString, CStr};
18 use old_io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
19 use old_io::{IoResult, FileStat, SeekStyle};
20 use old_io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
22 use libc::{self, c_int, c_void};
26 use sys_common::{keep_going, eof, mkerr_libc};
28 pub type fd_t = libc::c_int;
31 /// The underlying C file descriptor.
34 /// Whether to close the file descriptor on drop.
39 pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
40 FileDesc { fd: fd, close_on_drop: close_on_drop }
43 pub fn read(&self, buf: &mut [u8]) -> IoResult<uint> {
44 let ret = retry(|| unsafe {
46 buf.as_mut_ptr() as *mut libc::c_void,
47 buf.len() as libc::size_t)
52 Err(super::last_error())
57 pub fn write(&self, buf: &[u8]) -> IoResult<()> {
58 let ret = keep_going(buf, |buf, len| {
60 libc::write(self.fd(), buf as *const libc::c_void,
61 len as libc::size_t) as i64
65 Err(super::last_error())
71 pub fn fd(&self) -> fd_t { self.fd }
73 pub fn seek(&self, pos: i64, whence: SeekStyle) -> IoResult<u64> {
74 let whence = match whence {
75 SeekSet => libc::SEEK_SET,
76 SeekEnd => libc::SEEK_END,
77 SeekCur => libc::SEEK_CUR,
79 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
81 Err(super::last_error())
87 pub fn tell(&self) -> IoResult<u64> {
88 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
90 Err(super::last_error())
96 pub fn fsync(&self) -> IoResult<()> {
97 mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
100 pub fn datasync(&self) -> IoResult<()> {
101 return mkerr_libc(os_datasync(self.fd()));
103 #[cfg(any(target_os = "macos", target_os = "ios"))]
104 fn os_datasync(fd: c_int) -> c_int {
105 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
107 #[cfg(target_os = "linux")]
108 fn os_datasync(fd: c_int) -> c_int {
109 retry(|| unsafe { libc::fdatasync(fd) })
111 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
112 fn os_datasync(fd: c_int) -> c_int {
113 retry(|| unsafe { libc::fsync(fd) })
117 pub fn truncate(&self, offset: i64) -> IoResult<()> {
118 mkerr_libc(retry(|| unsafe {
119 libc::ftruncate(self.fd(), offset as libc::off_t)
123 pub fn fstat(&self) -> IoResult<FileStat> {
124 let mut stat: libc::stat = unsafe { mem::zeroed() };
125 match unsafe { libc::fstat(self.fd(), &mut stat) } {
126 0 => Ok(mkstat(&stat)),
127 _ => Err(super::last_error()),
131 /// Extract the actual filedescriptor without closing it.
132 pub fn unwrap(self) -> fd_t {
134 unsafe { mem::forget(self) };
139 impl Drop for FileDesc {
141 // closing stdio file handles makes no sense, so never do it. Also, note
142 // that errors are ignored when closing a file descriptor. The reason
143 // for this is that if an error occurs we don't actually know if the
144 // file descriptor was closed or not, and if we retried (for something
145 // like EINTR), we might close another valid file descriptor (opened
146 // after we closed ours.
147 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
148 let n = unsafe { libc::close(self.fd) };
150 println!("error {} when closing file descriptor {}", n, self.fd);
156 fn cstr(path: &Path) -> IoResult<CString> {
157 Ok(try!(CString::new(path.as_vec())))
160 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
161 let flags = match fm {
163 Append => libc::O_APPEND,
164 Truncate => libc::O_TRUNC,
166 // Opening with a write permission must silently create the file.
167 let (flags, mode) = match fa {
168 Read => (flags | libc::O_RDONLY, 0),
169 Write => (flags | libc::O_WRONLY | libc::O_CREAT,
170 libc::S_IRUSR | libc::S_IWUSR),
171 ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
172 libc::S_IRUSR | libc::S_IWUSR),
175 let path = try!(cstr(path));
176 match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
177 -1 => Err(super::last_error()),
178 fd => Ok(FileDesc::new(fd, true)),
182 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
183 let p = try!(cstr(p));
184 mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
187 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
188 use libc::{dirent_t};
189 use libc::{opendir, readdir_r, closedir};
191 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
192 let root = Path::new(root);
194 dirs.into_iter().filter(|path| {
195 path.as_vec() != b"." && path.as_vec() != b".."
196 }).map(|path| root.join(path)).collect()
200 fn rust_dirent_t_size() -> libc::c_int;
201 fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
204 let size = unsafe { rust_dirent_t_size() };
205 let mut buf = Vec::<u8>::with_capacity(size as uint);
206 let ptr = buf.as_mut_ptr() as *mut dirent_t;
208 let p = try!(CString::new(p.as_vec()));
209 let dir_ptr = unsafe {opendir(p.as_ptr())};
211 if dir_ptr as uint != 0 {
212 let mut paths = vec!();
213 let mut entry_ptr = ptr::null_mut();
214 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
215 if entry_ptr.is_null() { break }
217 Path::new(CStr::from_ptr(rust_list_dir_val(entry_ptr)).to_bytes())
220 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
223 Err(super::last_error())
227 pub fn unlink(p: &Path) -> IoResult<()> {
228 let p = try!(cstr(p));
229 mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
232 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
233 let old = try!(cstr(old));
234 let new = try!(cstr(new));
236 libc::rename(old.as_ptr(), new.as_ptr())
240 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
241 let p = try!(cstr(p));
242 mkerr_libc(retry(|| unsafe {
243 libc::chmod(p.as_ptr(), mode as libc::mode_t)
247 pub fn rmdir(p: &Path) -> IoResult<()> {
248 let p = try!(cstr(p));
249 mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
252 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
253 let p = try!(cstr(p));
254 mkerr_libc(retry(|| unsafe {
255 libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
259 pub fn readlink(p: &Path) -> IoResult<Path> {
260 let c_path = try!(cstr(p));
261 let p = c_path.as_ptr();
262 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
264 len = 1024; // FIXME: read PATH_MAX from C ffi?
266 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
268 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
269 len as libc::size_t) as libc::c_int
271 -1 => Err(super::last_error()),
274 unsafe { buf.set_len(n as uint); }
280 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
281 let src = try!(cstr(src));
282 let dst = try!(cstr(dst));
283 mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
286 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
287 let src = try!(cstr(src));
288 let dst = try!(cstr(dst));
289 mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
292 fn mkstat(stat: &libc::stat) -> FileStat {
293 // FileStat times are in milliseconds
294 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
296 fn ctime(stat: &libc::stat) -> u64 {
297 mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64)
300 fn atime(stat: &libc::stat) -> u64 {
301 mktime(stat.st_atime as u64, stat.st_atime_nsec as u64)
304 fn mtime(stat: &libc::stat) -> u64 {
305 mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64)
308 #[cfg(not(any(target_os = "linux", target_os = "android")))]
309 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
310 #[cfg(any(target_os = "linux", target_os = "android"))]
311 fn flags(_stat: &libc::stat) -> u64 { 0 }
313 #[cfg(not(any(target_os = "linux", target_os = "android")))]
314 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
315 #[cfg(any(target_os = "linux", target_os = "android"))]
316 fn gen(_stat: &libc::stat) -> u64 { 0 }
319 size: stat.st_size as u64,
320 kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
321 libc::S_IFREG => old_io::FileType::RegularFile,
322 libc::S_IFDIR => old_io::FileType::Directory,
323 libc::S_IFIFO => old_io::FileType::NamedPipe,
324 libc::S_IFBLK => old_io::FileType::BlockSpecial,
325 libc::S_IFLNK => old_io::FileType::Symlink,
326 _ => old_io::FileType::Unknown,
328 perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
329 created: ctime(stat),
330 modified: mtime(stat),
331 accessed: atime(stat),
332 unstable: UnstableFileStat {
333 device: stat.st_dev as u64,
334 inode: stat.st_ino as u64,
335 rdev: stat.st_rdev as u64,
336 nlink: stat.st_nlink as u64,
337 uid: stat.st_uid as u64,
338 gid: stat.st_gid as u64,
339 blksize: stat.st_blksize as u64,
340 blocks: stat.st_blocks as u64,
347 pub fn stat(p: &Path) -> IoResult<FileStat> {
348 let p = try!(cstr(p));
349 let mut stat: libc::stat = unsafe { mem::zeroed() };
350 match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
351 0 => Ok(mkstat(&stat)),
352 _ => Err(super::last_error()),
356 pub fn lstat(p: &Path) -> IoResult<FileStat> {
357 let p = try!(cstr(p));
358 let mut stat: libc::stat = unsafe { mem::zeroed() };
359 match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
360 0 => Ok(mkstat(&stat)),
361 _ => Err(super::last_error()),
365 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
366 let p = try!(cstr(p));
367 let buf = libc::utimbuf {
368 actime: (atime / 1000) as libc::time_t,
369 modtime: (mtime / 1000) as libc::time_t,
371 mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
381 #[cfg_attr(any(target_os = "freebsd",
382 target_os = "openbsd"),
384 // under some system, pipe(2) will return a bidrectionnal pipe
386 fn test_file_desc() {
387 // Run this test with some pipes so we don't have to mess around with
388 // opening or closing files.
389 let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
390 let mut reader = FileDesc::new(reader, true);
391 let mut writer = FileDesc::new(writer, true);
393 writer.write(b"test").ok().unwrap();
394 let mut buf = [0; 4];
395 match reader.read(&mut buf) {
397 assert_eq!(buf[0], 't' as u8);
398 assert_eq!(buf[1], 'e' as u8);
399 assert_eq!(buf[2], 's' as u8);
400 assert_eq!(buf[3], 't' as u8);
402 r => panic!("invalid read: {:?}", r),
405 assert!(writer.read(&mut buf).is_err());
406 assert!(reader.write(&buf).is_err());