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