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