]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Rollup merge of #51786 - cuviper:stat64-pointers, r=Mark-Simulacrum
[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", target_os = "l4re"))]
27 use libc::{stat64, fstat64, lstat64, off64_t, ftruncate64, lseek64, dirent64, readdir64_r, open64};
28 #[cfg(any(target_os = "linux", target_os = "emscripten"))]
29 use libc::fstatat64;
30 #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
31 use libc::dirfd;
32 #[cfg(target_os = "android")]
33 use libc::{stat as stat64, fstat as fstat64, fstatat as fstatat64, lstat as lstat64, lseek64,
34            dirent as dirent64, open as open64};
35 #[cfg(not(any(target_os = "linux",
36               target_os = "emscripten",
37               target_os = "l4re",
38               target_os = "android")))]
39 use libc::{stat as stat64, fstat as fstat64, lstat as lstat64, off_t as off64_t,
40            ftruncate as ftruncate64, lseek as lseek64, dirent as dirent64, open as open64};
41 #[cfg(not(any(target_os = "linux",
42               target_os = "emscripten",
43               target_os = "solaris",
44               target_os = "l4re",
45               target_os = "fuchsia")))]
46 use libc::{readdir_r as readdir64_r};
47
48 pub struct File(FileDesc);
49
50 #[derive(Clone)]
51 pub struct FileAttr {
52     stat: stat64,
53 }
54
55 // all DirEntry's will have a reference to this struct
56 struct InnerReadDir {
57     dirp: Dir,
58     root: PathBuf,
59 }
60
61 #[derive(Clone)]
62 pub struct ReadDir {
63     inner: Arc<InnerReadDir>,
64     end_of_stream: bool,
65 }
66
67 struct Dir(*mut libc::DIR);
68
69 unsafe impl Send for Dir {}
70 unsafe impl Sync for Dir {}
71
72 pub struct DirEntry {
73     entry: dirent64,
74     dir: ReadDir,
75     // We need to store an owned copy of the entry name
76     // on Solaris and Fuchsia because a) it uses a zero-length
77     // array to store the name, b) its lifetime between readdir
78     // calls is not guaranteed.
79     #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
80     name: Box<[u8]>
81 }
82
83 #[derive(Clone, Debug)]
84 pub struct OpenOptions {
85     // generic
86     read: bool,
87     write: bool,
88     append: bool,
89     truncate: bool,
90     create: bool,
91     create_new: bool,
92     // system-specific
93     custom_flags: i32,
94     mode: mode_t,
95 }
96
97 #[derive(Clone, PartialEq, Eq, Debug)]
98 pub struct FilePermissions { mode: mode_t }
99
100 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
101 pub struct FileType { mode: mode_t }
102
103 #[derive(Debug)]
104 pub struct DirBuilder { mode: mode_t }
105
106 impl FileAttr {
107     pub fn size(&self) -> u64 { self.stat.st_size as u64 }
108     pub fn perm(&self) -> FilePermissions {
109         FilePermissions { mode: (self.stat.st_mode as mode_t) }
110     }
111
112     pub fn file_type(&self) -> FileType {
113         FileType { mode: self.stat.st_mode as mode_t }
114     }
115 }
116
117 #[cfg(target_os = "netbsd")]
118 impl FileAttr {
119     pub fn modified(&self) -> io::Result<SystemTime> {
120         Ok(SystemTime::from(libc::timespec {
121             tv_sec: self.stat.st_mtime as libc::time_t,
122             tv_nsec: self.stat.st_mtimensec as libc::c_long,
123         }))
124     }
125
126     pub fn accessed(&self) -> io::Result<SystemTime> {
127         Ok(SystemTime::from(libc::timespec {
128             tv_sec: self.stat.st_atime as libc::time_t,
129             tv_nsec: self.stat.st_atimensec as libc::c_long,
130         }))
131     }
132
133     pub fn created(&self) -> io::Result<SystemTime> {
134         Ok(SystemTime::from(libc::timespec {
135             tv_sec: self.stat.st_birthtime as libc::time_t,
136             tv_nsec: self.stat.st_birthtimensec as libc::c_long,
137         }))
138     }
139 }
140
141 #[cfg(not(target_os = "netbsd"))]
142 impl FileAttr {
143     pub fn modified(&self) -> io::Result<SystemTime> {
144         Ok(SystemTime::from(libc::timespec {
145             tv_sec: self.stat.st_mtime as libc::time_t,
146             tv_nsec: self.stat.st_mtime_nsec as _,
147         }))
148     }
149
150     pub fn accessed(&self) -> io::Result<SystemTime> {
151         Ok(SystemTime::from(libc::timespec {
152             tv_sec: self.stat.st_atime as libc::time_t,
153             tv_nsec: self.stat.st_atime_nsec as _,
154         }))
155     }
156
157     #[cfg(any(target_os = "bitrig",
158               target_os = "freebsd",
159               target_os = "openbsd",
160               target_os = "macos",
161               target_os = "ios"))]
162     pub fn created(&self) -> io::Result<SystemTime> {
163         Ok(SystemTime::from(libc::timespec {
164             tv_sec: self.stat.st_birthtime as libc::time_t,
165             tv_nsec: self.stat.st_birthtime_nsec as libc::c_long,
166         }))
167     }
168
169     #[cfg(not(any(target_os = "bitrig",
170                   target_os = "freebsd",
171                   target_os = "openbsd",
172                   target_os = "macos",
173                   target_os = "ios")))]
174     pub fn created(&self) -> io::Result<SystemTime> {
175         Err(io::Error::new(io::ErrorKind::Other,
176                            "creation time is not available on this platform \
177                             currently"))
178     }
179 }
180
181 impl AsInner<stat64> for FileAttr {
182     fn as_inner(&self) -> &stat64 { &self.stat }
183 }
184
185 impl FilePermissions {
186     pub fn readonly(&self) -> bool {
187         // check if any class (owner, group, others) has write permission
188         self.mode & 0o222 == 0
189     }
190
191     pub fn set_readonly(&mut self, readonly: bool) {
192         if readonly {
193             // remove write permission for all classes; equivalent to `chmod a-w <file>`
194             self.mode &= !0o222;
195         } else {
196             // add write permission for all classes; equivalent to `chmod a+w <file>`
197             self.mode |= 0o222;
198         }
199     }
200     pub fn mode(&self) -> u32 { self.mode as u32 }
201 }
202
203 impl FileType {
204     pub fn is_dir(&self) -> bool { self.is(libc::S_IFDIR) }
205     pub fn is_file(&self) -> bool { self.is(libc::S_IFREG) }
206     pub fn is_symlink(&self) -> bool { self.is(libc::S_IFLNK) }
207
208     pub fn is(&self, mode: mode_t) -> bool { self.mode & libc::S_IFMT == mode }
209 }
210
211 impl FromInner<u32> for FilePermissions {
212     fn from_inner(mode: u32) -> FilePermissions {
213         FilePermissions { mode: mode as mode_t }
214     }
215 }
216
217 impl fmt::Debug for ReadDir {
218     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
219         // This will only be called from std::fs::ReadDir, which will add a "ReadDir()" frame.
220         // Thus the result will be e g 'ReadDir("/home")'
221         fmt::Debug::fmt(&*self.inner.root, f)
222     }
223 }
224
225 impl Iterator for ReadDir {
226     type Item = io::Result<DirEntry>;
227
228     #[cfg(any(target_os = "solaris", target_os = "fuchsia"))]
229     fn next(&mut self) -> Option<io::Result<DirEntry>> {
230         unsafe {
231             loop {
232                 // Although readdir_r(3) would be a correct function to use here because
233                 // of the thread safety, on Illumos and Fuchsia the readdir(3C) function
234                 // is safe to use in threaded applications and it is generally preferred
235                 // over the readdir_r(3C) function.
236                 super::os::set_errno(0);
237                 let entry_ptr = libc::readdir(self.inner.dirp.0);
238                 if entry_ptr.is_null() {
239                     // NULL can mean either the end is reached or an error occurred.
240                     // So we had to clear errno beforehand to check for an error now.
241                     return match super::os::errno() {
242                         0 => None,
243                         e => Some(Err(Error::from_raw_os_error(e))),
244                     }
245                 }
246
247                 let name = (*entry_ptr).d_name.as_ptr();
248                 let namelen = libc::strlen(name) as usize;
249
250                 let ret = DirEntry {
251                     entry: *entry_ptr,
252                     name: ::slice::from_raw_parts(name as *const u8,
253                                                   namelen as usize).to_owned().into_boxed_slice(),
254                     dir: self.clone()
255                 };
256                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
257                     return Some(Ok(ret))
258                 }
259             }
260         }
261     }
262
263     #[cfg(not(any(target_os = "solaris", target_os = "fuchsia")))]
264     fn next(&mut self) -> Option<io::Result<DirEntry>> {
265         if self.end_of_stream {
266             return None;
267         }
268
269         unsafe {
270             let mut ret = DirEntry {
271                 entry: mem::zeroed(),
272                 dir: self.clone(),
273             };
274             let mut entry_ptr = ptr::null_mut();
275             loop {
276                 if readdir64_r(self.inner.dirp.0, &mut ret.entry, &mut entry_ptr) != 0 {
277                     if entry_ptr.is_null() {
278                         // We encountered an error (which will be returned in this iteration), but
279                         // we also reached the end of the directory stream. The `end_of_stream`
280                         // flag is enabled to make sure that we return `None` in the next iteration
281                         // (instead of looping forever)
282                         self.end_of_stream = true;
283                     }
284                     return Some(Err(Error::last_os_error()))
285                 }
286                 if entry_ptr.is_null() {
287                     return None
288                 }
289                 if ret.name_bytes() != b"." && ret.name_bytes() != b".." {
290                     return Some(Ok(ret))
291                 }
292             }
293         }
294     }
295 }
296
297 impl Drop for Dir {
298     fn drop(&mut self) {
299         let r = unsafe { libc::closedir(self.0) };
300         debug_assert_eq!(r, 0);
301     }
302 }
303
304 impl DirEntry {
305     pub fn path(&self) -> PathBuf {
306         self.dir.inner.root.join(OsStr::from_bytes(self.name_bytes()))
307     }
308
309     pub fn file_name(&self) -> OsString {
310         OsStr::from_bytes(self.name_bytes()).to_os_string()
311     }
312
313     #[cfg(any(target_os = "linux", target_os = "emscripten", target_os = "android"))]
314     pub fn metadata(&self) -> io::Result<FileAttr> {
315         let fd = cvt(unsafe {dirfd(self.dir.inner.dirp.0)})?;
316         let mut stat: stat64 = unsafe { mem::zeroed() };
317         cvt(unsafe {
318             fstatat64(fd, self.entry.d_name.as_ptr(), &mut stat, libc::AT_SYMLINK_NOFOLLOW)
319         })?;
320         Ok(FileAttr { stat: stat })
321     }
322
323     #[cfg(not(any(target_os = "linux", target_os = "emscripten", target_os = "android")))]
324     pub fn metadata(&self) -> io::Result<FileAttr> {
325         lstat(&self.path())
326     }
327
328     #[cfg(any(target_os = "solaris", target_os = "haiku"))]
329     pub fn file_type(&self) -> io::Result<FileType> {
330         lstat(&self.path()).map(|m| m.file_type())
331     }
332
333     #[cfg(not(any(target_os = "solaris", target_os = "haiku")))]
334     pub fn file_type(&self) -> io::Result<FileType> {
335         match self.entry.d_type {
336             libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
337             libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
338             libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
339             libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
340             libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
341             libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
342             libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
343             _ => lstat(&self.path()).map(|m| m.file_type()),
344         }
345     }
346
347     #[cfg(any(target_os = "macos",
348               target_os = "ios",
349               target_os = "linux",
350               target_os = "emscripten",
351               target_os = "android",
352               target_os = "solaris",
353               target_os = "haiku",
354               target_os = "l4re",
355               target_os = "fuchsia"))]
356     pub fn ino(&self) -> u64 {
357         self.entry.d_ino as u64
358     }
359
360     #[cfg(any(target_os = "freebsd",
361               target_os = "openbsd",
362               target_os = "bitrig",
363               target_os = "netbsd",
364               target_os = "dragonfly"))]
365     pub fn ino(&self) -> u64 {
366         self.entry.d_fileno as u64
367     }
368
369     #[cfg(any(target_os = "macos",
370               target_os = "ios",
371               target_os = "netbsd",
372               target_os = "openbsd",
373               target_os = "freebsd",
374               target_os = "dragonfly",
375               target_os = "bitrig"))]
376     fn name_bytes(&self) -> &[u8] {
377         unsafe {
378             ::slice::from_raw_parts(self.entry.d_name.as_ptr() as *const u8,
379                                     self.entry.d_namlen as usize)
380         }
381     }
382     #[cfg(any(target_os = "android",
383               target_os = "linux",
384               target_os = "emscripten",
385               target_os = "l4re",
386               target_os = "haiku"))]
387     fn name_bytes(&self) -> &[u8] {
388         unsafe {
389             CStr::from_ptr(self.entry.d_name.as_ptr()).to_bytes()
390         }
391     }
392     #[cfg(any(target_os = "solaris",
393               target_os = "fuchsia"))]
394     fn name_bytes(&self) -> &[u8] {
395         &*self.name
396     }
397 }
398
399 impl OpenOptions {
400     pub fn new() -> OpenOptions {
401         OpenOptions {
402             // generic
403             read: false,
404             write: false,
405             append: false,
406             truncate: false,
407             create: false,
408             create_new: false,
409             // system-specific
410             custom_flags: 0,
411             mode: 0o666,
412         }
413     }
414
415     pub fn read(&mut self, read: bool) { self.read = read; }
416     pub fn write(&mut self, write: bool) { self.write = write; }
417     pub fn append(&mut self, append: bool) { self.append = append; }
418     pub fn truncate(&mut self, truncate: bool) { self.truncate = truncate; }
419     pub fn create(&mut self, create: bool) { self.create = create; }
420     pub fn create_new(&mut self, create_new: bool) { self.create_new = create_new; }
421
422     pub fn custom_flags(&mut self, flags: i32) { self.custom_flags = flags; }
423     pub fn mode(&mut self, mode: u32) { self.mode = mode as mode_t; }
424
425     fn get_access_mode(&self) -> io::Result<c_int> {
426         match (self.read, self.write, self.append) {
427             (true,  false, false) => Ok(libc::O_RDONLY),
428             (false, true,  false) => Ok(libc::O_WRONLY),
429             (true,  true,  false) => Ok(libc::O_RDWR),
430             (false, _,     true)  => Ok(libc::O_WRONLY | libc::O_APPEND),
431             (true,  _,     true)  => Ok(libc::O_RDWR | libc::O_APPEND),
432             (false, false, false) => Err(Error::from_raw_os_error(libc::EINVAL)),
433         }
434     }
435
436     fn get_creation_mode(&self) -> io::Result<c_int> {
437         match (self.write, self.append) {
438             (true, false) => {}
439             (false, false) =>
440                 if self.truncate || self.create || self.create_new {
441                     return Err(Error::from_raw_os_error(libc::EINVAL));
442                 },
443             (_, true) =>
444                 if self.truncate && !self.create_new {
445                     return Err(Error::from_raw_os_error(libc::EINVAL));
446                 },
447         }
448
449         Ok(match (self.create, self.truncate, self.create_new) {
450                 (false, false, false) => 0,
451                 (true,  false, false) => libc::O_CREAT,
452                 (false, true,  false) => libc::O_TRUNC,
453                 (true,  true,  false) => libc::O_CREAT | libc::O_TRUNC,
454                 (_,      _,    true)  => libc::O_CREAT | libc::O_EXCL,
455            })
456     }
457 }
458
459 impl File {
460     pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
461         let path = cstr(path)?;
462         File::open_c(&path, opts)
463     }
464
465     pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
466         let flags = libc::O_CLOEXEC |
467                     opts.get_access_mode()? |
468                     opts.get_creation_mode()? |
469                     (opts.custom_flags as c_int & !libc::O_ACCMODE);
470         let fd = cvt_r(|| unsafe {
471             open64(path.as_ptr(), flags, opts.mode as c_int)
472         })?;
473         let fd = FileDesc::new(fd);
474
475         // Currently the standard library supports Linux 2.6.18 which did not
476         // have the O_CLOEXEC flag (passed above). If we're running on an older
477         // Linux kernel then the flag is just ignored by the OS. After we open
478         // the first file, we check whether it has CLOEXEC set. If it doesn't,
479         // we will explicitly ask for a CLOEXEC fd for every further file we
480         // open, if it does, we will skip that step.
481         //
482         // The CLOEXEC flag, however, is supported on versions of macOS/BSD/etc
483         // that we support, so we only do this on Linux currently.
484         #[cfg(target_os = "linux")]
485         fn ensure_cloexec(fd: &FileDesc) -> io::Result<()> {
486             use sync::atomic::{AtomicUsize, Ordering};
487
488             const OPEN_CLOEXEC_UNKNOWN: usize = 0;
489             const OPEN_CLOEXEC_SUPPORTED: usize = 1;
490             const OPEN_CLOEXEC_NOTSUPPORTED: usize = 2;
491             static OPEN_CLOEXEC: AtomicUsize = AtomicUsize::new(OPEN_CLOEXEC_UNKNOWN);
492
493             let need_to_set;
494             match OPEN_CLOEXEC.load(Ordering::Relaxed) {
495                 OPEN_CLOEXEC_UNKNOWN => {
496                     need_to_set = !fd.get_cloexec()?;
497                     OPEN_CLOEXEC.store(if need_to_set {
498                         OPEN_CLOEXEC_NOTSUPPORTED
499                     } else {
500                         OPEN_CLOEXEC_SUPPORTED
501                     }, Ordering::Relaxed);
502                 },
503                 OPEN_CLOEXEC_SUPPORTED => need_to_set = false,
504                 OPEN_CLOEXEC_NOTSUPPORTED => need_to_set = true,
505                 _ => unreachable!(),
506             }
507             if need_to_set {
508                 fd.set_cloexec()?;
509             }
510             Ok(())
511         }
512
513         #[cfg(not(target_os = "linux"))]
514         fn ensure_cloexec(_: &FileDesc) -> io::Result<()> {
515             Ok(())
516         }
517
518         ensure_cloexec(&fd)?;
519         Ok(File(fd))
520     }
521
522     pub fn file_attr(&self) -> io::Result<FileAttr> {
523         let mut stat: stat64 = unsafe { mem::zeroed() };
524         cvt(unsafe {
525             fstat64(self.0.raw(), &mut stat)
526         })?;
527         Ok(FileAttr { stat: stat })
528     }
529
530     pub fn fsync(&self) -> io::Result<()> {
531         cvt_r(|| unsafe { libc::fsync(self.0.raw()) })?;
532         Ok(())
533     }
534
535     pub fn datasync(&self) -> io::Result<()> {
536         cvt_r(|| unsafe { os_datasync(self.0.raw()) })?;
537         return Ok(());
538
539         #[cfg(any(target_os = "macos", target_os = "ios"))]
540         unsafe fn os_datasync(fd: c_int) -> c_int {
541             libc::fcntl(fd, libc::F_FULLFSYNC)
542         }
543         #[cfg(target_os = "linux")]
544         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fdatasync(fd) }
545         #[cfg(not(any(target_os = "macos",
546                       target_os = "ios",
547                       target_os = "linux")))]
548         unsafe fn os_datasync(fd: c_int) -> c_int { libc::fsync(fd) }
549     }
550
551     pub fn truncate(&self, size: u64) -> io::Result<()> {
552         #[cfg(target_os = "android")]
553         return ::sys::android::ftruncate64(self.0.raw(), size);
554
555         #[cfg(not(target_os = "android"))]
556         return cvt_r(|| unsafe {
557             ftruncate64(self.0.raw(), size as off64_t)
558         }).map(|_| ());
559     }
560
561     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
562         self.0.read(buf)
563     }
564
565     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
566         self.0.read_at(buf, offset)
567     }
568
569     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
570         self.0.write(buf)
571     }
572
573     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
574         self.0.write_at(buf, offset)
575     }
576
577     pub fn flush(&self) -> io::Result<()> { Ok(()) }
578
579     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
580         let (whence, pos) = match pos {
581             // Casting to `i64` is fine, too large values will end up as
582             // negative which will cause an error in `lseek64`.
583             SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
584             SeekFrom::End(off) => (libc::SEEK_END, off),
585             SeekFrom::Current(off) => (libc::SEEK_CUR, off),
586         };
587         #[cfg(target_os = "emscripten")]
588         let pos = pos as i32;
589         let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
590         Ok(n as u64)
591     }
592
593     pub fn duplicate(&self) -> io::Result<File> {
594         self.0.duplicate().map(File)
595     }
596
597     pub fn fd(&self) -> &FileDesc { &self.0 }
598
599     pub fn into_fd(self) -> FileDesc { self.0 }
600
601     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
602         cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
603         Ok(())
604     }
605 }
606
607 impl DirBuilder {
608     pub fn new() -> DirBuilder {
609         DirBuilder { mode: 0o777 }
610     }
611
612     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
613         let p = cstr(p)?;
614         cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
615         Ok(())
616     }
617
618     pub fn set_mode(&mut self, mode: u32) {
619         self.mode = mode as mode_t;
620     }
621 }
622
623 fn cstr(path: &Path) -> io::Result<CString> {
624     Ok(CString::new(path.as_os_str().as_bytes())?)
625 }
626
627 impl FromInner<c_int> for File {
628     fn from_inner(fd: c_int) -> File {
629         File(FileDesc::new(fd))
630     }
631 }
632
633 impl fmt::Debug for File {
634     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
635         #[cfg(target_os = "linux")]
636         fn get_path(fd: c_int) -> Option<PathBuf> {
637             let mut p = PathBuf::from("/proc/self/fd");
638             p.push(&fd.to_string());
639             readlink(&p).ok()
640         }
641
642         #[cfg(target_os = "macos")]
643         fn get_path(fd: c_int) -> Option<PathBuf> {
644             // FIXME: The use of PATH_MAX is generally not encouraged, but it
645             // is inevitable in this case because macOS defines `fcntl` with
646             // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
647             // alternatives. If a better method is invented, it should be used
648             // instead.
649             let mut buf = vec![0;libc::PATH_MAX as usize];
650             let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
651             if n == -1 {
652                 return None;
653             }
654             let l = buf.iter().position(|&c| c == 0).unwrap();
655             buf.truncate(l as usize);
656             buf.shrink_to_fit();
657             Some(PathBuf::from(OsString::from_vec(buf)))
658         }
659
660         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
661         fn get_path(_fd: c_int) -> Option<PathBuf> {
662             // FIXME(#24570): implement this for other Unix platforms
663             None
664         }
665
666         #[cfg(any(target_os = "linux", target_os = "macos"))]
667         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
668             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
669             if mode == -1 {
670                 return None;
671             }
672             match mode & libc::O_ACCMODE {
673                 libc::O_RDONLY => Some((true, false)),
674                 libc::O_RDWR => Some((true, true)),
675                 libc::O_WRONLY => Some((false, true)),
676                 _ => None
677             }
678         }
679
680         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
681         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
682             // FIXME(#24570): implement this for other Unix platforms
683             None
684         }
685
686         let fd = self.0.raw();
687         let mut b = f.debug_struct("File");
688         b.field("fd", &fd);
689         if let Some(path) = get_path(fd) {
690             b.field("path", &path);
691         }
692         if let Some((read, write)) = get_mode(fd) {
693             b.field("read", &read).field("write", &write);
694         }
695         b.finish()
696     }
697 }
698
699 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
700     let root = p.to_path_buf();
701     let p = cstr(p)?;
702     unsafe {
703         let ptr = libc::opendir(p.as_ptr());
704         if ptr.is_null() {
705             Err(Error::last_os_error())
706         } else {
707             let inner = InnerReadDir { dirp: Dir(ptr), root };
708             Ok(ReadDir{
709                 inner: Arc::new(inner),
710                 end_of_stream: false,
711             })
712         }
713     }
714 }
715
716 pub fn unlink(p: &Path) -> io::Result<()> {
717     let p = cstr(p)?;
718     cvt(unsafe { libc::unlink(p.as_ptr()) })?;
719     Ok(())
720 }
721
722 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
723     let old = cstr(old)?;
724     let new = cstr(new)?;
725     cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
726     Ok(())
727 }
728
729 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
730     let p = cstr(p)?;
731     cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
732     Ok(())
733 }
734
735 pub fn rmdir(p: &Path) -> io::Result<()> {
736     let p = cstr(p)?;
737     cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
738     Ok(())
739 }
740
741 pub fn remove_dir_all(path: &Path) -> io::Result<()> {
742     let filetype = lstat(path)?.file_type();
743     if filetype.is_symlink() {
744         unlink(path)
745     } else {
746         remove_dir_all_recursive(path)
747     }
748 }
749
750 fn remove_dir_all_recursive(path: &Path) -> io::Result<()> {
751     for child in readdir(path)? {
752         let child = child?;
753         if child.file_type()?.is_dir() {
754             remove_dir_all_recursive(&child.path())?;
755         } else {
756             unlink(&child.path())?;
757         }
758     }
759     rmdir(path)
760 }
761
762 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
763     let c_path = cstr(p)?;
764     let p = c_path.as_ptr();
765
766     let mut buf = Vec::with_capacity(256);
767
768     loop {
769         let buf_read = cvt(unsafe {
770             libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
771         })? as usize;
772
773         unsafe { buf.set_len(buf_read); }
774
775         if buf_read != buf.capacity() {
776             buf.shrink_to_fit();
777
778             return Ok(PathBuf::from(OsString::from_vec(buf)));
779         }
780
781         // Trigger the internal buffer resizing logic of `Vec` by requiring
782         // more space than the current capacity. The length is guaranteed to be
783         // the same as the capacity due to the if statement above.
784         buf.reserve(1);
785     }
786 }
787
788 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
789     let src = cstr(src)?;
790     let dst = cstr(dst)?;
791     cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
792     Ok(())
793 }
794
795 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
796     let src = cstr(src)?;
797     let dst = cstr(dst)?;
798     cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
799     Ok(())
800 }
801
802 pub fn stat(p: &Path) -> io::Result<FileAttr> {
803     let p = cstr(p)?;
804     let mut stat: stat64 = unsafe { mem::zeroed() };
805     cvt(unsafe {
806         stat64(p.as_ptr(), &mut stat)
807     })?;
808     Ok(FileAttr { stat: stat })
809 }
810
811 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
812     let p = cstr(p)?;
813     let mut stat: stat64 = unsafe { mem::zeroed() };
814     cvt(unsafe {
815         lstat64(p.as_ptr(), &mut stat)
816     })?;
817     Ok(FileAttr { stat: stat })
818 }
819
820 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
821     let path = CString::new(p.as_os_str().as_bytes())?;
822     let buf;
823     unsafe {
824         let r = libc::realpath(path.as_ptr(), ptr::null_mut());
825         if r.is_null() {
826             return Err(io::Error::last_os_error())
827         }
828         buf = CStr::from_ptr(r).to_bytes().to_vec();
829         libc::free(r as *mut _);
830     }
831     Ok(PathBuf::from(OsString::from_vec(buf)))
832 }
833
834 #[cfg(not(any(target_os = "linux", target_os = "android")))]
835 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
836     use fs::File;
837     if !from.is_file() {
838         return Err(Error::new(ErrorKind::InvalidInput,
839                               "the source path is not an existing regular file"))
840     }
841
842     let mut reader = File::open(from)?;
843     let mut writer = File::create(to)?;
844     let perm = reader.metadata()?.permissions();
845
846     let ret = io::copy(&mut reader, &mut writer)?;
847     writer.set_permissions(perm)?;
848     Ok(ret)
849 }
850
851 #[cfg(any(target_os = "linux", target_os = "android"))]
852 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
853     use cmp;
854     use fs::File;
855     use sync::atomic::{AtomicBool, Ordering};
856
857     // Kernel prior to 4.5 don't have copy_file_range
858     // We store the availability in a global to avoid unneccessary syscalls
859     static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
860
861     unsafe fn copy_file_range(
862         fd_in: libc::c_int,
863         off_in: *mut libc::loff_t,
864         fd_out: libc::c_int,
865         off_out: *mut libc::loff_t,
866         len: libc::size_t,
867         flags: libc::c_uint,
868     ) -> libc::c_long {
869         libc::syscall(
870             libc::SYS_copy_file_range,
871             fd_in,
872             off_in,
873             fd_out,
874             off_out,
875             len,
876             flags,
877         )
878     }
879
880     if !from.is_file() {
881         return Err(Error::new(ErrorKind::InvalidInput,
882                               "the source path is not an existing regular file"))
883     }
884
885     let mut reader = File::open(from)?;
886     let mut writer = File::create(to)?;
887     let (perm, len) = {
888         let metadata = reader.metadata()?;
889         (metadata.permissions(), metadata.size())
890     };
891
892     let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
893     let mut written = 0u64;
894     while written < len {
895         let copy_result = if has_copy_file_range {
896             let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
897             let copy_result = unsafe {
898                 // We actually don't have to adjust the offsets,
899                 // because copy_file_range adjusts the file offset automatically
900                 cvt(copy_file_range(reader.as_raw_fd(),
901                                     ptr::null_mut(),
902                                     writer.as_raw_fd(),
903                                     ptr::null_mut(),
904                                     bytes_to_copy,
905                                     0)
906                     )
907             };
908             if let Err(ref copy_err) = copy_result {
909                 match copy_err.raw_os_error() {
910                     Some(libc::ENOSYS) | Some(libc::EPERM) => {
911                         HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
912                     }
913                     _ => {}
914                 }
915             }
916             copy_result
917         } else {
918             Err(io::Error::from_raw_os_error(libc::ENOSYS))
919         };
920         match copy_result {
921             Ok(ret) => written += ret as u64,
922             Err(err) => {
923                 match err.raw_os_error() {
924                     Some(os_err) if os_err == libc::ENOSYS
925                                  || os_err == libc::EXDEV
926                                  || os_err == libc::EPERM => {
927                         // Try fallback io::copy if either:
928                         // - Kernel version is < 4.5 (ENOSYS)
929                         // - Files are mounted on different fs (EXDEV)
930                         // - copy_file_range is disallowed, for example by seccomp (EPERM)
931                         assert_eq!(written, 0);
932                         let ret = io::copy(&mut reader, &mut writer)?;
933                         writer.set_permissions(perm)?;
934                         return Ok(ret)
935                     },
936                     _ => return Err(err),
937                 }
938             }
939         }
940     }
941     writer.set_permissions(perm)?;
942     Ok(written)
943 }