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