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_os = "redox",
1337 target_vendor = "apple",
1338 ) => {
1339 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX) })?;
1340 Ok(())
1341 }
1342 _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock() not supported")),
1343 }
1344 }
1345
1346 pub fn lock_shared(&self) -> io::Result<()> {
1347 cfg_select! {
1348 any(
1349 target_os = "freebsd",
1350 target_os = "fuchsia",
1351 target_os = "hurd",
1352 target_os = "linux",
1353 target_os = "netbsd",
1354 target_os = "openbsd",
1355 target_os = "cygwin",
1356 target_os = "illumos",
1357 target_os = "aix",
1358 target_os = "android",
1359 target_os = "redox",
1360 target_vendor = "apple",
1361 ) => {
1362 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH) })?;
1363 Ok(())
1364 }
1365 _ => Err(io::const_error!(io::ErrorKind::Unsupported, "lock_shared() not supported")),
1366 }
1367 }
1368
1369 pub fn try_lock(&self) -> Result<(), TryLockError> {
1370 cfg_select! {
1371 any(
1372 target_os = "freebsd",
1373 target_os = "fuchsia",
1374 target_os = "hurd",
1375 target_os = "linux",
1376 target_os = "netbsd",
1377 target_os = "openbsd",
1378 target_os = "cygwin",
1379 target_os = "illumos",
1380 target_os = "aix",
1381 target_os = "android",
1382 target_os = "redox",
1383 target_vendor = "apple",
1384 ) => {
1385 let result =
1386 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) });
1387 if let Err(err) = result {
1388 if err.kind() == io::ErrorKind::WouldBlock {
1389 Err(TryLockError::WouldBlock)
1390 } else {
1391 Err(TryLockError::Error(err))
1392 }
1393 } else {
1394 Ok(())
1395 }
1396 }
1397 _ => Err(TryLockError::Error(io::const_error!(
1398 io::ErrorKind::Unsupported,
1399 "try_lock() not supported"
1400 ))),
1401 }
1402 }
1403
1404 pub fn try_lock_shared(&self) -> Result<(), TryLockError> {
1405 cfg_select! {
1406 any(
1407 target_os = "freebsd",
1408 target_os = "fuchsia",
1409 target_os = "hurd",
1410 target_os = "linux",
1411 target_os = "netbsd",
1412 target_os = "openbsd",
1413 target_os = "cygwin",
1414 target_os = "illumos",
1415 target_os = "aix",
1416 target_os = "android",
1417 target_os = "redox",
1418 target_vendor = "apple",
1419 ) => {
1420 let result =
1421 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_SH | libc::LOCK_NB) });
1422 if let Err(err) = result {
1423 if err.kind() == io::ErrorKind::WouldBlock {
1424 Err(TryLockError::WouldBlock)
1425 } else {
1426 Err(TryLockError::Error(err))
1427 }
1428 } else {
1429 Ok(())
1430 }
1431 }
1432 _ => Err(TryLockError::Error(io::const_error!(
1433 io::ErrorKind::Unsupported,
1434 "try_lock_shared() not supported"
1435 ))),
1436 }
1437 }
1438
1439 pub fn unlock(&self) -> io::Result<()> {
1440 cfg_select! {
1441 any(
1442 target_os = "freebsd",
1443 target_os = "fuchsia",
1444 target_os = "hurd",
1445 target_os = "linux",
1446 target_os = "netbsd",
1447 target_os = "openbsd",
1448 target_os = "cygwin",
1449 target_os = "illumos",
1450 target_os = "aix",
1451 target_os = "android",
1452 target_os = "redox",
1453 target_vendor = "apple",
1454 ) => {
1455 cvt(unsafe { libc::flock(self.as_raw_fd(), libc::LOCK_UN) })?;
1456 Ok(())
1457 }
1458 _ => Err(io::const_error!(io::ErrorKind::Unsupported, "unlock() not supported")),
1459 }
1460 }
1461
1462 pub fn truncate(&self, size: u64) -> io::Result<()> {
1463 let size: off64_t =
1464 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
1465 cvt_r(|| unsafe { ftruncate64(self.as_raw_fd(), size) }).map(drop)
1466 }
1467
1468 pub fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
1469 self.0.read(buf)
1470 }
1471
1472 pub fn read_vectored(&self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
1473 self.0.read_vectored(bufs)
1474 }
1475
1476 #[inline]
1477 pub fn is_read_vectored(&self) -> bool {
1478 self.0.is_read_vectored()
1479 }
1480
1481 pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
1482 self.0.read_at(buf, offset)
1483 }
1484
1485 pub fn read_buf(&self, cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
1486 self.0.read_buf(cursor)
1487 }
1488
1489 pub fn read_buf_at(&self, cursor: BorrowedCursor<'_, u8>, offset: u64) -> io::Result<()> {
1490 self.0.read_buf_at(cursor, offset)
1491 }
1492
1493 pub fn read_vectored_at(&self, bufs: &mut [IoSliceMut<'_>], offset: u64) -> io::Result<usize> {
1494 self.0.read_vectored_at(bufs, offset)
1495 }
1496
1497 pub fn write(&self, buf: &[u8]) -> io::Result<usize> {
1498 self.0.write(buf)
1499 }
1500
1501 pub fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
1502 self.0.write_vectored(bufs)
1503 }
1504
1505 #[inline]
1506 pub fn is_write_vectored(&self) -> bool {
1507 self.0.is_write_vectored()
1508 }
1509
1510 pub fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
1511 self.0.write_at(buf, offset)
1512 }
1513
1514 pub fn write_vectored_at(&self, bufs: &[IoSlice<'_>], offset: u64) -> io::Result<usize> {
1515 self.0.write_vectored_at(bufs, offset)
1516 }
1517
1518 #[inline]
1519 pub fn flush(&self) -> io::Result<()> {
1520 Ok(())
1521 }
1522
1523 pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
1524 let (whence, pos) = match pos {
1525 SeekFrom::Start(off) => (libc::SEEK_SET, off as i64),
1528 SeekFrom::End(off) => (libc::SEEK_END, off),
1529 SeekFrom::Current(off) => (libc::SEEK_CUR, off),
1530 };
1531 let n = cvt(unsafe { lseek64(self.as_raw_fd(), pos as off64_t, whence) })?;
1532 Ok(n as u64)
1533 }
1534
1535 pub fn size(&self) -> Option<io::Result<u64>> {
1536 match self.file_attr().map(|attr| attr.size()) {
1537 Ok(0) => None,
1540 result => Some(result),
1541 }
1542 }
1543
1544 pub fn tell(&self) -> io::Result<u64> {
1545 self.seek(SeekFrom::Current(0))
1546 }
1547
1548 pub fn duplicate(&self) -> io::Result<File> {
1549 self.0.duplicate().map(File)
1550 }
1551
1552 pub fn set_permissions(&self, perm: FilePermissions) -> io::Result<()> {
1553 cvt_r(|| unsafe { libc::fchmod(self.as_raw_fd(), perm.mode) })?;
1554 Ok(())
1555 }
1556
1557 pub fn set_times(&self, times: FileTimes) -> io::Result<()> {
1558 cfg_select! {
1559 any(
1560 target_os = "redox",
1561 target_os = "espidf",
1562 target_os = "horizon",
1563 target_os = "nuttx",
1564 target_os = "l4re"
1565 ) => {
1566 let _ = times;
1570 Err(io::const_error!(
1571 io::ErrorKind::Unsupported,
1572 "setting file times not supported",
1573 ))
1574 }
1575 target_vendor = "apple" => {
1576 let ta = TimesAttrlist::from_times(×)?;
1577 cvt(unsafe {
1578 libc::fsetattrlist(
1579 self.as_raw_fd(),
1580 ta.attrlist(),
1581 ta.times_buf(),
1582 ta.times_buf_size(),
1583 0,
1584 )
1585 })?;
1586 Ok(())
1587 }
1588 target_os = "android" => {
1589 let times = [
1590 file_time_to_timespec(times.accessed)?,
1591 file_time_to_timespec(times.modified)?,
1592 ];
1593 cvt(unsafe {
1595 weak!(
1596 fn futimens(fd: c_int, times: *const libc::timespec) -> c_int;
1597 );
1598 match futimens.get() {
1599 Some(futimens) => futimens(self.as_raw_fd(), times.as_ptr()),
1600 None => {
1601 return Err(io::const_error!(
1602 io::ErrorKind::Unsupported,
1603 "setting file times requires Android API level >= 19",
1604 ));
1605 }
1606 }
1607 })?;
1608 Ok(())
1609 }
1610 _ => {
1611 #[cfg(all(
1612 target_os = "linux",
1613 target_env = "gnu",
1614 target_pointer_width = "32",
1615 not(target_arch = "riscv32")
1616 ))]
1617 {
1618 use crate::sys::pal::time::__timespec64;
1619 use crate::sys::pal::weak::weak;
1620
1621 weak!(
1623 fn __futimens64(fd: c_int, times: *const __timespec64) -> c_int;
1624 );
1625
1626 if let Some(futimens64) = __futimens64.get() {
1627 let to_timespec = |time: Option<SystemTime>| {
1628 time.map(|time| time.t.to_timespec64())
1629 .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
1630 };
1631 let times = [to_timespec(times.accessed), to_timespec(times.modified)];
1632 cvt(unsafe { futimens64(self.as_raw_fd(), times.as_ptr()) })?;
1633 return Ok(());
1634 }
1635 }
1636 let times = [
1637 file_time_to_timespec(times.accessed)?,
1638 file_time_to_timespec(times.modified)?,
1639 ];
1640 cvt(unsafe { libc::futimens(self.as_raw_fd(), times.as_ptr()) })?;
1641 Ok(())
1642 }
1643 }
1644 }
1645}
1646
1647#[cfg(not(any(
1648 target_os = "redox",
1649 target_os = "espidf",
1650 target_os = "horizon",
1651 target_os = "nuttx",
1652)))]
1653fn file_time_to_timespec(time: Option<SystemTime>) -> io::Result<libc::timespec> {
1654 match time {
1655 Some(time) if let Some(ts) = time.t.to_timespec() => Ok(ts),
1656 Some(time) if time > crate::sys::time::UNIX_EPOCH => Err(io::const_error!(
1657 io::ErrorKind::InvalidInput,
1658 "timestamp is too large to set as a file time",
1659 )),
1660 Some(_) => Err(io::const_error!(
1661 io::ErrorKind::InvalidInput,
1662 "timestamp is too small to set as a file time",
1663 )),
1664 None => Ok({
1665 let mut ts = libc::timespec::default();
1666 ts.tv_sec = 0;
1667 ts.tv_nsec = libc::UTIME_OMIT as _;
1668 ts
1669 }),
1670 }
1671}
1672
1673#[cfg(target_vendor = "apple")]
1674struct TimesAttrlist {
1675 buf: [mem::MaybeUninit<libc::timespec>; 3],
1676 attrlist: libc::attrlist,
1677 num_times: usize,
1678}
1679
1680#[cfg(target_vendor = "apple")]
1681impl TimesAttrlist {
1682 fn from_times(times: &FileTimes) -> io::Result<Self> {
1683 let mut this = Self {
1684 buf: [mem::MaybeUninit::<libc::timespec>::uninit(); 3],
1685 attrlist: unsafe { mem::zeroed() },
1686 num_times: 0,
1687 };
1688 this.attrlist.bitmapcount = libc::ATTR_BIT_MAP_COUNT;
1689 if times.created.is_some() {
1690 this.buf[this.num_times].write(file_time_to_timespec(times.created)?);
1691 this.num_times += 1;
1692 this.attrlist.commonattr |= libc::ATTR_CMN_CRTIME;
1693 }
1694 if times.modified.is_some() {
1695 this.buf[this.num_times].write(file_time_to_timespec(times.modified)?);
1696 this.num_times += 1;
1697 this.attrlist.commonattr |= libc::ATTR_CMN_MODTIME;
1698 }
1699 if times.accessed.is_some() {
1700 this.buf[this.num_times].write(file_time_to_timespec(times.accessed)?);
1701 this.num_times += 1;
1702 this.attrlist.commonattr |= libc::ATTR_CMN_ACCTIME;
1703 }
1704 Ok(this)
1705 }
1706
1707 fn attrlist(&self) -> *mut libc::c_void {
1708 (&raw const self.attrlist).cast::<libc::c_void>().cast_mut()
1709 }
1710
1711 fn times_buf(&self) -> *mut libc::c_void {
1712 self.buf.as_ptr().cast::<libc::c_void>().cast_mut()
1713 }
1714
1715 fn times_buf_size(&self) -> usize {
1716 self.num_times * size_of::<libc::timespec>()
1717 }
1718}
1719
1720impl DirBuilder {
1721 pub fn new() -> DirBuilder {
1722 DirBuilder { mode: 0o777 }
1723 }
1724
1725 pub fn mkdir(&self, p: &Path) -> io::Result<()> {
1726 run_path_with_cstr(p, &|p| cvt(unsafe { libc::mkdir(p.as_ptr(), self.mode) }).map(|_| ()))
1727 }
1728
1729 #[cfg(not(target_os = "wasi"))]
1730 pub fn set_mode(&mut self, mode: u32) {
1731 self.mode = mode as mode_t;
1732 }
1733}
1734
1735impl fmt::Debug for DirBuilder {
1736 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1737 let DirBuilder { mode } = self;
1738 f.debug_struct("DirBuilder").field("mode", &Mode(*mode)).finish()
1739 }
1740}
1741
1742impl AsInner<FileDesc> for File {
1743 #[inline]
1744 fn as_inner(&self) -> &FileDesc {
1745 &self.0
1746 }
1747}
1748
1749impl AsInnerMut<FileDesc> for File {
1750 #[inline]
1751 fn as_inner_mut(&mut self) -> &mut FileDesc {
1752 &mut self.0
1753 }
1754}
1755
1756impl IntoInner<FileDesc> for File {
1757 fn into_inner(self) -> FileDesc {
1758 self.0
1759 }
1760}
1761
1762impl FromInner<FileDesc> for File {
1763 fn from_inner(file_desc: FileDesc) -> Self {
1764 Self(file_desc)
1765 }
1766}
1767
1768impl AsFd for File {
1769 #[inline]
1770 fn as_fd(&self) -> BorrowedFd<'_> {
1771 self.0.as_fd()
1772 }
1773}
1774
1775impl AsRawFd for File {
1776 #[inline]
1777 fn as_raw_fd(&self) -> RawFd {
1778 self.0.as_raw_fd()
1779 }
1780}
1781
1782impl IntoRawFd for File {
1783 fn into_raw_fd(self) -> RawFd {
1784 self.0.into_raw_fd()
1785 }
1786}
1787
1788impl FromRawFd for File {
1789 unsafe fn from_raw_fd(raw_fd: RawFd) -> Self {
1790 Self(FromRawFd::from_raw_fd(raw_fd))
1791 }
1792}
1793
1794impl fmt::Debug for File {
1795 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1796 let fd = self.as_raw_fd();
1797 let mut b = debug_path_fd(fd, f, "File");
1798 b.finish()
1799 }
1800}
1801
1802impl fmt::Debug for Mode {
1812 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1813 let Self(mode) = *self;
1814 write!(f, "0o{mode:06o}")?;
1815
1816 let entry_type = match mode & libc::S_IFMT {
1817 libc::S_IFDIR => 'd',
1818 libc::S_IFBLK => 'b',
1819 libc::S_IFCHR => 'c',
1820 libc::S_IFLNK => 'l',
1821 libc::S_IFIFO => 'p',
1822 libc::S_IFREG => '-',
1823 _ => return Ok(()),
1824 };
1825
1826 f.write_str(" (")?;
1827 f.write_char(entry_type)?;
1828
1829 f.write_char(if mode & libc::S_IRUSR != 0 { 'r' } else { '-' })?;
1831 f.write_char(if mode & libc::S_IWUSR != 0 { 'w' } else { '-' })?;
1832 let owner_executable = mode & libc::S_IXUSR != 0;
1833 let setuid = mode as c_int & libc::S_ISUID as c_int != 0;
1834 f.write_char(match (owner_executable, setuid) {
1835 (true, true) => 's', (false, true) => 'S', (true, false) => 'x', (false, false) => '-',
1839 })?;
1840
1841 f.write_char(if mode & libc::S_IRGRP != 0 { 'r' } else { '-' })?;
1843 f.write_char(if mode & libc::S_IWGRP != 0 { 'w' } else { '-' })?;
1844 let group_executable = mode & libc::S_IXGRP != 0;
1845 let setgid = mode as c_int & libc::S_ISGID as c_int != 0;
1846 f.write_char(match (group_executable, setgid) {
1847 (true, true) => 's', (false, true) => 'S', (true, false) => 'x', (false, false) => '-',
1851 })?;
1852
1853 f.write_char(if mode & libc::S_IROTH != 0 { 'r' } else { '-' })?;
1855 f.write_char(if mode & libc::S_IWOTH != 0 { 'w' } else { '-' })?;
1856 let other_executable = mode & libc::S_IXOTH != 0;
1857 let sticky = mode as c_int & libc::S_ISVTX as c_int != 0;
1858 f.write_char(match (entry_type, other_executable, sticky) {
1859 ('d', true, true) => 't', ('d', false, true) => 'T', (_, true, _) => 'x', (_, false, _) => '-',
1863 })?;
1864
1865 f.write_char(')')
1866 }
1867}
1868
1869pub fn readdir(path: &Path) -> io::Result<ReadDir> {
1870 let ptr = run_path_with_cstr(path, &|p| unsafe { Ok(libc::opendir(p.as_ptr())) })?;
1871 if ptr.is_null() {
1872 Err(Error::last_os_error())
1873 } else {
1874 let root = path.to_path_buf();
1875 let inner = InnerReadDir { dirp: DirStream(ptr), root };
1876 Ok(ReadDir::new(inner))
1877 }
1878}
1879
1880pub fn unlink(p: &CStr) -> io::Result<()> {
1881 cvt(unsafe { libc::unlink(p.as_ptr()) }).map(|_| ())
1882}
1883
1884pub fn rename(old: &CStr, new: &CStr) -> io::Result<()> {
1885 cvt(unsafe { libc::rename(old.as_ptr(), new.as_ptr()) }).map(|_| ())
1886}
1887
1888pub fn set_perm(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1889 cvt_r(|| unsafe { libc::chmod(p.as_ptr(), perm.mode) }).map(|_| ())
1890}
1891
1892#[cfg(target_os = "vxworks")]
1893pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1894 Err(crate::io::ErrorKind::Unsupported.into())
1897}
1898
1899#[cfg(target_os = "android")]
1900pub fn set_perm_nofollow(_p: &CStr, _perm: FilePermissions) -> io::Result<()> {
1901 Err(crate::io::ErrorKind::Unsupported.into())
1909}
1910
1911#[cfg(not(any(target_os = "android", target_os = "vxworks")))]
1912pub fn set_perm_nofollow(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1913 #[inline]
1914 fn open_and_set_permissions(p: &CStr, perm: FilePermissions) -> io::Result<()> {
1916 use crate::fs::{OpenOptions, Permissions};
1917
1918 let mut options = OpenOptions::new();
1919 options.read(true);
1920
1921 #[cfg(not(any(target_os = "espidf", target_os = "horizon")))]
1924 {
1925 #[cfg(not(target_os = "wasi"))]
1926 use crate::os::unix::fs::OpenOptionsExt;
1927 #[cfg(target_os = "wasi")]
1928 use crate::os::wasi::fs::OpenOptionsExt;
1929 options.custom_flags(libc::O_NOFOLLOW);
1930 }
1931
1932 let os_str = unsafe { OsStr::from_encoded_bytes_unchecked(p.to_bytes()) };
1936 options.open(Path::new(os_str))?.set_permissions(Permissions::from_inner(perm))
1937 }
1938
1939 #[allow(unused)]
1941 let mut res: Result<(), core::io::Error> = Err(crate::io::ErrorKind::Unsupported.into());
1942
1943 #[cfg(any(
1945 target_os = "linux",
1946 target_os = "macos",
1947 target_os = "freebsd",
1948 target_os = "openbsd",
1949 target_os = "netbsd",
1950 target_os = "dragonfly",
1951 target_os = "nto",
1952 target_os = "qnx"
1953 ))]
1954 {
1955 res = cvt_r(|| unsafe {
1956 libc::fchmodat(libc::AT_FDCWD, p.as_ptr(), perm.mode, libc::AT_SYMLINK_NOFOLLOW)
1957 })
1958 .map(|_| ());
1959 }
1960
1961 match res {
1965 Ok(_) => Ok(()),
1966 Err(err) => {
1967 if err.kind() == crate::io::ErrorKind::Unsupported {
1968 match open_and_set_permissions(p, perm) {
1969 Ok(_) => return Ok(()),
1970 Err(e) => {
1971 if e.kind() == crate::io::ErrorKind::FilesystemLoop {
1972 return Err(err);
1977 }
1978 return Err(e);
1979 }
1980 }
1981 }
1982
1983 Err(err)
1984 }
1985 }
1986}
1987
1988pub fn rmdir(p: &CStr) -> io::Result<()> {
1989 cvt(unsafe { libc::rmdir(p.as_ptr()) }).map(|_| ())
1990}
1991
1992pub fn readlink(c_path: &CStr) -> io::Result<PathBuf> {
1993 let p = c_path.as_ptr();
1994
1995 let mut buf = Vec::with_capacity(256);
1996
1997 loop {
1998 let buf_read =
1999 cvt(unsafe { libc::readlink(p, buf.as_mut_ptr() as *mut _, buf.capacity()) })? as usize;
2000
2001 unsafe {
2002 buf.set_len(buf_read);
2003 }
2004
2005 if buf_read != buf.capacity() {
2006 buf.shrink_to_fit();
2007
2008 return Ok(PathBuf::from(OsString::from_vec(buf)));
2009 }
2010
2011 buf.reserve(1);
2015 }
2016}
2017
2018pub fn symlink(original: &CStr, link: &CStr) -> io::Result<()> {
2019 cvt(unsafe { libc::symlink(original.as_ptr(), link.as_ptr()) }).map(|_| ())
2020}
2021
2022pub fn link(original: &CStr, link: &CStr) -> io::Result<()> {
2023 cfg_select! {
2024 any(
2025 target_os = "vxworks",
2030 target_os = "redox",
2031 target_os = "espidf",
2032 target_os = "horizon",
2034 target_os = "vita",
2035 target_os = "l4re",
2036 target_env = "nto70",
2037 ) => {
2038 cvt(unsafe { libc::link(original.as_ptr(), link.as_ptr()) })?;
2039 }
2040 _ => {
2041 cvt(unsafe {
2044 libc::linkat(libc::AT_FDCWD, original.as_ptr(), libc::AT_FDCWD, link.as_ptr(), 0)
2045 })?;
2046 }
2047 }
2048 Ok(())
2049}
2050
2051pub fn stat(p: &CStr) -> io::Result<FileAttr> {
2052 cfg_has_statx! {
2053 if let Some(ret) = unsafe { try_statx(
2054 libc::AT_FDCWD,
2055 p.as_ptr(),
2056 libc::AT_STATX_SYNC_AS_STAT,
2057 libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2058 ) } {
2059 return ret;
2060 }
2061 }
2062
2063 let mut stat: stat64 = unsafe { mem::zeroed() };
2064 cvt(unsafe { stat64(p.as_ptr(), &mut stat) })?;
2065 Ok(FileAttr::from_stat64(stat))
2066}
2067
2068pub fn lstat(p: &CStr) -> io::Result<FileAttr> {
2069 cfg_has_statx! {
2070 if let Some(ret) = unsafe { try_statx(
2071 libc::AT_FDCWD,
2072 p.as_ptr(),
2073 libc::AT_SYMLINK_NOFOLLOW | libc::AT_STATX_SYNC_AS_STAT,
2074 libc::STATX_BASIC_STATS | libc::STATX_BTIME,
2075 ) } {
2076 return ret;
2077 }
2078 }
2079
2080 let mut stat: stat64 = unsafe { mem::zeroed() };
2081 cvt(unsafe { lstat64(p.as_ptr(), &mut stat) })?;
2082 Ok(FileAttr::from_stat64(stat))
2083}
2084
2085pub fn canonicalize(path: &CStr) -> io::Result<PathBuf> {
2086 let r = unsafe { libc::realpath(path.as_ptr(), ptr::null_mut()) };
2087 if r.is_null() {
2088 return Err(io::Error::last_os_error());
2089 }
2090 Ok(PathBuf::from(OsString::from_vec(unsafe {
2091 let buf = CStr::from_ptr(r).to_bytes().to_vec();
2092 libc::free(r as *mut _);
2093 buf
2094 })))
2095}
2096
2097fn open_from(from: &Path) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2098 use crate::fs::File;
2099 use crate::sys::fs::common::NOT_FILE_ERROR;
2100
2101 let reader = File::open(from)?;
2102 let metadata = reader.metadata()?;
2103 if !metadata.is_file() {
2104 return Err(NOT_FILE_ERROR);
2105 }
2106 Ok((reader, metadata))
2107}
2108
2109fn set_times_impl(p: &CStr, times: FileTimes, follow_symlinks: bool) -> io::Result<()> {
2110 cfg_select! {
2111 any(
2112 target_os = "redox",
2113 target_os = "espidf",
2114 target_os = "horizon",
2115 target_os = "nuttx",
2116 target_os = "vita",
2117 target_os = "rtems"
2118 ) => {
2119 let _ = (p, times, follow_symlinks);
2120 Err(io::const_error!(io::ErrorKind::Unsupported, "setting file times not supported"))
2121 }
2122 target_vendor = "apple" => {
2123 let ta = TimesAttrlist::from_times(×)?;
2125 let options = if follow_symlinks { 0 } else { libc::FSOPT_NOFOLLOW };
2126
2127 cvt(unsafe {
2128 libc::setattrlist(
2129 p.as_ptr(),
2130 ta.attrlist(),
2131 ta.times_buf(),
2132 ta.times_buf_size(),
2133 options as u32,
2134 )
2135 })?;
2136 Ok(())
2137 }
2138 target_os = "android" => {
2139 let times =
2140 [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2141 let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2142 cvt(unsafe {
2144 weak!(
2145 fn utimensat(
2146 dirfd: c_int,
2147 path: *const libc::c_char,
2148 times: *const libc::timespec,
2149 flags: c_int,
2150 ) -> c_int;
2151 );
2152 match utimensat.get() {
2153 Some(utimensat) => utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags),
2154 None => {
2155 return Err(io::const_error!(
2156 io::ErrorKind::Unsupported,
2157 "setting file times requires Android API level >= 19",
2158 ));
2159 }
2160 }
2161 })?;
2162 Ok(())
2163 }
2164 _ => {
2165 let flags = if follow_symlinks { 0 } else { libc::AT_SYMLINK_NOFOLLOW };
2166 #[cfg(all(
2167 target_os = "linux",
2168 target_env = "gnu",
2169 target_pointer_width = "32",
2170 not(target_arch = "riscv32")
2171 ))]
2172 {
2173 use crate::sys::pal::time::__timespec64;
2174 use crate::sys::pal::weak::weak;
2175
2176 weak!(
2178 fn __utimensat64(
2179 dirfd: c_int,
2180 path: *const c_char,
2181 times: *const __timespec64,
2182 flags: c_int,
2183 ) -> c_int;
2184 );
2185
2186 if let Some(utimensat64) = __utimensat64.get() {
2187 let to_timespec = |time: Option<SystemTime>| {
2188 time.map(|time| time.t.to_timespec64())
2189 .unwrap_or(__timespec64::new(0, libc::UTIME_OMIT as _))
2190 };
2191 let times = [to_timespec(times.accessed), to_timespec(times.modified)];
2192 cvt(unsafe { utimensat64(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2193 return Ok(());
2194 }
2195 }
2196 let times =
2197 [file_time_to_timespec(times.accessed)?, file_time_to_timespec(times.modified)?];
2198 cvt(unsafe { libc::utimensat(libc::AT_FDCWD, p.as_ptr(), times.as_ptr(), flags) })?;
2199 Ok(())
2200 }
2201 }
2202}
2203
2204#[inline(always)]
2205pub fn set_times(p: &CStr, times: FileTimes) -> io::Result<()> {
2206 set_times_impl(p, times, true)
2207}
2208
2209#[inline(always)]
2210pub fn set_times_nofollow(p: &CStr, times: FileTimes) -> io::Result<()> {
2211 set_times_impl(p, times, false)
2212}
2213
2214#[cfg(any(target_os = "espidf", target_os = "wasi"))]
2215fn open_to_and_set_permissions(
2216 to: &Path,
2217 _reader_metadata: &crate::fs::Metadata,
2218) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2219 use crate::fs::OpenOptions;
2220 let writer = OpenOptions::new().write(true).create(true).truncate(true).open(to)?;
2221 let writer_metadata = writer.metadata()?;
2222 Ok((writer, writer_metadata))
2223}
2224
2225#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
2226fn open_to_and_set_permissions(
2227 to: &Path,
2228 reader_metadata: &crate::fs::Metadata,
2229) -> io::Result<(crate::fs::File, crate::fs::Metadata)> {
2230 use crate::fs::OpenOptions;
2231 use crate::os::unix::fs::{OpenOptionsExt, PermissionsExt};
2232
2233 let perm = reader_metadata.permissions();
2234 let writer = OpenOptions::new()
2235 .mode(perm.mode())
2237 .write(true)
2238 .create(true)
2239 .truncate(true)
2240 .open(to)?;
2241 let writer_metadata = writer.metadata()?;
2242 #[cfg(not(target_os = "vita"))]
2244 if writer_metadata.is_file() {
2245 writer.set_permissions(perm)?;
2249 }
2250 Ok((writer, writer_metadata))
2251}
2252
2253mod cfm {
2254 use crate::fs::{File, Metadata};
2255 use crate::io::{BorrowedCursor, IoSlice, IoSliceMut, Read, Result, Write};
2256
2257 #[allow(dead_code)]
2258 pub struct CachedFileMetadata(pub File, pub Metadata);
2259
2260 impl Read for CachedFileMetadata {
2261 fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
2262 self.0.read(buf)
2263 }
2264 fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize> {
2265 self.0.read_vectored(bufs)
2266 }
2267 fn read_buf(&mut self, cursor: BorrowedCursor<'_, u8>) -> Result<()> {
2268 self.0.read_buf(cursor)
2269 }
2270 #[inline]
2271 fn is_read_vectored(&self) -> bool {
2272 self.0.is_read_vectored()
2273 }
2274 fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
2275 self.0.read_to_end(buf)
2276 }
2277 fn read_to_string(&mut self, buf: &mut String) -> Result<usize> {
2278 self.0.read_to_string(buf)
2279 }
2280 }
2281 impl Write for CachedFileMetadata {
2282 fn write(&mut self, buf: &[u8]) -> Result<usize> {
2283 self.0.write(buf)
2284 }
2285 fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize> {
2286 self.0.write_vectored(bufs)
2287 }
2288 #[inline]
2289 fn is_write_vectored(&self) -> bool {
2290 self.0.is_write_vectored()
2291 }
2292 #[inline]
2293 fn flush(&mut self) -> Result<()> {
2294 self.0.flush()
2295 }
2296 }
2297}
2298#[cfg(any(target_os = "linux", target_os = "android"))]
2299pub(in crate::sys) use cfm::CachedFileMetadata;
2300
2301#[cfg(not(target_vendor = "apple"))]
2302pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2303 let (reader, reader_metadata) = open_from(from)?;
2304 let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2305
2306 io::copy(
2307 &mut cfm::CachedFileMetadata(reader, reader_metadata),
2308 &mut cfm::CachedFileMetadata(writer, writer_metadata),
2309 )
2310}
2311
2312#[cfg(target_vendor = "apple")]
2313pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
2314 const COPYFILE_ALL: libc::copyfile_flags_t = libc::COPYFILE_METADATA | libc::COPYFILE_DATA;
2315
2316 struct FreeOnDrop(libc::copyfile_state_t);
2317 impl Drop for FreeOnDrop {
2318 fn drop(&mut self) {
2319 unsafe {
2321 libc::copyfile_state_free(self.0);
2324 }
2325 }
2326 }
2327
2328 let (reader, reader_metadata) = open_from(from)?;
2329
2330 let clonefile_result = run_path_with_cstr(to, &|to| {
2331 cvt(unsafe { libc::fclonefileat(reader.as_raw_fd(), libc::AT_FDCWD, to.as_ptr(), 0) })
2332 });
2333 match clonefile_result {
2334 Ok(_) => return Ok(reader_metadata.len()),
2335 Err(e) => match e.raw_os_error() {
2336 Some(libc::ENOTSUP) | Some(libc::EEXIST) | Some(libc::EXDEV) => (),
2341 _ => return Err(e),
2342 },
2343 }
2344
2345 let (writer, writer_metadata) = open_to_and_set_permissions(to, &reader_metadata)?;
2347
2348 let state = unsafe {
2351 let state = libc::copyfile_state_alloc();
2352 if state.is_null() {
2353 return Err(crate::io::Error::last_os_error());
2354 }
2355 FreeOnDrop(state)
2356 };
2357
2358 let flags = if writer_metadata.is_file() { COPYFILE_ALL } else { libc::COPYFILE_DATA };
2359
2360 cvt(unsafe { libc::fcopyfile(reader.as_raw_fd(), writer.as_raw_fd(), state.0, flags) })?;
2361
2362 let mut bytes_copied: libc::off_t = 0;
2363 cvt(unsafe {
2364 libc::copyfile_state_get(
2365 state.0,
2366 libc::COPYFILE_STATE_COPIED as u32,
2367 (&raw mut bytes_copied) as *mut libc::c_void,
2368 )
2369 })?;
2370 Ok(bytes_copied as u64)
2371}
2372
2373#[cfg(not(target_os = "wasi"))]
2374pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2375 run_path_with_cstr(path, &|path| {
2376 cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2377 .map(|_| ())
2378 })
2379}
2380
2381#[cfg(not(target_os = "wasi"))]
2382pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
2383 cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
2384 Ok(())
2385}
2386
2387#[cfg(not(any(target_os = "vxworks", target_os = "wasi")))]
2388pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2389 run_path_with_cstr(path, &|path| {
2390 cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })
2391 .map(|_| ())
2392 })
2393}
2394
2395#[cfg(target_os = "vxworks")]
2396pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
2397 let (_, _, _) = (path, uid, gid);
2398 Err(io::const_error!(io::ErrorKind::Unsupported, "lchown not supported by vxworks"))
2399}
2400
2401#[cfg(not(any(target_os = "fuchsia", target_os = "vxworks", target_os = "wasi")))]
2402pub fn chroot(dir: &Path) -> io::Result<()> {
2403 run_path_with_cstr(dir, &|dir| cvt(unsafe { libc::chroot(dir.as_ptr()) }).map(|_| ()))
2404}
2405
2406#[cfg(target_os = "vxworks")]
2407pub fn chroot(dir: &Path) -> io::Result<()> {
2408 let _ = dir;
2409 Err(io::const_error!(io::ErrorKind::Unsupported, "chroot not supported by vxworks"))
2410}
2411
2412#[cfg(not(target_os = "wasi"))]
2413pub fn mkfifo(path: &Path, mode: u32) -> io::Result<()> {
2414 run_path_with_cstr(path, &|path| {
2415 cvt(unsafe { libc::mkfifo(path.as_ptr(), mode.try_into().unwrap()) }).map(|_| ())
2416 })
2417}
2418
2419pub use remove_dir_impl::remove_dir_all;
2420
2421#[cfg(any(
2423 target_os = "redox",
2424 target_os = "espidf",
2425 target_os = "horizon",
2426 target_os = "vita",
2427 target_os = "nto",
2428 target_os = "qnx",
2429 target_os = "vxworks",
2430 target_os = "l4re",
2431 miri
2432))]
2433mod remove_dir_impl {
2434 pub use crate::sys::fs::common::remove_dir_all;
2435}
2436
2437#[cfg(not(any(
2439 target_os = "redox",
2440 target_os = "espidf",
2441 target_os = "horizon",
2442 target_os = "vita",
2443 target_os = "nto",
2444 target_os = "qnx",
2445 target_os = "vxworks",
2446 target_os = "l4re",
2447 miri
2448)))]
2449mod remove_dir_impl {
2450 #[cfg(not(all(target_os = "linux", target_env = "gnu")))]
2451 use libc::{fdopendir, openat, unlinkat};
2452 #[cfg(all(target_os = "linux", target_env = "gnu"))]
2453 use libc::{fdopendir, openat64 as openat, unlinkat};
2454
2455 use super::{
2456 AsRawFd, DirEntry, DirStream, FromRawFd, InnerReadDir, IntoRawFd, OwnedFd, RawFd, ReadDir,
2457 lstat,
2458 };
2459 use crate::ffi::CStr;
2460 use crate::io;
2461 use crate::path::{Path, PathBuf};
2462 use crate::sys::helpers::{ignore_notfound, run_path_with_cstr};
2463 use crate::sys::{cvt, cvt_r};
2464
2465 pub fn openat_nofollow_dironly(parent_fd: Option<RawFd>, p: &CStr) -> io::Result<OwnedFd> {
2466 let fd = cvt_r(|| unsafe {
2467 openat(
2468 parent_fd.unwrap_or(libc::AT_FDCWD),
2469 p.as_ptr(),
2470 libc::O_CLOEXEC | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY,
2471 )
2472 })?;
2473 Ok(unsafe { OwnedFd::from_raw_fd(fd) })
2474 }
2475
2476 fn fdreaddir(dir_fd: OwnedFd) -> io::Result<(ReadDir, RawFd)> {
2477 let ptr = unsafe { fdopendir(dir_fd.as_raw_fd()) };
2478 if ptr.is_null() {
2479 return Err(io::Error::last_os_error());
2480 }
2481 let dirp = DirStream(ptr);
2482 let new_parent_fd = dir_fd.into_raw_fd();
2484 let dummy_root = PathBuf::new();
2487 let inner = InnerReadDir { dirp, root: dummy_root };
2488 Ok((ReadDir::new(inner), new_parent_fd))
2489 }
2490
2491 #[cfg(any(
2492 target_os = "solaris",
2493 target_os = "illumos",
2494 target_os = "haiku",
2495 target_os = "vxworks",
2496 target_os = "aix",
2497 ))]
2498 fn is_dir(_ent: &DirEntry) -> Option<bool> {
2499 None
2500 }
2501
2502 #[cfg(not(any(
2503 target_os = "solaris",
2504 target_os = "illumos",
2505 target_os = "haiku",
2506 target_os = "vxworks",
2507 target_os = "aix",
2508 )))]
2509 fn is_dir(ent: &DirEntry) -> Option<bool> {
2510 match ent.entry.d_type {
2511 libc::DT_UNKNOWN => None,
2512 libc::DT_DIR => Some(true),
2513 _ => Some(false),
2514 }
2515 }
2516
2517 fn is_enoent(result: &io::Result<()>) -> bool {
2518 if let Err(err) = result
2519 && matches!(err.raw_os_error(), Some(libc::ENOENT))
2520 {
2521 true
2522 } else {
2523 false
2524 }
2525 }
2526
2527 fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
2528 let fd = match openat_nofollow_dironly(parent_fd, path) {
2530 Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
2531 return match parent_fd {
2534 Some(parent_fd) => {
2536 cvt(unsafe { unlinkat(parent_fd, path.as_ptr(), 0) }).map(drop)
2537 }
2538 None => Err(err),
2540 };
2541 }
2542 result => result?,
2543 };
2544
2545 let (dir, fd) = fdreaddir(fd)?;
2547
2548 #[cfg(target_os = "wasi")]
2555 let dir = dir.collect::<Vec<_>>();
2556
2557 for child in dir {
2558 let child = child?;
2559 let result: io::Result<()> = try {
2563 match is_dir(&child) {
2564 Some(true) => {
2565 remove_dir_all_recursive(Some(fd), &child.name)?;
2566 }
2567 Some(false) => {
2568 cvt(unsafe { unlinkat(fd, child.name.as_ptr(), 0) })?;
2569 }
2570 None => {
2571 remove_dir_all_recursive(Some(fd), &child.name)?;
2576 }
2577 }
2578 };
2579 if result.is_err() && !is_enoent(&result) {
2580 return result;
2581 }
2582 }
2583
2584 ignore_notfound(cvt(unsafe {
2586 unlinkat(parent_fd.unwrap_or(libc::AT_FDCWD), path.as_ptr(), libc::AT_REMOVEDIR)
2587 }))?;
2588 Ok(())
2589 }
2590
2591 fn remove_dir_all_modern(p: &CStr) -> io::Result<()> {
2592 let attr = lstat(p)?;
2596 if attr.file_type().is_symlink() {
2597 super::unlink(p)
2598 } else {
2599 remove_dir_all_recursive(None, p)
2600 }
2601 }
2602
2603 pub fn remove_dir_all(p: &Path) -> io::Result<()> {
2604 run_path_with_cstr(p, &remove_dir_all_modern)
2605 }
2606}