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