]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Rollup merge of #63259 - JohnTitor:add-tests-for-some-issues, r=Centril
[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         return cvt_r(|| unsafe {
561             ftruncate64(self.0.raw(), size as off64_t)
562         }).map(|_| ());
563     }
564
565     pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
566         self.0.read(buf)
567     }
568
569     pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
570         self.0.read_vectored(bufs)
571     }
572
573     pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
574         self.0.read_at(buf, offset)
575     }
576
577     pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
578         self.0.write(buf)
579     }
580
581     pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
582         self.0.write_vectored(bufs)
583     }
584
585     pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
586         self.0.write_at(buf, offset)
587     }
588
589     pub fn flush(&self) -> io::Result<()> { Ok(()) }
590
591     pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
592         let (whence, pos) = match pos {
593             // Casting to `i64` is fine, too large values will end up as
594             // negative which will cause an error in `lseek64`.
595             SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
596             SeekFrom::End(off) => (libc::SEEK_END, off),
597             SeekFrom::Current(off) => (libc::SEEK_CUR, off),
598         };
599         #[cfg(target_os = "emscripten")]
600         let pos = pos as i32;
601         let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
602         Ok(n as u64)
603     }
604
605     pub fn duplicate(&self) -> io::Result<File> {
606         self.0.duplicate().map(File)
607     }
608
609     pub fn fd(&self) -> &FileDesc { &self.0 }
610
611     pub fn into_fd(self) -> FileDesc { self.0 }
612
613     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
614         cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
615         Ok(())
616     }
617 }
618
619 impl DirBuilder {
620     pub fn new() -> DirBuilder {
621         DirBuilder { mode: 0o777 }
622     }
623
624     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
625         let p = cstr(p)?;
626         cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
627         Ok(())
628     }
629
630     pub fn set_mode(&mut self, mode: u32) {
631         self.mode = mode as mode_t;
632     }
633 }
634
635 fn cstr(path: &Path) -> io::Result<CString> {
636     Ok(CString::new(path.as_os_str().as_bytes())?)
637 }
638
639 impl FromInner<c_int> for File {
640     fn from_inner(fd: c_int) -> File {
641         File(FileDesc::new(fd))
642     }
643 }
644
645 impl fmt::Debug for File {
646     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
647         #[cfg(target_os = "linux")]
648         fn get_path(fd: c_int) -> Option<PathBuf> {
649             let mut p = PathBuf::from("/proc/self/fd");
650             p.push(&fd.to_string());
651             readlink(&p).ok()
652         }
653
654         #[cfg(target_os = "macos")]
655         fn get_path(fd: c_int) -> Option<PathBuf> {
656             // FIXME: The use of PATH_MAX is generally not encouraged, but it
657             // is inevitable in this case because macOS defines `fcntl` with
658             // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
659             // alternatives. If a better method is invented, it should be used
660             // instead.
661             let mut buf = vec![0;libc::PATH_MAX as usize];
662             let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
663             if n == -1 {
664                 return None;
665             }
666             let l = buf.iter().position(|&c| c == 0).unwrap();
667             buf.truncate(l as usize);
668             buf.shrink_to_fit();
669             Some(PathBuf::from(OsString::from_vec(buf)))
670         }
671
672         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
673         fn get_path(_fd: c_int) -> Option<PathBuf> {
674             // FIXME(#24570): implement this for other Unix platforms
675             None
676         }
677
678         #[cfg(any(target_os = "linux", target_os = "macos"))]
679         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
680             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
681             if mode == -1 {
682                 return None;
683             }
684             match mode & libc::O_ACCMODE {
685                 libc::O_RDONLY => Some((true, false)),
686                 libc::O_RDWR => Some((true, true)),
687                 libc::O_WRONLY => Some((false, true)),
688                 _ => None
689             }
690         }
691
692         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
693         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
694             // FIXME(#24570): implement this for other Unix platforms
695             None
696         }
697
698         let fd = self.0.raw();
699         let mut b = f.debug_struct("File");
700         b.field("fd", &fd);
701         if let Some(path) = get_path(fd) {
702             b.field("path", &path);
703         }
704         if let Some((read, write)) = get_mode(fd) {
705             b.field("read", &read).field("write", &write);
706         }
707         b.finish()
708     }
709 }
710
711 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
712     let root = p.to_path_buf();
713     let p = cstr(p)?;
714     unsafe {
715         let ptr = libc::opendir(p.as_ptr());
716         if ptr.is_null() {
717             Err(Error::last_os_error())
718         } else {
719             let inner = InnerReadDir { dirp: Dir(ptr), root };
720             Ok(ReadDir{
721                 inner: Arc::new(inner),
722                 end_of_stream: false,
723             })
724         }
725     }
726 }
727
728 pub fn unlink(p: &Path) -> io::Result<()> {
729     let p = cstr(p)?;
730     cvt(unsafe { libc::unlink(p.as_ptr()) })?;
731     Ok(())
732 }
733
734 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
735     let old = cstr(old)?;
736     let new = cstr(new)?;
737     cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
738     Ok(())
739 }
740
741 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
742     let p = cstr(p)?;
743     cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
744     Ok(())
745 }
746
747 pub fn rmdir(p: &Path) -> io::Result<()> {
748     let p = cstr(p)?;
749     cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
750     Ok(())
751 }
752
753 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
754     let c_path = cstr(p)?;
755     let p = c_path.as_ptr();
756
757     let mut buf = Vec::with_capacity(256);
758
759     loop {
760         let buf_read = cvt(unsafe {
761             libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
762         })? as usize;
763
764         unsafe { buf.set_len(buf_read); }
765
766         if buf_read != buf.capacity() {
767             buf.shrink_to_fit();
768
769             return Ok(PathBuf::from(OsString::from_vec(buf)));
770         }
771
772         // Trigger the internal buffer resizing logic of `Vec` by requiring
773         // more space than the current capacity. The length is guaranteed to be
774         // the same as the capacity due to the if statement above.
775         buf.reserve(1);
776     }
777 }
778
779 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
780     let src = cstr(src)?;
781     let dst = cstr(dst)?;
782     cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
783     Ok(())
784 }
785
786 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
787     let src = cstr(src)?;
788     let dst = cstr(dst)?;
789     cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
790     Ok(())
791 }
792
793 pub fn stat(p: &Path) -> io::Result<FileAttr> {
794     let p = cstr(p)?;
795     let mut stat: stat64 = unsafe { mem::zeroed() };
796     cvt(unsafe {
797         stat64(p.as_ptr(), &mut stat)
798     })?;
799     Ok(FileAttr { stat })
800 }
801
802 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
803     let p = cstr(p)?;
804     let mut stat: stat64 = unsafe { mem::zeroed() };
805     cvt(unsafe {
806         lstat64(p.as_ptr(), &mut stat)
807     })?;
808     Ok(FileAttr { stat })
809 }
810
811 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
812     let path = CString::new(p.as_os_str().as_bytes())?;
813     let buf;
814     unsafe {
815         let r = libc::realpath(path.as_ptr(), ptr::null_mut());
816         if r.is_null() {
817             return Err(io::Error::last_os_error())
818         }
819         buf = CStr::from_ptr(r).to_bytes().to_vec();
820         libc::free(r as *mut _);
821     }
822     Ok(PathBuf::from(OsString::from_vec(buf)))
823 }
824
825 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
826     use crate::fs::File;
827
828     let reader = File::open(from)?;
829     let metadata = reader.metadata()?;
830     if !metadata.is_file() {
831         return Err(Error::new(
832             ErrorKind::InvalidInput,
833             "the source path is not an existing regular file",
834         ));
835     }
836     Ok((reader, metadata))
837 }
838
839 fn open_to_and_set_permissions(
840     to: &Path,
841     reader_metadata: crate::fs::Metadata,
842 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
843     use crate::fs::OpenOptions;
844     use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
845
846     let perm = reader_metadata.permissions();
847     let writer = OpenOptions::new()
848         // create the file with the correct mode right away
849         .mode(perm.mode())
850         .write(true)
851         .create(true)
852         .truncate(true)
853         .open(to)?;
854     let writer_metadata = writer.metadata()?;
855     if writer_metadata.is_file() {
856         // Set the correct file permissions, in case the file already existed.
857         // Don't set the permissions on already existing non-files like
858         // pipes/FIFOs or device nodes.
859         writer.set_permissions(perm)?;
860     }
861     Ok((writer, writer_metadata))
862 }
863
864 #[cfg(not(any(target_os = "linux",
865               target_os = "android",
866               target_os = "macos",
867               target_os = "ios")))]
868 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
869     let (mut reader, reader_metadata) = open_from(from)?;
870     let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
871
872     io::copy(&mut reader, &mut writer)
873 }
874
875 #[cfg(any(target_os = "linux", target_os = "android"))]
876 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
877     use crate::cmp;
878     use crate::sync::atomic::{AtomicBool, Ordering};
879
880     // Kernel prior to 4.5 don't have copy_file_range
881     // We store the availability in a global to avoid unnecessary syscalls
882     static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
883
884     unsafe fn copy_file_range(
885         fd_in: libc::c_int,
886         off_in: *mut libc::loff_t,
887         fd_out: libc::c_int,
888         off_out: *mut libc::loff_t,
889         len: libc::size_t,
890         flags: libc::c_uint,
891     ) -> libc::c_long {
892         libc::syscall(
893             libc::SYS_copy_file_range,
894             fd_in,
895             off_in,
896             fd_out,
897             off_out,
898             len,
899             flags,
900         )
901     }
902
903     let (mut reader, reader_metadata) = open_from(from)?;
904     let len = reader_metadata.len();
905     let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
906
907     let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
908     let mut written = 0u64;
909     while written < len {
910         let copy_result = if has_copy_file_range {
911             let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
912             let copy_result = unsafe {
913                 // We actually don't have to adjust the offsets,
914                 // because copy_file_range adjusts the file offset automatically
915                 cvt(copy_file_range(
916                     reader.as_raw_fd(),
917                     ptr::null_mut(),
918                     writer.as_raw_fd(),
919                     ptr::null_mut(),
920                     bytes_to_copy,
921                     0,
922                 ))
923             };
924             if let Err(ref copy_err) = copy_result {
925                 match copy_err.raw_os_error() {
926                     Some(libc::ENOSYS) | Some(libc::EPERM) => {
927                         HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
928                     }
929                     _ => {}
930                 }
931             }
932             copy_result
933         } else {
934             Err(io::Error::from_raw_os_error(libc::ENOSYS))
935         };
936         match copy_result {
937             Ok(ret) => written += ret as u64,
938             Err(err) => {
939                 match err.raw_os_error() {
940                     Some(os_err)
941                     if os_err == libc::ENOSYS
942                         || os_err == libc::EXDEV
943                         || os_err == libc::EINVAL
944                         || os_err == libc::EPERM =>
945                         {
946                             // Try fallback io::copy if either:
947                             // - Kernel version is < 4.5 (ENOSYS)
948                             // - Files are mounted on different fs (EXDEV)
949                             // - copy_file_range is disallowed, for example by seccomp (EPERM)
950                             // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
951                             assert_eq!(written, 0);
952                             return io::copy(&mut reader, &mut writer);
953                         }
954                     _ => return Err(err),
955                 }
956             }
957         }
958     }
959     Ok(written)
960 }
961
962 #[cfg(any(target_os = "macos", target_os = "ios"))]
963 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
964     use crate::sync::atomic::{AtomicBool, Ordering};
965
966     const COPYFILE_ACL: u32 = 1 << 0;
967     const COPYFILE_STAT: u32 = 1 << 1;
968     const COPYFILE_XATTR: u32 = 1 << 2;
969     const COPYFILE_DATA: u32 = 1 << 3;
970
971     const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
972     const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
973     const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
974
975     const COPYFILE_STATE_COPIED: u32 = 8;
976
977     #[allow(non_camel_case_types)]
978     type copyfile_state_t = *mut libc::c_void;
979     #[allow(non_camel_case_types)]
980     type copyfile_flags_t = u32;
981
982     extern "C" {
983         fn fcopyfile(
984             from: libc::c_int,
985             to: libc::c_int,
986             state: copyfile_state_t,
987             flags: copyfile_flags_t,
988         ) -> libc::c_int;
989         fn copyfile_state_alloc() -> copyfile_state_t;
990         fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
991         fn copyfile_state_get(
992             state: copyfile_state_t,
993             flag: u32,
994             dst: *mut libc::c_void,
995         ) -> libc::c_int;
996     }
997
998     struct FreeOnDrop(copyfile_state_t);
999     impl Drop for FreeOnDrop {
1000         fn drop(&mut self) {
1001             // The code below ensures that `FreeOnDrop` is never a null pointer
1002             unsafe {
1003                 // `copyfile_state_free` returns -1 if the `to` or `from` files
1004                 // cannot be closed. However, this is not considerd this an
1005                 // error.
1006                 copyfile_state_free(self.0);
1007             }
1008         }
1009     }
1010
1011     // MacOS prior to 10.12 don't support `fclonefileat`
1012     // We store the availability in a global to avoid unnecessary syscalls
1013     static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1014     syscall! {
1015         fn fclonefileat(
1016             srcfd: libc::c_int,
1017             dst_dirfd: libc::c_int,
1018             dst: *const libc::c_char,
1019             flags: libc::c_int
1020         ) -> libc::c_int
1021     }
1022
1023     let (reader, reader_metadata) = open_from(from)?;
1024
1025     // Opportunistically attempt to create a copy-on-write clone of `from`
1026     // using `fclonefileat`.
1027     if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1028         let to = cstr(to)?;
1029         let clonefile_result = cvt(unsafe {
1030             fclonefileat(
1031                 reader.as_raw_fd(),
1032                 libc::AT_FDCWD,
1033                 to.as_ptr(),
1034                 0,
1035             )
1036         });
1037         match clonefile_result {
1038             Ok(_) => return Ok(reader_metadata.len()),
1039             Err(err) => match err.raw_os_error() {
1040                 // `fclonefileat` will fail on non-APFS volumes, if the
1041                 // destination already exists, or if the source and destination
1042                 // are on different devices. In all these cases `fcopyfile`
1043                 // should succeed.
1044                 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1045                 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1046                 _ => return Err(err),
1047             }
1048         }
1049     }
1050
1051     // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1052     let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1053
1054     // We ensure that `FreeOnDrop` never contains a null pointer so it is
1055     // always safe to call `copyfile_state_free`
1056     let state = unsafe {
1057         let state = copyfile_state_alloc();
1058         if state.is_null() {
1059             return Err(crate::io::Error::last_os_error());
1060         }
1061         FreeOnDrop(state)
1062     };
1063
1064     let flags = if writer_metadata.is_file() {
1065         COPYFILE_ALL
1066     } else {
1067         COPYFILE_DATA
1068     };
1069
1070     cvt(unsafe {
1071         fcopyfile(
1072             reader.as_raw_fd(),
1073             writer.as_raw_fd(),
1074             state.0,
1075             flags,
1076         )
1077     })?;
1078
1079     let mut bytes_copied: libc::off_t = 0;
1080     cvt(unsafe {
1081         copyfile_state_get(
1082             state.0,
1083             COPYFILE_STATE_COPIED,
1084             &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1085         )
1086     })?;
1087     Ok(bytes_copied as u64)
1088 }