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