1#![allow(nonstandard_style)]
2#![allow(unsafe_op_in_unsafe_fn)]
3#![cfg_attr(miri, allow(unused))]
5
6#[cfg(test)]
7mod tests;
8
9#[cfg(all(target_os = "linux", target_env = "gnu"))]
10use libc::c_char;
11#[cfg(any(
12 all(target_os = "linux", not(target_env = "musl")),
13 target_os = "android",
14 target_os = "fuchsia",
15 target_os = "hurd",
16 target_os = "illumos",
17 target_vendor = "apple",
18))]
19use libc::dirfd;
20#[cfg(any(target_os = "fuchsia", target_os = "illumos", target_vendor = "apple"))]
21use libc::fstatat as fstatat64;
22#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
23use libc::fstatat64;
24use libc::{c_int, mode_t};
25#[cfg(target_os = "android")]
26use libc::{
27 dirent as dirent64, fstat as fstat64, fstatat as fstatat64, ftruncate64, lseek64,
28 lstat as lstat64, off64_t, open as open64, stat as stat64,
29};
30#[cfg(not(any(
31 all(target_os = "linux", not(target_env = "musl")),
32 target_os = "android",
33 target_os = "hurd",
34 target_os = "l4re",
35)))]
36use libc::{
37 dirent as dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64,
38 lstat as lstat64, off_t as off64_t, open as open64, stat as stat64,
39};
40#[cfg(target_os = "l4re")]
41use libc::{
42 dirent64, fstat as fstat64, ftruncate as ftruncate64, lseek as lseek64, lstat as lstat64,
43 off_t as off64_t, open as open64, stat as stat64,
44};
45#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))]
46use libc::{dirent64, fstat64, ftruncate64, lseek64, lstat64, off64_t, open64, stat64};
47
48use crate::ffi::{CStr, OsStr, OsString};
49use crate::fmt::{self, Write as _};
50use crate::fs::TryLockError;
51use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom};
52use crate::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd};
53#[cfg(target_family = "unix")]
54use crate::os::unix::prelude::*;
55#[cfg(target_os = "wasi")]
56use crate::os::wasi::prelude::*;
57use crate::path::{Path, PathBuf};
58use crate::sync::Arc;
59use crate::sys::fd::FileDesc;
60pub use crate::sys::fs::common::exists;
61use crate::sys::helpers::run_path_with_cstr;
62use crate::sys::time::SystemTime;
63#[cfg(all(target_os = "linux", target_env = "gnu"))]
64use crate::sys::weak::syscall;
65#[cfg(target_os = "android")]
66use crate::sys::weak::weak;
67use crate::sys::{AsInner, AsInnerMut, FromInner, IntoInner, cvt, cvt_r};
68use crate::{mem, ptr};
69
70#[cfg(not(test))]
74mod runtime_symbols {
75 use core::ffi::{c_char, c_int, c_size_t, c_ssize_t, c_void};
76
77 unsafe extern "C" {
78 #[rustc_canonical_symbol]
79 fn open(pathname: *const c_char, flags: c_int, ...) -> c_int;
80
81 #[rustc_canonical_symbol]
82 fn read(fd: c_int, buf: *mut c_void, count: c_size_t) -> c_ssize_t;
83
84 #[rustc_canonical_symbol]
85 fn write(fd: c_int, buf: *const c_void, count: c_size_t) -> c_ssize_t;
86
87 #[rustc_canonical_symbol]
88 fn close(fd: c_int) -> c_int;
89 }
90}
91
92pub struct File(FileDesc);
93
94macro_rules! cfg_has_statx {
99 ({ $($then_tt:tt)* } else { $($else_tt:tt)* }) => {
100 cfg_select! {
101 all(target_os = "linux", target_env = "gnu") => {
102 $($then_tt)*
103 }
104 _ => {
105 $($else_tt)*
106 }
107 }
108 };
109 ($($block_inner:tt)*) => {
110 #[cfg(all(target_os = "linux", target_env = "gnu"))]
111 {
112 $($block_inner)*
113 }
114 };
115}
116
117cfg_has_statx! {{
118 #[derive(Clone)]
119 pub struct FileAttr {
120 stat: stat64,
121 statx_extra_fields: Option<StatxExtraFields>,
122 }
123
124 #[derive(Clone)]
125 struct StatxExtraFields {
126 stx_mask: u32,
128 stx_btime: libc::statx_timestamp,
129 #[cfg(target_pointer_width = "32")]
131 stx_atime: libc::statx_timestamp,
132 #[cfg(target_pointer_width = "32")]
133 stx_ctime: libc::statx_timestamp,
134 #[cfg(target_pointer_width = "32")]
135 stx_mtime: libc::statx_timestamp,
136
137 }
138
139 unsafe fn try_statx(
143 fd: c_int,
144 path: *const c_char,
145 flags: i32,
146 mask: u32,
147 ) -> Option<io::Result<FileAttr>> {
148 use crate::sync::atomic::{Atomic, AtomicU8, Ordering};
149
150 #[repr(u8)]
154 enum STATX_STATE{ Unknown = 0, Present, Unavailable }
155 static STATX_SAVED_STATE: Atomic<u8> = AtomicU8::new(STATX_STATE::Unknown as u8);
156
157 syscall!(
158 fn statx(
159 fd: c_int,
160 pathname: *const c_char,
161 flags: c_int,
162 mask: libc::c_uint,
163 statxbuf: *mut libc::statx,
164 ) -> c_int;
165 );
166
167 let statx_availability = STATX_SAVED_STATE.load(Ordering::Relaxed);
168 if statx_availability == STATX_STATE::Unavailable as u8 {
169 return None;
170 }
171
172 let mut buf: libc::statx = mem::zeroed();
173 if let Err(err) = cvt(statx(fd, path, flags, mask, &mut buf)) {
174 if STATX_SAVED_STATE.load(Ordering::Relaxed) == STATX_STATE::Present as u8 {
175 return Some(Err(err));
176 }
177
178 let err2 = cvt(statx(0, ptr::null(), 0, libc::STATX_BASIC_STATS | libc::STATX_BTIME, ptr::null_mut()))
190 .err()
191 .and_then(|e| e.raw_os_error());
192 if err2 == Some(libc::EFAULT) {
193 STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed);
194 return Some(Err(err));
195 } else {
196 STATX_SAVED_STATE.store(STATX_STATE::Unavailable as u8, Ordering::Relaxed);
197 return None;
198 }
199 }
200 if statx_availability == STATX_STATE::Unknown as u8 {
201 STATX_SAVED_STATE.store(STATX_STATE::Present as u8, Ordering::Relaxed);
202 }
203
204 let mut stat: stat64 = mem::zeroed();
206 stat.st_dev = libc::makedev(buf.stx_dev_major, buf.stx_dev_minor) as _;
208 stat.st_ino = buf.stx_ino as libc::ino64_t;
209 stat.st_nlink = buf.stx_nlink as libc::nlink_t;
210 stat.st_mode = buf.stx_mode as libc::mode_t;
211 stat.st_uid = buf.stx_uid as libc::uid_t;
212 stat.st_gid = buf.stx_gid as libc::gid_t;
213 stat.st_rdev = libc::makedev(buf.stx_rdev_major, buf.stx_rdev_minor) as _;
214 stat.st_size = buf.stx_size as off64_t;
215 stat.st_blksize = buf.stx_blksize as libc::blksize_t;
216 stat.st_blocks = buf.stx_blocks as libc::blkcnt64_t;
217 stat.st_atime = buf.stx_atime.tv_sec as libc::time_t;
218 stat.st_atime_nsec = buf.stx_atime.tv_nsec as _;
220 stat.st_mtime = buf.stx_mtime.tv_sec as libc::time_t;
221 stat.st_mtime_nsec = buf.stx_mtime.tv_nsec as _;
222 stat.st_ctime = buf.stx_ctime.tv_sec as libc::time_t;
223 stat.st_ctime_nsec = buf.stx_ctime.tv_nsec as _;
224
225 let extra = StatxExtraFields {
226 stx_mask: buf.stx_mask,
227 stx_btime: buf.stx_btime,
228 #[cfg(target_pointer_width = "32")]
230 stx_atime: buf.stx_atime,
231 #[cfg(target_pointer_width = "32")]
232 stx_ctime: buf.stx_ctime,
233 #[cfg(target_pointer_width = "32")]
234 stx_mtime: buf.stx_mtime,
235 };
236
237 Some(Ok(FileAttr { stat, statx_extra_fields: Some(extra) }))
238 }
239
240} else {
241 #[derive(Clone)]
242 pub struct FileAttr {
243 stat: stat64,
244 }
245}}
246
247struct InnerReadDir {
249 dirp: DirStream,
250 root: PathBuf,
251}
252
253pub struct ReadDir {
254 inner: Arc<InnerReadDir>,
255 end_of_stream: bool,
256}
257
258impl ReadDir {
259 fn new(inner: InnerReadDir) -> Self {
260 Self { inner: Arc::new(inner), end_of_stream: false }
261 }
262}
263
264struct DirStream(*mut libc::DIR);
265
266cfg_select! {
268 any(
269 target_os = "redox",
270 target_os = "espidf",
271 target_os = "horizon",
272 target_os = "vita",
273 target_os = "nto",
274 target_os = "qnx",
275 target_os = "vxworks",
276 target_os = "l4re",
277 ) => {
278 pub use crate::sys::fs::common::Dir;
279 }
280 _ => {
281 mod dir;
282 pub use dir::Dir;
283 }
284}
285
286fn debug_path_fd<'a, 'b>(
287 fd: c_int,
288 f: &'a mut fmt::Formatter<'b>,
289 name: &str,
290) -> fmt::DebugStruct<'a, 'b> {
291 let mut b = f.debug_struct(name);
292
293 fn get_mode(fd: c_int) -> Option<(bool, bool)> {
294 let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
295 if mode == -1 {
296 return None;
297 }
298 match mode & libc::O_ACCMODE {
299 libc::O_RDONLY => Some((true, false)),
300 libc::O_RDWR => Some((true, true)),
301 libc::O_WRONLY => Some((false, true)),
302 _ => None,
303 }
304 }
305
306 b.field("fd", &fd);
307 if let Some(path) = get_path_from_fd(fd) {
308 b.field("path", &path);
309 }
310 if let Some((read, write)) = get_mode(fd) {
311 b.field("read", &read).field("write", &write);
312 }
313
314 b
315}
316
317fn get_path_from_fd(fd: c_int) -> Option<PathBuf> {
318 #[cfg(any(target_os = "linux", target_os = "illumos", target_os = "solaris"))]
319 fn get_path(fd: c_int) -> Option<PathBuf> {
320 let mut p = PathBuf::from("/proc/self/fd");
321 p.push(&fd.to_string());
322 run_path_with_cstr(&p, &readlink).ok()
323 }
324
325 #[cfg(any(target_vendor = "apple", target_os = "netbsd"))]
326 fn get_path(fd: c_int) -> Option<PathBuf> {
327 let mut buf = vec![0; libc::PATH_MAX as usize];
333 let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_mut_ptr()) };
334 if n == -1 {
335 cfg_select! {
336 target_os = "netbsd" => {
337 let mut p = PathBuf::from("/proc/self/fd");
339 p.push(&fd.to_string());
340 return run_path_with_cstr(&p, &readlink).ok();
341 }
342 _ => {
343 return None;
344 }
345 }
346 }
347 let l = buf.iter().position(|&c| c == 0).unwrap();
348 buf.truncate(l as usize);
349 buf.shrink_to_fit();
350 Some(PathBuf::from(OsString::from_vec(buf)))
351 }
352
353 #[cfg(target_os = "freebsd")]
354 fn get_path(fd: c_int) -> Option<PathBuf> {
355 let info = Box::<libc::kinfo_file>::new_zeroed();
356 let mut info = unsafe { info.assume_init() };
357 info.kf_structsize = size_of::<libc::kinfo_file>() as libc::c_int;
358 let n = unsafe { libc::fcntl(fd, libc::F_KINFO, &mut *info) };
359 if n == -1 {
360 return None;
361 }
362 let buf = unsafe { CStr::from_ptr(info.kf_path.as_mut_ptr()).to_bytes().to_vec() };
363 Some(PathBuf::from(OsString::from_vec(buf)))
364 }
365
366 #[cfg(target_os = "vxworks")]
367 fn get_path(fd: c_int) -> Option<PathBuf> {
368 let mut buf = vec![0; libc::PATH_MAX as usize];
369 let n = unsafe { libc::ioctl(fd, libc::FIOGETNAME, buf.as_mut_ptr()) };
370 if n == -1 {
371 return None;
372 }
373 let l = buf.iter().position(|&c| c == 0).unwrap();
374 buf.truncate(l as usize);
375 Some(PathBuf::from(OsString::from_vec(buf)))
376 }
377
378 #[cfg(not(any(
379 target_os = "linux",
380 target_os = "vxworks",
381 target_os = "freebsd",
382 target_os = "netbsd",
383 target_os = "illumos",
384 target_os = "solaris",
385 target_vendor = "apple",
386 )))]
387 fn get_path(_fd: c_int) -> Option<PathBuf> {
388 None
390 }
391
392 get_path(fd)
393}
394
395pub struct DirEntry {
396 dir: Arc<InnerReadDir>,
397 entry: dirent64_min,
398 name: crate::ffi::CString,
402}
403
404struct dirent64_min {
408 d_ino: u64,
409 #[cfg(not(any(
410 target_os = "solaris",
411 target_os = "illumos",
412 target_os = "haiku",
413 target_os = "vxworks",
414 target_os = "aix",
415 target_os = "nto",
416 target_os = "qnx",
417 target_os = "vita",
418 )))]
419 d_type: u8,
420}
421
422#[derive(Clone)]
423pub struct OpenOptions {
424 read: bool,
426 write: bool,
427 append: bool,
428 truncate: bool,
429 create: bool,
430 create_new: bool,
431 custom_flags: i32,
433 mode: mode_t,
434}
435
436#[derive(Clone, PartialEq, Eq)]
437pub struct FilePermissions {
438 mode: mode_t,
439}
440
441#[derive(Copy, Clone, Debug, Default)]
442pub struct FileTimes {
443 accessed: Option<SystemTime>,
444 modified: Option<SystemTime>,
445 #[cfg(target_vendor = "apple")]
446 created: Option<SystemTime>,
447}
448
449#[derive(Copy, Clone, Eq)]
450pub struct FileType {
451 mode: mode_t,
452}
453
454impl PartialEq for FileType {
455 fn eq(&self, other: &Self) -> bool {
456 self.masked() == other.masked()
457 }
458}
459
460impl core::hash::Hash for FileType {
461 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
462 self.masked().hash(state);
463 }
464}
465
466pub struct DirBuilder {
467 mode: mode_t,
468}
469
470#[derive(Copy, Clone)]
471struct Mode(mode_t);
472
473cfg_has_statx! {{
474 impl FileAttr {
475 fn from_stat64(stat: stat64) -> Self {
476 Self { stat, statx_extra_fields: None }
477 }
478
479 #[cfg(target_pointer_width = "32")]
480 pub fn stx_mtime(&self) -> Option<&libc::statx_timestamp> {
481 if let Some(ext) = &self.statx_extra_fields {
482 if (ext.stx_mask & libc::STATX_MTIME) != 0 {
483 return Some(&ext.stx_mtime);
484 }
485 }
486 None
487 }
488
489 #[cfg(target_pointer_width = "32")]
490 pub fn stx_atime(&self) -> Option<&libc::statx_timestamp> {
491 if let Some(ext) = &self.statx_extra_fields {
492 if (ext.stx_mask & libc::STATX_ATIME) != 0 {
493 return Some(&ext.stx_atime);
494 }
495 }
496 None
497 }
498
499 #[cfg(target_pointer_width = "32")]
500 pub fn stx_ctime(&self) -> Option<&libc::statx_timestamp> {
501 if let Some(ext) = &self.statx_extra_fields {
502 if (ext.stx_mask & libc::STATX_CTIME) != 0 {
503 return Some(&ext.stx_ctime);
504 }
505 }
506 None
507 }
508 }
509} else {
510 impl FileAttr {
511 fn from_stat64(stat: stat64) -> Self {
512 Self { stat }
513 }
514 }
515}}
516
517impl FileAttr {
518 pub fn size(&self) -> u64 {
519 self.stat.st_size as u64
520 }
521 pub fn perm(&self) -> FilePermissions {
522 FilePermissions { mode: (self.stat.st_mode as mode_t) }
523 }
524
525 pub fn file_type(&self) -> FileType {
526 FileType { mode: self.stat.st_mode as mode_t }
527 }
528}
529
530#[cfg(target_os = "netbsd")]
531impl FileAttr {
532 pub fn modified(&self) -> io::Result<SystemTime> {
533 SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtimensec as i64)
534 }
535
536 pub fn accessed(&self) -> io::Result<SystemTime> {
537 SystemTime::new(self.stat.st_atime as i64, self.stat.st_atimensec as i64)
538 }
539
540 pub fn created(&self) -> io::Result<SystemTime> {
541 SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtimensec as i64)
542 }
543}
544
545#[cfg(target_os = "aix")]
546impl FileAttr {
547 pub fn modified(&self) -> io::Result<SystemTime> {
548 SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64)
549 }
550
551 pub fn accessed(&self) -> io::Result<SystemTime> {
552 SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64)
553 }
554
555 pub fn created(&self) -> io::Result<SystemTime> {
556 SystemTime::new(self.stat.st_ctim.tv_sec as i64, self.stat.st_ctim.tv_nsec as i64)
557 }
558}
559
560#[cfg(not(any(
561 target_os = "netbsd",
562 target_os = "nto",
563 target_os = "qnx",
564 target_os = "aix",
565 target_os = "wasi",
566 target_os = "l4re"
567)))]
568impl FileAttr {
569 #[cfg(not(any(
570 target_os = "vxworks",
571 target_os = "espidf",
572 target_os = "horizon",
573 target_os = "vita",
574 target_os = "hurd",
575 target_os = "rtems",
576 target_os = "nuttx",
577 )))]
578 pub fn modified(&self) -> io::Result<SystemTime> {
579 #[cfg(target_pointer_width = "32")]
580 cfg_has_statx! {
581 if let Some(mtime) = self.stx_mtime() {
582 return SystemTime::new(mtime.tv_sec, mtime.tv_nsec as i64);
583 }
584 }
585
586 SystemTime::new(self.stat.st_mtime as i64, self.stat.st_mtime_nsec as i64)
587 }
588
589 #[cfg(any(
590 all(target_os = "vxworks", vxworks_lt_25_09),
591 target_os = "espidf",
592 target_os = "vita",
593 target_os = "rtems",
594 ))]
595 pub fn modified(&self) -> io::Result<SystemTime> {
596 SystemTime::new(self.stat.st_mtime as i64, 0)
597 }
598
599 #[cfg(any(
600 target_os = "horizon",
601 target_os = "hurd",
602 target_os = "nuttx",
603 all(target_os = "vxworks", not(vxworks_lt_25_09))
604 ))]
605 pub fn modified(&self) -> io::Result<SystemTime> {
606 SystemTime::new(self.stat.st_mtim.tv_sec as i64, self.stat.st_mtim.tv_nsec as i64)
607 }
608
609 #[cfg(not(any(
610 target_os = "vxworks",
611 target_os = "espidf",
612 target_os = "horizon",
613 target_os = "vita",
614 target_os = "hurd",
615 target_os = "rtems",
616 target_os = "nuttx",
617 )))]
618 pub fn accessed(&self) -> io::Result<SystemTime> {
619 #[cfg(target_pointer_width = "32")]
620 cfg_has_statx! {
621 if let Some(atime) = self.stx_atime() {
622 return SystemTime::new(atime.tv_sec, atime.tv_nsec as i64);
623 }
624 }
625
626 SystemTime::new(self.stat.st_atime as i64, self.stat.st_atime_nsec as i64)
627 }
628
629 #[cfg(any(
630 all(target_os = "vxworks", vxworks_lt_25_09),
631 target_os = "espidf",
632 target_os = "vita",
633 target_os = "rtems"
634 ))]
635 pub fn accessed(&self) -> io::Result<SystemTime> {
636 SystemTime::new(self.stat.st_atime as i64, 0)
637 }
638
639 #[cfg(any(
640 target_os = "horizon",
641 target_os = "hurd",
642 target_os = "nuttx",
643 all(target_os = "vxworks", not(vxworks_lt_25_09))
644 ))]
645 pub fn accessed(&self) -> io::Result<SystemTime> {
646 SystemTime::new(self.stat.st_atim.tv_sec as i64, self.stat.st_atim.tv_nsec as i64)
647 }
648
649 #[cfg(any(
650 target_os = "freebsd",
651 target_os = "openbsd",
652 target_vendor = "apple",
653 target_os = "cygwin",
654 ))]
655 pub fn created(&self) -> io::Result<SystemTime> {
656 SystemTime::new(self.stat.st_birthtime as i64, self.stat.st_birthtime_nsec as i64)
657 }
658
659 #[cfg(not(any(
660 target_os = "freebsd",
661 target_os = "openbsd",
662 target_os = "vita",
663 target_vendor = "apple",
664 target_os = "cygwin",
665 )))]
666 pub fn created(&self) -> io::Result<SystemTime> {
667 cfg_has_statx! {
668 if let Some(ext) = &self.statx_extra_fields {
669 return if (ext.stx_mask & libc::STATX_BTIME) != 0 {
670 SystemTime::new(ext.stx_btime.tv_sec, ext.stx_btime.tv_nsec as i64)
671 } else {
672 Err(io::const_error!(
673 io::ErrorKind::Unsupported,
674 "creation time is not available for the filesystem",
675 ))
676 };
677 }
678 }
679
680 Err(io::const_error!(
681 io::ErrorKind::Unsupported,
682 "creation time is not available on this platform currently",
683 ))
684 }
685
686 #[cfg(target_os = "vita")]
687 pub fn created(&self) -> io::Result<SystemTime> {
688 SystemTime::new(self.stat.st_ctime as i64, 0)
689 }
690}
691
692#[cfg(any(target_os = "nto", target_os = "qnx", target_os = "wasi", target_os = "l4re"))]
693impl FileAttr {
694 pub fn modified(&self) -> io::Result<SystemTime> {
695 SystemTime::new(self.stat.st_mtim.tv_sec, self.stat.st_mtim.tv_nsec.into())
696 }
697
698 pub fn accessed(&self) -> io::Result<SystemTime> {
699 SystemTime::new(self.stat.st_atim.tv_sec, self.stat.st_atim.tv_nsec.into())
700 }
701
702 pub fn created(&self) -> io::Result<SystemTime> {
703 SystemTime::new(self.stat.st_ctim.tv_sec, self.stat.st_ctim.tv_nsec.into())
704 }
705}
706
707impl AsInner<stat64> for FileAttr {
708 #[inline]
709 fn as_inner(&self) -> &stat64 {
710 &self.stat
711 }
712}
713
714impl FilePermissions {
715 pub fn readonly(&self) -> bool {
716 self.mode & 0o222 == 0
718 }
719
720 pub fn set_readonly(&mut self, readonly: bool) {
721 if readonly {
722 self.mode &= !0o222;
724 } else {
725 self.mode |= 0o222;
727 }
728 }
729 #[cfg(not(target_os = "wasi"))]
730 pub fn mode(&self) -> u32 {
731 self.mode as u32
732 }
733}
734
735impl FileTimes {
736 pub fn set_accessed(&mut self, t: SystemTime) {
737 self.accessed = Some(t);
738 }
739
740 pub fn set_modified(&mut self, t: SystemTime) {
741 self.modified = Some(t);
742 }
743
744 #[cfg(target_vendor = "apple")]
745 pub fn set_created(&mut self, t: SystemTime) {
746 self.created = Some(t);
747 }
748}
749
750impl FileType {
751 pub fn is_dir(&self) -> bool {
752 self.is(libc::S_IFDIR)
753 }
754 pub fn is_file(&self) -> bool {
755 self.is(libc::S_IFREG)
756 }
757 pub fn is_symlink(&self) -> bool {
758 self.is(libc::S_IFLNK)
759 }
760
761 pub fn is(&self, mode: mode_t) -> bool {
762 self.masked() == mode
763 }
764
765 fn masked(&self) -> mode_t {
766 self.mode & libc::S_IFMT
767 }
768}
769
770impl fmt::Debug for FileType {
771 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
772 let FileType { mode } = self;
773 f.debug_struct("FileType").field("mode", &Mode(*mode)).finish()
774 }
775}
776
777impl FromInner<u32> for FilePermissions {
778 fn from_inner(mode: u32) -> FilePermissions {
779 FilePermissions { mode: mode as mode_t }
780 }
781}
782
783impl fmt::Debug for FilePermissions {
784 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
785 let FilePermissions { mode } = self;
786 f.debug_struct("FilePermissions").field("mode", &Mode(*mode)).finish()
787 }
788}
789
790impl fmt::Debug for ReadDir {
791 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
792 fmt::Debug::fmt(&*self.inner.root, f)
795 }
796}
797
798impl Iterator for ReadDir {
799 type Item = io::Result<DirEntry>;
800
801 fn next(&mut self) -> Option<io::Result<DirEntry>> {
802 if self.end_of_stream {
803 return None;
804 }
805
806 unsafe {
807 loop {
808 cfg_select! {
824 any(
825 target_os = "espidf", target_os = "lynxos178",
827 target_os = "qurt",
828 target_os = "rtems",
829 target_os = "vxworks",
830 ) => {
831 use crate::mem::MaybeUninit;
832
833 let mut entry = MaybeUninit::uninit();
834 let mut entry_ptr: *mut dirent64 = ptr::null_mut();
835 let err =
836 libc::readdir_r(self.inner.dirp.0, entry.as_mut_ptr(), &mut entry_ptr);
837 if err != 0 {
838 if entry_ptr.is_null() {
839 self.end_of_stream = true;
844 }
845 return Some(Err(Error::from_raw_os_error(err)));
846 }
847 if entry_ptr.is_null() {
848 return None;
849 }
850
851 let entry_ptr = entry_ptr.cast_const();
852 }
853 _ => {
854 #[cfg(not(any(
855 all(target_os = "linux", not(target_env = "musl")),
856 target_os = "hurd",
857 target_os = "l4re",
858 )))]
859 use libc::readdir as readdir64;
860 #[cfg(any(
861 all(target_os = "linux", not(target_env = "musl")),
862 target_os = "hurd",
863 target_os = "l4re"
864 ))]
865 use libc::readdir64;
866
867 use crate::sys::io::{errno, set_errno};
868
869 set_errno(0);
870 let entry_ptr: *const dirent64 = readdir64(self.inner.dirp.0);
871 if entry_ptr.is_null() {
872 self.end_of_stream = true;
875
876 return match errno() {
879 0 => None,
880 e => Some(Err(Error::from_raw_os_error(e))),
881 };
882 }
883 }
884 }
885
886 let name = CStr::from_ptr((&raw const (*entry_ptr).d_name).cast());
906 let name_bytes = name.to_bytes();
907 if name_bytes == b"." || name_bytes == b".." {
908 continue;
909 }
910
911 let entry = dirent64_min {
915 #[cfg(any(
916 target_os = "dragonfly",
917 target_os = "freebsd",
918 target_os = "netbsd",
919 target_os = "openbsd",
920 ))]
921 d_ino: (*entry_ptr).d_fileno,
922 #[cfg(any(target_os = "nuttx", target_os = "vita",))]
923 d_ino: 0,
924 #[cfg(not(any(
925 target_os = "dragonfly",
926 target_os = "freebsd",
927 target_os = "netbsd",
928 target_os = "nuttx",
929 target_os = "openbsd",
930 target_os = "vita",
931 )))]
932 d_ino: (*entry_ptr).d_ino as u64,
933 #[cfg(not(any(
934 target_os = "solaris",
935 target_os = "illumos",
936 target_os = "haiku",
937 target_os = "vxworks",
938 target_os = "aix",
939 target_os = "nto",
940 target_os = "qnx",
941 target_os = "vita",
942 )))]
943 d_type: (*entry_ptr).d_type as u8,
944 };
945
946 return Some(Ok(DirEntry {
947 entry,
948 name: name.to_owned(),
949 dir: Arc::clone(&self.inner),
950 }));
951 }
952 }
953 }
954}
955
956#[inline]
965pub(crate) fn debug_assert_fd_is_open(fd: RawFd) {
966 use crate::sys::io::errno;
967
968 if core::ub_checks::check_library_ub() {
970 if unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1 && errno() == libc::EBADF {
971 rtabort!("IO Safety violation: owned file descriptor already closed");
972 }
973 }
974}
975
976impl Drop for DirStream {
977 fn drop(&mut self) {
978 #[cfg(not(any(
980 miri,
981 target_os = "redox",
982 target_os = "nto",
983 target_os = "qnx",
984 target_os = "vita",
985 target_os = "hurd",
986 target_os = "espidf",
987 target_os = "horizon",
988 target_os = "vxworks",
989 target_os = "rtems",
990 target_os = "nuttx",
991 )))]
992 {
993 let fd = unsafe { libc::dirfd(self.0) };
994 debug_assert_fd_is_open(fd);
995 }
996 let r = unsafe { libc::closedir(self.0) };
997 assert!(
998 r == 0 || crate::io::Error::last_os_error().is_interrupted(),
999 "unexpected error during closedir: {:?}",
1000 crate::io::Error::last_os_error()
1001 );
1002 }
1003}
1004
1005unsafe impl Send for DirStream {}
1008unsafe impl Sync for DirStream {}
1009
1010impl DirEntry {
1011 pub fn path(&self) -> PathBuf {
1012 self.dir.root.join(self.file_name_os_str())
1013 }
1014
1015 pub fn file_name(&self) -> OsString {
1016 self.file_name_os_str().to_os_string()
1017 }
1018
1019 #[cfg(all(
1020 any(
1021 all(target_os = "linux", not(target_env = "musl")),
1022 target_os = "android",
1023 target_os = "fuchsia",
1024 target_os = "hurd",
1025 target_os = "illumos",
1026 target_vendor = "apple",
1027 ),
1028 not(miri) ))]
1030 pub fn metadata(&self) -> io::Result<FileAttr> {
1031 let fd = cvt(unsafe { dirfd(self.dir.dirp.0) })?;
1032 let name = self.name.as_ptr();
1033
1034 cfg_has_statx! {
1035 if let Some(ret) = unsafe { try_statx(
1036 fd,
1037 name,
1038 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
1039 libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1040 ) } {
1041 return ret;
1042 }
1043 }
1044
1045 let mut stat: stat64 = unsafe { mem::zeroed() };
1046 cvt(unsafe { fstatat64(fd, name, &mut stat, libc::AT_SYMLINK_NOFOLLOW) })?;
1047 Ok(FileAttr::from_stat64(stat))
1048 }
1049
1050 #[cfg(any(
1051 not(any(
1052 all(target_os = "linux", not(target_env = "musl")),
1053 target_os = "android",
1054 target_os = "fuchsia",
1055 target_os = "hurd",
1056 target_os = "illumos",
1057 target_vendor = "apple",
1058 )),
1059 miri ))]
1061 pub fn metadata(&self) -> io::Result<FileAttr> {
1062 run_path_with_cstr(&self.path(), &lstat)
1063 }
1064
1065 #[cfg(any(
1066 target_os = "solaris",
1067 target_os = "illumos",
1068 target_os = "haiku",
1069 target_os = "vxworks",
1070 target_os = "aix",
1071 target_os = "nto",
1072 target_os = "qnx",
1073 target_os = "vita",
1074 target_os = "l4re",
1075 ))]
1076 pub fn file_type(&self) -> io::Result<FileType> {
1077 self.metadata().map(|m| m.file_type())
1078 }
1079
1080 #[cfg(not(any(
1081 target_os = "solaris",
1082 target_os = "illumos",
1083 target_os = "haiku",
1084 target_os = "vxworks",
1085 target_os = "aix",
1086 target_os = "nto",
1087 target_os = "qnx",
1088 target_os = "vita",
1089 target_os = "l4re",
1090 )))]
1091 pub fn file_type(&self) -> io::Result<FileType> {
1092 match self.entry.d_type {
1093 libc::DT_CHR => Ok(FileType { mode: libc::S_IFCHR }),
1094 libc::DT_FIFO => Ok(FileType { mode: libc::S_IFIFO }),
1095 libc::DT_LNK => Ok(FileType { mode: libc::S_IFLNK }),
1096 libc::DT_REG => Ok(FileType { mode: libc::S_IFREG }),
1097 libc::DT_SOCK => Ok(FileType { mode: libc::S_IFSOCK }),
1098 libc::DT_DIR => Ok(FileType { mode: libc::S_IFDIR }),
1099 libc::DT_BLK => Ok(FileType { mode: libc::S_IFBLK }),
1100 _ => self.metadata().map(|m| m.file_type()),
1101 }
1102 }
1103
1104 pub fn ino(&self) -> u64 {
1105 self.entry.d_ino
1106 }
1107
1108 pub fn file_name_os_str(&self) -> &OsStr {
1109 OsStr::from_bytes(self.name.as_bytes())
1110 }
1111}
1112
1113impl OpenOptions {
1114 pub fn new() -> OpenOptions {
1115 OpenOptions {
1116 read: false,
1118 write: false,
1119 append: false,
1120 truncate: false,
1121 create: false,
1122 create_new: false,
1123 custom_flags: 0,
1125 mode: 0o666,
1126 }
1127 }
1128
1129 pub fn read(&mut self, read: bool) {
1130 self.read = read;
1131 }
1132 pub fn write(&mut self, write: bool) {
1133 self.write = write;
1134 }
1135 pub fn append(&mut self, append: bool) {
1136 self.append = append;
1137 }
1138 pub fn truncate(&mut self, truncate: bool) {
1139 self.truncate = truncate;
1140 }
1141 pub fn create(&mut self, create: bool) {
1142 self.create = create;
1143 }
1144 pub fn create_new(&mut self, create_new: bool) {
1145 self.create_new = create_new;
1146 }
1147
1148 pub fn custom_flags(&mut self, flags: i32) {
1149 self.custom_flags = flags;
1150 }
1151 #[cfg(not(target_os = "wasi"))]
1152 pub fn mode(&mut self, mode: u32) {
1153 self.mode = mode as mode_t;
1154 }
1155
1156 fn get_access_mode(&self) -> io::Result<c_int> {
1157 match (self.read, self.write, self.append) {
1158 (true, false, false) => Ok(libc::O_RDONLY),
1159 (false, true, false) => Ok(libc::O_WRONLY),
1160 (true, true, false) => Ok(libc::O_RDWR),
1161 (false, _, true) => Ok(libc::O_WRONLY | libc::O_APPEND),
1162 (true, _, true) => Ok(libc::O_RDWR | libc::O_APPEND),
1163 (false, false, false) => {
1164 if self.create || self.create_new || self.truncate {
1167 Err(io::Error::new(
1168 io::ErrorKind::InvalidInput,
1169 "creating or truncating a file requires write or append access",
1170 ))
1171 } else {
1172 Err(io::Error::new(
1173 io::ErrorKind::InvalidInput,
1174 "must specify at least one of read, write, or append access",
1175 ))
1176 }
1177 }
1178 }
1179 }
1180
1181 fn get_creation_mode(&self) -> io::Result<c_int> {
1182 match (self.write, self.append) {
1183 (true, false) => {}
1184 (false, false) => {
1185 if self.truncate || self.create || self.create_new {
1186 return Err(io::Error::new(
1187 io::ErrorKind::InvalidInput,
1188 "creating or truncating a file requires write or append access",
1189 ));
1190 }
1191 }
1192 (_, true) => {
1193 if self.truncate && !self.create_new {
1194 return Err(io::Error::new(
1195 io::ErrorKind::InvalidInput,
1196 "append and truncate cannot both be enabled",
1197 ));
1198 }
1199 }
1200 }
1201
1202 Ok(match (self.create, self.truncate, self.create_new) {
1203 (false, false, false) => 0,
1204 (true, false, false) => libc::O_CREAT,
1205 (false, true, false) => libc::O_TRUNC,
1206 (true, true, false) => libc::O_CREAT | libc::O_TRUNC,
1207 (_, _, true) => libc::O_CREAT | libc::O_EXCL,
1208 })
1209 }
1210}
1211
1212impl fmt::Debug for OpenOptions {
1213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1214 let OpenOptions { read, write, append, truncate, create, create_new, custom_flags, mode } =
1215 self;
1216 f.debug_struct("OpenOptions")
1217 .field("read", read)
1218 .field("write", write)
1219 .field("append", append)
1220 .field("truncate", truncate)
1221 .field("create", create)
1222 .field("create_new", create_new)
1223 .field("custom_flags", custom_flags)
1224 .field("mode", &Mode(*mode))
1225 .finish()
1226 }
1227}
1228
1229impl File {
1230 pub fn open(path: &Path, opts: &OpenOptions) -> io::Result<File> {
1231 run_path_with_cstr(path, &|path| File::open_c(path, opts))
1232 }
1233
1234 pub fn open_c(path: &CStr, opts: &OpenOptions) -> io::Result<File> {
1235 let flags = libc::O_CLOEXEC
1236 | opts.get_access_mode()?
1237 | opts.get_creation_mode()?
1238 | (opts.custom_flags as c_int & !libc::O_ACCMODE);
1239 let fd = cvt_r(|| unsafe { open64(path.as_ptr(), flags, opts.mode as c_int) })?;
1244 Ok(File(unsafe { FileDesc::from_raw_fd(fd) }))
1245 }
1246
1247 pub fn file_attr(&self) -> io::Result<FileAttr> {
1248 let fd = self.as_raw_fd();
1249
1250 cfg_has_statx! {
1251 if let Some(ret) = unsafe { try_statx(
1252 fd,
1253 c"".as_ptr() as *const c_char,
1254 libc::AT_EMPTY_PATH | libc::AT_STATX_SYNC_AS_STAT,
1255 libc::STATX_BASIC_STATS | libc::STATX_BTIME,
1256 ) } {
1257 return ret;
1258 }
1259 }
1260
1261 let mut stat: stat64 = unsafe { mem::zeroed() };
1262 cvt(unsafe { fstat64(fd, &mut stat) })?;
1263 Ok(FileAttr::from_stat64(stat))
1264 }
1265
1266 pub fn fsync(&self) -> io::Result<()> {
1267 cvt_r(|| unsafe { os_fsync(self.as_raw_fd()) })?;
1268 return Ok(());
1269
1270 #[cfg(target_vendor = "apple")]
1271 unsafe fn os_fsync(fd: c_int) -> c_int {
1272 libc::fcntl(fd, libc::F_FULLFSYNC)
1273 }
1274 #[cfg(not(target_vendor = "apple"))]
1275 unsafe fn os_fsync(fd: c_int) -> c_int {
1276 libc::fsync(fd)
1277 }
1278 }
1279
1280 pub fn datasync(&self) -> io::Result<()> {
1281 cvt_r(|| unsafe { os_datasync(self.as_raw_fd()) })?;
1282 return Ok(());
1283
1284 #[cfg(target_vendor = "apple")]
1285 unsafe fn os_datasync(fd: c_int) -> c_int {
1286 libc::fcntl(fd, libc::F_FULLFSYNC)
1287 }
1288 #[cfg(any(
1289 target_os = "freebsd",
1290 target_os = "fuchsia",
1291 target_os = "linux",
1292 target_os = "cygwin",
1293 target_os = "android",
1294 target_os = "netbsd",
1295 target_os = "openbsd",
1296 target_os = "nto",
1297 target_os = "qnx",
1298 target_os = "hurd",
1299 target_os = "l4re",
1300 ))]
1301 unsafe fn os_datasync(fd: c_int) -> c_int {
1302 libc::fdatasync(fd)
1303 }
1304 #[cfg(not(any(
1305 target_os = "android",
1306 target_os = "fuchsia",
1307 target_os = "freebsd",
1308 target_os = "linux",
1309 target_os = "cygwin",
1310 target_os = "netbsd",
1311 target_os = "openbsd",
1312 target_os = "nto",
1313 target_os = "qnx",
1314 target_os = "hurd",
1315 target_os = "l4re",
1316 target_vendor = "apple",
1317 )))]
1318 unsafe fn os_datasync(fd: c_int) -> c_int {
1319 libc::fsync(fd)
1320 }
1321 }
1322
1323 pub fn lock(&self) -> io::Result<()> {
1324 cfg_select! {
1325 any(
1326 target_os = "freebsd",
1327 target_os = "fuchsia",
1328 target_os = "hurd",
1329 target_os = "linux",
1330 target_os = "netbsd",
1331 target_os = "openbsd",
1332 target_os = "cygwin",
1333 target_os = "illumos",
1334 target_os = "aix",
1335 target_os = "android",
1336 target_vendor = "apple",
1337 ) => {
1338 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1339 Ok(())
1340 }
1341 _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported")),
1342 }
1343 }
1344
1345 pub fn lock_shared(&self) -> io::Result<()> {
1346 cfg_select! {
1347 any(
1348 target_os = "freebsd",
1349 target_os = "fuchsia",
1350 target_os = "hurd",
1351 target_os = "linux",
1352 target_os = "netbsd",
1353 target_os = "openbsd",
1354 target_os = "cygwin",
1355 target_os = "illumos",
1356 target_os = "aix",
1357 target_os = "android",
1358 target_vendor = "apple",
1359 ) => {
1360 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1361 Ok(())
1362 }
1363 _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported")),
1364 }
1365 }
1366
1367 pub fn try_lock(&self) -> Result<(), TryLockError> {
1368 cfg_select! {
1369 any(
1370 target_os = "freebsd",
1371 target_os = "fuchsia",
1372 target_os = "hurd",
1373 target_os = "linux",
1374 target_os = "netbsd",
1375 target_os = "openbsd",
1376 target_os = "cygwin",
1377 target_os = "illumos",
1378 target_os = "aix",
1379 target_os = "android",
1380 target_vendor = "apple",
1381 ) => {
1382 let result =
1383 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1384 if let Err(err) = result {
1385 if err.kind() == io::ErrorKind::WouldBlock {
1386 Err(TryLockError::WouldBlock)
1387 } else {
1388 Err(TryLockError::Error(err))
1389 }
1390 } else {
1391 Ok(())
1392 }
1393 }
1394 _ => Err(TryLockError::Error(io::const_error!(
1395 io::ErrorKind::Unsupported,
1396 "try_lock() not supported"
1397 ))),
1398 }
1399 }
1400
1401 pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
1402 cfg_select! {
1403 any(
1404 target_os = "freebsd",
1405 target_os = "fuchsia",
1406 target_os = "hurd",
1407 target_os = "linux",
1408 target_os = "netbsd",
1409 target_os = "openbsd",
1410 target_os = "cygwin",
1411 target_os = "illumos",
1412 target_os = "aix",
1413 target_os = "android",
1414 target_vendor = "apple",
1415 ) => {
1416 let result =
1417 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1418 if let Err(err) = result {
1419 if err.kind() == io::ErrorKind::WouldBlock {
1420 Err(TryLockError::WouldBlock)
1421 } else {
1422 Err(TryLockError::Error(err))
1423 }
1424 } else {
1425 Ok(())
1426 }
1427 }
1428 _ => Err(TryLockError::Error(io::const_error!(
1429 io::ErrorKind::Unsupported,
1430 "try_lock_shared() not supported"
1431 ))),
1432 }
1433 }
1434
1435 pub fn unlock(&self) -> io::Result<()> {
1436 cfg_select! {
1437 any(
1438 target_os = "freebsd",
1439 target_os = "fuchsia",
1440 target_os = "hurd",
1441 target_os = "linux",
1442 target_os = "netbsd",
1443 target_os = "openbsd",
1444 target_os = "cygwin",
1445 target_os = "illumos",
1446 target_os = "aix",
1447 target_os = "android",
1448 target_vendor = "apple",
1449 ) => {
1450 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1451 Ok(())
1452 }
1453 _ => Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported")),
1454 }
1455 }
1456
1457 pub fn truncate(&self, size: u64) -> io::Result<()> {
1458 let size: off64_t =
1459 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1460 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1461 }
1462
1463 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1464 self.0.read(buf)
1465 }
1466
1467 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1468 self.0.read_vectored(bufs)
1469 }
1470
1471 #[inline]
1472 pub fn is_read_vectored(&self) -> bool {
1473 self.0.is_read_vectored()
1474 }
1475
1476 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1477 self.0.read_at(buf, offset)
1478 }
1479
1480 pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
1481 self.0.read_buf(cursor)
1482 }
1483
1484 pub fn read_buf_at(&self, cursor: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
1485 self.0.read_buf_at(cursor, offset)
1486 }
1487
1488 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
1489 self.0.read_vectored_at(bufs, offset)
1490 }
1491
1492 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1493 self.0.write(buf)
1494 }
1495
1496 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1497 self.0.write_vectored(bufs)
1498 }
1499
1500 #[inline]
1501 pub fn is_write_vectored(&self) -> bool {
1502 self.0.is_write_vectored()
1503 }
1504
1505 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1506 self.0.write_at(buf, offset)
1507 }
1508
1509 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
1510 self.0.write_vectored_at(bufs, offset)
1511 }
1512
1513 #[inline]
1514 pub fn flush(&self) -> io::Result<()> {
1515 Ok(())
1516 }
1517
1518 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1519 let (whence, pos) = match pos {
1520 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1523 SeekFrom::End(off) => (libc::SEEK_END, off),
1524 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1525 };
1526 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1527 Ok(n as u64)
1528 }
1529
1530 pub fn size(&self) -> Option<io::Result<u64>> {
1531 match self.file_attr().map(|attr| attr.size()) {
1532 Ok(0) => None,
1535 result => Some(result),
1536 }
1537 }
1538
1539 pub fn tell(&self) -> io::Result<u64> {
1540 self.seek(SeekFrom::Current(0))
1541 }
1542
1543 pub fn duplicate(&self) -> io::Result<File> {
1544 self.0.duplicate().map(File)
1545 }
1546
1547 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1548 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1549 Ok(())
1550 }
1551
1552 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1553 cfg_select! {
1554 any(
1555 target_os = "redox",
1556 target_os = "espidf",
1557 target_os = "horizon",
1558 target_os = "nuttx",
1559 target_os = "l4re"
1560 ) => {
1561 let _ = times;
1565 Err(io::const_error!(
1566 io::ErrorKind::Unsupported,
1567 "setting file times not supported",
1568 ))
1569 }
1570 target_vendor = "apple" => {
1571 let ta = TimesAttrlist::from_times(×)?;
1572 cvt(unsafe {
1573 libc::fsetattrlist(
1574 self.as_raw_fd(),
1575 ta.attrlist(),
1576 ta.times_buf(),
1577 ta.times_buf_size(),
1578 0,
1579 )
1580 })?;
1581 Ok(())
1582 }
1583 target_os = "android" => {
1584 let times = [
1585 file_time_to_timespec(times.accessed)?,
1586 file_time_to_timespec(times.modified)?,
1587 ];
1588 cvt(unsafe {
1590 weak!(
1591 fn futimens(fd: c_int, times: *const libc::timespec) -> c_int;
1592 );
1593 match futimens.get() {
1594 Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1595 None => {
1596 return Err(io::const_error!(
1597 io::ErrorKind::Unsupported,
1598 "setting file times requires Android API level >= 19",
1599 ));
1600 }
1601 }
1602 })?;
1603 Ok(())
1604 }
1605 _ => {
1606 #[cfg(all(
1607 target_os = "linux",
1608 target_env = "gnu",
1609 target_pointer_width = "32",
1610 not(target_arch = "riscv32")
1611 ))]
1612 {
1613 use crate::sys::pal::time::__timespec64;
1614 use crate::sys::pal::weak::weak;
1615
1616 weak!(
1618 fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int;
1619 );
1620
1621 if let Some(futimens64) = __futimens64.get() {
1622 let to_timespec = |time: Option<SystemTime>| {
1623 time.map(|time| time.t.to_timespec64())
1624 .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
1625 };
1626 let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1627 cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1628 return Ok(());
1629 }
1630 }
1631 let times = [
1632 file_time_to_timespec(times.accessed)?,
1633 file_time_to_timespec(times.modified)?,
1634 ];
1635 cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1636 Ok(())
1637 }
1638 }
1639 }
1640}
1641
1642#[cfg(not(any(
1643 target_os = "redox",
1644 target_os = "espidf",
1645 target_os = "horizon",
1646 target_os = "nuttx",
1647)))]
1648fn file_time_to_timespec(time: Option<SystemTime>) -> io::Result<libc::timespec> {
1649 match time {
1650 Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1651 Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
1652 io::ErrorKind::InvalidInput,
1653 "timestamp is too large to set as a file time",
1654 )),
1655 Some(_) => Err(io::const_error!(
1656 io::ErrorKind::InvalidInput,
1657 "timestamp is too small to set as a file time",
1658 )),
1659 None => Ok({
1660 let mut ts = libc::timespec::default();
1661 ts.tv_sec = 0;
1662 ts.tv_nsec = libc::UTIME_OMIT as _;
1663 ts
1664 }),
1665 }
1666}
1667
1668#[cfg(target_vendor = "apple")]
1669struct TimesAttrlist {
1670 buf: [mem::MaybeUninit<libc::timespec>; 3],
1671 attrlist: libc::attrlist,
1672 num_times: usize,
1673}
1674
1675#[cfg(target_vendor = "apple")]
1676impl TimesAttrlist {
1677 fn from_times(times: &FileTimes) -> io::Result<Self> {
1678 let mut this = Self {
1679 buf: [mem::MaybeUninit::<libc::timespec>::uninit(); 3],
1680 attrlist: unsafe { mem::zeroed() },
1681 num_times: 0,
1682 };
1683 this.attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1684 if times.created.is_some() {
1685 this.buf[this.num_times].write(file_time_to_timespec(times.created)?);
1686 this.num_times += 1;
1687 this.attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1688 }
1689 if times.modified.is_some() {
1690 this.buf[this.num_times].write(file_time_to_timespec(times.modified)?);
1691 this.num_times += 1;
1692 this.attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1693 }
1694 if times.accessed.is_some() {
1695 this.buf[this.num_times].write(file_time_to_timespec(times.accessed)?);
1696 this.num_times += 1;
1697 this.attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1698 }
1699 Ok(this)
1700 }
1701
1702 fn attrlist(&self) -> *mut libc::c_void {
1703 (&raw const self.attrlist).cast::<libc::c_void>().cast_mut()
1704 }
1705
1706 fn times_buf(&self) -> *mut libc::c_void {
1707 self.buf.as_ptr().cast::<libc::c_void>().cast_mut()
1708 }
1709
1710 fn times_buf_size(&self) -> usize {
1711 self.num_times * size_of::<libc::timespec>()
1712 }
1713}
1714
1715impl DirBuilder {
1716 pub fn new() -> DirBuilder {
1717 DirBuilder { mode: 0o777 }
1718 }
1719
1720 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1721 run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1722 }
1723
1724 #[cfg(not(target_os = "wasi"))]
1725 pub fn set_mode(&mut self, mode: u32) {
1726 self.mode = mode as mode_t;
1727 }
1728}
1729
1730impl fmt::Debug for DirBuilder {
1731 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1732 let DirBuilder { mode } = self;
1733 f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1734 }
1735}
1736
1737impl AsInner<FileDesc> for File {
1738 #[inline]
1739 fn as_inner(&self) -> &FileDesc {
1740 &self.0
1741 }
1742}
1743
1744impl AsInnerMut<FileDesc> for File {
1745 #[inline]
1746 fn as_inner_mut(&mut self) -> &mut FileDesc {
1747 &mut self.0
1748 }
1749}
1750
1751impl IntoInner<FileDesc> for File {
1752 fn into_inner(self) -> FileDesc {
1753 self.0
1754 }
1755}
1756
1757impl FromInner<FileDesc> for File {
1758 fn from_inner(file_desc: FileDesc) -> Self {
1759 Self(file_desc)
1760 }
1761}
1762
1763impl AsFd for File {
1764 #[inline]
1765 fn as_fd(&self) -> BorrowedFd<'_> {
1766 self.0.as_fd()
1767 }
1768}
1769
1770impl AsRawFd for File {
1771 #[inline]
1772 fn as_raw_fd(&self) -> RawFd {
1773 self.0.as_raw_fd()
1774 }
1775}
1776
1777impl IntoRawFd for File {
1778 fn into_raw_fd(self) -> RawFd {
1779 self.0.into_raw_fd()
1780 }
1781}
1782
1783impl FromRawFd for File {
1784 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1785 Self(FromRawFd::from_raw_fd(raw_fd))
1786 }
1787}
1788
1789impl fmt::Debug for File {
1790 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1791 let fd = self.as_raw_fd();
1792 let mut b = debug_path_fd(fd, f, "File");
1793 b.finish()
1794 }
1795}
1796
1797impl fmt::Debug for Mode {
1807 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1808 let Self(mode) = *self;
1809 write!(f, "0o{mode:06o}")?;
1810
1811 let entry_type = match mode & libc::S_IFMT {
1812 libc::S_IFDIR => 'd',
1813 libc::S_IFBLK => 'b',
1814 libc::S_IFCHR => 'c',
1815 libc::S_IFLNK => 'l',
1816 libc::S_IFIFO => 'p',
1817 libc::S_IFREG => '-',
1818 _ => return Ok(()),
1819 };
1820
1821 f.write_str(" (")?;
1822 f.write_char(entry_type)?;
1823
1824 f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1826 f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1827 let owner_executable = mode & libc::S_IXUSR != 0;
1828 let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1829 f.write_char(match (owner_executable, setuid) {
1830 (true, true) => 's', (false, true) => 'S', (true, false) => 'x', (false, false) => '-',
1834 })?;
1835
1836 f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1838 f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1839 let group_executable = mode & libc::S_IXGRP != 0;
1840 let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1841 f.write_char(match (group_executable, setgid) {
1842 (true, true) => 's', (false, true) => 'S', (true, false) => 'x', (false, false) => '-',
1846 })?;
1847
1848 f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1850 f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1851 let other_executable = mode & libc::S_IXOTH != 0;
1852 let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1853 f.write_char(match (entry_type, other_executable, sticky) {
1854 ('d', true, true) => 't', ('d', false, true) => 'T', (_, true, _) => 'x', (_, false, _) => '-',
1858 })?;
1859
1860 f.write_char(')')
1861 }
1862}
1863
1864pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1865 let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1866 if ptr.is_null() {
1867 Err(Error::last_os_error())
1868 } else {
1869 let root = path.to_path_buf();
1870 let inner = InnerReadDir { dirp: DirStream(ptr), root };
1871 Ok(ReadDir::new(inner))
1872 }
1873}
1874
1875pub fn unlink(p: &CStr) -> io::Result<()> {
1876 cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ())
1877}
1878
1879pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
1880 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1881}
1882
1883pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1884 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
1885}
1886
1887#[cfg(target_os = "vxworks")]
1888pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1889 Err(crate::io::ErrorKind::Unsupported.into())
1892}
1893
1894#[cfg(target_os = "android")]
1895pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1896 Err(crate::io::ErrorKind::Unsupported.into())
1904}
1905
1906#[cfg(not(any(target_os = "android", target_os = "vxworks")))]
1907pub fn set_perm_nofollow(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1908 #[inline]
1909 fn open_and_set_permissions(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1911 use crate::fs::{OpenOptions, Permissions};
1912
1913 let mut options = OpenOptions::new();
1914 options.read(true);
1915
1916 #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
1919 {
1920 #[cfg(not(target_os = "wasi"))]
1921 use crate::os::unix::fs::OpenOptionsExt;
1922 #[cfg(target_os = "wasi")]
1923 use crate::os::wasi::fs::OpenOptionsExt;
1924 options.custom_flags(libc::O_NOFOLLOW);
1925 }
1926
1927 let os_str = unsafe { OsStr::from_encoded_bytes_unchecked(p.to_bytes()) };
1931 options.open(Path::new(os_str))?.set_permissions(Permissions::from_inner(perm))
1932 }
1933
1934 #[allow(unused)]
1936 let mut res: Result<(), core::io::Error> = Err(crate::io::ErrorKind::Unsupported.into());
1937
1938 #[cfg(any(
1940 target_os = "linux",
1941 target_os = "macos",
1942 target_os = "freebsd",
1943 target_os = "openbsd",
1944 target_os = "netbsd",
1945 target_os = "dragonfly",
1946 target_os = "nto",
1947 target_os = "qnx"
1948 ))]
1949 {
1950 res = cvt_r(|| unsafe {
1951 libc::fchmodat(libc::AT_FDCWD, p.as_ptr(), perm.mode, libc::AT_SYMLINK_NOFOLLOW)
1952 })
1953 .map(|_| ());
1954 }
1955
1956 match res {
1960 Ok(_) => Ok(()),
1961 Err(err) => {
1962 if err.kind() == crate::io::ErrorKind::Unsupported {
1963 match open_and_set_permissions(p, perm) {
1964 Ok(_) => return Ok(()),
1965 Err(e) => {
1966 if e.kind() == crate::io::ErrorKind::FilesystemLoop {
1967 return Err(err);
1972 }
1973 return Err(e);
1974 }
1975 }
1976 }
1977
1978 Err(err)
1979 }
1980 }
1981}
1982
1983pub fn rmdir(p: &CStr) -> io::Result<()> {
1984 cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ())
1985}
1986
1987pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> {
1988 let p = c_path.as_ptr();
1989
1990 let mut buf = Vec::with_capacity(256);
1991
1992 loop {
1993 let buf_read =
1994 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
1995
1996 unsafe {
1997 buf.set_len(buf_read);
1998 }
1999
2000 if buf_read != buf.capacity() {
2001 buf.shrink_to_fit();
2002
2003 return Ok(PathBuf::from(OsString::from_vec(buf)));
2004 }
2005
2006 buf.reserve(1);
2010 }
2011}
2012
2013pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> {
2014 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
2015}
2016
2017pub fn link(original: &CStr, link: &CStr) -> io::Result<()> {
2018 cfg_select! {
2019 any(
2020 target_os = "vxworks",
2025 target_os = "redox",
2026 target_os = "espidf",
2027 target_os = "horizon",
2029 target_os = "vita",
2030 target_os = "l4re",
2031 target_env = "nto70",
2032 ) => {
2033 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
2034 }
2035 _ => {
2036 cvt(unsafe {
2039 libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0)
2040 })?;
2041 }
2042 }
2043 Ok(())
2044}
2045
2046pub fn stat(p: &CStr) -> io::Result<FileAttr> {
2047 cfg_has_statx! {
2048 if let Some(ret) = unsafe { try_statx(
2049 libc::AT_FDCWD,
2050 p.as_ptr(),
2051 libc::AT_STATX_SYNC_AS_STAT,
2052 libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2053 ) } {
2054 return ret;
2055 }
2056 }
2057
2058 let mut stat: stat64 = unsafe { mem::zeroed() };
2059 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
2060 Ok(FileAttr::from_stat64(stat))
2061}
2062
2063pub fn lstat(p: &CStr) -> io::Result<FileAttr> {
2064 cfg_has_statx! {
2065 if let Some(ret) = unsafe { try_statx(
2066 libc::AT_FDCWD,
2067 p.as_ptr(),
2068 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
2069 libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2070 ) } {
2071 return ret;
2072 }
2073 }
2074
2075 let mut stat: stat64 = unsafe { mem::zeroed() };
2076 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
2077 Ok(FileAttr::from_stat64(stat))
2078}
2079
2080pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
2081 let r = unsafe { libc::realpath(path.as_ptr(), ptr::null_mut()) };
2082 if r.is_null() {
2083 return Err(io::Error::last_os_error());
2084 }
2085 Ok(PathBuf::from(OsString::from_vec(unsafe {
2086 let buf = CStr::from_ptr(r).to_bytes().to_vec();
2087 libc::free(r as *mut _);
2088 buf
2089 })))
2090}
2091
2092fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2093 use crate::fs::File;
2094 use crate::sys::fs::common::NOT_FILE_ERROR;
2095
2096 let reader = File::open(from)?;
2097 let metadata = reader.metadata()?;
2098 if !metadata.is_file() {
2099 return Err(NOT_FILE_ERROR);
2100 }
2101 Ok((reader, metadata))
2102}
2103
2104fn set_times_impl(p: &CStr, times: FileTimes, follow_symlinks: bool) -> io::Result<()> {
2105 cfg_select! {
2106 any(
2107 target_os = "redox",
2108 target_os = "espidf",
2109 target_os = "horizon",
2110 target_os = "nuttx",
2111 target_os = "vita",
2112 target_os = "rtems"
2113 ) => {
2114 let _ = (p, times, follow_symlinks);
2115 Err(io::const_error!(io::ErrorKind::Unsupported, "setting file times not supported"))
2116 }
2117 target_vendor = "apple" => {
2118 let ta = TimesAttrlist::from_times(×)?;
2120 let options = if follow_symlinks { 0 } else { libc::FSOPT_NOFOLLOW };
2121
2122 cvt(unsafe {
2123 libc::setattrlist(
2124 p.as_ptr(),
2125 ta.attrlist(),
2126 ta.times_buf(),
2127 ta.times_buf_size(),
2128 options as u32,
2129 )
2130 })?;
2131 Ok(())
2132 }
2133 target_os = "android" => {
2134 let times =
2135 [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2136 let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2137 cvt(unsafe {
2139 weak!(
2140 fn utimensat(
2141 dirfd: c_int,
2142 path: *const libc::c_char,
2143 times: *const libc::timespec,
2144 flags: c_int,
2145 ) -> c_int;
2146 );
2147 match utimensat.get() {
2148 Some(utimensat) => utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags),
2149 None => {
2150 return Err(io::const_error!(
2151 io::ErrorKind::Unsupported,
2152 "setting file times requires Android API level >= 19",
2153 ));
2154 }
2155 }
2156 })?;
2157 Ok(())
2158 }
2159 _ => {
2160 let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2161 #[cfg(all(
2162 target_os = "linux",
2163 target_env = "gnu",
2164 target_pointer_width = "32",
2165 not(target_arch = "riscv32")
2166 ))]
2167 {
2168 use crate::sys::pal::time::__timespec64;
2169 use crate::sys::pal::weak::weak;
2170
2171 weak!(
2173 fn __utimensat64(
2174 dirfd: c_int,
2175 path: *const c_char,
2176 times: *const __timespec64,
2177 flags: c_int,
2178 ) -> c_int;
2179 );
2180
2181 if let Some(utimensat64) = __utimensat64.get() {
2182 let to_timespec = |time: Option<SystemTime>| {
2183 time.map(|time| time.t.to_timespec64())
2184 .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
2185 };
2186 let times = [to_timespec(times.accessed), to_timespec(times.modified)];
2187 cvt(unsafe { utimensat64(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2188 return Ok(());
2189 }
2190 }
2191 let times =
2192 [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2193 cvt(unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2194 Ok(())
2195 }
2196 }
2197}
2198
2199#[inline(always)]
2200pub fn set_times(p: &CStr, times: FileTimes) -> io::Result<()> {
2201 set_times_impl(p, times, true)
2202}
2203
2204#[inline(always)]
2205pub fn set_times_nofollow(p: &CStr, times: FileTimes) -> io::Result<()> {
2206 set_times_impl(p, times, false)
2207}
2208
2209#[cfg(any(target_os = "espidf", target_os = "wasi"))]
2210fn open_to_and_set_permissions(
2211 to: &Path,
2212 _reader_metadata: &crate::fs::Metadata,
2213) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2214 use crate::fs::OpenOptions;
2215 let writer = OpenOptions::new().write(true).create(true).truncate(true).open(to)?;
2216 let writer_metadata = writer.metadata()?;
2217 Ok((writer, writer_metadata))
2218}
2219
2220#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
2221fn open_to_and_set_permissions(
2222 to: &Path,
2223 reader_metadata: &crate::fs::Metadata,
2224) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2225 use crate::fs::OpenOptions;
2226 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
2227
2228 let perm = reader_metadata.permissions();
2229 let writer = OpenOptions::new()
2230 .mode(perm.mode())
2232 .write(true)
2233 .create(true)
2234 .truncate(true)
2235 .open(to)?;
2236 let writer_metadata = writer.metadata()?;
2237 #[cfg(not(target_os = "vita"))]
2239 if writer_metadata.is_file() {
2240 writer.set_permissions(perm)?;
2244 }
2245 Ok((writer, writer_metadata))
2246}
2247
2248mod cfm {
2249 use crate::fs::{File, Metadata};
2250 use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
2251
2252 #[allow(dead_code)]
2253 pub struct CachedFileMetadata(pub File, pub Metadata);
2254
2255 impl Read for CachedFileMetadata {
2256 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2257 self.0.read(buf)
2258 }
2259 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2260 self.0.read_vectored(bufs)
2261 }
2262 fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
2263 self.0.read_buf(cursor)
2264 }
2265 #[inline]
2266 fn is_read_vectored(&self) -> bool {
2267 self.0.is_read_vectored()
2268 }
2269 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2270 self.0.read_to_end(buf)
2271 }
2272 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2273 self.0.read_to_string(buf)
2274 }
2275 }
2276 impl Write for CachedFileMetadata {
2277 fn write(&mut self, buf: &[u8]) -> Result<usize> {
2278 self.0.write(buf)
2279 }
2280 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2281 self.0.write_vectored(bufs)
2282 }
2283 #[inline]
2284 fn is_write_vectored(&self) -> bool {
2285 self.0.is_write_vectored()
2286 }
2287 #[inline]
2288 fn flush(&mut self) -> Result<()> {
2289 self.0.flush()
2290 }
2291 }
2292}
2293#[cfg(any(target_os = "linux", target_os = "android"))]
2294pub(in crate::sys) use cfm::CachedFileMetadata;
2295
2296#[cfg(not(target_vendor = "apple"))]
2297pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2298 let (reader, reader_metadata) = open_from(from)?;
2299 let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2300
2301 io::copy(
2302 &mut cfm::CachedFileMetadata(reader, reader_metadata),
2303 &mut cfm::CachedFileMetadata(writer, writer_metadata),
2304 )
2305}
2306
2307#[cfg(target_vendor = "apple")]
2308pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2309 const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2310
2311 struct FreeOnDrop(libc::copyfile_state_t);
2312 impl Drop for FreeOnDrop {
2313 fn drop(&mut self) {
2314 unsafe {
2316 libc::copyfile_state_free(self.0);
2319 }
2320 }
2321 }
2322
2323 let (reader, reader_metadata) = open_from(from)?;
2324
2325 let clonefile_result = run_path_with_cstr(to, &|to| {
2326 cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2327 });
2328 match clonefile_result {
2329 Ok(_) => return Ok(reader_metadata.len()),
2330 Err(e) => match e.raw_os_error() {
2331 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2336 _ => return Err(e),
2337 },
2338 }
2339
2340 let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2342
2343 let state = unsafe {
2346 let state = libc::copyfile_state_alloc();
2347 if state.is_null() {
2348 return Err(crate::io::Error::last_os_error());
2349 }
2350 FreeOnDrop(state)
2351 };
2352
2353 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2354
2355 cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2356
2357 let mut bytes_copied: libc::off_t = 0;
2358 cvt(unsafe {
2359 libc::copyfile_state_get(
2360 state.0,
2361 libc::COPYFILE_STATE_COPIED as u32,
2362 (&raw mut bytes_copied) as *mut libc::c_void,
2363 )
2364 })?;
2365 Ok(bytes_copied as u64)
2366}
2367
2368#[cfg(not(target_os = "wasi"))]
2369pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2370 run_path_with_cstr(path, &|path| {
2371 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2372 .map(|_| ())
2373 })
2374}
2375
2376#[cfg(not(target_os = "wasi"))]
2377pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2378 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2379 Ok(())
2380}
2381
2382#[cfg(not(any(target_os = "vxworks", target_os = "wasi")))]
2383pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2384 run_path_with_cstr(path, &|path| {
2385 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2386 .map(|_| ())
2387 })
2388}
2389
2390#[cfg(target_os = "vxworks")]
2391pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2392 let (_, _, _) = (path, uid, gid);
2393 Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2394}
2395
2396#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks", target_os = "wasi")))]
2397pub fn chroot(dir: &Path) -> io::Result<()> {
2398 run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2399}
2400
2401#[cfg(target_os = "vxworks")]
2402pub fn chroot(dir: &Path) -> io::Result<()> {
2403 let _ = dir;
2404 Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2405}
2406
2407#[cfg(not(target_os = "wasi"))]
2408pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
2409 run_path_with_cstr(path, &|path| {
2410 cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
2411 })
2412}
2413
2414pub use remove_dir_impl::remove_dir_all;
2415
2416#[cfg(any(
2418 target_os = "redox",
2419 target_os = "espidf",
2420 target_os = "horizon",
2421 target_os = "vita",
2422 target_os = "nto",
2423 target_os = "qnx",
2424 target_os = "vxworks",
2425 target_os = "l4re",
2426 miri
2427))]
2428mod remove_dir_impl {
2429 pub use crate::sys::fs::common::remove_dir_all;
2430}
2431
2432#[cfg(not(any(
2434 target_os = "redox",
2435 target_os = "espidf",
2436 target_os = "horizon",
2437 target_os = "vita",
2438 target_os = "nto",
2439 target_os = "qnx",
2440 target_os = "vxworks",
2441 target_os = "l4re",
2442 miri
2443)))]
2444mod remove_dir_impl {
2445 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2446 use libc::{fdopendir, openat, unlinkat};
2447 #[cfg(all(target_os = "linux", target_env = "gnu"))]
2448 use libc::{fdopendir, openat64 as openat, unlinkat};
2449
2450 use super::{
2451 AsRawFd, DirEntry, DirStream, FromRawFd, InnerReadDir, IntoRawFd, OwnedFd, RawFd, ReadDir,
2452 lstat,
2453 };
2454 use crate::ffi::CStr;
2455 use crate::io;
2456 use crate::path::{Path, PathBuf};
2457 use crate::sys::helpers::{ignore_notfound, run_path_with_cstr};
2458 use crate::sys::{cvt, cvt_r};
2459
2460 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2461 let fd = cvt_r(|| unsafe {
2462 openat(
2463 parent_fd.unwrap_or(libc::AT_FDCWD),
2464 p.as_ptr(),
2465 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2466 )
2467 })?;
2468 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2469 }
2470
2471 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2472 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2473 if ptr.is_null() {
2474 return Err(io::Error::last_os_error());
2475 }
2476 let dirp = DirStream(ptr);
2477 let new_parent_fd = dir_fd.into_raw_fd();
2479 let dummy_root = PathBuf::new();
2482 let inner = InnerReadDir { dirp, root: dummy_root };
2483 Ok((ReadDir::new(inner), new_parent_fd))
2484 }
2485
2486 #[cfg(any(
2487 target_os = "solaris",
2488 target_os = "illumos",
2489 target_os = "haiku",
2490 target_os = "vxworks",
2491 target_os = "aix",
2492 ))]
2493 fn is_dir(_ent: &DirEntry) -> Option<bool> {
2494 None
2495 }
2496
2497 #[cfg(not(any(
2498 target_os = "solaris",
2499 target_os = "illumos",
2500 target_os = "haiku",
2501 target_os = "vxworks",
2502 target_os = "aix",
2503 )))]
2504 fn is_dir(ent: &DirEntry) -> Option<bool> {
2505 match ent.entry.d_type {
2506 libc::DT_UNKNOWN => None,
2507 libc::DT_DIR => Some(true),
2508 _ => Some(false),
2509 }
2510 }
2511
2512 fn is_enoent(result: &io::Result<()>) -> bool {
2513 if let Err(err) = result
2514 && matches!(err.raw_os_error(), Some(libc::ENOENT))
2515 {
2516 true
2517 } else {
2518 false
2519 }
2520 }
2521
2522 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2523 let fd = match openat_nofollow_dironly(parent_fd, path) {
2525 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2526 return match parent_fd {
2529 Some(parent_fd) => {
2531 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2532 }
2533 None => Err(err),
2535 };
2536 }
2537 result => result?,
2538 };
2539
2540 let (dir, fd) = fdreaddir(fd)?;
2542
2543 #[cfg(target_os = "wasi")]
2550 let dir = dir.collect::<Vec<_>>();
2551
2552 for child in dir {
2553 let child = child?;
2554 let result: io::Result<()> = try {
2558 match is_dir(&child) {
2559 Some(true) => {
2560 remove_dir_all_recursive(Some(fd), &child.name)?;
2561 }
2562 Some(false) => {
2563 cvt(unsafe { unlinkat(fd, child.name.as_ptr(), 0) })?;
2564 }
2565 None => {
2566 remove_dir_all_recursive(Some(fd), &child.name)?;
2571 }
2572 }
2573 };
2574 if result.is_err() && !is_enoent(&result) {
2575 return result;
2576 }
2577 }
2578
2579 ignore_notfound(cvt(unsafe {
2581 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2582 }))?;
2583 Ok(())
2584 }
2585
2586 fn remove_dir_all_modern(p: &CStr) -> io::Result<()> {
2587 let attr = lstat(p)?;
2591 if attr.file_type().is_symlink() {
2592 super::unlink(p)
2593 } else {
2594 remove_dir_all_recursive(None, p)
2595 }
2596 }
2597
2598 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2599 run_path_with_cstr(p, &remove_dir_all_modern)
2600 }
2601}