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 libc::{mod, c_int, c_void};
20 use io::{FilePermission, Write, UnstableFileStat, Open, FileAccess, FileMode};
21 use io::{IoResult, FileStat, SeekStyle};
22 use io::{Read, Truncate, SeekCur, SeekSet, ReadWrite, SeekEnd, Append};
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 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
155 let flags = match fm {
157 Append => libc::O_APPEND,
158 Truncate => libc::O_TRUNC,
160 // Opening with a write permission must silently create the file.
161 let (flags, mode) = match fa {
162 Read => (flags | libc::O_RDONLY, 0),
163 Write => (flags | libc::O_WRONLY | libc::O_CREAT,
164 libc::S_IRUSR | libc::S_IWUSR),
165 ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
166 libc::S_IRUSR | libc::S_IWUSR),
169 let path = path.to_c_str();
170 match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
171 -1 => Err(super::last_error()),
172 fd => Ok(FileDesc::new(fd, true)),
176 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
177 let p = p.to_c_str();
178 mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
181 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
182 use libc::{dirent_t};
183 use libc::{opendir, readdir_r, closedir};
185 fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
186 let root = unsafe { CString::new(root.as_ptr(), false) };
187 let root = Path::new(root);
189 dirs.into_iter().filter(|path| {
190 path.as_vec() != b"." && path.as_vec() != b".."
191 }).map(|path| root.join(path)).collect()
195 fn rust_dirent_t_size() -> libc::c_int;
196 fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
199 let size = unsafe { rust_dirent_t_size() };
200 let mut buf = Vec::<u8>::with_capacity(size as uint);
201 let ptr = buf.as_mut_ptr() as *mut dirent_t;
203 let p = p.to_c_str();
204 let dir_ptr = unsafe {opendir(p.as_ptr())};
206 if dir_ptr as uint != 0 {
207 let mut paths = vec!();
208 let mut entry_ptr = 0 as *mut dirent_t;
209 while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
210 if entry_ptr.is_null() { break }
212 CString::new(rust_list_dir_val(entry_ptr), false)
214 paths.push(Path::new(cstr));
216 assert_eq!(unsafe { closedir(dir_ptr) }, 0);
219 Err(super::last_error())
223 pub fn unlink(p: &Path) -> IoResult<()> {
224 let p = p.to_c_str();
225 mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
228 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
229 let old = old.to_c_str();
230 let new = new.to_c_str();
232 libc::rename(old.as_ptr(), new.as_ptr())
236 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
237 let p = p.to_c_str();
238 mkerr_libc(retry(|| unsafe {
239 libc::chmod(p.as_ptr(), mode as libc::mode_t)
243 pub fn rmdir(p: &Path) -> IoResult<()> {
244 let p = p.to_c_str();
245 mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
248 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
249 let p = p.to_c_str();
250 mkerr_libc(retry(|| unsafe {
251 libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
255 pub fn readlink(p: &Path) -> IoResult<Path> {
256 let c_path = p.to_c_str();
257 let p = c_path.as_ptr();
258 let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
260 len = 1024; // FIXME: read PATH_MAX from C ffi?
262 let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
264 libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
265 len as libc::size_t) as libc::c_int
267 -1 => Err(super::last_error()),
270 unsafe { buf.set_len(n as uint); }
276 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
277 let src = src.to_c_str();
278 let dst = dst.to_c_str();
279 mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
282 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
283 let src = src.to_c_str();
284 let dst = dst.to_c_str();
285 mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
288 fn mkstat(stat: &libc::stat) -> FileStat {
289 // FileStat times are in milliseconds
290 fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
292 #[cfg(not(any(target_os = "linux", target_os = "android")))]
293 fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
294 #[cfg(any(target_os = "linux", target_os = "android"))]
295 fn flags(_stat: &libc::stat) -> u64 { 0 }
297 #[cfg(not(any(target_os = "linux", target_os = "android")))]
298 fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
299 #[cfg(any(target_os = "linux", target_os = "android"))]
300 fn gen(_stat: &libc::stat) -> u64 { 0 }
303 size: stat.st_size as u64,
304 kind: match (stat.st_mode as libc::mode_t) & libc::S_IFMT {
305 libc::S_IFREG => io::FileType::RegularFile,
306 libc::S_IFDIR => io::FileType::Directory,
307 libc::S_IFIFO => io::FileType::NamedPipe,
308 libc::S_IFBLK => io::FileType::BlockSpecial,
309 libc::S_IFLNK => io::FileType::Symlink,
310 _ => io::FileType::Unknown,
312 perm: FilePermission::from_bits_truncate(stat.st_mode as u32),
313 created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
314 modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
315 accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
316 unstable: UnstableFileStat {
317 device: stat.st_dev as u64,
318 inode: stat.st_ino as u64,
319 rdev: stat.st_rdev as u64,
320 nlink: stat.st_nlink as u64,
321 uid: stat.st_uid as u64,
322 gid: stat.st_gid as u64,
323 blksize: stat.st_blksize as u64,
324 blocks: stat.st_blocks as u64,
331 pub fn stat(p: &Path) -> IoResult<FileStat> {
332 let p = p.to_c_str();
333 let mut stat: libc::stat = unsafe { mem::zeroed() };
334 match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
335 0 => Ok(mkstat(&stat)),
336 _ => Err(super::last_error()),
340 pub fn lstat(p: &Path) -> IoResult<FileStat> {
341 let p = p.to_c_str();
342 let mut stat: libc::stat = unsafe { mem::zeroed() };
343 match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
344 0 => Ok(mkstat(&stat)),
345 _ => Err(super::last_error()),
349 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
350 let p = p.to_c_str();
351 let buf = libc::utimbuf {
352 actime: (atime / 1000) as libc::time_t,
353 modtime: (mtime / 1000) as libc::time_t,
355 mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
365 #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
367 fn test_file_desc() {
368 // Run this test with some pipes so we don't have to mess around with
369 // opening or closing files.
370 let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
371 let mut reader = FileDesc::new(reader, true);
372 let mut writer = FileDesc::new(writer, true);
374 writer.write(b"test").ok().unwrap();
375 let mut buf = [0u8; 4];
376 match reader.read(&mut buf) {
378 assert_eq!(buf[0], 't' as u8);
379 assert_eq!(buf[1], 'e' as u8);
380 assert_eq!(buf[2], 's' as u8);
381 assert_eq!(buf[3], 't' as u8);
383 r => panic!("invalid read: {}", r),
386 assert!(writer.read(&mut buf).is_err());
387 assert!(reader.write(&buf).is_err());