]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Replace `0 as *const/mut T` with `ptr::null/null_mut()`
[rust.git] / src / libstd / sys / unix / fs.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 prelude::v1::*;
14
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};
19 use io;
20 use libc::{self, c_int, c_void};
21 use mem;
22 use ptr;
23 use sys::retry;
24 use sys_common::{keep_going, eof, mkerr_libc};
25
26 pub type fd_t = libc::c_int;
27
28 pub struct FileDesc {
29     /// The underlying C file descriptor.
30     fd: fd_t,
31
32     /// Whether to close the file descriptor on drop.
33     close_on_drop: bool,
34 }
35
36 impl FileDesc {
37     pub fn new(fd: fd_t, close_on_drop: bool) -> FileDesc {
38         FileDesc { fd: fd, close_on_drop: close_on_drop }
39     }
40
41     pub fn read(&self, buf: &mut [u8]) -> IoResult<uint> {
42         let ret = retry(|| unsafe {
43             libc::read(self.fd(),
44                        buf.as_mut_ptr() as *mut libc::c_void,
45                        buf.len() as libc::size_t)
46         });
47         if ret == 0 {
48             Err(eof())
49         } else if ret < 0 {
50             Err(super::last_error())
51         } else {
52             Ok(ret as uint)
53         }
54     }
55     pub fn write(&self, buf: &[u8]) -> IoResult<()> {
56         let ret = keep_going(buf, |buf, len| {
57             unsafe {
58                 libc::write(self.fd(), buf as *const libc::c_void,
59                             len as libc::size_t) as i64
60             }
61         });
62         if ret < 0 {
63             Err(super::last_error())
64         } else {
65             Ok(())
66         }
67     }
68
69     pub fn fd(&self) -> fd_t { self.fd }
70
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,
76         };
77         let n = unsafe { libc::lseek(self.fd(), pos as libc::off_t, whence) };
78         if n < 0 {
79             Err(super::last_error())
80         } else {
81             Ok(n as u64)
82         }
83     }
84
85     pub fn tell(&self) -> IoResult<u64> {
86         let n = unsafe { libc::lseek(self.fd(), 0, libc::SEEK_CUR) };
87         if n < 0 {
88             Err(super::last_error())
89         } else {
90             Ok(n as u64)
91         }
92     }
93
94     pub fn fsync(&self) -> IoResult<()> {
95         mkerr_libc(retry(|| unsafe { libc::fsync(self.fd()) }))
96     }
97
98     pub fn datasync(&self) -> IoResult<()> {
99         return mkerr_libc(os_datasync(self.fd()));
100
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) }
104         }
105         #[cfg(target_os = "linux")]
106         fn os_datasync(fd: c_int) -> c_int {
107             retry(|| unsafe { libc::fdatasync(fd) })
108         }
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) })
112         }
113     }
114
115     pub fn truncate(&self, offset: i64) -> IoResult<()> {
116         mkerr_libc(retry(|| unsafe {
117             libc::ftruncate(self.fd(), offset as libc::off_t)
118         }))
119     }
120
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()),
126         }
127     }
128
129     /// Extract the actual filedescriptor without closing it.
130     pub fn unwrap(self) -> fd_t {
131         let fd = self.fd;
132         unsafe { mem::forget(self) };
133         fd
134     }
135 }
136
137 impl Drop for FileDesc {
138     fn drop(&mut self) {
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) };
147             if n != 0 {
148                 println!("error {} when closing file descriptor {}", n, self.fd);
149             }
150         }
151     }
152 }
153
154 fn cstr(path: &Path) -> CString {
155     CString::from_slice(path.as_vec())
156 }
157
158 pub fn open(path: &Path, fm: FileMode, fa: FileAccess) -> IoResult<FileDesc> {
159     let flags = match fm {
160         Open => 0,
161         Append => libc::O_APPEND,
162         Truncate => libc::O_TRUNC,
163     };
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),
171     };
172
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)),
177     }
178 }
179
180 pub fn mkdir(p: &Path, mode: uint) -> IoResult<()> {
181     let p = cstr(p);
182     mkerr_libc(unsafe { libc::mkdir(p.as_ptr(), mode as libc::mode_t) })
183 }
184
185 pub fn readdir(p: &Path) -> IoResult<Vec<Path>> {
186     use libc::{dirent_t};
187     use libc::{opendir, readdir_r, closedir};
188
189     fn prune(root: &CString, dirs: Vec<Path>) -> Vec<Path> {
190         let root = Path::new(root);
191
192         dirs.into_iter().filter(|path| {
193             path.as_vec() != b"." && path.as_vec() != b".."
194         }).map(|path| root.join(path)).collect()
195     }
196
197     extern {
198         fn rust_dirent_t_size() -> libc::c_int;
199         fn rust_list_dir_val(ptr: *mut dirent_t) -> *const libc::c_char;
200     }
201
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;
205
206     let p = CString::from_slice(p.as_vec());
207     let dir_ptr = unsafe {opendir(p.as_ptr())};
208
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 }
214             paths.push(unsafe {
215                 Path::new(ffi::c_str_to_bytes(&rust_list_dir_val(entry_ptr)))
216             });
217         }
218         assert_eq!(unsafe { closedir(dir_ptr) }, 0);
219         Ok(prune(&p, paths))
220     } else {
221         Err(super::last_error())
222     }
223 }
224
225 pub fn unlink(p: &Path) -> IoResult<()> {
226     let p = cstr(p);
227     mkerr_libc(unsafe { libc::unlink(p.as_ptr()) })
228 }
229
230 pub fn rename(old: &Path, new: &Path) -> IoResult<()> {
231     let old = cstr(old);
232     let new = cstr(new);
233     mkerr_libc(unsafe {
234         libc::rename(old.as_ptr(), new.as_ptr())
235     })
236 }
237
238 pub fn chmod(p: &Path, mode: uint) -> IoResult<()> {
239     let p = cstr(p);
240     mkerr_libc(retry(|| unsafe {
241         libc::chmod(p.as_ptr(), mode as libc::mode_t)
242     }))
243 }
244
245 pub fn rmdir(p: &Path) -> IoResult<()> {
246     let p = cstr(p);
247     mkerr_libc(unsafe { libc::rmdir(p.as_ptr()) })
248 }
249
250 pub fn chown(p: &Path, uid: int, gid: int) -> IoResult<()> {
251     let p = cstr(p);
252     mkerr_libc(retry(|| unsafe {
253         libc::chown(p.as_ptr(), uid as libc::uid_t, gid as libc::gid_t)
254     }))
255 }
256
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) };
261     if len == -1 {
262         len = 1024; // FIXME: read PATH_MAX from C ffi?
263     }
264     let mut buf: Vec<u8> = Vec::with_capacity(len as uint);
265     match unsafe {
266         libc::readlink(p, buf.as_ptr() as *mut libc::c_char,
267                        len as libc::size_t) as libc::c_int
268     } {
269         -1 => Err(super::last_error()),
270         n => {
271             assert!(n > 0);
272             unsafe { buf.set_len(n as uint); }
273             Ok(Path::new(buf))
274         }
275     }
276 }
277
278 pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> {
279     let src = cstr(src);
280     let dst = cstr(dst);
281     mkerr_libc(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })
282 }
283
284 pub fn link(src: &Path, dst: &Path) -> IoResult<()> {
285     let src = cstr(src);
286     let dst = cstr(dst);
287     mkerr_libc(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })
288 }
289
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 }
293
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 }
298
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 }
303
304     FileStat {
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,
313         },
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,
327             flags: flags(stat),
328             gen: gen(stat),
329         },
330     }
331 }
332
333 pub fn stat(p: &Path) -> IoResult<FileStat> {
334     let p = cstr(p);
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()),
339     }
340 }
341
342 pub fn lstat(p: &Path) -> IoResult<FileStat> {
343     let p = cstr(p);
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()),
348     }
349 }
350
351 pub fn utime(p: &Path, atime: u64, mtime: u64) -> IoResult<()> {
352     let p = cstr(p);
353     let buf = libc::utimbuf {
354         actime: (atime / 1000) as libc::time_t,
355         modtime: (mtime / 1000) as libc::time_t,
356     };
357     mkerr_libc(unsafe { libc::utime(p.as_ptr(), &buf) })
358 }
359
360 #[cfg(test)]
361 mod tests {
362     use super::FileDesc;
363     use libc;
364     use os;
365     use prelude::v1::*;
366
367     #[cfg_attr(target_os = "freebsd", ignore)] // hmm, maybe pipes have a tiny buffer
368     #[test]
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);
375
376         writer.write(b"test").ok().unwrap();
377         let mut buf = [0u8; 4];
378         match reader.read(&mut buf) {
379             Ok(4) => {
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);
384             }
385             r => panic!("invalid read: {:?}", r),
386         }
387
388         assert!(writer.read(&mut buf).is_err());
389         assert!(reader.write(&buf).is_err());
390     }
391 }