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