]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/file_unix.rs
Ignore tests broken by failing on ICE
[rust.git] / src / libnative / io / file_unix.rs
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.
4 //
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.
10
11 //! Blocking posix-based file I/O
12
13 use std::sync::arc::UnsafeArc;
14 use std::c_str::CString;
15 use std::io::IoError;
16 use std::io;
17 use libc::{c_int, c_void};
18 use libc;
19 use std::mem;
20 use std::rt::rtio;
21
22 use io::{IoResult, retry, keep_going};
23
24 pub type fd_t = libc::c_int;
25
26 struct Inner {
27     fd: fd_t,
28     close_on_drop: bool,
29 }
30
31 pub struct FileDesc {
32     inner: UnsafeArc<Inner>
33 }
34
35 impl FileDesc {
36     /// Create a `FileDesc` from an open C file descriptor.
37     ///
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.
41     ///
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 {
46             fd: fd,
47             close_on_drop: close_on_drop
48         }) }
49     }
50
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 {
56             libc::read(self.fd(),
57                        buf.as_mut_ptr() as *mut libc::c_void,
58                        buf.len() as libc::size_t) as libc::c_int
59         });
60         if ret == 0 {
61             Err(io::standard_error(io::EndOfFile))
62         } else if ret < 0 {
63             Err(super::last_error())
64         } else {
65             Ok(ret as uint)
66         }
67     }
68     pub fn inner_write(&mut self, buf: &[u8]) -> Result<(), IoError> {
69         let ret = keep_going(buf, |buf, len| {
70             unsafe {
71                 libc::write(self.fd(), buf as *libc::c_void,
72                             len as libc::size_t) as i64
73             }
74         });
75         if ret < 0 {
76             Err(super::last_error())
77         } else {
78             Ok(())
79         }
80     }
81
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 }
86     }
87 }
88
89 impl io::Reader for FileDesc {
90     fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
91         self.inner_read(buf)
92     }
93 }
94
95 impl io::Writer for FileDesc {
96     fn write(&mut self, buf: &[u8]) -> io::IoResult<()> {
97         self.inner_write(buf)
98     }
99 }
100
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)
104     }
105     fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
106         self.inner_write(buf)
107     }
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
113         }) {
114             -1 => Err(super::last_error()),
115             n => Ok(n as int)
116         }
117     }
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)
122         } as c_int))
123     }
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,
129         };
130         let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
131         if n < 0 {
132             Err(super::last_error())
133         } else {
134             Ok(n as u64)
135         }
136     }
137     fn tell(&self) -> Result<u64, IoError> {
138         let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
139         if n < 0 {
140             Err(super::last_error())
141         } else {
142             Ok(n as u64)
143         }
144     }
145     fn fsync(&mut self) -> Result<(), IoError> {
146         super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
147     }
148     fn datasync(&mut self) -> Result<(), IoError> {
149         return super::mkerr_libc(os_datasync(self.fd()));
150
151         #[cfg(target_os = "macos")]
152         fn os_datasync(fd: c_int) -> c_int {
153             unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
154         }
155         #[cfg(target_os = "linux")]
156         fn os_datasync(fd: c_int) -> c_int {
157             retry(|| unsafe { libc::fdatasync(fd) })
158         }
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) })
162         }
163     }
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)
167         }))
168     }
169 }
170
171 impl rtio::RtioPipe for FileDesc {
172     fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
173         self.inner_read(buf)
174     }
175     fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
176         self.inner_write(buf)
177     }
178     fn clone(&self) -> ~rtio::RtioPipe:Send {
179         box FileDesc { inner: self.inner.clone() } as ~rtio::RtioPipe:Send
180     }
181 }
182
183 impl rtio::RtioTTY for FileDesc {
184     fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError> {
185         self.inner_read(buf)
186     }
187     fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
188         self.inner_write(buf)
189     }
190     fn set_raw(&mut self, _raw: bool) -> Result<(), IoError> {
191         Err(super::unimpl())
192     }
193     fn get_winsize(&mut self) -> Result<(int, int), IoError> {
194         Err(super::unimpl())
195     }
196     fn isatty(&self) -> bool { false }
197 }
198
199 impl Drop for Inner {
200     fn drop(&mut self) {
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) };
209             if n != 0 {
210                 println!("error {} when closing file descriptor {}", n,
211                          self.fd);
212             }
213         }
214     }
215 }
216
217 pub struct CFile {
218     file: *libc::FILE,
219     fd: FileDesc,
220 }
221
222 impl CFile {
223     /// Create a `CFile` from an open `FILE` pointer.
224     ///
225     /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
226     /// destruction.
227     pub fn new(file: *libc::FILE) -> CFile {
228         CFile {
229             file: file,
230             fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
231         }
232     }
233
234     pub fn flush(&mut self) -> Result<(), IoError> {
235         super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
236     }
237 }
238
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| {
242             unsafe {
243                 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
244                             self.file) as i64
245             }
246         });
247         if ret == 0 {
248             Err(io::standard_error(io::EndOfFile))
249         } else if ret < 0 {
250             Err(super::last_error())
251         } else {
252             Ok(ret as int)
253         }
254     }
255
256     fn write(&mut self, buf: &[u8]) -> Result<(), IoError> {
257         let ret = keep_going(buf, |buf, len| {
258             unsafe {
259                 libc::fwrite(buf as *libc::c_void, 1, len as libc::size_t,
260                             self.file) as i64
261             }
262         });
263         if ret < 0 {
264             Err(super::last_error())
265         } else {
266             Ok(())
267         }
268     }
269
270     fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError> {
271         self.flush().and_then(|()| self.fd.pread(buf, offset))
272     }
273     fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError> {
274         self.flush().and_then(|()| self.fd.pwrite(buf, offset))
275     }
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,
281         };
282         let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
283         if n < 0 {
284             Err(super::last_error())
285         } else {
286             Ok(n as u64)
287         }
288     }
289     fn tell(&self) -> Result<u64, IoError> {
290         let ret = unsafe { libc::ftell(self.file) };
291         if ret < 0 {
292             Err(super::last_error())
293         } else {
294             Ok(ret as u64)
295         }
296     }
297     fn fsync(&mut self) -> Result<(), IoError> {
298         self.flush().and_then(|()| self.fd.fsync())
299     }
300     fn datasync(&mut self) -> Result<(), IoError> {
301         self.flush().and_then(|()| self.fd.fsync())
302     }
303     fn truncate(&mut self, offset: i64) -> Result<(), IoError> {
304         self.flush().and_then(|()| self.fd.truncate(offset))
305     }
306 }
307
308 impl Drop for CFile {
309     fn drop(&mut self) {
310         unsafe { let _ = libc::fclose(self.file); }
311     }
312 }
313
314 pub fn open(path: &CString, fm: io::FileMode, fa: io::FileAccess)
315         -> IoResult<FileDesc> {
316     let flags = match fm {
317         io::Open => 0,
318         io::Append => libc::O_APPEND,
319         io::Truncate => libc::O_TRUNC,
320     };
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),
328     };
329
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)),
333     }
334 }
335
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)
339     }))
340 }
341
342 pub fn readdir(p: &CString) -> IoResult<Vec<Path>> {
343     use libc::{dirent_t};
344     use libc::{opendir, readdir_r, closedir};
345
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);
349
350         dirs.move_iter().filter(|path| {
351             path.as_vec() != bytes!(".") && path.as_vec() != bytes!("..")
352         }).map(|path| root.join(path)).collect()
353     }
354
355     extern {
356         fn rust_dirent_t_size() -> libc::c_int;
357         fn rust_list_dir_val(ptr: *mut dirent_t) -> *libc::c_char;
358     }
359
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;
363
364     let dir_ptr = p.with_ref(|buf| unsafe { opendir(buf) });
365
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 }
371             let cstr = unsafe {
372                 CString::new(rust_list_dir_val(entry_ptr), false)
373             };
374             paths.push(Path::new(cstr));
375         }
376         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
377         Ok(prune(p, paths))
378     } else {
379         Err(super::last_error())
380     }
381 }
382
383 pub fn unlink(p: &CString) -> IoResult<()> {
384     super::mkerr_libc(retry(|| unsafe { libc::unlink(p.with_ref(|p| p)) }))
385 }
386
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))
390     }))
391 }
392
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)
396     }))
397 }
398
399 pub fn rmdir(p: &CString) -> IoResult<()> {
400     super::mkerr_libc(retry(|| unsafe {
401         libc::rmdir(p.with_ref(|p| p))
402     }))
403 }
404
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,
408                     gid as libc::gid_t)
409     }))
410 }
411
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) };
415     if len == -1 {
416         len = 1024; // FIXME: read PATH_MAX from C ffi?
417     }
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
422     }) {
423         -1 => Err(super::last_error()),
424         n => {
425             assert!(n > 0);
426             unsafe { buf.set_len(n as uint); }
427             Ok(Path::new(buf))
428         }
429     }
430 }
431
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))
435     }))
436 }
437
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))
441     }))
442 }
443
444 fn mkstat(stat: &libc::stat, path: &CString) -> io::FileStat {
445     let path = unsafe { CString::new(path.with_ref(|p| p), false) };
446
447     // FileStat times are in milliseconds
448     fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
449
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,
457     };
458
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 }
463
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 }
468
469     io::FileStat {
470         path: Path::new(path),
471         size: stat.st_size as u64,
472         kind: kind,
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,
486             flags: flags(stat),
487             gen: gen(stat),
488         }
489     }
490 }
491
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()),
497     }
498 }
499
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()),
505     }
506 }
507
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,
512     };
513     super::mkerr_libc(retry(|| unsafe {
514         libc::utime(p.with_ref(|p| p), &buf)
515     }))
516 }
517
518 #[cfg(test)]
519 mod tests {
520     use super::{CFile, FileDesc};
521     use std::io;
522     use libc;
523     use std::os;
524     use std::rt::rtio::RtioFileStream;
525
526     #[ignore(cfg(target_os = "freebsd"))] // hmm, maybe pipes have a tiny buffer
527     #[test]
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);
534
535         writer.inner_write(bytes!("test")).unwrap();
536         let mut buf = [0u8, ..4];
537         match reader.inner_read(buf) {
538             Ok(4) => {
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);
543             }
544             r => fail!("invalid read: {:?}", r)
545         }
546
547         assert!(writer.inner_read(buf).is_err());
548         assert!(reader.inner_write(buf).is_err());
549     }
550
551     #[test]
552     fn test_cfile() {
553         unsafe {
554             let f = libc::tmpfile();
555             assert!(!f.is_null());
556             let mut file = CFile::new(f);
557
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) {
562                 Ok(4) => {
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);
567                 }
568                 r => fail!("invalid read: {:?}", r)
569             }
570         }
571     }
572 }