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