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