]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/file_unix.rs
auto merge of #17654 : gereeter/rust/no-unnecessary-cell, r=alexcrichton
[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 alloc::arc::Arc;
14 use libc::{mod, c_int, c_void};
15 use std::c_str::CString;
16 use std::mem;
17 use std::rt::rtio::{mod, IoResult};
18
19 use io::{retry, keep_going};
20 use io::util;
21
22 pub type fd_t = libc::c_int;
23
24 struct Inner {
25     fd: fd_t,
26     close_on_drop: bool,
27 }
28
29 pub struct FileDesc {
30     inner: Arc<Inner>
31 }
32
33 impl FileDesc {
34     /// Create a `FileDesc` from an open C file descriptor.
35     ///
36     /// The `FileDesc` will take ownership of the specified file descriptor and
37     /// close it upon destruction if the `close_on_drop` flag is true, otherwise
38     /// it will not close the file descriptor when this `FileDesc` is dropped.
39     ///
40     /// Note that all I/O operations done on this object will be *blocking*, but
41     /// they do not require the runtime to be active.
42     pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
43         FileDesc { inner: Arc::new(Inner {
44             fd: fd,
45             close_on_drop: close_on_drop
46         }) }
47     }
48
49     // FIXME(#10465) these functions should not be public, but anything in
50     //               native::io wanting to use them is forced to have all the
51     //               rtio traits in scope
52     pub fn inner_read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
53         let ret = retry(|| unsafe {
54             libc::read(self.fd(),
55                        buf.as_mut_ptr() as *mut libc::c_void,
56                        buf.len() as libc::size_t)
57         });
58         if ret == 0 {
59             Err(util::eof())
60         } else if ret < 0 {
61             Err(super::last_error())
62         } else {
63             Ok(ret as uint)
64         }
65     }
66     pub fn inner_write(&mut self, buf: &[u8]) -> IoResult<()> {
67         let ret = keep_going(buf, |buf, len| {
68             unsafe {
69                 libc::write(self.fd(), buf as *const libc::c_void,
70                             len as libc::size_t) as i64
71             }
72         });
73         if ret < 0 {
74             Err(super::last_error())
75         } else {
76             Ok(())
77         }
78     }
79
80     pub fn fd(&self) -> fd_t { self.inner.fd }
81 }
82
83 impl rtio::RtioFileStream for FileDesc {
84     fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
85         self.inner_read(buf).map(|i| i as int)
86     }
87     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
88         self.inner_write(buf)
89     }
90     fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
91         match retry(|| unsafe {
92             libc::pread(self.fd(), buf.as_ptr() as *mut _,
93                         buf.len() as libc::size_t,
94                         offset as libc::off_t)
95         }) {
96             -1 => Err(super::last_error()),
97             n => Ok(n as int)
98         }
99     }
100     fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
101         super::mkerr_libc(retry(|| unsafe {
102             libc::pwrite(self.fd(), buf.as_ptr() as *const _,
103                          buf.len() as libc::size_t, offset as libc::off_t)
104         }))
105     }
106     fn seek(&mut self, pos: i64, whence: rtio::SeekStyle) -> IoResult<u64> {
107         let whence = match whence {
108             rtio::SeekSet => libc::SEEK_SET,
109             rtio::SeekEnd => libc::SEEK_END,
110             rtio::SeekCur => libc::SEEK_CUR,
111         };
112         let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
113         if n < 0 {
114             Err(super::last_error())
115         } else {
116             Ok(n as u64)
117         }
118     }
119     fn tell(&self) -> IoResult<u64> {
120         let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
121         if n < 0 {
122             Err(super::last_error())
123         } else {
124             Ok(n as u64)
125         }
126     }
127     fn fsync(&mut self) -> IoResult<()> {
128         super::mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
129     }
130     fn datasync(&mut self) -> IoResult<()> {
131         return super::mkerr_libc(os_datasync(self.fd()));
132
133         #[cfg(any(target_os = "macos", target_os = "ios"))]
134         fn os_datasync(fd: c_int) -> c_int {
135             unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }
136         }
137         #[cfg(target_os = "linux")]
138         fn os_datasync(fd: c_int) -> c_int {
139             retry(|| unsafe { libc::fdatasync(fd) })
140         }
141         #[cfg(not(any(target_os = "macos", target_os = "ios", target_os = "linux")))]
142         fn os_datasync(fd: c_int) -> c_int {
143             retry(|| unsafe { libc::fsync(fd) })
144         }
145     }
146     fn truncate(&mut self, offset: i64) -> IoResult<()> {
147         super::mkerr_libc(retry(|| unsafe {
148             libc::ftruncate(self.fd(), offset as libc::off_t)
149         }))
150     }
151
152     fn fstat(&mut self) -> IoResult<rtio::FileStat> {
153         let mut stat: libc::stat = unsafe { mem::zeroed() };
154         match unsafe { libc::fstat(self.fd(), &mut stat) } {
155             0 => Ok(mkstat(&stat)),
156             _ => Err(super::last_error()),
157         }
158     }
159 }
160
161 impl rtio::RtioPipe for FileDesc {
162     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
163         self.inner_read(buf)
164     }
165     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
166         self.inner_write(buf)
167     }
168     fn clone(&self) -> Box<rtio::RtioPipe + Send> {
169         box FileDesc { inner: self.inner.clone() } as Box<rtio::RtioPipe + Send>
170     }
171
172     // Only supported on named pipes currently. Note that this doesn't have an
173     // impact on the std::io primitives, this is never called via
174     // std::io::PipeStream. If the functionality is exposed in the future, then
175     // these methods will need to be implemented.
176     fn close_read(&mut self) -> IoResult<()> {
177         Err(super::unimpl())
178     }
179     fn close_write(&mut self) -> IoResult<()> {
180         Err(super::unimpl())
181     }
182     fn set_timeout(&mut self, _t: Option<u64>) {}
183     fn set_read_timeout(&mut self, _t: Option<u64>) {}
184     fn set_write_timeout(&mut self, _t: Option<u64>) {}
185 }
186
187 impl rtio::RtioTTY for FileDesc {
188     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
189         self.inner_read(buf)
190     }
191     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
192         self.inner_write(buf)
193     }
194     fn set_raw(&mut self, _raw: bool) -> IoResult<()> {
195         Err(super::unimpl())
196     }
197     fn get_winsize(&mut self) -> IoResult<(int, int)> {
198         Err(super::unimpl())
199     }
200     fn isatty(&self) -> bool { false }
201 }
202
203 impl Drop for Inner {
204     fn drop(&mut self) {
205         // closing stdio file handles makes no sense, so never do it. Also, note
206         // that errors are ignored when closing a file descriptor. The reason
207         // for this is that if an error occurs we don't actually know if the
208         // file descriptor was closed or not, and if we retried (for something
209         // like EINTR), we might close another valid file descriptor (opened
210         // after we closed ours.
211         if self.close_on_drop && self.fd > libc::STDERR_FILENO {
212             let n = unsafe { libc::close(self.fd) };
213             if n != 0 {
214                 println!("error {} when closing file descriptor {}", n,
215                          self.fd);
216             }
217         }
218     }
219 }
220
221 pub struct CFile {
222     file: *mut libc::FILE,
223     fd: FileDesc,
224 }
225
226 impl CFile {
227     /// Create a `CFile` from an open `FILE` pointer.
228     ///
229     /// The `CFile` takes ownership of the `FILE` pointer and will close it upon
230     /// destruction.
231     pub fn new(file: *mut libc::FILE) -> CFile {
232         CFile {
233             file: file,
234             fd: FileDesc::new(unsafe { libc::fileno(file) }, false)
235         }
236     }
237
238     pub fn flush(&mut self) -> IoResult<()> {
239         super::mkerr_libc(retry(|| unsafe { libc::fflush(self.file) }))
240     }
241 }
242
243 impl rtio::RtioFileStream for CFile {
244     fn read(&mut self, buf: &mut [u8]) -> IoResult<int> {
245         let ret = keep_going(buf, |buf, len| {
246             unsafe {
247                 libc::fread(buf as *mut libc::c_void, 1, len as libc::size_t,
248                             self.file) as i64
249             }
250         });
251         if ret == 0 {
252             Err(util::eof())
253         } else if ret < 0 {
254             Err(super::last_error())
255         } else {
256             Ok(ret as int)
257         }
258     }
259
260     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
261         let ret = keep_going(buf, |buf, len| {
262             unsafe {
263                 libc::fwrite(buf as *const libc::c_void, 1, len as libc::size_t,
264                             self.file) as i64
265             }
266         });
267         if ret < 0 {
268             Err(super::last_error())
269         } else {
270             Ok(())
271         }
272     }
273
274     fn pread(&mut self, buf: &mut [u8], offset: u64) -> IoResult<int> {
275         self.flush().and_then(|()| self.fd.pread(buf, offset))
276     }
277     fn pwrite(&mut self, buf: &[u8], offset: u64) -> IoResult<()> {
278         self.flush().and_then(|()| self.fd.pwrite(buf, offset))
279     }
280     fn seek(&mut self, pos: i64, style: rtio::SeekStyle) -> IoResult<u64> {
281         let whence = match style {
282             rtio::SeekSet => libc::SEEK_SET,
283             rtio::SeekEnd => libc::SEEK_END,
284             rtio::SeekCur => libc::SEEK_CUR,
285         };
286         let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) };
287         if n < 0 {
288             Err(super::last_error())
289         } else {
290             Ok(n as u64)
291         }
292     }
293     fn tell(&self) -> IoResult<u64> {
294         let ret = unsafe { libc::ftell(self.file) };
295         if ret < 0 {
296             Err(super::last_error())
297         } else {
298             Ok(ret as u64)
299         }
300     }
301     fn fsync(&mut self) -> IoResult<()> {
302         self.flush().and_then(|()| self.fd.fsync())
303     }
304     fn datasync(&mut self) -> IoResult<()> {
305         self.flush().and_then(|()| self.fd.datasync())
306     }
307     fn truncate(&mut self, offset: i64) -> IoResult<()> {
308         self.flush().and_then(|()| self.fd.truncate(offset))
309     }
310
311     fn fstat(&mut self) -> IoResult<rtio::FileStat> {
312         self.flush().and_then(|()| self.fd.fstat())
313     }
314 }
315
316 impl Drop for CFile {
317     fn drop(&mut self) {
318         unsafe { let _ = libc::fclose(self.file); }
319     }
320 }
321
322 pub fn open(path: &CString, fm: rtio::FileMode, fa: rtio::FileAccess)
323     -> IoResult<FileDesc>
324 {
325     let flags = match fm {
326         rtio::Open => 0,
327         rtio::Append => libc::O_APPEND,
328         rtio::Truncate => libc::O_TRUNC,
329     };
330     // Opening with a write permission must silently create the file.
331     let (flags, mode) = match fa {
332         rtio::Read => (flags | libc::O_RDONLY, 0),
333         rtio::Write => (flags | libc::O_WRONLY | libc::O_CREAT,
334                         libc::S_IRUSR | libc::S_IWUSR),
335         rtio::ReadWrite => (flags | libc::O_RDWR | libc::O_CREAT,
336                             libc::S_IRUSR | libc::S_IWUSR),
337     };
338
339     match retry(|| unsafe { libc::open(path.as_ptr(), flags, mode) }) {
340         -1 => Err(super::last_error()),
341         fd => Ok(FileDesc::new(fd, true)),
342     }
343 }
344
345 pub fn mkdir(p: &CString, mode: uint) -> IoResult<()> {
346     super::mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
347 }
348
349 pub fn readdir(p: &CString) -> IoResult<Vec<CString>> {
350     use libc::{dirent_t};
351     use libc::{opendir, readdir_r, closedir};
352
353     fn prune(root: &CString, dirs: Vec<Path>) -> Vec<CString> {
354         let root = unsafe { CString::new(root.as_ptr(), false) };
355         let root = Path::new(root);
356
357         dirs.into_iter().filter(|path| {
358             path.as_vec() != b"." && path.as_vec() != b".."
359         }).map(|path| root.join(path).to_c_str()).collect()
360     }
361
362     extern {
363         fn rust_dirent_t_size() -> libc::c_int;
364         fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
365     }
366
367     let size = unsafe { rust_dirent_t_size() };
368     let mut buf = Vec::<u8>::with_capacity(size as uint);
369     let ptr = buf.as_mut_slice().as_mut_ptr() as *mut dirent_t;
370
371     let dir_ptr = unsafe {opendir(p.as_ptr())};
372
373     if dir_ptr as uint != 0 {
374         let mut paths = vec!();
375         let mut entry_ptr = 0 as *mut dirent_t;
376         while unsafe { readdir_r(dir_ptr, ptr, &mut entry_ptr) == 0 } {
377             if entry_ptr.is_null() { break }
378             let cstr = unsafe {
379                 CString::new(rust_list_dir_val(entry_ptr), false)
380             };
381             paths.push(Path::new(cstr));
382         }
383         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
384         Ok(prune(p, paths))
385     } else {
386         Err(super::last_error())
387     }
388 }
389
390 pub fn unlink(p: &CString) -> IoResult<()> {
391     super::mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
392 }
393
394 pub fn rename(old: &CString, new: &CString) -> IoResult<()> {
395     super::mkerr_libc(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })
396 }
397
398 pub fn chmod(p: &CString, mode: uint) -> IoResult<()> {
399     super::mkerr_libc(retry(|| unsafe {
400         libc::chmod(p.as_ptr(), mode as libc::mode_t)
401     }))
402 }
403
404 pub fn rmdir(p: &CString) -> IoResult<()> {
405     super::mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
406 }
407
408 pub fn chown(p: &CString, uid: int, gid: int) -> IoResult<()> {
409     super::mkerr_libc(retry(|| unsafe {
410         libc::chown(p.as_ptr(), uid as libc::uid_t,
411                     gid as libc::gid_t)
412     }))
413 }
414
415 pub fn readlink(p: &CString) -> IoResult<CString> {
416     let p = p.as_ptr();
417     let mut len = unsafe { libc::pathconf(p as *mut _, libc::_PC_NAME_MAX) };
418     if len == -1 {
419         len = 1024; // FIXME: read PATH_MAX from C ffi?
420     }
421     let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
422     match unsafe {
423         libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
424                        len as libc::size_t) as libc::c_int
425     } {
426         -1 => Err(super::last_error()),
427         n => {
428             assert!(n > 0);
429             unsafe { buf.set_len(n as uint); }
430             Ok(buf.as_slice().to_c_str())
431         }
432     }
433 }
434
435 pub fn symlink(src: &CString, dst: &CString) -> IoResult<()> {
436     super::mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
437 }
438
439 pub fn link(src: &CString, dst: &CString) -> IoResult<()> {
440     super::mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
441 }
442
443 fn mkstat(stat: &libc::stat) -> rtio::FileStat {
444     // FileStat times are in milliseconds
445     fn mktime(secs: u64, nsecs: u64) -> u64 { secs * 1000 + nsecs / 1000000 }
446
447     #[cfg(not(any(target_os = "linux", target_os = "android")))]
448     fn flags(stat: &libc::stat) -> u64 { stat.st_flags as u64 }
449     #[cfg(any(target_os = "linux", target_os = "android"))]
450     fn flags(_stat: &libc::stat) -> u64 { 0 }
451
452     #[cfg(not(any(target_os = "linux", target_os = "android")))]
453     fn gen(stat: &libc::stat) -> u64 { stat.st_gen as u64 }
454     #[cfg(any(target_os = "linux", target_os = "android"))]
455     fn gen(_stat: &libc::stat) -> u64 { 0 }
456
457     rtio::FileStat {
458         size: stat.st_size as u64,
459         kind: stat.st_mode as u64,
460         perm: stat.st_mode as u64,
461         created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64),
462         modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64),
463         accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64),
464         device: stat.st_dev as u64,
465         inode: stat.st_ino as u64,
466         rdev: stat.st_rdev as u64,
467         nlink: stat.st_nlink as u64,
468         uid: stat.st_uid as u64,
469         gid: stat.st_gid as u64,
470         blksize: stat.st_blksize as u64,
471         blocks: stat.st_blocks as u64,
472         flags: flags(stat),
473         gen: gen(stat),
474     }
475 }
476
477 pub fn stat(p: &CString) -> IoResult<rtio::FileStat> {
478     let mut stat: libc::stat = unsafe { mem::zeroed() };
479     match unsafe { libc::stat(p.as_ptr(), &mut stat) } {
480         0 => Ok(mkstat(&stat)),
481         _ => Err(super::last_error()),
482     }
483 }
484
485 pub fn lstat(p: &CString) -> IoResult<rtio::FileStat> {
486     let mut stat: libc::stat = unsafe { mem::zeroed() };
487     match unsafe { libc::lstat(p.as_ptr(), &mut stat) } {
488         0 => Ok(mkstat(&stat)),
489         _ => Err(super::last_error()),
490     }
491 }
492
493 pub fn utime(p: &CString, atime: u64, mtime: u64) -> IoResult<()> {
494     let buf = libc::utimbuf {
495         actime: (atime / 1000) as libc::time_t,
496         modtime: (mtime / 1000) as libc::time_t,
497     };
498     super::mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
499 }
500
501 #[cfg(test)]
502 mod tests {
503     use super::{CFile, FileDesc};
504     use libc;
505     use std::os;
506     use std::rt::rtio::{RtioFileStream, SeekSet};
507
508     #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
509     #[test]
510     fn test_file_desc() {
511         // Run this test with some pipes so we don't have to mess around with
512         // opening or closing files.
513         let os::Pipe { reader, writer } = unsafe { os::pipe().unwrap() };
514         let mut reader = FileDesc::new(reader, true);
515         let mut writer = FileDesc::new(writer, true);
516
517         writer.inner_write(b"test").ok().unwrap();
518         let mut buf = [0u8, ..4];
519         match reader.inner_read(buf) {
520             Ok(4) => {
521                 assert_eq!(buf[0], 't' as u8);
522                 assert_eq!(buf[1], 'e' as u8);
523                 assert_eq!(buf[2], 's' as u8);
524                 assert_eq!(buf[3], 't' as u8);
525             }
526             r => fail!("invalid read: {:?}", r)
527         }
528
529         assert!(writer.inner_read(buf).is_err());
530         assert!(reader.inner_write(buf).is_err());
531     }
532
533     #[test]
534     fn test_cfile() {
535         unsafe {
536             let f = libc::tmpfile();
537             assert!(!f.is_null());
538             let mut file = CFile::new(f);
539
540             file.write(b"test").ok().unwrap();
541             let mut buf = [0u8, ..4];
542             let _ = file.seek(0, SeekSet).ok().unwrap();
543             match file.read(buf) {
544                 Ok(4) => {
545                     assert_eq!(buf[0], 't' as u8);
546                     assert_eq!(buf[1], 'e' as u8);
547                     assert_eq!(buf[2], 's' as u8);
548                     assert_eq!(buf[3], 't' as u8);
549                 }
550                 r => fail!("invalid read: {:?}", r)
551             }
552         }
553     }
554 }