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