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 c_str::{CString, ToCStr};
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::{mod, c_int, c_void};
23 use sys_common::{keep_going, eof, mkerr_libc};
25 pub type fd_t = libc::c_int;
28 /// The underlying C file descriptor.
31 /// Whether to close the file descriptor on drop.
36 pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
37 FileDesc { fd: fd, close_on_drop: close_on_drop }
40 pub fn read(&self, buf: &mut [u8]) -> IoResult<uint> {
41 let ret = retry(|| unsafe {
43 buf.as_mut_ptr() as *mut libc::c_void,
44 buf.len() as libc::size_t)
49 Err(super::last_error())
54 pub fn write(&self, buf: &[u8]) -> IoResult<()> {
55 let ret = keep_going(buf, |buf, len| {
57 libc::write(self.fd(), buf as *const libc::c_void,
58 len as libc::size_t) as i64
62 Err(super::last_error())
68 pub fn fd(&self) -> fd_t { self.fd }
70 pub fn seek(&self, pos: i64, whence: SeekStyle) -> IoResult<u64> {
71 let whence = match whence {
72 SeekSet => libc::SEEK_SET,
73 SeekEnd => libc::SEEK_END,
74 SeekCur => libc::SEEK_CUR,
76 let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
78 Err(super::last_error())
84 pub fn tell(&self) -> IoResult<u64> {
85 let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
87 Err(super::last_error())
93 pub fn fsync(&self) -> IoResult<()> {
94 mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
97 pub fn datasync(&self) -> IoResult<()> {
98 return mkerr_libc(os_datasync(self.fd()));
100 #[cfg(any(target_os = "macos", target_os = "ios"))]
101 fn os_datasync(fd: c_int) -> c_int {
102 unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
104 #[cfg(target_os = "linux")]
105 fn os_datasync(fd: c_int) -> c_int {
106 retry(|| unsafe { libc::fdatasync(fd) })
108 #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
109 fn os_datasync(fd: c_int) -> c_int {
110 retry(|| unsafe { libc::fsync(fd) })
114 pub fn truncate(&self, offset: i64) -> IoResult<()> {
115 mkerr_libc(retry(|| unsafe {
116 libc::ftruncate(self.fd(), offset as libc::off_t)
120 pub fn fstat(&self) -> IoResult<FileStat> {
121 let mut stat: libc::stat = unsafe { mem::zeroed() };
122 match unsafe { libc::fstat(self.fd(), &mut stat) } {
123 0 => Ok(mkstat(&stat)),
124 _ => Err(super::last_error()),
128 /// Extract the actual filedescriptor without closing it.
129 pub fn unwrap(self) -> fd_t {
131 unsafe { mem::forget(self) };
136 impl Drop for FileDesc {
138 // closing stdio file handles makes no sense, so never do it. Also, note
139 // that errors are ignored when closing a file descriptor. The reason
140 // for this is that if an error occurs we don't actually know if the
141 // file descriptor was closed or not, and if we retried (for something
142 // like EINTR), we might close another valid file descriptor (opened
143 // after we closed ours.
144 if self.close_on_drop && self.fd > libc::STDERR_FILENO {
145 let n = unsafe { libc::close(self.fd) };
147 println!("error {} when closing file descriptor {}", n, self.fd);
153 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
154 let flags = match fm {
156 Append => libc::O_APPEND,
157 Truncate => libc::O_TRUNC,
159 // Opening with a write permission must silently create the file.
160 let (flags, mode) = match fa {
161 Read => (flags | libc::O_RDONLY, 0),
162 Write => (flags | libc::O_WRONLY | libc::O_CREAT,
163 libc::S_IRUSR | libc::S_IWUSR),
164 ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
165 libc::S_IRUSR | libc::S_IWUSR),
168 let path = path.to_c_str();
169 match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
170 -1 => Err(super::last_error()),
171 fd => Ok(FileDesc::new(fd, true)),
175 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
176 let p = p.to_c_str();
177 mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
180 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
181 use libc::{dirent_t};
182 use libc::{opendir, readdir_r, closedir};
184 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
185 let root = unsafe { CString::new(root.as_ptr(), false) };
186 let root = Path::new(root);
188 dirs.into_iter().filter(|path| {
189 path.as_vec() != b"." && path.as_vec() != b".."
190 }).map(|path| root.join(path)).collect()
194 fn rust_dirent_t_size() -> libc::c_int;
195 fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
198 let size = unsafe { rust_dirent_t_size() };
199 let mut buf = Vec::<u8>::with_capacity(size as uint);
200 let ptr = buf.as_mut_ptr() as *mut dirent_t;
202 let p = p.to_c_str();
203 let dir_ptr = unsafe {opendir(p.as_ptr())};
205 if dir_ptr as uint != 0 {
206 let mut paths = vec!();
207 let mut entry_ptr = 0 as *mut dirent_t;
208 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
209 if entry_ptr.is_null() { break }
211 CString::new(rust_list_dir_val(entry_ptr), false)
213 paths.push(Path::new(cstr));
215 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
218 Err(super::last_error())
222 pub fn unlink(p: &Path) -> IoResult<()> {
223 let p = p.to_c_str();
224 mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
227 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
228 let old = old.to_c_str();
229 let new = new.to_c_str();
231 libc::rename(old.as_ptr(), new.as_ptr())
235 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
236 let p = p.to_c_str();
237 mkerr_libc(retry(|| unsafe {
238 libc::chmod(p.as_ptr(), mode as libc::mode_t)
242 pub fn rmdir(p: &Path) -> IoResult<()> {
243 let p = p.to_c_str();
244 mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
247 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
248 let p = p.to_c_str();
249 mkerr_libc(retry(|| unsafe {
250 libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
254 pub fn readlink(p: &Path) -> IoResult<Path> {
255 let c_path = p.to_c_str();
256 let p = c_path.as_ptr();
257 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
259 len = 1024; // FIXME: read PATH_MAX from C ffi?
261 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
263 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
264 len as libc::size_t) as libc::c_int
266 -1 => Err(super::last_error()),
269 unsafe { buf.set_len(n as uint); }
275 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
276 let src = src.to_c_str();
277 let dst = dst.to_c_str();
278 mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
281 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
282 let src = src.to_c_str();
283 let dst = dst.to_c_str();
284 mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
287 fn mkstat(stat: &libc::stat) -> FileStat {
288 // FileStat times are in milliseconds
289 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
291 #[cfg(not(any(target_os = "linux", target_os = "android")))]
292 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
293 #[cfg(any(target_os = "linux", target_os = "android"))]
294 fn flags(_stat: &libc::stat) -> u64 { 0 }
296 #[cfg(not(any(target_os = "linux", target_os = "android")))]
297 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
298 #[cfg(any(target_os = "linux", target_os = "android"))]
299 fn gen(_stat: &libc::stat) -> u64 { 0 }
302 size: stat.st_size as u64,
303 kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
304 libc::S_IFREG => io::FileType::RegularFile,
305 libc::S_IFDIR => io::FileType::Directory,
306 libc::S_IFIFO => io::FileType::NamedPipe,
307 libc::S_IFBLK => io::FileType::BlockSpecial,
308 libc::S_IFLNK => io::FileType::Symlink,
309 _ => io::FileType::Unknown,
311 perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
312 created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
313 modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
314 accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
315 unstable: UnstableFileStat {
316 device: stat.st_dev as u64,
317 inode: stat.st_ino as u64,
318 rdev: stat.st_rdev as u64,
319 nlink: stat.st_nlink as u64,
320 uid: stat.st_uid as u64,
321 gid: stat.st_gid as u64,
322 blksize: stat.st_blksize as u64,
323 blocks: stat.st_blocks as u64,
330 pub fn stat(p: &Path) -> IoResult<FileStat> {
331 let p = p.to_c_str();
332 let mut stat: libc::stat = unsafe { mem::zeroed() };
333 match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
334 0 => Ok(mkstat(&stat)),
335 _ => Err(super::last_error()),
339 pub fn lstat(p: &Path) -> IoResult<FileStat> {
340 let p = p.to_c_str();
341 let mut stat: libc::stat = unsafe { mem::zeroed() };
342 match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
343 0 => Ok(mkstat(&stat)),
344 _ => Err(super::last_error()),
348 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
349 let p = p.to_c_str();
350 let buf = libc::utimbuf {
351 actime: (atime / 1000) as libc::time_t,
352 modtime: (mtime / 1000) as libc::time_t,
354 mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
364 #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
366 fn test_file_desc() {
367 // Run this test with some pipes so we don't have to mess around with
368 // opening or closing files.
369 let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
370 let mut reader = FileDesc::new(reader, true);
371 let mut writer = FileDesc::new(writer, true);
373 writer.write(b"test").ok().unwrap();
374 let mut buf = [0u8; 4];
375 match reader.read(&mut buf) {
377 assert_eq!(buf[0], 't' as u8);
378 assert_eq!(buf[1], 'e' as u8);
379 assert_eq!(buf[2], 's' as u8);
380 assert_eq!(buf[3], 't' as u8);
382 r => panic!("invalid read: {}", r),
385 assert!(writer.read(&mut buf).is_err());
386 assert!(reader.write(&buf).is_err());