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