Debian Codegraph @

third_party/rust/rustix/src/backend/libc/fs/syscalls.rs

raw
1 //! libc syscalls supporting `rustix::fs`.
2
3 use crate::backend::c;
4 #[cfg(any(
5 not(target_os = "redox"),
6 feature = "alloc",
7 all(linux_kernel, feature = "procfs")
8 ))]
9 use crate::backend::conv::ret_usize;
10 use crate::backend::conv::{borrowed_fd, c_str, ret, ret_c_int, ret_off_t, ret_owned_fd};
11 use crate::fd::{BorrowedFd, OwnedFd};
12 use crate::ffi::CStr;
13 #[cfg(all(apple, feature = "alloc"))]
14 use crate::ffi::CString;
15 #[cfg(not(any(target_os = "espidf", target_os = "vita")))]
16 use crate::fs::Access;
17 #[cfg(not(any(
18 apple,
19 netbsdlike,
20 target_os = "solaris",
21 target_os = "dragonfly",
22 target_os = "espidf",
23 target_os = "haiku",
24 target_os = "redox",
25 target_os = "vita",
26 )))]
27 use crate::fs::Advice;
28 #[cfg(not(any(target_os = "espidf", target_os = "redox")))]
29 use crate::fs::AtFlags;
30 #[cfg(not(any(
31 netbsdlike,
32 target_os = "dragonfly",
33 target_os = "espidf",
34 target_os = "nto",
35 target_os = "redox",
36 target_os = "vita",
37 )))]
38 use crate::fs::FallocateFlags;
39 #[cfg(not(any(target_os = "espidf", target_os = "vita", target_os = "wasi")))]
40 use crate::fs::FlockOperation;
41 #[cfg(any(linux_kernel, target_os = "freebsd"))]
42 use crate::fs::MemfdFlags;
43 #[cfg(any(linux_kernel, target_os = "freebsd", target_os = "fuchsia"))]
44 use crate::fs::SealFlags;
45 #[cfg(not(any(
46 solarish,
47 target_os = "espidf",
48 target_os = "haiku",
49 target_os = "netbsd",
50 target_os = "nto",
51 target_os = "redox",
52 target_os = "vita",
53 target_os = "wasi",
54 )))]
55 use crate::fs::StatFs;
56 #[cfg(not(any(target_os = "espidf", target_os = "vita")))]
57 use crate::fs::Timestamps;
58 #[cfg(not(any(
59 apple,
60 target_os = "espidf",
61 target_os = "redox",
62 target_os = "vita",
63 target_os = "wasi"
64 )))]
65 use crate::fs::{Dev, FileType};
66 use crate::fs::{Mode, OFlags, SeekFrom, Stat};
67 #[cfg(not(any(target_os = "haiku", target_os = "redox", target_os = "wasi")))]
68 use crate::fs::{StatVfs, StatVfsMountFlags};
69 use crate::io;
70 #[cfg(all(target_env = "gnu", fix_y2038))]
71 use crate::timespec::LibcTimespec;
72 #[cfg(not(target_os = "wasi"))]
73 use crate::ugid::{Gid, Uid};
74 #[cfg(all(apple, feature = "alloc"))]
75 use alloc::vec;
76 use core::mem::MaybeUninit;
77 #[cfg(apple)]
78 use {
79 crate::backend::conv::nonnegative_ret,
80 crate::fs::{copyfile_state_t, CloneFlags, CopyfileFlags},
81 };
82 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
83 use {crate::fs::XattrFlags, core::mem::size_of, core::ptr::null_mut};
84 #[cfg(linux_kernel)]
85 use {
86 crate::fs::{RenameFlags, ResolveFlags, Statx, StatxFlags, CWD},
87 core::ptr::null,
88 };
89
90 #[cfg(all(target_env = "gnu", fix_y2038))]
91 weak!(fn __utimensat64(c::c_int, *const c::c_char, *const LibcTimespec, c::c_int) -> c::c_int);
92 #[cfg(all(target_env = "gnu", fix_y2038))]
93 weak!(fn __futimens64(c::c_int, *const LibcTimespec) -> c::c_int);
94
95 /// Use a direct syscall (via libc) for `open`.
96 ///
97 /// This is only currently necessary as a workaround for old glibc; see below.
98 #[cfg(all(unix, target_env = "gnu"))]
99 fn open_via_syscall(path: &CStr, oflags: OFlags, mode: Mode) -> io::Result<OwnedFd> {
100 // Linux on aarch64, loongarch64 and riscv64 has no `open` syscall so use
101 // `openat`.
102 #[cfg(any(
103 target_arch = "aarch64",
104 target_arch = "riscv32",
105 target_arch = "riscv64",
106 target_arch = "csky",
107 target_arch = "loongarch64"
108 ))]
109 {
110 openat_via_syscall(CWD, path, oflags, mode)
111 }
112
113 // Use the `open` syscall.
114 #[cfg(not(any(
115 target_arch = "aarch64",
116 target_arch = "riscv32",
117 target_arch = "riscv64",
118 target_arch = "csky",
119 target_arch = "loongarch64"
120 )))]
121 unsafe {
122 syscall! {
123 fn open(
124 pathname: *const c::c_char,
125 oflags: c::c_int,
126 mode: c::mode_t
127 ) via SYS_open -> c::c_int
128 }
129
130 ret_owned_fd(open(
131 c_str(path),
132 bitflags_bits!(oflags),
133 bitflags_bits!(mode),
134 ))
135 }
136 }
137
138 pub(crate) fn open(path: &CStr, oflags: OFlags, mode: Mode) -> io::Result<OwnedFd> {
139 // Work around <https://sourceware.org/bugzilla/show_bug.cgi?id=17523>.
140 // glibc versions before 2.25 don't handle `O_TMPFILE` correctly.
141 #[cfg(all(
142 unix,
143 target_env = "gnu",
144 not(target_os = "hurd"),
145 not(target_os = "freebsd")
146 ))]
147 if oflags.contains(OFlags::TMPFILE) && crate::backend::if_glibc_is_less_than_2_25() {
148 return open_via_syscall(path, oflags, mode);
149 }
150
151 // On these platforms, `mode_t` is `u16` and can't be passed directly to a
152 // variadic function.
153 #[cfg(any(
154 apple,
155 freebsdlike,
156 all(target_os = "android", target_pointer_width = "32")
157 ))]
158 let mode: c::c_uint = mode.bits().into();
159
160 // Otherwise, cast to `mode_t` as that's what `open` is documented to take.
161 #[cfg(not(any(
162 apple,
163 freebsdlike,
164 all(target_os = "android", target_pointer_width = "32")
165 )))]
166 let mode: c::mode_t = mode.bits() as _;
167
168 unsafe { ret_owned_fd(c::open(c_str(path), bitflags_bits!(oflags), mode)) }
169 }
170
171 /// Use a direct syscall (via libc) for `openat`.
172 ///
173 /// This is only currently necessary as a workaround for old glibc; see below.
174 #[cfg(all(unix, target_env = "gnu", not(target_os = "hurd")))]
175 fn openat_via_syscall(
176 dirfd: BorrowedFd<'_>,
177 path: &CStr,
178 oflags: OFlags,
179 mode: Mode,
180 ) -> io::Result<OwnedFd> {
181 syscall! {
182 fn openat(
183 base_dirfd: c::c_int,
184 pathname: *const c::c_char,
185 oflags: c::c_int,
186 mode: c::mode_t
187 ) via SYS_openat -> c::c_int
188 }
189
190 unsafe {
191 ret_owned_fd(openat(
192 borrowed_fd(dirfd),
193 c_str(path),
194 bitflags_bits!(oflags),
195 bitflags_bits!(mode),
196 ))
197 }
198 }
199
200 #[cfg(not(target_os = "redox"))]
201 pub(crate) fn openat(
202 dirfd: BorrowedFd<'_>,
203 path: &CStr,
204 oflags: OFlags,
205 mode: Mode,
206 ) -> io::Result<OwnedFd> {
207 // Work around <https://sourceware.org/bugzilla/show_bug.cgi?id=17523>.
208 // glibc versions before 2.25 don't handle `O_TMPFILE` correctly.
209 #[cfg(all(
210 unix,
211 target_env = "gnu",
212 not(target_os = "hurd"),
213 not(target_os = "freebsd")
214 ))]
215 if oflags.contains(OFlags::TMPFILE) && crate::backend::if_glibc_is_less_than_2_25() {
216 return openat_via_syscall(dirfd, path, oflags, mode);
217 }
218
219 // On these platforms, `mode_t` is `u16` and can't be passed directly to a
220 // variadic function.
221 #[cfg(any(
222 apple,
223 freebsdlike,
224 all(target_os = "android", target_pointer_width = "32")
225 ))]
226 let mode: c::c_uint = mode.bits().into();
227
228 // Otherwise, cast to `mode_t` as that's what `open` is documented to take.
229 #[cfg(not(any(
230 apple,
231 freebsdlike,
232 all(target_os = "android", target_pointer_width = "32")
233 )))]
234 let mode: c::mode_t = mode.bits() as _;
235
236 unsafe {
237 ret_owned_fd(c::openat(
238 borrowed_fd(dirfd),
239 c_str(path),
240 bitflags_bits!(oflags),
241 mode,
242 ))
243 }
244 }
245
246 #[cfg(not(any(
247 solarish,
248 target_os = "espidf",
249 target_os = "haiku",
250 target_os = "netbsd",
251 target_os = "nto",
252 target_os = "redox",
253 target_os = "vita",
254 target_os = "wasi",
255 )))]
256 #[inline]
257 pub(crate) fn statfs(filename: &CStr) -> io::Result<StatFs> {
258 unsafe {
259 let mut result = MaybeUninit::<StatFs>::uninit();
260 ret(c::statfs(c_str(filename), result.as_mut_ptr()))?;
261 Ok(result.assume_init())
262 }
263 }
264
265 #[cfg(not(any(target_os = "haiku", target_os = "redox", target_os = "wasi")))]
266 #[inline]
267 pub(crate) fn statvfs(filename: &CStr) -> io::Result<StatVfs> {
268 unsafe {
269 let mut result = MaybeUninit::<c::statvfs>::uninit();
270 ret(c::statvfs(c_str(filename), result.as_mut_ptr()))?;
271 Ok(libc_statvfs_to_statvfs(result.assume_init()))
272 }
273 }
274
275 #[cfg(feature = "alloc")]
276 #[inline]
277 pub(crate) fn readlink(path: &CStr, buf: &mut [u8]) -> io::Result<usize> {
278 unsafe {
279 ret_usize(
280 c::readlink(c_str(path), buf.as_mut_ptr().cast::<c::c_char>(), buf.len()) as isize,
281 )
282 }
283 }
284
285 #[cfg(not(target_os = "redox"))]
286 #[inline]
287 pub(crate) fn readlinkat(
288 dirfd: BorrowedFd<'_>,
289 path: &CStr,
290 buf: &mut [MaybeUninit<u8>],
291 ) -> io::Result<usize> {
292 unsafe {
293 ret_usize(c::readlinkat(
294 borrowed_fd(dirfd),
295 c_str(path),
296 buf.as_mut_ptr().cast::<c::c_char>(),
297 buf.len(),
298 ) as isize)
299 }
300 }
301
302 pub(crate) fn mkdir(path: &CStr, mode: Mode) -> io::Result<()> {
303 unsafe { ret(c::mkdir(c_str(path), mode.bits() as c::mode_t)) }
304 }
305
306 #[cfg(not(target_os = "redox"))]
307 pub(crate) fn mkdirat(dirfd: BorrowedFd<'_>, path: &CStr, mode: Mode) -> io::Result<()> {
308 unsafe {
309 ret(c::mkdirat(
310 borrowed_fd(dirfd),
311 c_str(path),
312 mode.bits() as c::mode_t,
313 ))
314 }
315 }
316
317 #[cfg(linux_kernel)]
318 pub(crate) fn getdents_uninit(
319 fd: BorrowedFd<'_>,
320 buf: &mut [MaybeUninit<u8>],
321 ) -> io::Result<usize> {
322 syscall! {
323 fn getdents64(
324 fd: c::c_int,
325 dirp: *mut c::c_void,
326 count: usize
327 ) via SYS_getdents64 -> c::ssize_t
328 }
329 unsafe {
330 ret_usize(getdents64(
331 borrowed_fd(fd),
332 buf.as_mut_ptr().cast::<c::c_void>(),
333 buf.len(),
334 ))
335 }
336 }
337
338 pub(crate) fn link(old_path: &CStr, new_path: &CStr) -> io::Result<()> {
339 unsafe { ret(c::link(c_str(old_path), c_str(new_path))) }
340 }
341
342 #[cfg(not(any(target_os = "espidf", target_os = "redox")))]
343 pub(crate) fn linkat(
344 old_dirfd: BorrowedFd<'_>,
345 old_path: &CStr,
346 new_dirfd: BorrowedFd<'_>,
347 new_path: &CStr,
348 flags: AtFlags,
349 ) -> io::Result<()> {
350 // macOS ≤ 10.9 lacks `linkat`.
351 #[cfg(target_os = "macos")]
352 unsafe {
353 weak! {
354 fn linkat(
355 c::c_int,
356 *const c::c_char,
357 c::c_int,
358 *const c::c_char,
359 c::c_int
360 ) -> c::c_int
361 }
362 // If we have `linkat`, use it.
363 if let Some(libc_linkat) = linkat.get() {
364 return ret(libc_linkat(
365 borrowed_fd(old_dirfd),
366 c_str(old_path),
367 borrowed_fd(new_dirfd),
368 c_str(new_path),
369 bitflags_bits!(flags),
370 ));
371 }
372 // Otherwise, see if we can emulate the `AT_FDCWD` case.
373 if borrowed_fd(old_dirfd) != c::AT_FDCWD || borrowed_fd(new_dirfd) != c::AT_FDCWD {
374 return Err(io::Errno::NOSYS);
375 }
376 if flags.intersects(!AtFlags::SYMLINK_FOLLOW) {
377 return Err(io::Errno::INVAL);
378 }
379 if !flags.is_empty() {
380 return Err(io::Errno::OPNOTSUPP);
381 }
382 ret(c::link(c_str(old_path), c_str(new_path)))
383 }
384
385 #[cfg(not(target_os = "macos"))]
386 unsafe {
387 ret(c::linkat(
388 borrowed_fd(old_dirfd),
389 c_str(old_path),
390 borrowed_fd(new_dirfd),
391 c_str(new_path),
392 bitflags_bits!(flags),
393 ))
394 }
395 }
396
397 pub(crate) fn rmdir(path: &CStr) -> io::Result<()> {
398 unsafe { ret(c::rmdir(c_str(path))) }
399 }
400
401 pub(crate) fn unlink(path: &CStr) -> io::Result<()> {
402 unsafe { ret(c::unlink(c_str(path))) }
403 }
404
405 #[cfg(not(any(target_os = "espidf", target_os = "redox")))]
406 pub(crate) fn unlinkat(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<()> {
407 // macOS ≤ 10.9 lacks `unlinkat`.
408 #[cfg(target_os = "macos")]
409 unsafe {
410 weak! {
411 fn unlinkat(
412 c::c_int,
413 *const c::c_char,
414 c::c_int
415 ) -> c::c_int
416 }
417 // If we have `unlinkat`, use it.
418 if let Some(libc_unlinkat) = unlinkat.get() {
419 return ret(libc_unlinkat(
420 borrowed_fd(dirfd),
421 c_str(path),
422 bitflags_bits!(flags),
423 ));
424 }
425 // Otherwise, see if we can emulate the `AT_FDCWD` case.
426 if borrowed_fd(dirfd) != c::AT_FDCWD {
427 return Err(io::Errno::NOSYS);
428 }
429 if flags.intersects(!AtFlags::REMOVEDIR) {
430 return Err(io::Errno::INVAL);
431 }
432 if flags.contains(AtFlags::REMOVEDIR) {
433 ret(c::rmdir(c_str(path)))
434 } else {
435 ret(c::unlink(c_str(path)))
436 }
437 }
438
439 #[cfg(not(target_os = "macos"))]
440 unsafe {
441 ret(c::unlinkat(
442 borrowed_fd(dirfd),
443 c_str(path),
444 bitflags_bits!(flags),
445 ))
446 }
447 }
448
449 pub(crate) fn rename(old_path: &CStr, new_path: &CStr) -> io::Result<()> {
450 unsafe { ret(c::rename(c_str(old_path), c_str(new_path))) }
451 }
452
453 #[cfg(not(target_os = "redox"))]
454 pub(crate) fn renameat(
455 old_dirfd: BorrowedFd<'_>,
456 old_path: &CStr,
457 new_dirfd: BorrowedFd<'_>,
458 new_path: &CStr,
459 ) -> io::Result<()> {
460 // macOS ≤ 10.9 lacks `renameat`.
461 #[cfg(target_os = "macos")]
462 unsafe {
463 weak! {
464 fn renameat(
465 c::c_int,
466 *const c::c_char,
467 c::c_int,
468 *const c::c_char
469 ) -> c::c_int
470 }
471 // If we have `renameat`, use it.
472 if let Some(libc_renameat) = renameat.get() {
473 return ret(libc_renameat(
474 borrowed_fd(old_dirfd),
475 c_str(old_path),
476 borrowed_fd(new_dirfd),
477 c_str(new_path),
478 ));
479 }
480 // Otherwise, see if we can emulate the `AT_FDCWD` case.
481 if borrowed_fd(old_dirfd) != c::AT_FDCWD || borrowed_fd(new_dirfd) != c::AT_FDCWD {
482 return Err(io::Errno::NOSYS);
483 }
484 ret(c::rename(c_str(old_path), c_str(new_path)))
485 }
486
487 #[cfg(not(target_os = "macos"))]
488 unsafe {
489 ret(c::renameat(
490 borrowed_fd(old_dirfd),
491 c_str(old_path),
492 borrowed_fd(new_dirfd),
493 c_str(new_path),
494 ))
495 }
496 }
497
498 #[cfg(all(target_os = "linux", target_env = "gnu"))]
499 pub(crate) fn renameat2(
500 old_dirfd: BorrowedFd<'_>,
501 old_path: &CStr,
502 new_dirfd: BorrowedFd<'_>,
503 new_path: &CStr,
504 flags: RenameFlags,
505 ) -> io::Result<()> {
506 // `renameat2` wasn't supported in glibc until 2.28.
507 weak_or_syscall! {
508 fn renameat2(
509 olddirfd: c::c_int,
510 oldpath: *const c::c_char,
511 newdirfd: c::c_int,
512 newpath: *const c::c_char,
513 flags: c::c_uint
514 ) via SYS_renameat2 -> c::c_int
515 }
516
517 unsafe {
518 ret(renameat2(
519 borrowed_fd(old_dirfd),
520 c_str(old_path),
521 borrowed_fd(new_dirfd),
522 c_str(new_path),
523 flags.bits(),
524 ))
525 }
526 }
527
528 #[cfg(any(
529 target_os = "android",
530 all(target_os = "linux", not(target_env = "gnu")),
531 ))]
532 #[inline]
533 pub(crate) fn renameat2(
534 old_dirfd: BorrowedFd<'_>,
535 old_path: &CStr,
536 new_dirfd: BorrowedFd<'_>,
537 new_path: &CStr,
538 flags: RenameFlags,
539 ) -> io::Result<()> {
540 // At present, `libc` only has `renameat2` defined for glibc. If we have
541 // no flags, we can use plain `renameat`, but otherwise we use `syscall!`.
542 // to call `renameat2` ourselves.
543 if flags.is_empty() {
544 renameat(old_dirfd, old_path, new_dirfd, new_path)
545 } else {
546 syscall! {
547 fn renameat2(
548 olddirfd: c::c_int,
549 oldpath: *const c::c_char,
550 newdirfd: c::c_int,
551 newpath: *const c::c_char,
552 flags: c::c_uint
553 ) via SYS_renameat2 -> c::c_int
554 }
555
556 unsafe {
557 ret(renameat2(
558 borrowed_fd(old_dirfd),
559 c_str(old_path),
560 borrowed_fd(new_dirfd),
561 c_str(new_path),
562 flags.bits(),
563 ))
564 }
565 }
566 }
567
568 pub(crate) fn symlink(old_path: &CStr, new_path: &CStr) -> io::Result<()> {
569 unsafe { ret(c::symlink(c_str(old_path), c_str(new_path))) }
570 }
571
572 #[cfg(not(target_os = "redox"))]
573 pub(crate) fn symlinkat(
574 old_path: &CStr,
575 new_dirfd: BorrowedFd<'_>,
576 new_path: &CStr,
577 ) -> io::Result<()> {
578 unsafe {
579 ret(c::symlinkat(
580 c_str(old_path),
581 borrowed_fd(new_dirfd),
582 c_str(new_path),
583 ))
584 }
585 }
586
587 pub(crate) fn stat(path: &CStr) -> io::Result<Stat> {
588 // See the comments in `fstat` about using `crate::fs::statx` here.
589 #[cfg(all(
590 linux_kernel,
591 any(
592 target_pointer_width = "32",
593 target_arch = "mips64",
594 target_arch = "mips64r6"
595 )
596 ))]
597 {
598 match crate::fs::statx(CWD, path, AtFlags::empty(), StatxFlags::BASIC_STATS) {
599 Ok(x) => statx_to_stat(x),
600 Err(io::Errno::NOSYS) => statat_old(CWD, path, AtFlags::empty()),
601 Err(err) => Err(err),
602 }
603 }
604
605 // Main version: libc is y2038 safe. Or, the platform is not y2038 safe and
606 // there's nothing practical we can do.
607 #[cfg(not(all(
608 linux_kernel,
609 any(
610 target_pointer_width = "32",
611 target_arch = "mips64",
612 target_arch = "mips64r6"
613 )
614 )))]
615 unsafe {
616 let mut stat = MaybeUninit::<Stat>::uninit();
617 ret(c::stat(c_str(path), stat.as_mut_ptr()))?;
618 Ok(stat.assume_init())
619 }
620 }
621
622 pub(crate) fn lstat(path: &CStr) -> io::Result<Stat> {
623 // See the comments in `fstat` about using `crate::fs::statx` here.
624 #[cfg(all(
625 linux_kernel,
626 any(
627 target_pointer_width = "32",
628 target_arch = "mips64",
629 target_arch = "mips64r6"
630 )
631 ))]
632 {
633 match crate::fs::statx(
634 CWD,
635 path,
636 AtFlags::SYMLINK_NOFOLLOW,
637 StatxFlags::BASIC_STATS,
638 ) {
639 Ok(x) => statx_to_stat(x),
640 Err(io::Errno::NOSYS) => statat_old(CWD, path, AtFlags::SYMLINK_NOFOLLOW),
641 Err(err) => Err(err),
642 }
643 }
644
645 // Main version: libc is y2038 safe. Or, the platform is not y2038 safe and
646 // there's nothing practical we can do.
647 #[cfg(not(all(
648 linux_kernel,
649 any(
650 target_pointer_width = "32",
651 target_arch = "mips64",
652 target_arch = "mips64r6"
653 )
654 )))]
655 unsafe {
656 let mut stat = MaybeUninit::<Stat>::uninit();
657 ret(c::lstat(c_str(path), stat.as_mut_ptr()))?;
658 Ok(stat.assume_init())
659 }
660 }
661
662 #[cfg(not(any(target_os = "espidf", target_os = "redox")))]
663 pub(crate) fn statat(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<Stat> {
664 // See the comments in `fstat` about using `crate::fs::statx` here.
665 #[cfg(all(
666 linux_kernel,
667 any(
668 target_pointer_width = "32",
669 target_arch = "mips64",
670 target_arch = "mips64r6"
671 )
672 ))]
673 {
674 match crate::fs::statx(dirfd, path, flags, StatxFlags::BASIC_STATS) {
675 Ok(x) => statx_to_stat(x),
676 Err(io::Errno::NOSYS) => statat_old(dirfd, path, flags),
677 Err(err) => Err(err),
678 }
679 }
680
681 // Main version: libc is y2038 safe. Or, the platform is not y2038 safe and
682 // there's nothing practical we can do.
683 #[cfg(not(all(
684 linux_kernel,
685 any(
686 target_pointer_width = "32",
687 target_arch = "mips64",
688 target_arch = "mips64r6"
689 )
690 )))]
691 unsafe {
692 let mut stat = MaybeUninit::<Stat>::uninit();
693 ret(c::fstatat(
694 borrowed_fd(dirfd),
695 c_str(path),
696 stat.as_mut_ptr(),
697 bitflags_bits!(flags),
698 ))?;
699 Ok(stat.assume_init())
700 }
701 }
702
703 #[cfg(all(
704 linux_kernel,
705 any(
706 target_pointer_width = "32",
707 target_arch = "mips64",
708 target_arch = "mips64r6"
709 )
710 ))]
711 fn statat_old(dirfd: BorrowedFd<'_>, path: &CStr, flags: AtFlags) -> io::Result<Stat> {
712 unsafe {
713 let mut result = MaybeUninit::<c::stat64>::uninit();
714 ret(c::fstatat(
715 borrowed_fd(dirfd),
716 c_str(path),
717 result.as_mut_ptr(),
718 bitflags_bits!(flags),
719 ))?;
720 stat64_to_stat(result.assume_init())
721 }
722 }
723
724 #[cfg(not(any(target_os = "espidf", target_os = "emscripten", target_os = "vita")))]
725 pub(crate) fn access(path: &CStr, access: Access) -> io::Result<()> {
726 unsafe { ret(c::access(c_str(path), access.bits())) }
727 }
728
729 #[cfg(not(any(
730 target_os = "emscripten",
731 target_os = "espidf",
732 target_os = "redox",
733 target_os = "vita"
734 )))]
735 pub(crate) fn accessat(
736 dirfd: BorrowedFd<'_>,
737 path: &CStr,
738 access: Access,
739 flags: AtFlags,
740 ) -> io::Result<()> {
741 // macOS ≤ 10.9 lacks `faccessat`.
742 #[cfg(target_os = "macos")]
743 unsafe {
744 weak! {
745 fn faccessat(
746 c::c_int,
747 *const c::c_char,
748 c::c_int,
749 c::c_int
750 ) -> c::c_int
751 }
752 // If we have `faccessat`, use it.
753 if let Some(libc_faccessat) = faccessat.get() {
754 return ret(libc_faccessat(
755 borrowed_fd(dirfd),
756 c_str(path),
757 bitflags_bits!(access),
758 bitflags_bits!(flags),
759 ));
760 }
761 // Otherwise, see if we can emulate the `AT_FDCWD` case.
762 if borrowed_fd(dirfd) != c::AT_FDCWD {
763 return Err(io::Errno::NOSYS);
764 }
765 if flags.intersects(!(AtFlags::EACCESS | AtFlags::SYMLINK_NOFOLLOW)) {
766 return Err(io::Errno::INVAL);
767 }
768 if !flags.is_empty() {
769 return Err(io::Errno::OPNOTSUPP);
770 }
771 ret(c::access(c_str(path), bitflags_bits!(access)))
772 }
773
774 #[cfg(not(target_os = "macos"))]
775 unsafe {
776 ret(c::faccessat(
777 borrowed_fd(dirfd),
778 c_str(path),
779 bitflags_bits!(access),
780 bitflags_bits!(flags),
781 ))
782 }
783 }
784
785 #[cfg(target_os = "emscripten")]
786 pub(crate) fn access(_path: &CStr, _access: Access) -> io::Result<()> {
787 Ok(())
788 }
789
790 #[cfg(target_os = "emscripten")]
791 pub(crate) fn accessat(
792 _dirfd: BorrowedFd<'_>,
793 _path: &CStr,
794 _access: Access,
795 _flags: AtFlags,
796 ) -> io::Result<()> {
797 Ok(())
798 }
799
800 #[cfg(not(any(target_os = "espidf", target_os = "redox", target_os = "vita")))]
801 pub(crate) fn utimensat(
802 dirfd: BorrowedFd<'_>,
803 path: &CStr,
804 times: &Timestamps,
805 flags: AtFlags,
806 ) -> io::Result<()> {
807 // Old 32-bit version: libc has `utimensat` but it is not y2038 safe by
808 // default. But there may be a `__utimensat64` we can use.
809 #[cfg(all(fix_y2038, not(apple)))]
810 {
811 #[cfg(target_env = "gnu")]
812 if let Some(libc_utimensat) = __utimensat64.get() {
813 let libc_times: [LibcTimespec; 2] = [
814 times.last_access.clone().into(),
815 times.last_modification.clone().into(),
816 ];
817
818 unsafe {
819 return ret(libc_utimensat(
820 borrowed_fd(dirfd),
821 c_str(path),
822 libc_times.as_ptr(),
823 bitflags_bits!(flags),
824 ));
825 }
826 }
827
828 utimensat_old(dirfd, path, times, flags)
829 }
830
831 // Main version: libc is y2038 safe and has `utimensat`. Or, the platform
832 // is not y2038 safe and there's nothing practical we can do.
833 #[cfg(not(any(apple, fix_y2038)))]
834 unsafe {
835 use crate::utils::as_ptr;
836
837 ret(c::utimensat(
838 borrowed_fd(dirfd),
839 c_str(path),
840 as_ptr(times).cast(),
841 bitflags_bits!(flags),
842 ))
843 }
844
845 // Apple version: `utimensat` was introduced in macOS 10.13.
846 #[cfg(apple)]
847 unsafe {
848 use crate::utils::as_ptr;
849
850 // ABI details
851 weak! {
852 fn utimensat(
853 c::c_int,
854 *const c::c_char,
855 *const c::timespec,
856 c::c_int
857 ) -> c::c_int
858 }
859 extern "C" {
860 fn setattrlist(
861 path: *const c::c_char,
862 attr_list: *const Attrlist,
863 attr_buf: *const c::c_void,
864 attr_buf_size: c::size_t,
865 options: c::c_ulong,
866 ) -> c::c_int;
867 }
868 const FSOPT_NOFOLLOW: c::c_ulong = 0x0000_0001;
869
870 // If we have `utimensat`, use it.
871 if let Some(have_utimensat) = utimensat.get() {
872 return ret(have_utimensat(
873 borrowed_fd(dirfd),
874 c_str(path),
875 as_ptr(times).cast(),
876 bitflags_bits!(flags),
877 ));
878 }
879
880 // Convert `times`. We only need this in the child, but do it before
881 // calling `fork` because it might fail.
882 let (attrbuf_size, times, attrs) = times_to_attrlist(times)?;
883
884 // `setattrlistat` was introduced in 10.13 along with `utimensat`, so
885 // if we don't have `utimensat`, we don't have `setattrlistat` either.
886 // Emulate it using `fork`, and `fchdir` and [`setattrlist`].
887 //
888 // [`setattrlist`]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/setattrlist.2.html
889 match c::fork() {
890 -1 => Err(io::Errno::IO),
891 0 => {
892 if c::fchdir(borrowed_fd(dirfd)) != 0 {
893 let code = match libc_errno::errno().0 {
894 c::EACCES => 2,
895 c::ENOTDIR => 3,
896 _ => 1,
897 };
898 c::_exit(code);
899 }
900
901 let mut flags_arg = 0;
902 if flags.contains(AtFlags::SYMLINK_NOFOLLOW) {
903 flags_arg |= FSOPT_NOFOLLOW;
904 }
905
906 if setattrlist(
907 c_str(path),
908 &attrs,
909 as_ptr(&times).cast(),
910 attrbuf_size,
911 flags_arg,
912 ) != 0
913 {
914 // Translate expected `errno` codes into ad-hoc integer
915 // values suitable for exit statuses.
916 let code = match libc_errno::errno().0 {
917 c::EACCES => 2,
918 c::ENOTDIR => 3,
919 c::EPERM => 4,
920 c::EROFS => 5,
921 c::ELOOP => 6,
922 c::ENOENT => 7,
923 c::ENAMETOOLONG => 8,
924 c::EINVAL => 9,
925 c::ESRCH => 10,
926 c::ENOTSUP => 11,
927 _ => 1,
928 };
929 c::_exit(code);
930 }
931
932 c::_exit(0);
933 }
934 child_pid => {
935 let mut wstatus = 0;
936 let _ = ret_c_int(c::waitpid(child_pid, &mut wstatus, 0))?;
937 if c::WIFEXITED(wstatus) {
938 // Translate our ad-hoc exit statuses back to `errno`
939 // codes.
940 match c::WEXITSTATUS(wstatus) {
941 0 => Ok(()),
942 2 => Err(io::Errno::ACCESS),
943 3 => Err(io::Errno::NOTDIR),
944 4 => Err(io::Errno::PERM),
945 5 => Err(io::Errno::ROFS),
946 6 => Err(io::Errno::LOOP),
947 7 => Err(io::Errno::NOENT),
948 8 => Err(io::Errno::NAMETOOLONG),
949 9 => Err(io::Errno::INVAL),
950 10 => Err(io::Errno::SRCH),
951 11 => Err(io::Errno::NOTSUP),
952 _ => Err(io::Errno::IO),
953 }
954 } else {
955 Err(io::Errno::IO)
956 }
957 }
958 }
959 }
960 }
961
962 #[cfg(all(fix_y2038, not(apple)))]
963 fn utimensat_old(
964 dirfd: BorrowedFd<'_>,
965 path: &CStr,
966 times: &Timestamps,
967 flags: AtFlags,
968 ) -> io::Result<()> {
969 let old_times = [
970 c::timespec {
971 tv_sec: times
972 .last_access
973 .tv_sec
974 .try_into()
975 .map_err(|_| io::Errno::OVERFLOW)?,
976 tv_nsec: times
977 .last_access
978 .tv_nsec
979 .try_into()
980 .map_err(|_| io::Errno::OVERFLOW)?,
981 },
982 c::timespec {
983 tv_sec: times
984 .last_modification
985 .tv_sec
986 .try_into()
987 .map_err(|_| io::Errno::OVERFLOW)?,
988 tv_nsec: times
989 .last_modification
990 .tv_nsec
991 .try_into()
992 .map_err(|_| io::Errno::OVERFLOW)?,
993 },
994 ];
995 unsafe {
996 ret(c::utimensat(
997 borrowed_fd(dirfd),
998 c_str(path),
999 old_times.as_ptr(),
1000 bitflags_bits!(flags),
1001 ))
1002 }
1003 }
1004
1005 #[cfg(not(target_os = "wasi"))]
1006 pub(crate) fn chmod(path: &CStr, mode: Mode) -> io::Result<()> {
1007 unsafe { ret(c::chmod(c_str(path), mode.bits() as c::mode_t)) }
1008 }
1009
1010 #[cfg(not(any(
1011 linux_kernel,
1012 target_os = "espidf",
1013 target_os = "redox",
1014 target_os = "wasi"
1015 )))]
1016 pub(crate) fn chmodat(
1017 dirfd: BorrowedFd<'_>,
1018 path: &CStr,
1019 mode: Mode,
1020 flags: AtFlags,
1021 ) -> io::Result<()> {
1022 unsafe {
1023 ret(c::fchmodat(
1024 borrowed_fd(dirfd),
1025 c_str(path),
1026 mode.bits() as c::mode_t,
1027 bitflags_bits!(flags),
1028 ))
1029 }
1030 }
1031
1032 #[cfg(linux_kernel)]
1033 pub(crate) fn chmodat(
1034 dirfd: BorrowedFd<'_>,
1035 path: &CStr,
1036 mode: Mode,
1037 flags: AtFlags,
1038 ) -> io::Result<()> {
1039 // Linux's `fchmodat` does not have a flags argument.
1040 //
1041 // Use `c::syscall` rather than `c::fchmodat` because some libc
1042 // implementations, such as musl, add extra logic to `fchmod` to emulate
1043 // support for `AT_SYMLINK_NOFOLLOW`, which uses `/proc` outside our
1044 // control.
1045 syscall! {
1046 fn fchmodat(
1047 base_dirfd: c::c_int,
1048 pathname: *const c::c_char,
1049 mode: c::mode_t
1050 ) via SYS_fchmodat -> c::c_int
1051 }
1052 if flags == AtFlags::SYMLINK_NOFOLLOW {
1053 return Err(io::Errno::OPNOTSUPP);
1054 }
1055 if !flags.is_empty() {
1056 return Err(io::Errno::INVAL);
1057 }
1058 unsafe {
1059 ret(fchmodat(
1060 borrowed_fd(dirfd),
1061 c_str(path),
1062 mode.bits() as c::mode_t,
1063 ))
1064 }
1065 }
1066
1067 #[cfg(apple)]
1068 pub(crate) fn fclonefileat(
1069 srcfd: BorrowedFd<'_>,
1070 dst_dirfd: BorrowedFd<'_>,
1071 dst: &CStr,
1072 flags: CloneFlags,
1073 ) -> io::Result<()> {
1074 syscall! {
1075 fn fclonefileat(
1076 srcfd: BorrowedFd<'_>,
1077 dst_dirfd: BorrowedFd<'_>,
1078 dst: *const c::c_char,
1079 flags: c::c_int
1080 ) via SYS_fclonefileat -> c::c_int
1081 }
1082
1083 unsafe {
1084 ret(fclonefileat(
1085 srcfd,
1086 dst_dirfd,
1087 c_str(dst),
1088 bitflags_bits!(flags),
1089 ))
1090 }
1091 }
1092
1093 #[cfg(not(any(target_os = "espidf", target_os = "redox", target_os = "wasi")))]
1094 pub(crate) fn chownat(
1095 dirfd: BorrowedFd<'_>,
1096 path: &CStr,
1097 owner: Option<Uid>,
1098 group: Option<Gid>,
1099 flags: AtFlags,
1100 ) -> io::Result<()> {
1101 unsafe {
1102 let (ow, gr) = crate::ugid::translate_fchown_args(owner, group);
1103 ret(c::fchownat(
1104 borrowed_fd(dirfd),
1105 c_str(path),
1106 ow,
1107 gr,
1108 bitflags_bits!(flags),
1109 ))
1110 }
1111 }
1112
1113 #[cfg(not(any(
1114 apple,
1115 target_os = "espidf",
1116 target_os = "redox",
1117 target_os = "vita",
1118 target_os = "wasi"
1119 )))]
1120 pub(crate) fn mknodat(
1121 dirfd: BorrowedFd<'_>,
1122 path: &CStr,
1123 file_type: FileType,
1124 mode: Mode,
1125 dev: Dev,
1126 ) -> io::Result<()> {
1127 unsafe {
1128 ret(c::mknodat(
1129 borrowed_fd(dirfd),
1130 c_str(path),
1131 (mode.bits() | file_type.as_raw_mode()) as c::mode_t,
1132 dev.try_into().map_err(|_e| io::Errno::PERM)?,
1133 ))
1134 }
1135 }
1136
1137 #[cfg(linux_kernel)]
1138 pub(crate) fn copy_file_range(
1139 fd_in: BorrowedFd<'_>,
1140 off_in: Option<&mut u64>,
1141 fd_out: BorrowedFd<'_>,
1142 off_out: Option<&mut u64>,
1143 len: usize,
1144 ) -> io::Result<usize> {
1145 syscall! {
1146 fn copy_file_range(
1147 fd_in: c::c_int,
1148 off_in: *mut c::loff_t,
1149 fd_out: c::c_int,
1150 off_out: *mut c::loff_t,
1151 len: usize,
1152 flags: c::c_uint
1153 ) via SYS_copy_file_range -> c::ssize_t
1154 }
1155
1156 let mut off_in_val: c::loff_t = 0;
1157 let mut off_out_val: c::loff_t = 0;
1158 // Silently cast; we'll get `EINVAL` if the value is negative.
1159 let off_in_ptr = if let Some(off_in) = &off_in {
1160 off_in_val = **off_in as i64;
1161 &mut off_in_val
1162 } else {
1163 null_mut()
1164 };
1165 let off_out_ptr = if let Some(off_out) = &off_out {
1166 off_out_val = **off_out as i64;
1167 &mut off_out_val
1168 } else {
1169 null_mut()
1170 };
1171 let copied = unsafe {
1172 ret_usize(copy_file_range(
1173 borrowed_fd(fd_in),
1174 off_in_ptr,
1175 borrowed_fd(fd_out),
1176 off_out_ptr,
1177 len,
1178 0, // no flags are defined yet
1179 ))?
1180 };
1181 if let Some(off_in) = off_in {
1182 *off_in = off_in_val as u64;
1183 }
1184 if let Some(off_out) = off_out {
1185 *off_out = off_out_val as u64;
1186 }
1187 Ok(copied)
1188 }
1189
1190 #[cfg(not(any(
1191 apple,
1192 netbsdlike,
1193 target_os = "solaris",
1194 target_os = "dragonfly",
1195 target_os = "espidf",
1196 target_os = "haiku",
1197 target_os = "redox",
1198 target_os = "vita",
1199 )))]
1200 pub(crate) fn fadvise(fd: BorrowedFd<'_>, offset: u64, len: u64, advice: Advice) -> io::Result<()> {
1201 let offset = offset as i64;
1202 let len = len as i64;
1203
1204 // FreeBSD returns `EINVAL` on invalid offsets; emulate the POSIX behavior.
1205 #[cfg(target_os = "freebsd")]
1206 let offset = if (offset as i64) < 0 {
1207 i64::MAX
1208 } else {
1209 offset
1210 };
1211
1212 // FreeBSD returns `EINVAL` on overflow; emulate the POSIX behavior.
1213 #[cfg(target_os = "freebsd")]
1214 let len = if len > 0 && offset.checked_add(len).is_none() {
1215 i64::MAX - offset
1216 } else {
1217 len
1218 };
1219
1220 let err = unsafe { c::posix_fadvise(borrowed_fd(fd), offset, len, advice as c::c_int) };
1221
1222 // `posix_fadvise` returns its error status rather than using `errno`.
1223 if err == 0 {
1224 Ok(())
1225 } else {
1226 Err(io::Errno(err))
1227 }
1228 }
1229
1230 pub(crate) fn fcntl_getfl(fd: BorrowedFd<'_>) -> io::Result<OFlags> {
1231 let flags = unsafe { ret_c_int(c::fcntl(borrowed_fd(fd), c::F_GETFL))? };
1232 Ok(OFlags::from_bits_retain(bitcast!(flags)))
1233 }
1234
1235 pub(crate) fn fcntl_setfl(fd: BorrowedFd<'_>, flags: OFlags) -> io::Result<()> {
1236 unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_SETFL, flags.bits())) }
1237 }
1238
1239 #[cfg(any(linux_kernel, target_os = "freebsd", target_os = "fuchsia"))]
1240 pub(crate) fn fcntl_get_seals(fd: BorrowedFd<'_>) -> io::Result<SealFlags> {
1241 let flags = unsafe { ret_c_int(c::fcntl(borrowed_fd(fd), c::F_GET_SEALS))? };
1242 Ok(SealFlags::from_bits_retain(bitcast!(flags)))
1243 }
1244
1245 #[cfg(any(linux_kernel, target_os = "freebsd", target_os = "fuchsia"))]
1246 pub(crate) fn fcntl_add_seals(fd: BorrowedFd<'_>, seals: SealFlags) -> io::Result<()> {
1247 unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_ADD_SEALS, seals.bits())) }
1248 }
1249
1250 #[cfg(not(any(
1251 target_os = "emscripten",
1252 target_os = "espidf",
1253 target_os = "fuchsia",
1254 target_os = "redox",
1255 target_os = "vita",
1256 target_os = "wasi"
1257 )))]
1258 #[inline]
1259 pub(crate) fn fcntl_lock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::Result<()> {
1260 use c::{flock, F_RDLCK, F_SETLK, F_SETLKW, F_UNLCK, F_WRLCK, SEEK_SET};
1261
1262 let (cmd, l_type) = match operation {
1263 FlockOperation::LockShared => (F_SETLKW, F_RDLCK),
1264 FlockOperation::LockExclusive => (F_SETLKW, F_WRLCK),
1265 FlockOperation::Unlock => (F_SETLKW, F_UNLCK),
1266 FlockOperation::NonBlockingLockShared => (F_SETLK, F_RDLCK),
1267 FlockOperation::NonBlockingLockExclusive => (F_SETLK, F_WRLCK),
1268 FlockOperation::NonBlockingUnlock => (F_SETLK, F_UNLCK),
1269 };
1270
1271 unsafe {
1272 let mut lock: flock = core::mem::zeroed();
1273 lock.l_type = l_type as _;
1274
1275 // When `l_len` is zero, this locks all the bytes from
1276 // `l_whence`/`l_start` to the end of the file, even as the
1277 // file grows dynamically.
1278 lock.l_whence = SEEK_SET as _;
1279 lock.l_start = 0;
1280 lock.l_len = 0;
1281
1282 ret(c::fcntl(borrowed_fd(fd), cmd, &lock))
1283 }
1284 }
1285
1286 pub(crate) fn seek(fd: BorrowedFd<'_>, pos: SeekFrom) -> io::Result<u64> {
1287 let (whence, offset) = match pos {
1288 SeekFrom::Start(pos) => {
1289 let pos: u64 = pos;
1290 // Silently cast; we'll get `EINVAL` if the value is negative.
1291 (c::SEEK_SET, pos as i64)
1292 }
1293 SeekFrom::End(offset) => (c::SEEK_END, offset),
1294 SeekFrom::Current(offset) => (c::SEEK_CUR, offset),
1295 #[cfg(any(apple, freebsdlike, linux_kernel, solarish))]
1296 SeekFrom::Data(offset) => (c::SEEK_DATA, offset),
1297 #[cfg(any(apple, freebsdlike, linux_kernel, solarish))]
1298 SeekFrom::Hole(offset) => (c::SEEK_HOLE, offset),
1299 };
1300
1301 // ESP-IDF and Vita don't support 64-bit offsets.
1302 #[cfg(any(target_os = "espidf", target_os = "vita"))]
1303 let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1304
1305 let offset = unsafe { ret_off_t(c::lseek(borrowed_fd(fd), offset, whence))? };
1306 Ok(offset as u64)
1307 }
1308
1309 pub(crate) fn tell(fd: BorrowedFd<'_>) -> io::Result<u64> {
1310 let offset = unsafe { ret_off_t(c::lseek(borrowed_fd(fd), 0, c::SEEK_CUR))? };
1311 Ok(offset as u64)
1312 }
1313
1314 #[cfg(not(any(linux_kernel, target_os = "wasi")))]
1315 pub(crate) fn fchmod(fd: BorrowedFd<'_>, mode: Mode) -> io::Result<()> {
1316 unsafe { ret(c::fchmod(borrowed_fd(fd), bitflags_bits!(mode))) }
1317 }
1318
1319 #[cfg(linux_kernel)]
1320 pub(crate) fn fchmod(fd: BorrowedFd<'_>, mode: Mode) -> io::Result<()> {
1321 // Use `c::syscall` rather than `c::fchmod` because some libc
1322 // implementations, such as musl, add extra logic to `fchmod` to emulate
1323 // support for `O_PATH`, which uses `/proc` outside our control and
1324 // interferes with our own use of `O_PATH`.
1325 syscall! {
1326 fn fchmod(
1327 fd: c::c_int,
1328 mode: c::mode_t
1329 ) via SYS_fchmod -> c::c_int
1330 }
1331 unsafe { ret(fchmod(borrowed_fd(fd), mode.bits() as c::mode_t)) }
1332 }
1333
1334 #[cfg(not(target_os = "wasi"))]
1335 pub(crate) fn chown(path: &CStr, owner: Option<Uid>, group: Option<Gid>) -> io::Result<()> {
1336 unsafe {
1337 let (ow, gr) = crate::ugid::translate_fchown_args(owner, group);
1338 ret(c::chown(c_str(path), ow, gr))
1339 }
1340 }
1341
1342 #[cfg(linux_kernel)]
1343 pub(crate) fn fchown(fd: BorrowedFd<'_>, owner: Option<Uid>, group: Option<Gid>) -> io::Result<()> {
1344 // Use `c::syscall` rather than `c::fchown` because some libc
1345 // implementations, such as musl, add extra logic to `fchown` to emulate
1346 // support for `O_PATH`, which uses `/proc` outside our control and
1347 // interferes with our own use of `O_PATH`.
1348 syscall! {
1349 fn fchown(
1350 fd: c::c_int,
1351 owner: c::uid_t,
1352 group: c::gid_t
1353 ) via SYS_fchown -> c::c_int
1354 }
1355 unsafe {
1356 let (ow, gr) = crate::ugid::translate_fchown_args(owner, group);
1357 ret(fchown(borrowed_fd(fd), ow, gr))
1358 }
1359 }
1360
1361 #[cfg(not(any(linux_kernel, target_os = "wasi")))]
1362 pub(crate) fn fchown(fd: BorrowedFd<'_>, owner: Option<Uid>, group: Option<Gid>) -> io::Result<()> {
1363 unsafe {
1364 let (ow, gr) = crate::ugid::translate_fchown_args(owner, group);
1365 ret(c::fchown(borrowed_fd(fd), ow, gr))
1366 }
1367 }
1368
1369 #[cfg(not(any(
1370 target_os = "espidf",
1371 target_os = "solaris",
1372 target_os = "vita",
1373 target_os = "wasi"
1374 )))]
1375 pub(crate) fn flock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::Result<()> {
1376 unsafe { ret(c::flock(borrowed_fd(fd), operation as c::c_int)) }
1377 }
1378
1379 #[cfg(linux_kernel)]
1380 pub(crate) fn syncfs(fd: BorrowedFd<'_>) -> io::Result<()> {
1381 // Some versions of Android libc lack a `syncfs` function.
1382 #[cfg(target_os = "android")]
1383 syscall! {
1384 fn syncfs(fd: c::c_int) via SYS_syncfs -> c::c_int
1385 }
1386
1387 // `syncfs` was added to glibc in 2.20.
1388 #[cfg(not(target_os = "android"))]
1389 weak_or_syscall! {
1390 fn syncfs(fd: c::c_int) via SYS_syncfs -> c::c_int
1391 }
1392
1393 unsafe { ret(syncfs(borrowed_fd(fd))) }
1394 }
1395
1396 #[cfg(not(any(
1397 target_os = "espidf",
1398 target_os = "redox",
1399 target_os = "vita",
1400 target_os = "wasi"
1401 )))]
1402 pub(crate) fn sync() {
1403 unsafe { c::sync() }
1404 }
1405
1406 pub(crate) fn fstat(fd: BorrowedFd<'_>) -> io::Result<Stat> {
1407 // 32-bit and mips64 Linux: `struct stat64` is not y2038 compatible; use
1408 // `statx`.
1409 //
1410 // And, some old platforms don't support `statx`, and some fail with a
1411 // confusing error code, so we call `crate::fs::statx` to handle that. If
1412 // `statx` isn't available, fall back to the buggy system call.
1413 #[cfg(all(
1414 linux_kernel,
1415 any(
1416 target_pointer_width = "32",
1417 target_arch = "mips64",
1418 target_arch = "mips64r6"
1419 )
1420 ))]
1421 {
1422 match crate::fs::statx(fd, cstr!(""), AtFlags::EMPTY_PATH, StatxFlags::BASIC_STATS) {
1423 Ok(x) => statx_to_stat(x),
1424 Err(io::Errno::NOSYS) => fstat_old(fd),
1425 Err(err) => Err(err),
1426 }
1427 }
1428
1429 // Main version: libc is y2038 safe. Or, the platform is not y2038 safe and
1430 // there's nothing practical we can do.
1431 #[cfg(not(all(
1432 linux_kernel,
1433 any(
1434 target_pointer_width = "32",
1435 target_arch = "mips64",
1436 target_arch = "mips64r6"
1437 )
1438 )))]
1439 unsafe {
1440 let mut stat = MaybeUninit::<Stat>::uninit();
1441 ret(c::fstat(borrowed_fd(fd), stat.as_mut_ptr()))?;
1442 Ok(stat.assume_init())
1443 }
1444 }
1445
1446 #[cfg(all(
1447 linux_kernel,
1448 any(
1449 target_pointer_width = "32",
1450 target_arch = "mips64",
1451 target_arch = "mips64r6"
1452 )
1453 ))]
1454 fn fstat_old(fd: BorrowedFd<'_>) -> io::Result<Stat> {
1455 unsafe {
1456 let mut result = MaybeUninit::<c::stat64>::uninit();
1457 ret(c::fstat(borrowed_fd(fd), result.as_mut_ptr()))?;
1458 stat64_to_stat(result.assume_init())
1459 }
1460 }
1461
1462 #[cfg(not(any(
1463 solarish,
1464 target_os = "espidf",
1465 target_os = "haiku",
1466 target_os = "netbsd",
1467 target_os = "nto",
1468 target_os = "redox",
1469 target_os = "vita",
1470 target_os = "wasi",
1471 )))]
1472 pub(crate) fn fstatfs(fd: BorrowedFd<'_>) -> io::Result<StatFs> {
1473 let mut statfs = MaybeUninit::<StatFs>::uninit();
1474 unsafe {
1475 ret(c::fstatfs(borrowed_fd(fd), statfs.as_mut_ptr()))?;
1476 Ok(statfs.assume_init())
1477 }
1478 }
1479
1480 #[cfg(not(any(target_os = "haiku", target_os = "redox", target_os = "wasi")))]
1481 pub(crate) fn fstatvfs(fd: BorrowedFd<'_>) -> io::Result<StatVfs> {
1482 let mut statvfs = MaybeUninit::<c::statvfs>::uninit();
1483 unsafe {
1484 ret(c::fstatvfs(borrowed_fd(fd), statvfs.as_mut_ptr()))?;
1485 Ok(libc_statvfs_to_statvfs(statvfs.assume_init()))
1486 }
1487 }
1488
1489 #[cfg(not(any(target_os = "haiku", target_os = "redox", target_os = "wasi")))]
1490 fn libc_statvfs_to_statvfs(from: c::statvfs) -> StatVfs {
1491 StatVfs {
1492 f_bsize: from.f_bsize as u64,
1493 f_frsize: from.f_frsize as u64,
1494 f_blocks: from.f_blocks as u64,
1495 f_bfree: from.f_bfree as u64,
1496 f_bavail: from.f_bavail as u64,
1497 f_files: from.f_files as u64,
1498 f_ffree: from.f_ffree as u64,
1499 f_favail: from.f_ffree as u64,
1500 #[cfg(not(target_os = "aix"))]
1501 f_fsid: from.f_fsid as u64,
1502 #[cfg(target_os = "aix")]
1503 f_fsid: ((from.f_fsid.val[0] as u64) << 32) | from.f_fsid.val[1],
1504 f_flag: StatVfsMountFlags::from_bits_retain(from.f_flag as u64),
1505 f_namemax: from.f_namemax as u64,
1506 }
1507 }
1508
1509 #[cfg(not(any(target_os = "espidf", target_os = "vita")))]
1510 pub(crate) fn futimens(fd: BorrowedFd<'_>, times: &Timestamps) -> io::Result<()> {
1511 // Old 32-bit version: libc has `futimens` but it is not y2038 safe by
1512 // default. But there may be a `__futimens64` we can use.
1513 #[cfg(all(fix_y2038, not(apple)))]
1514 {
1515 #[cfg(target_env = "gnu")]
1516 if let Some(libc_futimens) = __futimens64.get() {
1517 let libc_times: [LibcTimespec; 2] = [
1518 times.last_access.clone().into(),
1519 times.last_modification.clone().into(),
1520 ];
1521
1522 unsafe {
1523 return ret(libc_futimens(borrowed_fd(fd), libc_times.as_ptr()));
1524 }
1525 }
1526
1527 futimens_old(fd, times)
1528 }
1529
1530 // Main version: libc is y2038 safe and has `futimens`. Or, the platform
1531 // is not y2038 safe and there's nothing practical we can do.
1532 #[cfg(not(any(apple, fix_y2038)))]
1533 unsafe {
1534 use crate::utils::as_ptr;
1535
1536 ret(c::futimens(borrowed_fd(fd), as_ptr(times).cast()))
1537 }
1538
1539 // Apple version: `futimens` was introduced in macOS 10.13.
1540 #[cfg(apple)]
1541 unsafe {
1542 use crate::utils::as_ptr;
1543
1544 // ABI details.
1545 weak! {
1546 fn futimens(c::c_int, *const c::timespec) -> c::c_int
1547 }
1548 extern "C" {
1549 fn fsetattrlist(
1550 fd: c::c_int,
1551 attr_list: *const Attrlist,
1552 attr_buf: *const c::c_void,
1553 attr_buf_size: c::size_t,
1554 options: c::c_ulong,
1555 ) -> c::c_int;
1556 }
1557
1558 // If we have `futimens`, use it.
1559 if let Some(have_futimens) = futimens.get() {
1560 return ret(have_futimens(borrowed_fd(fd), as_ptr(times).cast()));
1561 }
1562
1563 // Otherwise use `fsetattrlist`.
1564 let (attrbuf_size, times, attrs) = times_to_attrlist(times)?;
1565
1566 ret(fsetattrlist(
1567 borrowed_fd(fd),
1568 &attrs,
1569 as_ptr(&times).cast(),
1570 attrbuf_size,
1571 0,
1572 ))
1573 }
1574 }
1575
1576 #[cfg(all(fix_y2038, not(apple)))]
1577 fn futimens_old(fd: BorrowedFd<'_>, times: &Timestamps) -> io::Result<()> {
1578 let old_times = [
1579 c::timespec {
1580 tv_sec: times
1581 .last_access
1582 .tv_sec
1583 .try_into()
1584 .map_err(|_| io::Errno::OVERFLOW)?,
1585 tv_nsec: times
1586 .last_access
1587 .tv_nsec
1588 .try_into()
1589 .map_err(|_| io::Errno::OVERFLOW)?,
1590 },
1591 c::timespec {
1592 tv_sec: times
1593 .last_modification
1594 .tv_sec
1595 .try_into()
1596 .map_err(|_| io::Errno::OVERFLOW)?,
1597 tv_nsec: times
1598 .last_modification
1599 .tv_nsec
1600 .try_into()
1601 .map_err(|_| io::Errno::OVERFLOW)?,
1602 },
1603 ];
1604
1605 unsafe { ret(c::futimens(borrowed_fd(fd), old_times.as_ptr())) }
1606 }
1607
1608 #[cfg(not(any(
1609 apple,
1610 netbsdlike,
1611 target_os = "dragonfly",
1612 target_os = "espidf",
1613 target_os = "nto",
1614 target_os = "redox",
1615 target_os = "vita",
1616 )))]
1617 pub(crate) fn fallocate(
1618 fd: BorrowedFd<'_>,
1619 mode: FallocateFlags,
1620 offset: u64,
1621 len: u64,
1622 ) -> io::Result<()> {
1623 // Silently cast; we'll get `EINVAL` if the value is negative.
1624 let offset = offset as i64;
1625 let len = len as i64;
1626
1627 #[cfg(any(linux_kernel, target_os = "fuchsia"))]
1628 unsafe {
1629 ret(c::fallocate(
1630 borrowed_fd(fd),
1631 bitflags_bits!(mode),
1632 offset,
1633 len,
1634 ))
1635 }
1636
1637 #[cfg(not(any(linux_kernel, target_os = "fuchsia")))]
1638 {
1639 assert!(mode.is_empty());
1640 let err = unsafe { c::posix_fallocate(borrowed_fd(fd), offset, len) };
1641
1642 // `posix_fallocate` returns its error status rather than using
1643 // `errno`.
1644 if err == 0 {
1645 Ok(())
1646 } else {
1647 Err(io::Errno(err))
1648 }
1649 }
1650 }
1651
1652 #[cfg(apple)]
1653 pub(crate) fn fallocate(
1654 fd: BorrowedFd<'_>,
1655 mode: FallocateFlags,
1656 offset: u64,
1657 len: u64,
1658 ) -> io::Result<()> {
1659 let offset: i64 = offset.try_into().map_err(|_e| io::Errno::INVAL)?;
1660 let len = len as i64;
1661
1662 assert!(mode.is_empty());
1663
1664 let new_len = offset.checked_add(len).ok_or(io::Errno::FBIG)?;
1665 let mut store = c::fstore_t {
1666 fst_flags: c::F_ALLOCATECONTIG,
1667 fst_posmode: c::F_PEOFPOSMODE,
1668 fst_offset: 0,
1669 fst_length: new_len,
1670 fst_bytesalloc: 0,
1671 };
1672 unsafe {
1673 if c::fcntl(borrowed_fd(fd), c::F_PREALLOCATE, &store) == -1 {
1674 // Unable to allocate contiguous disk space; attempt to allocate
1675 // non-contiguously.
1676 store.fst_flags = c::F_ALLOCATEALL;
1677 let _ = ret_c_int(c::fcntl(borrowed_fd(fd), c::F_PREALLOCATE, &store))?;
1678 }
1679 ret(c::ftruncate(borrowed_fd(fd), new_len))
1680 }
1681 }
1682
1683 pub(crate) fn fsync(fd: BorrowedFd<'_>) -> io::Result<()> {
1684 unsafe { ret(c::fsync(borrowed_fd(fd))) }
1685 }
1686
1687 #[cfg(not(any(
1688 apple,
1689 target_os = "dragonfly",
1690 target_os = "espidf",
1691 target_os = "haiku",
1692 target_os = "redox",
1693 target_os = "vita",
1694 )))]
1695 pub(crate) fn fdatasync(fd: BorrowedFd<'_>) -> io::Result<()> {
1696 unsafe { ret(c::fdatasync(borrowed_fd(fd))) }
1697 }
1698
1699 pub(crate) fn ftruncate(fd: BorrowedFd<'_>, length: u64) -> io::Result<()> {
1700 let length = length.try_into().map_err(|_overflow_err| io::Errno::FBIG)?;
1701 unsafe { ret(c::ftruncate(borrowed_fd(fd), length)) }
1702 }
1703
1704 #[cfg(any(linux_kernel, target_os = "freebsd"))]
1705 pub(crate) fn memfd_create(name: &CStr, flags: MemfdFlags) -> io::Result<OwnedFd> {
1706 #[cfg(target_os = "freebsd")]
1707 weakcall! {
1708 fn memfd_create(
1709 name: *const c::c_char,
1710 flags: c::c_uint
1711 ) -> c::c_int
1712 }
1713
1714 #[cfg(linux_kernel)]
1715 weak_or_syscall! {
1716 fn memfd_create(
1717 name: *const c::c_char,
1718 flags: c::c_uint
1719 ) via SYS_memfd_create -> c::c_int
1720 }
1721
1722 unsafe { ret_owned_fd(memfd_create(c_str(name), bitflags_bits!(flags))) }
1723 }
1724
1725 #[cfg(linux_kernel)]
1726 pub(crate) fn openat2(
1727 dirfd: BorrowedFd<'_>,
1728 path: &CStr,
1729 oflags: OFlags,
1730 mode: Mode,
1731 resolve: ResolveFlags,
1732 ) -> io::Result<OwnedFd> {
1733 use linux_raw_sys::general::open_how;
1734
1735 syscall! {
1736 fn openat2(
1737 base_dirfd: c::c_int,
1738 pathname: *const c::c_char,
1739 how: *mut open_how,
1740 size: usize
1741 ) via SYS_OPENAT2 -> c::c_int
1742 }
1743
1744 let oflags = oflags.bits();
1745 let mut open_how = open_how {
1746 flags: u64::from(oflags),
1747 mode: u64::from(mode.bits()),
1748 resolve: resolve.bits(),
1749 };
1750
1751 unsafe {
1752 ret_owned_fd(openat2(
1753 borrowed_fd(dirfd),
1754 c_str(path),
1755 &mut open_how,
1756 size_of::<open_how>(),
1757 ))
1758 }
1759 }
1760 #[cfg(all(linux_kernel, target_pointer_width = "32"))]
1761 const SYS_OPENAT2: i32 = 437;
1762 #[cfg(all(linux_kernel, target_pointer_width = "64"))]
1763 const SYS_OPENAT2: i64 = 437;
1764
1765 #[cfg(target_os = "linux")]
1766 pub(crate) fn sendfile(
1767 out_fd: BorrowedFd<'_>,
1768 in_fd: BorrowedFd<'_>,
1769 offset: Option<&mut u64>,
1770 count: usize,
1771 ) -> io::Result<usize> {
1772 unsafe {
1773 ret_usize(c::sendfile64(
1774 borrowed_fd(out_fd),
1775 borrowed_fd(in_fd),
1776 offset.map_or(null_mut(), crate::utils::as_mut_ptr).cast(),
1777 count,
1778 ))
1779 }
1780 }
1781
1782 /// Convert from a Linux `statx` value to rustix's `Stat`.
1783 #[cfg(all(linux_kernel, target_pointer_width = "32"))]
1784 #[allow(deprecated)] // for `st_[amc]time` u64->i64 transition
1785 fn statx_to_stat(x: crate::fs::Statx) -> io::Result<Stat> {
1786 Ok(Stat {
1787 st_dev: crate::fs::makedev(x.stx_dev_major, x.stx_dev_minor).into(),
1788 st_mode: x.stx_mode.into(),
1789 st_nlink: x.stx_nlink.into(),
1790 st_uid: x.stx_uid.into(),
1791 st_gid: x.stx_gid.into(),
1792 st_rdev: crate::fs::makedev(x.stx_rdev_major, x.stx_rdev_minor).into(),
1793 st_size: x.stx_size.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1794 st_blksize: x.stx_blksize.into(),
1795 st_blocks: x.stx_blocks.into(),
1796 st_atime: bitcast!(i64::from(x.stx_atime.tv_sec)),
1797 st_atime_nsec: x.stx_atime.tv_nsec as _,
1798 st_mtime: bitcast!(i64::from(x.stx_mtime.tv_sec)),
1799 st_mtime_nsec: x.stx_mtime.tv_nsec as _,
1800 st_ctime: bitcast!(i64::from(x.stx_ctime.tv_sec)),
1801 st_ctime_nsec: x.stx_ctime.tv_nsec as _,
1802 st_ino: x.stx_ino.into(),
1803 })
1804 }
1805
1806 /// Convert from a Linux `statx` value to rustix's `Stat`.
1807 ///
1808 /// mips64' `struct stat64` in libc has private fields, and `stx_blocks`
1809 #[cfg(all(linux_kernel, any(target_arch = "mips64", target_arch = "mips64r6")))]
1810 fn statx_to_stat(x: crate::fs::Statx) -> io::Result<Stat> {
1811 let mut result: Stat = unsafe { core::mem::zeroed() };
1812
1813 result.st_dev = crate::fs::makedev(x.stx_dev_major, x.stx_dev_minor);
1814 result.st_mode = x.stx_mode.into();
1815 result.st_nlink = x.stx_nlink.into();
1816 result.st_uid = x.stx_uid.into();
1817 result.st_gid = x.stx_gid.into();
1818 result.st_rdev = crate::fs::makedev(x.stx_rdev_major, x.stx_rdev_minor);
1819 result.st_size = x.stx_size.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1820 result.st_blksize = x.stx_blksize.into();
1821 result.st_blocks = x.stx_blocks.try_into().map_err(|_e| io::Errno::OVERFLOW)?;
1822 result.st_atime = bitcast!(i64::from(x.stx_atime.tv_sec));
1823 result.st_atime_nsec = x.stx_atime.tv_nsec as _;
1824 result.st_mtime = bitcast!(i64::from(x.stx_mtime.tv_sec));
1825 result.st_mtime_nsec = x.stx_mtime.tv_nsec as _;
1826 result.st_ctime = bitcast!(i64::from(x.stx_ctime.tv_sec));
1827 result.st_ctime_nsec = x.stx_ctime.tv_nsec as _;
1828 result.st_ino = x.stx_ino.into();
1829
1830 Ok(result)
1831 }
1832
1833 /// Convert from a Linux `stat64` value to rustix's `Stat`.
1834 #[cfg(all(linux_kernel, target_pointer_width = "32"))]
1835 #[allow(deprecated)] // for `st_[amc]time` u64->i64 transition
1836 fn stat64_to_stat(s64: c::stat64) -> io::Result<Stat> {
1837 Ok(Stat {
1838 st_dev: s64.st_dev.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1839 st_mode: s64.st_mode.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1840 st_nlink: s64.st_nlink.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1841 st_uid: s64.st_uid.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1842 st_gid: s64.st_gid.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1843 st_rdev: s64.st_rdev.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1844 st_size: s64.st_size.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1845 st_blksize: s64.st_blksize.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1846 st_blocks: s64.st_blocks.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1847 st_atime: bitcast!(i64::from(s64.st_atime)),
1848 st_atime_nsec: s64
1849 .st_atime_nsec
1850 .try_into()
1851 .map_err(|_| io::Errno::OVERFLOW)?,
1852 st_mtime: bitcast!(i64::from(s64.st_mtime)),
1853 st_mtime_nsec: s64
1854 .st_mtime_nsec
1855 .try_into()
1856 .map_err(|_| io::Errno::OVERFLOW)?,
1857 st_ctime: bitcast!(i64::from(s64.st_ctime)),
1858 st_ctime_nsec: s64
1859 .st_ctime_nsec
1860 .try_into()
1861 .map_err(|_| io::Errno::OVERFLOW)?,
1862 st_ino: s64.st_ino.try_into().map_err(|_| io::Errno::OVERFLOW)?,
1863 })
1864 }
1865
1866 /// Convert from a Linux `stat64` value to rustix's `Stat`.
1867 ///
1868 /// mips64' `struct stat64` in libc has private fields, and `st_blocks` has
1869 /// type `i64`.
1870 #[cfg(all(linux_kernel, any(target_arch = "mips64", target_arch = "mips64r6")))]
1871 fn stat64_to_stat(s64: c::stat64) -> io::Result<Stat> {
1872 let mut result: Stat = unsafe { core::mem::zeroed() };
1873
1874 result.st_dev = s64.st_dev.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1875 result.st_mode = s64.st_mode.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1876 result.st_nlink = s64.st_nlink.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1877 result.st_uid = s64.st_uid.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1878 result.st_gid = s64.st_gid.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1879 result.st_rdev = s64.st_rdev.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1880 result.st_size = s64.st_size.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1881 result.st_blksize = s64.st_blksize.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1882 result.st_blocks = s64.st_blocks.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1883 result.st_atime = i64::from(s64.st_atime) as _;
1884 result.st_atime_nsec = s64
1885 .st_atime_nsec
1886 .try_into()
1887 .map_err(|_| io::Errno::OVERFLOW)?;
1888 result.st_mtime = i64::from(s64.st_mtime) as _;
1889 result.st_mtime_nsec = s64
1890 .st_mtime_nsec
1891 .try_into()
1892 .map_err(|_| io::Errno::OVERFLOW)?;
1893 result.st_ctime = i64::from(s64.st_ctime) as _;
1894 result.st_ctime_nsec = s64
1895 .st_ctime_nsec
1896 .try_into()
1897 .map_err(|_| io::Errno::OVERFLOW)?;
1898 result.st_ino = s64.st_ino.try_into().map_err(|_| io::Errno::OVERFLOW)?;
1899
1900 Ok(result)
1901 }
1902
1903 #[cfg(linux_kernel)]
1904 #[allow(non_upper_case_globals)]
1905 mod sys {
1906 use super::{c, BorrowedFd, Statx};
1907
1908 weak_or_syscall! {
1909 pub(super) fn statx(
1910 dirfd_: BorrowedFd<'_>,
1911 path: *const c::c_char,
1912 flags: c::c_int,
1913 mask: c::c_uint,
1914 buf: *mut Statx
1915 ) via SYS_statx -> c::c_int
1916 }
1917 }
1918
1919 #[cfg(linux_kernel)]
1920 #[allow(non_upper_case_globals)]
1921 pub(crate) fn statx(
1922 dirfd: BorrowedFd<'_>,
1923 path: &CStr,
1924 flags: AtFlags,
1925 mask: StatxFlags,
1926 ) -> io::Result<Statx> {
1927 // If a future Linux kernel adds more fields to `struct statx` and users
1928 // passing flags unknown to rustix in `StatxFlags`, we could end up
1929 // writing outside of the buffer. To prevent this possibility, we mask off
1930 // any flags that we don't know about.
1931 //
1932 // This includes `STATX__RESERVED`, which has a value that we know, but
1933 // which could take on arbitrary new meaning in the future. Linux currently
1934 // rejects this flag with `EINVAL`, so we do the same.
1935 //
1936 // This doesn't rely on `STATX_ALL` because [it's deprecated] and already
1937 // doesn't represent all the known flags.
1938 //
1939 // [it's deprecated]: https://patchwork.kernel.org/project/linux-fsdevel/patch/[email protected]/
1940 #[cfg(not(any(target_os = "android", target_env = "musl")))]
1941 const STATX__RESERVED: u32 = c::STATX__RESERVED as u32;
1942 #[cfg(any(target_os = "android", target_env = "musl"))]
1943 const STATX__RESERVED: u32 = linux_raw_sys::general::STATX__RESERVED;
1944 if (mask.bits() & STATX__RESERVED) == STATX__RESERVED {
1945 return Err(io::Errno::INVAL);
1946 }
1947 let mask = mask & StatxFlags::all();
1948
1949 let mut statx_buf = MaybeUninit::<Statx>::uninit();
1950 unsafe {
1951 ret(sys::statx(
1952 dirfd,
1953 c_str(path),
1954 bitflags_bits!(flags),
1955 mask.bits(),
1956 statx_buf.as_mut_ptr(),
1957 ))?;
1958 Ok(statx_buf.assume_init())
1959 }
1960 }
1961
1962 #[cfg(linux_kernel)]
1963 #[inline]
1964 pub(crate) fn is_statx_available() -> bool {
1965 unsafe {
1966 // Call `statx` with null pointers so that if it fails for any reason
1967 // other than `EFAULT`, we know it's not supported.
1968 matches!(
1969 ret(sys::statx(CWD, null(), 0, 0, null_mut())),
1970 Err(io::Errno::FAULT)
1971 )
1972 }
1973 }
1974
1975 #[cfg(apple)]
1976 pub(crate) unsafe fn fcopyfile(
1977 from: BorrowedFd<'_>,
1978 to: BorrowedFd<'_>,
1979 state: copyfile_state_t,
1980 flags: CopyfileFlags,
1981 ) -> io::Result<()> {
1982 extern "C" {
1983 fn fcopyfile(
1984 from: c::c_int,
1985 to: c::c_int,
1986 state: copyfile_state_t,
1987 flags: c::c_uint,
1988 ) -> c::c_int;
1989 }
1990
1991 nonnegative_ret(fcopyfile(
1992 borrowed_fd(from),
1993 borrowed_fd(to),
1994 state,
1995 bitflags_bits!(flags),
1996 ))
1997 }
1998
1999 #[cfg(apple)]
2000 pub(crate) fn copyfile_state_alloc() -> io::Result<copyfile_state_t> {
2001 extern "C" {
2002 fn copyfile_state_alloc() -> copyfile_state_t;
2003 }
2004
2005 let result = unsafe { copyfile_state_alloc() };
2006 if result.0.is_null() {
2007 Err(io::Errno::last_os_error())
2008 } else {
2009 Ok(result)
2010 }
2011 }
2012
2013 #[cfg(apple)]
2014 pub(crate) unsafe fn copyfile_state_free(state: copyfile_state_t) -> io::Result<()> {
2015 extern "C" {
2016 fn copyfile_state_free(state: copyfile_state_t) -> c::c_int;
2017 }
2018
2019 nonnegative_ret(copyfile_state_free(state))
2020 }
2021
2022 #[cfg(apple)]
2023 const COPYFILE_STATE_COPIED: u32 = 8;
2024
2025 #[cfg(apple)]
2026 pub(crate) unsafe fn copyfile_state_get_copied(state: copyfile_state_t) -> io::Result<u64> {
2027 let mut copied = MaybeUninit::<u64>::uninit();
2028 copyfile_state_get(state, COPYFILE_STATE_COPIED, copied.as_mut_ptr().cast())?;
2029 Ok(copied.assume_init())
2030 }
2031
2032 #[cfg(apple)]
2033 pub(crate) unsafe fn copyfile_state_get(
2034 state: copyfile_state_t,
2035 flag: u32,
2036 dst: *mut c::c_void,
2037 ) -> io::Result<()> {
2038 extern "C" {
2039 fn copyfile_state_get(state: copyfile_state_t, flag: u32, dst: *mut c::c_void) -> c::c_int;
2040 }
2041
2042 nonnegative_ret(copyfile_state_get(state, flag, dst))
2043 }
2044
2045 #[cfg(all(apple, feature = "alloc"))]
2046 pub(crate) fn getpath(fd: BorrowedFd<'_>) -> io::Result<CString> {
2047 // The use of `PATH_MAX` is generally not encouraged, but it
2048 // is inevitable in this case because macOS defines `fcntl` with
2049 // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no
2050 // alternatives. If a better method is invented, it should be used
2051 // instead.
2052 let mut buf = vec![0; c::PATH_MAX as usize];
2053
2054 // From the [macOS `fcntl` manual page]:
2055 // `F_GETPATH` - Get the path of the file descriptor `Fildes`. The argument
2056 // must be a buffer of size `MAXPATHLEN` or greater.
2057 //
2058 // [macOS `fcntl` manual page]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html
2059 unsafe {
2060 ret(c::fcntl(borrowed_fd(fd), c::F_GETPATH, buf.as_mut_ptr()))?;
2061 }
2062
2063 let l = buf.iter().position(|&c| c == 0).unwrap();
2064 buf.truncate(l);
2065 buf.shrink_to_fit();
2066
2067 Ok(CString::new(buf).unwrap())
2068 }
2069
2070 #[cfg(apple)]
2071 pub(crate) fn fcntl_rdadvise(fd: BorrowedFd<'_>, offset: u64, len: u64) -> io::Result<()> {
2072 // From the [macOS `fcntl` manual page]:
2073 // `F_RDADVISE` - Issue an advisory read async with no copy to user.
2074 //
2075 // The `F_RDADVISE` command operates on the following structure which holds
2076 // information passed from the user to the system:
2077 //
2078 // ```c
2079 // struct radvisory {
2080 // off_t ra_offset; /* offset into the file */
2081 // int ra_count; /* size of the read */
2082 // };
2083 // ```
2084 //
2085 // [macOS `fcntl` manual page]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/fcntl.2.html
2086 let ra_offset = match offset.try_into() {
2087 Ok(len) => len,
2088 // If this conversion fails, the user is providing an offset outside
2089 // any possible file extent, so just ignore it.
2090 Err(_) => return Ok(()),
2091 };
2092 let ra_count = match len.try_into() {
2093 Ok(len) => len,
2094 // If this conversion fails, the user is providing a dubiously large
2095 // hint which is unlikely to improve performance.
2096 Err(_) => return Ok(()),
2097 };
2098 unsafe {
2099 let radvisory = c::radvisory {
2100 ra_offset,
2101 ra_count,
2102 };
2103 ret(c::fcntl(borrowed_fd(fd), c::F_RDADVISE, &radvisory))
2104 }
2105 }
2106
2107 #[cfg(apple)]
2108 pub(crate) fn fcntl_fullfsync(fd: BorrowedFd<'_>) -> io::Result<()> {
2109 unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_FULLFSYNC)) }
2110 }
2111
2112 #[cfg(apple)]
2113 pub(crate) fn fcntl_nocache(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
2114 unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_NOCACHE, value as c::c_int)) }
2115 }
2116
2117 #[cfg(apple)]
2118 pub(crate) fn fcntl_global_nocache(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
2119 unsafe {
2120 ret(c::fcntl(
2121 borrowed_fd(fd),
2122 c::F_GLOBAL_NOCACHE,
2123 value as c::c_int,
2124 ))
2125 }
2126 }
2127
2128 /// Convert `times` from a `futimens`/`utimensat` argument into `setattrlist`
2129 /// arguments.
2130 #[cfg(apple)]
2131 fn times_to_attrlist(times: &Timestamps) -> io::Result<(c::size_t, [c::timespec; 2], Attrlist)> {
2132 // ABI details.
2133 const ATTR_CMN_MODTIME: u32 = 0x0000_0400;
2134 const ATTR_CMN_ACCTIME: u32 = 0x0000_1000;
2135 const ATTR_BIT_MAP_COUNT: u16 = 5;
2136
2137 let mut times = times.clone();
2138
2139 // If we have any `UTIME_NOW` elements, replace them with the current time.
2140 if times.last_access.tv_nsec == c::UTIME_NOW.into()
2141 || times.last_modification.tv_nsec == c::UTIME_NOW.into()
2142 {
2143 let now = {
2144 let mut tv = c::timeval {
2145 tv_sec: 0,
2146 tv_usec: 0,
2147 };
2148 unsafe {
2149 let r = c::gettimeofday(&mut tv, null_mut());
2150 assert_eq!(r, 0);
2151 }
2152 c::timespec {
2153 tv_sec: tv.tv_sec,
2154 tv_nsec: (tv.tv_usec * 1000) as _,
2155 }
2156 };
2157 if times.last_access.tv_nsec == c::UTIME_NOW.into() {
2158 times.last_access = crate::timespec::Timespec {
2159 tv_sec: now.tv_sec.into(),
2160 tv_nsec: now.tv_nsec as _,
2161 };
2162 }
2163 if times.last_modification.tv_nsec == c::UTIME_NOW.into() {
2164 times.last_modification = crate::timespec::Timespec {
2165 tv_sec: now.tv_sec.into(),
2166 tv_nsec: now.tv_nsec as _,
2167 };
2168 }
2169 }
2170
2171 // Pack the return values following the rules for [`getattrlist`].
2172 //
2173 // [`getattrlist`]: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/getattrlist.2.html
2174 let mut times_size = 0;
2175 let mut attrs = Attrlist {
2176 bitmapcount: ATTR_BIT_MAP_COUNT,
2177 reserved: 0,
2178 commonattr: 0,
2179 volattr: 0,
2180 dirattr: 0,
2181 fileattr: 0,
2182 forkattr: 0,
2183 };
2184 let mut return_times = [c::timespec {
2185 tv_sec: 0,
2186 tv_nsec: 0,
2187 }; 2];
2188 let mut times_index = 0;
2189 if times.last_modification.tv_nsec != c::UTIME_OMIT.into() {
2190 attrs.commonattr |= ATTR_CMN_MODTIME;
2191 return_times[times_index] = c::timespec {
2192 tv_sec: times
2193 .last_modification
2194 .tv_sec
2195 .try_into()
2196 .map_err(|_| io::Errno::OVERFLOW)?,
2197 tv_nsec: times.last_modification.tv_nsec as _,
2198 };
2199 times_index += 1;
2200 times_size += size_of::<c::timespec>();
2201 }
2202 if times.last_access.tv_nsec != c::UTIME_OMIT.into() {
2203 attrs.commonattr |= ATTR_CMN_ACCTIME;
2204 return_times[times_index] = c::timespec {
2205 tv_sec: times
2206 .last_access
2207 .tv_sec
2208 .try_into()
2209 .map_err(|_| io::Errno::OVERFLOW)?,
2210 tv_nsec: times.last_access.tv_nsec as _,
2211 };
2212 times_size += size_of::<c::timespec>();
2213 }
2214
2215 Ok((times_size, return_times, attrs))
2216 }
2217
2218 /// Support type for `Attrlist`.
2219 #[cfg(apple)]
2220 type Attrgroup = u32;
2221
2222 /// Attribute list for use with `setattrlist`.
2223 #[cfg(apple)]
2224 #[repr(C)]
2225 struct Attrlist {
2226 bitmapcount: u16,
2227 reserved: u16,
2228 commonattr: Attrgroup,
2229 volattr: Attrgroup,
2230 dirattr: Attrgroup,
2231 fileattr: Attrgroup,
2232 forkattr: Attrgroup,
2233 }
2234
2235 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2236 pub(crate) fn getxattr(path: &CStr, name: &CStr, value: &mut [u8]) -> io::Result<usize> {
2237 let value_ptr = value.as_mut_ptr();
2238
2239 #[cfg(not(apple))]
2240 unsafe {
2241 ret_usize(c::getxattr(
2242 path.as_ptr(),
2243 name.as_ptr(),
2244 value_ptr.cast::<c::c_void>(),
2245 value.len(),
2246 ))
2247 }
2248
2249 #[cfg(apple)]
2250 {
2251 // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS.
2252 // Pass null instead.
2253 let ptr = if value.is_empty() {
2254 core::ptr::null_mut()
2255 } else {
2256 value_ptr.cast::<c::c_void>()
2257 };
2258 unsafe {
2259 ret_usize(c::getxattr(
2260 path.as_ptr(),
2261 name.as_ptr(),
2262 ptr,
2263 value.len(),
2264 0,
2265 0,
2266 ))
2267 }
2268 }
2269 }
2270
2271 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2272 pub(crate) fn lgetxattr(path: &CStr, name: &CStr, value: &mut [u8]) -> io::Result<usize> {
2273 let value_ptr = value.as_mut_ptr();
2274
2275 #[cfg(not(apple))]
2276 unsafe {
2277 ret_usize(c::lgetxattr(
2278 path.as_ptr(),
2279 name.as_ptr(),
2280 value_ptr.cast::<c::c_void>(),
2281 value.len(),
2282 ))
2283 }
2284
2285 #[cfg(apple)]
2286 {
2287 // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS.
2288 // Pass null instead.
2289 let ptr = if value.is_empty() {
2290 core::ptr::null_mut()
2291 } else {
2292 value_ptr.cast::<c::c_void>()
2293 };
2294
2295 unsafe {
2296 ret_usize(c::getxattr(
2297 path.as_ptr(),
2298 name.as_ptr(),
2299 ptr,
2300 value.len(),
2301 0,
2302 c::XATTR_NOFOLLOW,
2303 ))
2304 }
2305 }
2306 }
2307
2308 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2309 pub(crate) fn fgetxattr(fd: BorrowedFd<'_>, name: &CStr, value: &mut [u8]) -> io::Result<usize> {
2310 let value_ptr = value.as_mut_ptr();
2311
2312 #[cfg(not(apple))]
2313 unsafe {
2314 ret_usize(c::fgetxattr(
2315 borrowed_fd(fd),
2316 name.as_ptr(),
2317 value_ptr.cast::<c::c_void>(),
2318 value.len(),
2319 ))
2320 }
2321
2322 #[cfg(apple)]
2323 {
2324 // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS.
2325 // Pass null instead.
2326 let ptr = if value.is_empty() {
2327 core::ptr::null_mut()
2328 } else {
2329 value_ptr.cast::<c::c_void>()
2330 };
2331 unsafe {
2332 ret_usize(c::fgetxattr(
2333 borrowed_fd(fd),
2334 name.as_ptr(),
2335 ptr,
2336 value.len(),
2337 0,
2338 0,
2339 ))
2340 }
2341 }
2342 }
2343
2344 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2345 pub(crate) fn setxattr(
2346 path: &CStr,
2347 name: &CStr,
2348 value: &[u8],
2349 flags: XattrFlags,
2350 ) -> io::Result<()> {
2351 #[cfg(not(apple))]
2352 unsafe {
2353 ret(c::setxattr(
2354 path.as_ptr(),
2355 name.as_ptr(),
2356 value.as_ptr().cast::<c::c_void>(),
2357 value.len(),
2358 flags.bits() as i32,
2359 ))
2360 }
2361
2362 #[cfg(apple)]
2363 unsafe {
2364 ret(c::setxattr(
2365 path.as_ptr(),
2366 name.as_ptr(),
2367 value.as_ptr().cast::<c::c_void>(),
2368 value.len(),
2369 0,
2370 flags.bits() as i32,
2371 ))
2372 }
2373 }
2374
2375 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2376 pub(crate) fn lsetxattr(
2377 path: &CStr,
2378 name: &CStr,
2379 value: &[u8],
2380 flags: XattrFlags,
2381 ) -> io::Result<()> {
2382 #[cfg(not(apple))]
2383 unsafe {
2384 ret(c::lsetxattr(
2385 path.as_ptr(),
2386 name.as_ptr(),
2387 value.as_ptr().cast::<c::c_void>(),
2388 value.len(),
2389 flags.bits() as i32,
2390 ))
2391 }
2392
2393 #[cfg(apple)]
2394 unsafe {
2395 ret(c::setxattr(
2396 path.as_ptr(),
2397 name.as_ptr(),
2398 value.as_ptr().cast::<c::c_void>(),
2399 value.len(),
2400 0,
2401 flags.bits() as i32 | c::XATTR_NOFOLLOW,
2402 ))
2403 }
2404 }
2405
2406 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2407 pub(crate) fn fsetxattr(
2408 fd: BorrowedFd<'_>,
2409 name: &CStr,
2410 value: &[u8],
2411 flags: XattrFlags,
2412 ) -> io::Result<()> {
2413 #[cfg(not(apple))]
2414 unsafe {
2415 ret(c::fsetxattr(
2416 borrowed_fd(fd),
2417 name.as_ptr(),
2418 value.as_ptr().cast::<c::c_void>(),
2419 value.len(),
2420 flags.bits() as i32,
2421 ))
2422 }
2423
2424 #[cfg(apple)]
2425 unsafe {
2426 ret(c::fsetxattr(
2427 borrowed_fd(fd),
2428 name.as_ptr(),
2429 value.as_ptr().cast::<c::c_void>(),
2430 value.len(),
2431 0,
2432 flags.bits() as i32,
2433 ))
2434 }
2435 }
2436
2437 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2438 pub(crate) fn listxattr(path: &CStr, list: &mut [c::c_char]) -> io::Result<usize> {
2439 #[cfg(not(apple))]
2440 unsafe {
2441 ret_usize(c::listxattr(path.as_ptr(), list.as_mut_ptr(), list.len()))
2442 }
2443
2444 #[cfg(apple)]
2445 unsafe {
2446 ret_usize(c::listxattr(
2447 path.as_ptr(),
2448 list.as_mut_ptr(),
2449 list.len(),
2450 0,
2451 ))
2452 }
2453 }
2454
2455 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2456 pub(crate) fn llistxattr(path: &CStr, list: &mut [c::c_char]) -> io::Result<usize> {
2457 #[cfg(not(apple))]
2458 unsafe {
2459 ret_usize(c::llistxattr(path.as_ptr(), list.as_mut_ptr(), list.len()))
2460 }
2461
2462 #[cfg(apple)]
2463 unsafe {
2464 ret_usize(c::listxattr(
2465 path.as_ptr(),
2466 list.as_mut_ptr(),
2467 list.len(),
2468 c::XATTR_NOFOLLOW,
2469 ))
2470 }
2471 }
2472
2473 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2474 pub(crate) fn flistxattr(fd: BorrowedFd<'_>, list: &mut [c::c_char]) -> io::Result<usize> {
2475 let fd = borrowed_fd(fd);
2476
2477 #[cfg(not(apple))]
2478 unsafe {
2479 ret_usize(c::flistxattr(fd, list.as_mut_ptr(), list.len()))
2480 }
2481
2482 #[cfg(apple)]
2483 unsafe {
2484 ret_usize(c::flistxattr(fd, list.as_mut_ptr(), list.len(), 0))
2485 }
2486 }
2487
2488 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2489 pub(crate) fn removexattr(path: &CStr, name: &CStr) -> io::Result<()> {
2490 #[cfg(not(apple))]
2491 unsafe {
2492 ret(c::removexattr(path.as_ptr(), name.as_ptr()))
2493 }
2494
2495 #[cfg(apple)]
2496 unsafe {
2497 ret(c::removexattr(path.as_ptr(), name.as_ptr(), 0))
2498 }
2499 }
2500
2501 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2502 pub(crate) fn lremovexattr(path: &CStr, name: &CStr) -> io::Result<()> {
2503 #[cfg(not(apple))]
2504 unsafe {
2505 ret(c::lremovexattr(path.as_ptr(), name.as_ptr()))
2506 }
2507
2508 #[cfg(apple)]
2509 unsafe {
2510 ret(c::removexattr(
2511 path.as_ptr(),
2512 name.as_ptr(),
2513 c::XATTR_NOFOLLOW,
2514 ))
2515 }
2516 }
2517
2518 #[cfg(any(apple, linux_kernel, target_os = "hurd"))]
2519 pub(crate) fn fremovexattr(fd: BorrowedFd<'_>, name: &CStr) -> io::Result<()> {
2520 let fd = borrowed_fd(fd);
2521
2522 #[cfg(not(apple))]
2523 unsafe {
2524 ret(c::fremovexattr(fd, name.as_ptr()))
2525 }
2526
2527 #[cfg(apple)]
2528 unsafe {
2529 ret(c::fremovexattr(fd, name.as_ptr(), 0))
2530 }
2531 }
2532
2533 #[test]
2534 fn test_sizes() {
2535 #[cfg(linux_kernel)]
2536 assert_eq_size!(c::loff_t, u64);
2537
2538 // Assert that `Timestamps` has the expected layout. If we're not fixing
2539 // y2038, libc's type should match ours. If we are, it's smaller.
2540 #[cfg(not(fix_y2038))]
2541 assert_eq_size!([c::timespec; 2], Timestamps);
2542 #[cfg(fix_y2038)]
2543 assert!(core::mem::size_of::<[c::timespec; 2]>() < core::mem::size_of::<Timestamps>());
2544 }
2545
2546 #[inline]
2547 #[cfg(linux_kernel)]
2548 pub(crate) fn inotify_init1(flags: super::inotify::CreateFlags) -> io::Result<OwnedFd> {
2549 // SAFETY: `inotify_init1` has no safety preconditions.
2550 unsafe { ret_owned_fd(c::inotify_init1(bitflags_bits!(flags))) }
2551 }
2552
2553 #[inline]
2554 #[cfg(linux_kernel)]
2555 pub(crate) fn inotify_add_watch(
2556 inot: BorrowedFd<'_>,
2557 path: &CStr,
2558 flags: super::inotify::WatchFlags,
2559 ) -> io::Result<i32> {
2560 // SAFETY: The fd and path we are passing is guaranteed valid by the
2561 // type system.
2562 unsafe {
2563 ret_c_int(c::inotify_add_watch(
2564 borrowed_fd(inot),
2565 c_str(path),
2566 flags.bits(),
2567 ))
2568 }
2569 }
2570
2571 #[inline]
2572 #[cfg(linux_kernel)]
2573 pub(crate) fn inotify_rm_watch(inot: BorrowedFd<'_>, wd: i32) -> io::Result<()> {
2574 // Android's `inotify_rm_watch` takes `u32` despite that
2575 // `inotify_add_watch` expects a `i32`.
2576 #[cfg(target_os = "android")]
2577 let wd = wd as u32;
2578 // SAFETY: The fd is valid and closing an arbitrary wd is valid.
2579 unsafe { ret(c::inotify_rm_watch(borrowed_fd(inot), wd)) }
2580 }