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