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