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