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