Debian Codegraph @

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