]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
ab8b700e193e2061b361e5ac5336240421785c2e
[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 use prelude::v1::*;
12 use io::prelude::*;
13 use os::unix::prelude::*;
14
15 use ffi::{CString, CStr, OsString, OsStr};
16 use fmt;
17 use io::{self, Error, ErrorKind, SeekFrom};
18 use libc::{self, dirent, c_int, mode_t};
19 use mem;
20 use path::{Path, PathBuf};
21 use ptr;
22 use sync::Arc;
23 use sys::fd::FileDesc;
24 use sys::time::SystemTime;
25 use sys::{cvt, cvt_r};
26 use sys_common::{AsInner, FromInner};
27
28 #[cfg(target_os = "linux")]
29 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64};
30 #[cfg(not(target_os = "linux"))]
31 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
32            ftruncate as ftruncate64, lseek as lseek64};
33
34 pub struct File(FileDesc);
35
36 #[derive(Clone)]
37 pub struct FileAttr {
38     stat: stat64,
39 }
40
41 pub struct ReadDir {
42     dirp: Dir,
43     root: Arc<PathBuf>,
44 }
45
46 struct Dir(*mut libc::DIR);
47
48 unsafe impl Send for Dir {}
49 unsafe impl Sync for Dir {}
50
51 pub struct DirEntry {
52     entry: dirent,
53     root: Arc<PathBuf>,
54     // We need to store an owned copy of the directory name
55     // on Solaris because a) it uses a zero-length array to
56     // store the name, b) its lifetime between readdir calls
57     // is not guaranteed.
58     #[cfg(target_os = "solaris")]
59     name: Box<[u8]>
60 }
61
62 #[derive(Clone)]
63 pub struct OpenOptions {
64     // generic
65     read: bool,
66     write: bool,
67     append: bool,
68     truncate: bool,
69     create: bool,
70     create_new: bool,
71     // system-specific
72     custom_flags: i32,
73     mode: mode_t,
74 }
75
76 #[derive(Clone, PartialEq, Eq, Debug)]
77 pub struct FilePermissions { mode: mode_t }
78
79 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
80 pub struct FileType { mode: mode_t }
81
82 pub struct DirBuilder { mode: mode_t }
83
84 impl FileAttr {
85     pub fn size(&self) -> u64 { self.stat.st_size as u64 }
86     pub fn perm(&self) -> FilePermissions {
87         FilePermissions { mode: (self.stat.st_mode as mode_t) & 0o777 }
88     }
89
90     pub fn file_type(&self) -> FileType {
91         FileType { mode: self.stat.st_mode as mode_t }
92     }
93 }
94
95 #[cfg(any(target_os = "ios", target_os = "macos"))]
96 // FIXME: update SystemTime to store a timespec and don't lose precision
97 impl FileAttr {
98     pub fn modified(&self) -> io::Result<SystemTime> {
99         Ok(SystemTime::from(libc::timeval {
100             tv_sec: self.stat.st_mtime,
101             tv_usec: (self.stat.st_mtime_nsec / 1000) as libc::suseconds_t,
102         }))
103     }
104
105     pub fn accessed(&self) -> io::Result<SystemTime> {
106         Ok(SystemTime::from(libc::timeval {
107             tv_sec: self.stat.st_atime,
108             tv_usec: (self.stat.st_atime_nsec / 1000) as libc::suseconds_t,
109         }))
110     }
111
112     pub fn created(&self) -> io::Result<SystemTime> {
113         Ok(SystemTime::from(libc::timeval {
114             tv_sec: self.stat.st_birthtime,
115             tv_usec: (self.stat.st_birthtime_nsec / 1000) as libc::suseconds_t,
116         }))
117     }
118 }
119
120 #[cfg(not(any(target_os = "ios", target_os = "macos")))]
121 impl FileAttr {
122     pub fn modified(&self) -> io::Result<SystemTime> {
123         Ok(SystemTime::from(libc::timespec {
124             tv_sec: self.stat.st_mtime as libc::time_t,
125             tv_nsec: self.stat.st_mtime_nsec as libc::c_long,
126         }))
127     }
128
129     pub fn accessed(&self) -> io::Result<SystemTime> {
130         Ok(SystemTime::from(libc::timespec {
131             tv_sec: self.stat.st_atime as libc::time_t,
132             tv_nsec: self.stat.st_atime_nsec as libc::c_long,
133         }))
134     }
135
136     #[cfg(any(target_os = "bitrig",
137               target_os = "freebsd",
138               target_os = "openbsd"))]
139     pub fn created(&self) -> io::Result<SystemTime> {
140         Ok(SystemTime::from(libc::timespec {
141             tv_sec: self.stat.st_birthtime as libc::time_t,
142             tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
143         }))
144     }
145
146     #[cfg(not(any(target_os = "bitrig",
147                   target_os = "freebsd",
148                   target_os = "openbsd")))]
149     pub fn created(&self) -> io::Result<SystemTime> {
150         Err(io::Error::new(io::ErrorKind::Other,
151                            "creation time is not available on this platform \
152                             currently"))
153     }
154 }
155
156 impl AsInner<stat64> for FileAttr {
157     fn as_inner(&self) -> &stat64 { &self.stat }
158 }
159
160 impl FilePermissions {
161     pub fn readonly(&self) -> bool { self.mode & 0o222 == 0 }
162     pub fn set_readonly(&mut self, readonly: bool) {
163         if readonly {
164             self.mode &= !0o222;
165         } else {
166             self.mode |= 0o222;
167         }
168     }
169     pub fn mode(&self) -> u32 { self.mode as u32 }
170 }
171
172 impl FileType {
173     pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
174     pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
175     pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
176
177     pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
178 }
179
180 impl FromInner<u32> for FilePermissions {
181     fn from_inner(mode: u32) -> FilePermissions {
182         FilePermissions { mode: mode as mode_t }
183     }
184 }
185
186 impl Iterator for ReadDir {
187     type Item = io::Result<DirEntry>;
188
189     #[cfg(target_os = "solaris")]
190     fn next(&mut self) -> Option<io::Result<DirEntry>> {
191         unsafe {
192             loop {
193                 // Although readdir_r(3) would be a correct function to use here because
194                 // of the thread safety, on Illumos the readdir(3C) function is safe to use
195                 // in threaded applications and it is generally preferred over the
196                 // readdir_r(3C) function.
197                 let entry_ptr = libc::readdir(self.dirp.0);
198                 if entry_ptr.is_null() {
199                     return None
200                 }
201
202                 let name = (*entry_ptr).d_name.as_ptr();
203                 let namelen = libc::strlen(name) as usize;
204
205                 let ret = DirEntry {
206                     entry: *entry_ptr,
207                     name: ::slice::from_raw_parts(name as *const u8,
208                                                   namelen as usize).to_owned().into_boxed_slice(),
209                     root: self.root.clone()
210                 };
211                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
212                     return Some(Ok(ret))
213                 }
214             }
215         }
216     }
217
218     #[cfg(not(target_os = "solaris"))]
219     fn next(&mut self) -> Option<io::Result<DirEntry>> {
220         unsafe {
221             let mut ret = DirEntry {
222                 entry: mem::zeroed(),
223                 root: self.root.clone()
224             };
225             let mut entry_ptr = ptr::null_mut();
226             loop {
227                 if libc::readdir_r(self.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
228                     return Some(Err(Error::last_os_error()))
229                 }
230                 if entry_ptr.is_null() {
231                     return None
232                 }
233                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
234                     return Some(Ok(ret))
235                 }
236             }
237         }
238     }
239 }
240
241 impl Drop for Dir {
242     fn drop(&mut self) {
243         let r = unsafe { libc::closedir(self.0) };
244         debug_assert_eq!(r, 0);
245     }
246 }
247
248 impl DirEntry {
249     pub fn path(&self) -> PathBuf {
250         self.root.join(OsStr::from_bytes(self.name_bytes()))
251     }
252
253     pub fn file_name(&self) -> OsString {
254         OsStr::from_bytes(self.name_bytes()).to_os_string()
255     }
256
257     pub fn metadata(&self) -> io::Result<FileAttr> {
258         lstat(&self.path())
259     }
260
261     #[cfg(target_os = "solaris")]
262     pub fn file_type(&self) -> io::Result<FileType> {
263         stat(&self.path()).map(|m| m.file_type())
264     }
265
266     #[cfg(not(target_os = "solaris"))]
267     pub fn file_type(&self) -> io::Result<FileType> {
268         match self.entry.d_type {
269             libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
270             libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
271             libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
272             libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
273             libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
274             libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
275             libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
276             _ => lstat(&self.path()).map(|m| m.file_type()),
277         }
278     }
279
280     #[cfg(any(target_os = "macos",
281               target_os = "ios",
282               target_os = "linux",
283               target_os = "emscripten",
284               target_os = "android",
285               target_os = "solaris"))]
286     pub fn ino(&self) -> u64 {
287         self.entry.d_ino as u64
288     }
289
290     #[cfg(any(target_os = "freebsd",
291               target_os = "openbsd",
292               target_os = "bitrig",
293               target_os = "netbsd",
294               target_os = "dragonfly"))]
295     pub fn ino(&self) -> u64 {
296         self.entry.d_fileno as u64
297     }
298
299     #[cfg(any(target_os = "macos",
300               target_os = "ios",
301               target_os = "netbsd",
302               target_os = "openbsd",
303               target_os = "freebsd",
304               target_os = "dragonfly",
305               target_os = "bitrig"))]
306     fn name_bytes(&self) -> &[u8] {
307         unsafe {
308             ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
309                                     self.entry.d_namlen as usize)
310         }
311     }
312     #[cfg(any(target_os = "android",
313               target_os = "linux",
314               target_os = "emscripten"))]
315     fn name_bytes(&self) -> &[u8] {
316         unsafe {
317             CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
318         }
319     }
320     #[cfg(target_os = "solaris")]
321     fn name_bytes(&self) -> &[u8] {
322         &*self.name
323     }
324 }
325
326 impl OpenOptions {
327     pub fn new() -> OpenOptions {
328         OpenOptions {
329             // generic
330             read: false,
331             write: false,
332             append: false,
333             truncate: false,
334             create: false,
335             create_new: false,
336             // system-specific
337             custom_flags: 0,
338             mode: 0o666,
339         }
340     }
341
342     pub fn read(&mut self, read: bool) { self.read = read; }
343     pub fn write(&mut self, write: bool) { self.write = write; }
344     pub fn append(&mut self, append: bool) { self.append = append; }
345     pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
346     pub fn create(&mut self, create: bool) { self.create = create; }
347     pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
348
349     pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
350     pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
351
352     fn get_access_mode(&self) -> io::Result<c_int> {
353         match (self.read, self.write, self.append) {
354             (true,  false, false) => Ok(libc::O_RDONLY),
355             (false, true,  false) => Ok(libc::O_WRONLY),
356             (true,  true,  false) => Ok(libc::O_RDWR),
357             (false, _,     true)  => Ok(libc::O_WRONLY | libc::O_APPEND),
358             (true,  _,     true)  => Ok(libc::O_RDWR | libc::O_APPEND),
359             (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
360         }
361     }
362
363     fn get_creation_mode(&self) -> io::Result<c_int> {
364         match (self.write, self.append) {
365             (true, false) => {}
366             (false, false) =>
367                 if self.truncate || self.create || self.create_new {
368                     return Err(Error::from_raw_os_error(libc::EINVAL));
369                 },
370             (_, true) =>
371                 if self.truncate && !self.create_new {
372                     return Err(Error::from_raw_os_error(libc::EINVAL));
373                 },
374         }
375
376         Ok(match (self.create, self.truncate, self.create_new) {
377                 (false, false, false) => 0,
378                 (true,  false, false) => libc::O_CREAT,
379                 (false, true,  false) => libc::O_TRUNC,
380                 (true,  true,  false) => libc::O_CREAT | libc::O_TRUNC,
381                 (_,      _,    true)  => libc::O_CREAT | libc::O_EXCL,
382            })
383     }
384 }
385
386 impl File {
387     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
388         let path = try!(cstr(path));
389         File::open_c(&path, opts)
390     }
391
392     pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
393         let flags = libc::O_CLOEXEC |
394                     try!(opts.get_access_mode()) |
395                     try!(opts.get_creation_mode()) |
396                     (opts.custom_flags as c_int & !libc::O_ACCMODE);
397         let fd = try!(cvt_r(|| unsafe {
398             libc::open(path.as_ptr(), flags, opts.mode as c_int)
399         }));
400         let fd = FileDesc::new(fd);
401
402         // Currently the standard library supports Linux 2.6.18 which did not
403         // have the O_CLOEXEC flag (passed above). If we're running on an older
404         // Linux kernel then the flag is just ignored by the OS, so we continue
405         // to explicitly ask for a CLOEXEC fd here.
406         //
407         // The CLOEXEC flag, however, is supported on versions of OSX/BSD/etc
408         // that we support, so we only do this on Linux currently.
409         if cfg!(target_os = "linux") {
410             fd.set_cloexec();
411         }
412
413         Ok(File(fd))
414     }
415
416     pub fn file_attr(&self) -> io::Result<FileAttr> {
417         let mut stat: stat64 = unsafe { mem::zeroed() };
418         try!(cvt(unsafe {
419             fstat64(self.0.raw(), &mut stat)
420         }));
421         Ok(FileAttr { stat: stat })
422     }
423
424     pub fn fsync(&self) -> io::Result<()> {
425         try!(cvt_r(|| unsafe { libc::fsync(self.0.raw()) }));
426         Ok(())
427     }
428
429     pub fn datasync(&self) -> io::Result<()> {
430         try!(cvt_r(|| unsafe { os_datasync(self.0.raw()) }));
431         return Ok(());
432
433         #[cfg(any(target_os = "macos", target_os = "ios"))]
434         unsafe fn os_datasync(fd: c_int) -> c_int {
435             libc::fcntl(fd, libc::F_FULLFSYNC)
436         }
437         #[cfg(target_os = "linux")]
438         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
439         #[cfg(not(any(target_os = "macos",
440                       target_os = "ios",
441                       target_os = "linux")))]
442         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
443     }
444
445     pub fn truncate(&self, size: u64) -> io::Result<()> {
446         try!(cvt_r(|| unsafe {
447             ftruncate64(self.0.raw(), size as off64_t)
448         }));
449         Ok(())
450     }
451
452     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
453         self.0.read(buf)
454     }
455
456     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
457         self.0.write(buf)
458     }
459
460     pub fn flush(&self) -> io::Result<()> { Ok(()) }
461
462     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
463         let (whence, pos) = match pos {
464             SeekFrom::Start(off) => (libc::SEEK_SET, off as off64_t),
465             SeekFrom::End(off) => (libc::SEEK_END, off as off64_t),
466             SeekFrom::Current(off) => (libc::SEEK_CUR, off as off64_t),
467         };
468         let n = try!(cvt(unsafe { lseek64(self.0.raw(), pos, whence) }));
469         Ok(n as u64)
470     }
471
472     pub fn duplicate(&self) -> io::Result<File> {
473         self.0.duplicate().map(File)
474     }
475
476     pub fn fd(&self) -> &FileDesc { &self.0 }
477
478     pub fn into_fd(self) -> FileDesc { self.0 }
479 }
480
481 impl DirBuilder {
482     pub fn new() -> DirBuilder {
483         DirBuilder { mode: 0o777 }
484     }
485
486     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
487         let p = try!(cstr(p));
488         try!(cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }));
489         Ok(())
490     }
491
492     pub fn set_mode(&mut self, mode: u32) {
493         self.mode = mode as mode_t;
494     }
495 }
496
497 fn cstr(path: &Path) -> io::Result<CString> {
498     Ok(try!(CString::new(path.as_os_str().as_bytes())))
499 }
500
501 impl FromInner<c_int> for File {
502     fn from_inner(fd: c_int) -> File {
503         File(FileDesc::new(fd))
504     }
505 }
506
507 impl fmt::Debug for File {
508     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
509         #[cfg(target_os = "linux")]
510         fn get_path(fd: c_int) -> Option<PathBuf> {
511             use string::ToString;
512             let mut p = PathBuf::from("/proc/self/fd");
513             p.push(&fd.to_string());
514             readlink(&p).ok()
515         }
516
517         #[cfg(target_os = "macos")]
518         fn get_path(fd: c_int) -> Option<PathBuf> {
519             // FIXME: The use of PATH_MAX is generally not encouraged, but it
520             // is inevitable in this case because OS X defines `fcntl` with
521             // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
522             // alternatives. If a better method is invented, it should be used
523             // instead.
524             let mut buf = vec![0;libc::PATH_MAX as usize];
525             let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
526             if n == -1 {
527                 return None;
528             }
529             let l = buf.iter().position(|&c| c == 0).unwrap();
530             buf.truncate(l as usize);
531             buf.shrink_to_fit();
532             Some(PathBuf::from(OsString::from_vec(buf)))
533         }
534
535         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
536         fn get_path(_fd: c_int) -> Option<PathBuf> {
537             // FIXME(#24570): implement this for other Unix platforms
538             None
539         }
540
541         #[cfg(any(target_os = "linux", target_os = "macos"))]
542         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
543             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
544             if mode == -1 {
545                 return None;
546             }
547             match mode & libc::O_ACCMODE {
548                 libc::O_RDONLY => Some((true, false)),
549                 libc::O_RDWR => Some((true, true)),
550                 libc::O_WRONLY => Some((false, true)),
551                 _ => None
552             }
553         }
554
555         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
556         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
557             // FIXME(#24570): implement this for other Unix platforms
558             None
559         }
560
561         let fd = self.0.raw();
562         let mut b = f.debug_struct("File");
563         b.field("fd", &fd);
564         if let Some(path) = get_path(fd) {
565             b.field("path", &path);
566         }
567         if let Some((read, write)) = get_mode(fd) {
568             b.field("read", &read).field("write", &write);
569         }
570         b.finish()
571     }
572 }
573
574 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
575     let root = Arc::new(p.to_path_buf());
576     let p = try!(cstr(p));
577     unsafe {
578         let ptr = libc::opendir(p.as_ptr());
579         if ptr.is_null() {
580             Err(Error::last_os_error())
581         } else {
582             Ok(ReadDir { dirp: Dir(ptr), root: root })
583         }
584     }
585 }
586
587 pub fn unlink(p: &Path) -> io::Result<()> {
588     let p = try!(cstr(p));
589     try!(cvt(unsafe { libc::unlink(p.as_ptr()) }));
590     Ok(())
591 }
592
593 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
594     let old = try!(cstr(old));
595     let new = try!(cstr(new));
596     try!(cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }));
597     Ok(())
598 }
599
600 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
601     let p = try!(cstr(p));
602     try!(cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }));
603     Ok(())
604 }
605
606 pub fn rmdir(p: &Path) -> io::Result<()> {
607     let p = try!(cstr(p));
608     try!(cvt(unsafe { libc::rmdir(p.as_ptr()) }));
609     Ok(())
610 }
611
612 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
613     let filetype = try!(lstat(path)).file_type();
614     if filetype.is_symlink() {
615         unlink(path)
616     } else {
617         remove_dir_all_recursive(path)
618     }
619 }
620
621 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
622     for child in try!(readdir(path)) {
623         let child = try!(child);
624         if try!(child.file_type()).is_dir() {
625             try!(remove_dir_all_recursive(&child.path()));
626         } else {
627             try!(unlink(&child.path()));
628         }
629     }
630     rmdir(path)
631 }
632
633 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
634     let c_path = try!(cstr(p));
635     let p = c_path.as_ptr();
636
637     let mut buf = Vec::with_capacity(256);
638
639     loop {
640         let buf_read = try!(cvt(unsafe {
641             libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity() as libc::size_t)
642         })) as usize;
643
644         unsafe { buf.set_len(buf_read); }
645
646         if buf_read != buf.capacity() {
647             buf.shrink_to_fit();
648
649             return Ok(PathBuf::from(OsString::from_vec(buf)));
650         }
651
652         // Trigger the internal buffer resizing logic of `Vec` by requiring
653         // more space than the current capacity. The length is guaranteed to be
654         // the same as the capacity due to the if statement above.
655         buf.reserve(1);
656     }
657 }
658
659 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
660     let src = try!(cstr(src));
661     let dst = try!(cstr(dst));
662     try!(cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) }));
663     Ok(())
664 }
665
666 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
667     let src = try!(cstr(src));
668     let dst = try!(cstr(dst));
669     try!(cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) }));
670     Ok(())
671 }
672
673 pub fn stat(p: &Path) -> io::Result<FileAttr> {
674     let p = try!(cstr(p));
675     let mut stat: stat64 = unsafe { mem::zeroed() };
676     try!(cvt(unsafe {
677         stat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
678     }));
679     Ok(FileAttr { stat: stat })
680 }
681
682 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
683     let p = try!(cstr(p));
684     let mut stat: stat64 = unsafe { mem::zeroed() };
685     try!(cvt(unsafe {
686         lstat64(p.as_ptr(), &mut stat as *mut _ as *mut _)
687     }));
688     Ok(FileAttr { stat: stat })
689 }
690
691 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
692     let path = try!(CString::new(p.as_os_str().as_bytes()));
693     let buf;
694     unsafe {
695         let r = libc::realpath(path.as_ptr(), ptr::null_mut());
696         if r.is_null() {
697             return Err(io::Error::last_os_error())
698         }
699         buf = CStr::from_ptr(r).to_bytes().to_vec();
700         libc::free(r as *mut _);
701     }
702     Ok(PathBuf::from(OsString::from_vec(buf)))
703 }
704
705 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
706     use fs::{File, set_permissions};
707     if !from.is_file() {
708         return Err(Error::new(ErrorKind::InvalidInput,
709                               "the source path is not an existing regular file"))
710     }
711
712     let mut reader = try!(File::open(from));
713     let mut writer = try!(File::create(to));
714     let perm = try!(reader.metadata()).permissions();
715
716     let ret = try!(io::copy(&mut reader, &mut writer));
717     try!(set_permissions(to, perm));
718     Ok(ret)
719 }