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
15 use ffi::{self, CString};
16 use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
17 use io::{IoResult, FileStat, SeekStyle};
18 use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
20 use libc::{self, c_int, c_void};
24 use sys_common::{keep_going, eof, mkerr_libc};
26 pub type fd_t = libc::c_int;
29 /// The underlying C file descriptor.
32 /// Whether to close the file descriptor on drop.
37 pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
38 FileDesc { fd: fd, close_on_drop: close_on_drop }
41 pub fn read(&self, buf: &mut [u8]) -> IoResult<uint> {
42 let ret = retry(|| unsafe {
44 buf.as_mut_ptr() as *mut libc::c_void,
45 buf.len() as libc::size_t)
50 Err(super::last_error())
55 pub fn write(&self, buf: &[u8]) -> IoResult<()> {
56 let ret = keep_going(buf, |buf, len| {
58 libc::write(self.fd(), buf as *const libc::c_void,
59 len as libc::size_t) as i64
63 Err(super::last_error())
69 pub fn fd(&self) -> fd_t { self.fd }
71 pub fn seek(&self, pos: i64, whence: SeekStyle) -> IoResult<u64> {
72 let whence = match whence {
73 SeekSet => libc::SEEK_SET,
74 SeekEnd => libc::SEEK_END,
75 SeekCur => libc::SEEK_CUR,
77 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
79 Err(super::last_error())
85 pub fn tell(&self) -> IoResult<u64> {
86 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
88 Err(super::last_error())
94 pub fn fsync(&self) -> IoResult<()> {
95 mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
98 pub fn datasync(&self) -> IoResult<()> {
99 return mkerr_libc(os_datasync(self.fd()));
101 #[cfg(any(target_os = "macos", target_os = "ios"))]
102 fn os_datasync(fd: c_int) -> c_int {
103 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
105 #[cfg(target_os = "linux")]
106 fn os_datasync(fd: c_int) -> c_int {
107 retry(|| unsafe { libc::fdatasync(fd) })
109 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
110 fn os_datasync(fd: c_int) -> c_int {
111 retry(|| unsafe { libc::fsync(fd) })
115 pub fn truncate(&self, offset: i64) -> IoResult<()> {
116 mkerr_libc(retry(|| unsafe {
117 libc::ftruncate(self.fd(), offset as libc::off_t)
121 pub fn fstat(&self) -> IoResult<FileStat> {
122 let mut stat: libc::stat = unsafe { mem::zeroed() };
123 match unsafe { libc::fstat(self.fd(), &mut stat) } {
124 0 => Ok(mkstat(&stat)),
125 _ => Err(super::last_error()),
129 /// Extract the actual filedescriptor without closing it.
130 pub fn unwrap(self) -> fd_t {
132 unsafe { mem::forget(self) };
137 impl Drop for FileDesc {
139 // closing stdio file handles makes no sense, so never do it. Also, note
140 // that errors are ignored when closing a file descriptor. The reason
141 // for this is that if an error occurs we don't actually know if the
142 // file descriptor was closed or not, and if we retried (for something
143 // like EINTR), we might close another valid file descriptor (opened
144 // after we closed ours.
145 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
146 let n = unsafe { libc::close(self.fd) };
148 println!("error {} when closing file descriptor {}", n, self.fd);
154 fn cstr(path: &Path) -> CString {
155 CString::from_slice(path.as_vec())
158 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
159 let flags = match fm {
161 Append => libc::O_APPEND,
162 Truncate => libc::O_TRUNC,
164 // Opening with a write permission must silently create the file.
165 let (flags, mode) = match fa {
166 Read => (flags | libc::O_RDONLY, 0),
167 Write => (flags | libc::O_WRONLY | libc::O_CREAT,
168 libc::S_IRUSR | libc::S_IWUSR),
169 ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
170 libc::S_IRUSR | libc::S_IWUSR),
173 let path = cstr(path);
174 match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
175 -1 => Err(super::last_error()),
176 fd => Ok(FileDesc::new(fd, true)),
180 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
182 mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
185 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
186 use libc::{dirent_t};
187 use libc::{opendir, readdir_r, closedir};
189 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
190 let root = Path::new(root);
192 dirs.into_iter().filter(|path| {
193 path.as_vec() != b"." && path.as_vec() != b".."
194 }).map(|path| root.join(path)).collect()
198 fn rust_dirent_t_size() -> libc::c_int;
199 fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
202 let size = unsafe { rust_dirent_t_size() };
203 let mut buf = Vec::<u8>::with_capacity(size as uint);
204 let ptr = buf.as_mut_ptr() as *mut dirent_t;
206 let p = CString::from_slice(p.as_vec());
207 let dir_ptr = unsafe {opendir(p.as_ptr())};
209 if dir_ptr as uint != 0 {
210 let mut paths = vec!();
211 let mut entry_ptr = ptr::null_mut();
212 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
213 if entry_ptr.is_null() { break }
215 Path::new(ffi::c_str_to_bytes(&rust_list_dir_val(entry_ptr)))
218 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
221 Err(super::last_error())
225 pub fn unlink(p: &Path) -> IoResult<()> {
227 mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
230 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
234 libc::rename(old.as_ptr(), new.as_ptr())
238 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
240 mkerr_libc(retry(|| unsafe {
241 libc::chmod(p.as_ptr(), mode as libc::mode_t)
245 pub fn rmdir(p: &Path) -> IoResult<()> {
247 mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
250 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
252 mkerr_libc(retry(|| unsafe {
253 libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
257 pub fn readlink(p: &Path) -> IoResult<Path> {
258 let c_path = cstr(p);
259 let p = c_path.as_ptr();
260 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
262 len = 1024; // FIXME: read PATH_MAX from C ffi?
264 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
266 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
267 len as libc::size_t) as libc::c_int
269 -1 => Err(super::last_error()),
272 unsafe { buf.set_len(n as uint); }
278 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
281 mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
284 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
287 mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
290 fn mkstat(stat: &libc::stat) -> FileStat {
291 // FileStat times are in milliseconds
292 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
294 #[cfg(not(any(target_os = "linux", target_os = "android")))]
295 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
296 #[cfg(any(target_os = "linux", target_os = "android"))]
297 fn flags(_stat: &libc::stat) -> u64 { 0 }
299 #[cfg(not(any(target_os = "linux", target_os = "android")))]
300 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
301 #[cfg(any(target_os = "linux", target_os = "android"))]
302 fn gen(_stat: &libc::stat) -> u64 { 0 }
305 size: stat.st_size as u64,
306 kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
307 libc::S_IFREG => io::FileType::RegularFile,
308 libc::S_IFDIR => io::FileType::Directory,
309 libc::S_IFIFO => io::FileType::NamedPipe,
310 libc::S_IFBLK => io::FileType::BlockSpecial,
311 libc::S_IFLNK => io::FileType::Symlink,
312 _ => io::FileType::Unknown,
314 perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
315 created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
316 modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
317 accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
318 unstable: UnstableFileStat {
319 device: stat.st_dev as u64,
320 inode: stat.st_ino as u64,
321 rdev: stat.st_rdev as u64,
322 nlink: stat.st_nlink as u64,
323 uid: stat.st_uid as u64,
324 gid: stat.st_gid as u64,
325 blksize: stat.st_blksize as u64,
326 blocks: stat.st_blocks as u64,
333 pub fn stat(p: &Path) -> IoResult<FileStat> {
335 let mut stat: libc::stat = unsafe { mem::zeroed() };
336 match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
337 0 => Ok(mkstat(&stat)),
338 _ => Err(super::last_error()),
342 pub fn lstat(p: &Path) -> IoResult<FileStat> {
344 let mut stat: libc::stat = unsafe { mem::zeroed() };
345 match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
346 0 => Ok(mkstat(&stat)),
347 _ => Err(super::last_error()),
351 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
353 let buf = libc::utimbuf {
354 actime: (atime / 1000) as libc::time_t,
355 modtime: (mtime / 1000) as libc::time_t,
357 mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
367 #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
369 fn test_file_desc() {
370 // Run this test with some pipes so we don't have to mess around with
371 // opening or closing files.
372 let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
373 let mut reader = FileDesc::new(reader, true);
374 let mut writer = FileDesc::new(writer, true);
376 writer.write(b"test").ok().unwrap();
377 let mut buf = [0u8; 4];
378 match reader.read(&mut buf) {
380 assert_eq!(buf[0], 't' as u8);
381 assert_eq!(buf[1], 'e' as u8);
382 assert_eq!(buf[2], 's' as u8);
383 assert_eq!(buf[3], 't' as u8);
385 r => panic!("invalid read: {:?}", r),
388 assert!(writer.read(&mut buf).is_err());
389 assert!(reader.write(&buf).is_err());