Debian Codegraph @

debian/rust-vendor/rustix/src/backend/libc/fs/syscalls.rs

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