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