]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/unix/fs.rs
Rollup merge of #65551 - sinkuu:cstring_spec, r=sfackler
[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 _,
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         let n = cvt(unsafe { lseek64(self.0.raw(), pos, whence) })?;
789         Ok(n as u64)
790     }
791
792     pub fn duplicate(&self) -> io::Result<File> {
793         self.0.duplicate().map(File)
794     }
795
796     pub fn fd(&self) -> &FileDesc { &self.0 }
797
798     pub fn into_fd(self) -> FileDesc { self.0 }
799
800     pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
801         cvt_r(|| unsafe { libc::fchmod(self.0.raw(), perm.mode) })?;
802         Ok(())
803     }
804 }
805
806 impl DirBuilder {
807     pub fn new() -> DirBuilder {
808         DirBuilder { mode: 0o777 }
809     }
810
811     pub fn mkdir(&self, p: &Path) -> io::Result<()> {
812         let p = cstr(p)?;
813         cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) })?;
814         Ok(())
815     }
816
817     pub fn set_mode(&mut self, mode: u32) {
818         self.mode = mode as mode_t;
819     }
820 }
821
822 fn cstr(path: &Path) -> io::Result<CString> {
823     Ok(CString::new(path.as_os_str().as_bytes())?)
824 }
825
826 impl FromInner<c_int> for File {
827     fn from_inner(fd: c_int) -> File {
828         File(FileDesc::new(fd))
829     }
830 }
831
832 impl fmt::Debug for File {
833     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834         #[cfg(target_os = "linux")]
835         fn get_path(fd: c_int) -> Option<PathBuf> {
836             let mut p = PathBuf::from("/proc/self/fd");
837             p.push(&fd.to_string());
838             readlink(&p).ok()
839         }
840
841         #[cfg(target_os = "macos")]
842         fn get_path(fd: c_int) -> Option<PathBuf> {
843             // FIXME: The use of PATH_MAX is generally not encouraged, but it
844             // is inevitable in this case because macOS defines `fcntl` with
845             // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
846             // alternatives. If a better method is invented, it should be used
847             // instead.
848             let mut buf = vec![0;libc::PATH_MAX as usize];
849             let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
850             if n == -1 {
851                 return None;
852             }
853             let l = buf.iter().position(|&c| c == 0).unwrap();
854             buf.truncate(l as usize);
855             buf.shrink_to_fit();
856             Some(PathBuf::from(OsString::from_vec(buf)))
857         }
858
859         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
860         fn get_path(_fd: c_int) -> Option<PathBuf> {
861             // FIXME(#24570): implement this for other Unix platforms
862             None
863         }
864
865         #[cfg(any(target_os = "linux", target_os = "macos"))]
866         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
867             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
868             if mode == -1 {
869                 return None;
870             }
871             match mode & libc::O_ACCMODE {
872                 libc::O_RDONLY => Some((true, false)),
873                 libc::O_RDWR => Some((true, true)),
874                 libc::O_WRONLY => Some((false, true)),
875                 _ => None
876             }
877         }
878
879         #[cfg(not(any(target_os = "linux", target_os = "macos")))]
880         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
881             // FIXME(#24570): implement this for other Unix platforms
882             None
883         }
884
885         let fd = self.0.raw();
886         let mut b = f.debug_struct("File");
887         b.field("fd", &fd);
888         if let Some(path) = get_path(fd) {
889             b.field("path", &path);
890         }
891         if let Some((read, write)) = get_mode(fd) {
892             b.field("read", &read).field("write", &write);
893         }
894         b.finish()
895     }
896 }
897
898 pub fn readdir(p: &Path) -> io::Result<ReadDir> {
899     let root = p.to_path_buf();
900     let p = cstr(p)?;
901     unsafe {
902         let ptr = libc::opendir(p.as_ptr());
903         if ptr.is_null() {
904             Err(Error::last_os_error())
905         } else {
906             let inner = InnerReadDir { dirp: Dir(ptr), root };
907             Ok(ReadDir{
908                 inner: Arc::new(inner),
909                 end_of_stream: false,
910             })
911         }
912     }
913 }
914
915 pub fn unlink(p: &Path) -> io::Result<()> {
916     let p = cstr(p)?;
917     cvt(unsafe { libc::unlink(p.as_ptr()) })?;
918     Ok(())
919 }
920
921 pub fn rename(old: &Path, new: &Path) -> io::Result<()> {
922     let old = cstr(old)?;
923     let new = cstr(new)?;
924     cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) })?;
925     Ok(())
926 }
927
928 pub fn set_perm(p: &Path, perm: FilePermissions) -> io::Result<()> {
929     let p = cstr(p)?;
930     cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) })?;
931     Ok(())
932 }
933
934 pub fn rmdir(p: &Path) -> io::Result<()> {
935     let p = cstr(p)?;
936     cvt(unsafe { libc::rmdir(p.as_ptr()) })?;
937     Ok(())
938 }
939
940 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
941     let c_path = cstr(p)?;
942     let p = c_path.as_ptr();
943
944     let mut buf = Vec::with_capacity(256);
945
946     loop {
947         let buf_read = cvt(unsafe {
948             libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity())
949         })? as usize;
950
951         unsafe { buf.set_len(buf_read); }
952
953         if buf_read != buf.capacity() {
954             buf.shrink_to_fit();
955
956             return Ok(PathBuf::from(OsString::from_vec(buf)));
957         }
958
959         // Trigger the internal buffer resizing logic of `Vec` by requiring
960         // more space than the current capacity. The length is guaranteed to be
961         // the same as the capacity due to the if statement above.
962         buf.reserve(1);
963     }
964 }
965
966 pub fn symlink(src: &Path, dst: &Path) -> io::Result<()> {
967     let src = cstr(src)?;
968     let dst = cstr(dst)?;
969     cvt(unsafe { libc::symlink(src.as_ptr(), dst.as_ptr()) })?;
970     Ok(())
971 }
972
973 pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
974     let src = cstr(src)?;
975     let dst = cstr(dst)?;
976     cvt(unsafe { libc::link(src.as_ptr(), dst.as_ptr()) })?;
977     Ok(())
978 }
979
980 pub fn stat(p: &Path) -> io::Result<FileAttr> {
981     let p = cstr(p)?;
982
983     cfg_has_statx! {
984         if let Some(ret) = unsafe { try_statx(
985             libc::AT_FDCWD,
986             p.as_ptr(),
987             libc::AT_STATX_SYNC_AS_STAT,
988             libc::STATX_ALL,
989         ) } {
990             return ret;
991         }
992     }
993
994     let mut stat: stat64 = unsafe { mem::zeroed() };
995     cvt(unsafe {
996         stat64(p.as_ptr(), &mut stat)
997     })?;
998     Ok(FileAttr::from_stat64(stat))
999 }
1000
1001 pub fn lstat(p: &Path) -> io::Result<FileAttr> {
1002     let p = cstr(p)?;
1003
1004     cfg_has_statx! {
1005         if let Some(ret) = unsafe { try_statx(
1006             libc::AT_FDCWD,
1007             p.as_ptr(),
1008             libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1009             libc::STATX_ALL,
1010         ) } {
1011             return ret;
1012         }
1013     }
1014
1015     let mut stat: stat64 = unsafe { mem::zeroed() };
1016     cvt(unsafe {
1017         lstat64(p.as_ptr(), &mut stat)
1018     })?;
1019     Ok(FileAttr::from_stat64(stat))
1020 }
1021
1022 pub fn canonicalize(p: &Path) -> io::Result<PathBuf> {
1023     let path = CString::new(p.as_os_str().as_bytes())?;
1024     let buf;
1025     unsafe {
1026         let r = libc::realpath(path.as_ptr(), ptr::null_mut());
1027         if r.is_null() {
1028             return Err(io::Error::last_os_error())
1029         }
1030         buf = CStr::from_ptr(r).to_bytes().to_vec();
1031         libc::free(r as *mut _);
1032     }
1033     Ok(PathBuf::from(OsString::from_vec(buf)))
1034 }
1035
1036 fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1037     use crate::fs::File;
1038
1039     let reader = File::open(from)?;
1040     let metadata = reader.metadata()?;
1041     if !metadata.is_file() {
1042         return Err(Error::new(
1043             ErrorKind::InvalidInput,
1044             "the source path is not an existing regular file",
1045         ));
1046     }
1047     Ok((reader, metadata))
1048 }
1049
1050 fn open_to_and_set_permissions(
1051     to: &Path,
1052     reader_metadata: crate::fs::Metadata,
1053 ) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
1054     use crate::fs::OpenOptions;
1055     use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1056
1057     let perm = reader_metadata.permissions();
1058     let writer = OpenOptions::new()
1059         // create the file with the correct mode right away
1060         .mode(perm.mode())
1061         .write(true)
1062         .create(true)
1063         .truncate(true)
1064         .open(to)?;
1065     let writer_metadata = writer.metadata()?;
1066     if writer_metadata.is_file() {
1067         // Set the correct file permissions, in case the file already existed.
1068         // Don't set the permissions on already existing non-files like
1069         // pipes/FIFOs or device nodes.
1070         writer.set_permissions(perm)?;
1071     }
1072     Ok((writer, writer_metadata))
1073 }
1074
1075 #[cfg(not(any(target_os = "linux",
1076               target_os = "android",
1077               target_os = "macos",
1078               target_os = "ios")))]
1079 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1080     let (mut reader, reader_metadata) = open_from(from)?;
1081     let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1082
1083     io::copy(&mut reader, &mut writer)
1084 }
1085
1086 #[cfg(any(target_os = "linux", target_os = "android"))]
1087 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1088     use crate::cmp;
1089     use crate::sync::atomic::{AtomicBool, Ordering};
1090
1091     // Kernel prior to 4.5 don't have copy_file_range
1092     // We store the availability in a global to avoid unnecessary syscalls
1093     static HAS_COPY_FILE_RANGE: AtomicBool = AtomicBool::new(true);
1094
1095     unsafe fn copy_file_range(
1096         fd_in: libc::c_int,
1097         off_in: *mut libc::loff_t,
1098         fd_out: libc::c_int,
1099         off_out: *mut libc::loff_t,
1100         len: libc::size_t,
1101         flags: libc::c_uint,
1102     ) -> libc::c_long {
1103         libc::syscall(
1104             libc::SYS_copy_file_range,
1105             fd_in,
1106             off_in,
1107             fd_out,
1108             off_out,
1109             len,
1110             flags,
1111         )
1112     }
1113
1114     let (mut reader, reader_metadata) = open_from(from)?;
1115     let len = reader_metadata.len();
1116     let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?;
1117
1118     let has_copy_file_range = HAS_COPY_FILE_RANGE.load(Ordering::Relaxed);
1119     let mut written = 0u64;
1120     while written < len {
1121         let copy_result = if has_copy_file_range {
1122             let bytes_to_copy = cmp::min(len - written, usize::max_value() as u64) as usize;
1123             let copy_result = unsafe {
1124                 // We actually don't have to adjust the offsets,
1125                 // because copy_file_range adjusts the file offset automatically
1126                 cvt(copy_file_range(
1127                     reader.as_raw_fd(),
1128                     ptr::null_mut(),
1129                     writer.as_raw_fd(),
1130                     ptr::null_mut(),
1131                     bytes_to_copy,
1132                     0,
1133                 ))
1134             };
1135             if let Err(ref copy_err) = copy_result {
1136                 match copy_err.raw_os_error() {
1137                     Some(libc::ENOSYS) | Some(libc::EPERM) => {
1138                         HAS_COPY_FILE_RANGE.store(false, Ordering::Relaxed);
1139                     }
1140                     _ => {}
1141                 }
1142             }
1143             copy_result
1144         } else {
1145             Err(io::Error::from_raw_os_error(libc::ENOSYS))
1146         };
1147         match copy_result {
1148             Ok(ret) => written += ret as u64,
1149             Err(err) => {
1150                 match err.raw_os_error() {
1151                     Some(os_err)
1152                     if os_err == libc::ENOSYS
1153                         || os_err == libc::EXDEV
1154                         || os_err == libc::EINVAL
1155                         || os_err == libc::EPERM =>
1156                         {
1157                             // Try fallback io::copy if either:
1158                             // - Kernel version is < 4.5 (ENOSYS)
1159                             // - Files are mounted on different fs (EXDEV)
1160                             // - copy_file_range is disallowed, for example by seccomp (EPERM)
1161                             // - copy_file_range cannot be used with pipes or device nodes (EINVAL)
1162                             assert_eq!(written, 0);
1163                             return io::copy(&mut reader, &mut writer);
1164                         }
1165                     _ => return Err(err),
1166                 }
1167             }
1168         }
1169     }
1170     Ok(written)
1171 }
1172
1173 #[cfg(any(target_os = "macos", target_os = "ios"))]
1174 pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
1175     use crate::sync::atomic::{AtomicBool, Ordering};
1176
1177     const COPYFILE_ACL: u32 = 1 << 0;
1178     const COPYFILE_STAT: u32 = 1 << 1;
1179     const COPYFILE_XATTR: u32 = 1 << 2;
1180     const COPYFILE_DATA: u32 = 1 << 3;
1181
1182     const COPYFILE_SECURITY: u32 = COPYFILE_STAT | COPYFILE_ACL;
1183     const COPYFILE_METADATA: u32 = COPYFILE_SECURITY | COPYFILE_XATTR;
1184     const COPYFILE_ALL: u32 = COPYFILE_METADATA | COPYFILE_DATA;
1185
1186     const COPYFILE_STATE_COPIED: u32 = 8;
1187
1188     #[allow(non_camel_case_types)]
1189     type copyfile_state_t = *mut libc::c_void;
1190     #[allow(non_camel_case_types)]
1191     type copyfile_flags_t = u32;
1192
1193     extern "C" {
1194         fn fcopyfile(
1195             from: libc::c_int,
1196             to: libc::c_int,
1197             state: copyfile_state_t,
1198             flags: copyfile_flags_t,
1199         ) -> libc::c_int;
1200         fn copyfile_state_alloc() -> copyfile_state_t;
1201         fn copyfile_state_free(state: copyfile_state_t) -> libc::c_int;
1202         fn copyfile_state_get(
1203             state: copyfile_state_t,
1204             flag: u32,
1205             dst: *mut libc::c_void,
1206         ) -> libc::c_int;
1207     }
1208
1209     struct FreeOnDrop(copyfile_state_t);
1210     impl Drop for FreeOnDrop {
1211         fn drop(&mut self) {
1212             // The code below ensures that `FreeOnDrop` is never a null pointer
1213             unsafe {
1214                 // `copyfile_state_free` returns -1 if the `to` or `from` files
1215                 // cannot be closed. However, this is not considerd this an
1216                 // error.
1217                 copyfile_state_free(self.0);
1218             }
1219         }
1220     }
1221
1222     // MacOS prior to 10.12 don't support `fclonefileat`
1223     // We store the availability in a global to avoid unnecessary syscalls
1224     static HAS_FCLONEFILEAT: AtomicBool = AtomicBool::new(true);
1225     syscall! {
1226         fn fclonefileat(
1227             srcfd: libc::c_int,
1228             dst_dirfd: libc::c_int,
1229             dst: *const libc::c_char,
1230             flags: libc::c_int
1231         ) -> libc::c_int
1232     }
1233
1234     let (reader, reader_metadata) = open_from(from)?;
1235
1236     // Opportunistically attempt to create a copy-on-write clone of `from`
1237     // using `fclonefileat`.
1238     if HAS_FCLONEFILEAT.load(Ordering::Relaxed) {
1239         let to = cstr(to)?;
1240         let clonefile_result = cvt(unsafe {
1241             fclonefileat(
1242                 reader.as_raw_fd(),
1243                 libc::AT_FDCWD,
1244                 to.as_ptr(),
1245                 0,
1246             )
1247         });
1248         match clonefile_result {
1249             Ok(_) => return Ok(reader_metadata.len()),
1250             Err(err) => match err.raw_os_error() {
1251                 // `fclonefileat` will fail on non-APFS volumes, if the
1252                 // destination already exists, or if the source and destination
1253                 // are on different devices. In all these cases `fcopyfile`
1254                 // should succeed.
1255                 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
1256                 Some(libc::ENOSYS) => HAS_FCLONEFILEAT.store(false, Ordering::Relaxed),
1257                 _ => return Err(err),
1258             }
1259         }
1260     }
1261
1262     // Fall back to using `fcopyfile` if `fclonefileat` does not succeed.
1263     let (writer, writer_metadata) = open_to_and_set_permissions(to, reader_metadata)?;
1264
1265     // We ensure that `FreeOnDrop` never contains a null pointer so it is
1266     // always safe to call `copyfile_state_free`
1267     let state = unsafe {
1268         let state = copyfile_state_alloc();
1269         if state.is_null() {
1270             return Err(crate::io::Error::last_os_error());
1271         }
1272         FreeOnDrop(state)
1273     };
1274
1275     let flags = if writer_metadata.is_file() {
1276         COPYFILE_ALL
1277     } else {
1278         COPYFILE_DATA
1279     };
1280
1281     cvt(unsafe {
1282         fcopyfile(
1283             reader.as_raw_fd(),
1284             writer.as_raw_fd(),
1285             state.0,
1286             flags,
1287         )
1288     })?;
1289
1290     let mut bytes_copied: libc::off_t = 0;
1291     cvt(unsafe {
1292         copyfile_state_get(
1293             state.0,
1294             COPYFILE_STATE_COPIED,
1295             &mut bytes_copied as *mut libc::off_t as *mut libc::c_void,
1296         )
1297     })?;
1298     Ok(bytes_copied as u64)
1299 }