From 51e58d35fb4ddb8ecd3d4cd26c6a16e06400576f Mon Sep 17 00:00:00 2001 From: Dan Gohman Date: Tue, 4 Mar 2025 21:08:20 -0800 Subject: [PATCH] Port to Rust nightly. --- Cargo.toml | 11 +- benches/mod.rs | 6 +- build.rs | 10 - examples/termios.rs | 2 +- examples/time.rs | 2 +- src/backend/libc/c.rs | 164 ++++----- src/backend/libc/conv.rs | 10 +- src/backend/libc/event/syscalls.rs | 140 ++++---- src/backend/libc/event/windows_syscalls.rs | 2 +- src/backend/libc/fs/dir.rs | 15 +- src/backend/libc/fs/syscalls.rs | 260 +++++++------- src/backend/libc/io/syscalls.rs | 38 +- src/backend/libc/io_uring/syscalls.rs | 94 ++--- src/backend/libc/mm/syscalls.rs | 140 ++++---- src/backend/libc/net/addr.rs | 18 +- src/backend/libc/net/msghdr.rs | 70 ++-- src/backend/libc/net/netdevice.rs | 2 +- src/backend/libc/net/read_sockaddr.rs | 120 ++++--- src/backend/libc/net/sockopt.rs | 16 +- src/backend/libc/net/syscalls.rs | 48 +-- src/backend/libc/net/write_sockaddr.rs | 2 +- src/backend/libc/pipe/syscalls.rs | 16 +- src/backend/libc/prctl/syscalls.rs | 2 +- src/backend/libc/process/syscalls.rs | 26 +- src/backend/libc/rand/syscalls.rs | 12 +- src/backend/libc/thread/cpu_set.rs | 2 +- src/backend/libc/thread/syscalls.rs | 236 ++++++------- src/backend/libc/time/syscalls.rs | 6 +- src/backend/libc/winsock_c.rs | 59 ++-- src/backend/linux_raw/arch/aarch64.rs | 2 +- src/backend/linux_raw/arch/arm.rs | 2 +- src/backend/linux_raw/arch/mips.rs | 2 +- src/backend/linux_raw/arch/mips32r6.rs | 2 +- src/backend/linux_raw/arch/mips64.rs | 2 +- src/backend/linux_raw/arch/mips64r6.rs | 2 +- src/backend/linux_raw/arch/mod.rs | 44 +-- src/backend/linux_raw/arch/powerpc.rs | 2 +- src/backend/linux_raw/arch/powerpc64.rs | 2 +- src/backend/linux_raw/arch/riscv64.rs | 2 +- src/backend/linux_raw/arch/s390x.rs | 2 +- src/backend/linux_raw/arch/thumb.rs | 2 +- src/backend/linux_raw/arch/x86.rs | 2 +- src/backend/linux_raw/arch/x86_64.rs | 360 ++++++++++--------- src/backend/linux_raw/c.rs | 86 ++--- src/backend/linux_raw/conv.rs | 32 +- src/backend/linux_raw/event/syscalls.rs | 290 ++++++++-------- src/backend/linux_raw/fs/dir.rs | 10 +- src/backend/linux_raw/fs/syscalls.rs | 86 ++--- src/backend/linux_raw/io/syscalls.rs | 100 +++--- src/backend/linux_raw/io_uring/syscalls.rs | 60 ++-- src/backend/linux_raw/mm/syscalls.rs | 150 ++++---- src/backend/linux_raw/net/addr.rs | 20 +- src/backend/linux_raw/net/msghdr.rs | 70 ++-- src/backend/linux_raw/net/netdevice.rs | 2 +- src/backend/linux_raw/net/read_sockaddr.rs | 30 +- src/backend/linux_raw/net/sockopt.rs | 10 +- src/backend/linux_raw/net/syscalls.rs | 146 ++++---- src/backend/linux_raw/param/auxv.rs | 304 ++++++++-------- src/backend/linux_raw/param/init.rs | 2 +- src/backend/linux_raw/param/libc_auxv.rs | 4 +- src/backend/linux_raw/pipe/syscalls.rs | 8 +- src/backend/linux_raw/prctl/syscalls.rs | 2 +- src/backend/linux_raw/process/syscalls.rs | 28 +- src/backend/linux_raw/process/wait.rs | 14 +- src/backend/linux_raw/rand/syscalls.rs | 2 +- src/backend/linux_raw/runtime/syscalls.rs | 386 +++++++++++---------- src/backend/linux_raw/termios/syscalls.rs | 4 +- src/backend/linux_raw/thread/syscalls.rs | 204 +++++------ src/backend/linux_raw/vdso.rs | 134 +++---- src/backend/linux_raw/vdso_wrappers.rs | 22 +- src/bitcast.rs | 6 +- src/buffer.rs | 38 +- src/event/mod.rs | 4 +- src/event/select.rs | 8 +- src/ffi.rs | 19 +- src/fs/inotify.rs | 4 +- src/fs/raw_dir.rs | 5 +- src/io/close.rs | 4 +- src/io/mod.rs | 2 +- src/io_uring/bindgen_types.rs | 8 +- src/io_uring/mod.rs | 81 +++-- src/ioctl/linux.rs | 4 +- src/ioctl/mod.rs | 36 +- src/ioctl/patterns.rs | 2 +- src/kernel_sigset.rs | 2 +- src/lib.rs | 8 +- src/mm/mmap.rs | 20 +- src/mm/mod.rs | 6 +- src/mm/msync.rs | 2 +- src/mm/userfaultfd.rs | 2 +- src/net/addr.rs | 26 +- src/net/send_recv/mod.rs | 2 +- src/net/send_recv/msg.rs | 18 +- src/net/socket.rs | 2 +- src/net/socket_addr_any.rs | 50 +-- src/net/sockopt.rs | 4 +- src/net/types.rs | 64 ++-- src/net/wsa.rs | 2 +- src/path/mod.rs | 2 +- src/pid.rs | 6 +- src/pipe.rs | 2 +- src/prctl.rs | 30 +- src/process/prctl.rs | 94 ++--- src/process/types.rs | 14 +- src/pty.rs | 4 +- src/rand/mod.rs | 2 +- src/runtime.rs | 26 +- src/signal.rs | 72 ++-- src/static_assertions.rs | 36 -- src/stdio.rs | 6 +- src/thread/futex.rs | 2 +- src/thread/mod.rs | 2 +- src/thread/prctl.rs | 60 ++-- src/timespec.rs | 3 +- src/utils.rs | 2 +- src/weak.rs | 36 +- tests/event/epoll.rs | 4 +- tests/event/epoll_timeout.rs | 2 +- tests/event/eventfd.rs | 2 +- tests/event/main.rs | 3 +- tests/event/select.rs | 12 +- tests/fs/chmodat.rs | 4 +- tests/fs/fcntl.rs | 2 +- tests/fs/fcntl_lock.rs | 2 +- tests/fs/flock.rs | 2 +- tests/fs/futimens.rs | 2 +- tests/fs/inotify.rs | 2 +- tests/fs/invalid_offset.rs | 12 +- tests/fs/linkat.rs | 4 +- tests/fs/long_paths.rs | 2 +- tests/fs/mkdirat.rs | 6 +- tests/fs/mknodat.rs | 2 +- tests/fs/negative_timestamp.rs | 4 +- tests/fs/openat.rs | 2 +- tests/fs/openat2.rs | 2 +- tests/fs/readlinkat.rs | 6 +- tests/fs/renameat.rs | 8 +- tests/fs/seals.rs | 2 +- tests/fs/seek.rs | 4 +- tests/fs/special.rs | 2 +- tests/fs/statfs.rs | 2 +- tests/fs/symlinkat.rs | 4 +- tests/fs/utimensat.rs | 6 +- tests/fs/y2038.rs | 6 +- tests/io/ioctl.rs | 4 +- tests/io/read_write.rs | 26 +- tests/io_uring/register.rs | 6 +- tests/mm/mmap.rs | 18 +- tests/net/addr.rs | 20 +- tests/net/main.rs | 3 +- tests/net/netlink.rs | 4 +- tests/net/poll.rs | 6 +- tests/net/sockopt.rs | 10 +- tests/net/unix.rs | 24 +- tests/net/unix_alloc.rs | 20 +- tests/net/v4.rs | 6 +- tests/net/v6.rs | 6 +- tests/param/weak.rs | 26 +- tests/path/dec_int.rs | 2 +- tests/pipe/basic.rs | 2 +- tests/pipe/splice.rs | 10 +- tests/pipe/tee.rs | 2 +- tests/process/fcntl_getlk.rs | 26 +- tests/process/pidfd.rs | 2 +- tests/process/wait.rs | 2 +- tests/process/working_directory.rs | 2 +- tests/pty/openpty.rs | 2 +- tests/rand/getrandom.rs | 2 +- tests/stdio/dup2_to_replace_stdio.rs | 20 +- tests/termios/isatty.rs | 2 +- tests/termios/pgrp.rs | 2 +- tests/termios/ttyname.rs | 10 +- tests/thread/clocks.rs | 4 +- tests/thread/futex.rs | 20 +- tests/thread/membarrier.rs | 2 +- tests/time/clocks.rs | 10 +- tests/time/dynamic_clocks.rs | 2 +- tests/time/monotonic.rs | 2 +- tests/time/settime.rs | 2 +- tests/time/timerfd.rs | 4 +- tests/time/wall.rs | 2 +- tests/time/y2038.rs | 4 +- 182 files changed, 2800 insertions(+), 2619 deletions(-) delete mode 100644 src/static_assertions.rs diff --git a/Cargo.toml b/Cargo.toml index ab9801143..39a67c457 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,11 +9,11 @@ description = "Safe Rust bindings to POSIX/Unix/Linux/Winsock-like syscalls" documentation = "https://docs.rs/rustix" license = "Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT" repository = "https://github.com/bytecodealliance/rustix" -edition = "2021" +edition = "2024" keywords = ["api", "file", "network", "safe", "syscall"] categories = ["os::unix-apis", "date-and-time", "filesystem", "network-programming"] include = ["src", "build.rs", "Cargo.toml", "COPYRIGHT", "LICENSE*", "/*.md", "benches"] -rust-version = "1.63" +rust-version = "1.85" [dependencies] bitflags = { version = "2.4.0", default-features = false } @@ -73,10 +73,6 @@ memoffset = "0.9.0" flate2 = "1.0" static_assertions = "1.1.0" -# With Rust 1.70 this can be removed in favor of `std::sync::OnceLock`. -[target.'cfg(windows)'.dev-dependencies] -once_cell = "1.20.3" - [target.'cfg(all(criterion, not(any(target_os = "emscripten", target_os = "wasi"))))'.dev-dependencies] criterion = "0.4" @@ -109,8 +105,7 @@ targets = [ # By default, use `std`. default = ["std"] -# This enables use of std. Disabling this enables `#![no_std]`, and requires -# Rust 1.77 or newer. +# This enables use of std. Disabling this enables `#![no_std]`. std = ["bitflags/std", "alloc", "libc?/std", "libc_errno?/std"] # Enable this to request the libc backend. diff --git a/benches/mod.rs b/benches/mod.rs index 966353923..17fd1f8a0 100644 --- a/benches/mod.rs +++ b/benches/mod.rs @@ -53,7 +53,7 @@ mod suite { use criterion::Criterion; pub(super) fn simple_statat(c: &mut Criterion) { - use rustix::fs::{statat, AtFlags, CWD}; + use rustix::fs::{AtFlags, CWD, statat}; c.bench_function("simple statat", |b| { b.iter(|| { @@ -101,7 +101,7 @@ mod suite { } pub(super) fn simple_statat_cstr(c: &mut Criterion) { - use rustix::fs::{statat, AtFlags, CWD}; + use rustix::fs::{AtFlags, CWD, statat}; c.bench_function("simple statat cstr", |b| { b.iter(|| { @@ -133,7 +133,7 @@ mod suite { #[cfg(not(target_os = "wasi"))] pub(super) fn simple_clock_gettime(c: &mut Criterion) { - use rustix::time::{clock_gettime, ClockId}; + use rustix::time::{ClockId, clock_gettime}; c.bench_function("simple clock_gettime", |b| { b.iter(|| { diff --git a/build.rs b/build.rs index 6a69dc4a3..1c70ca4bd 100644 --- a/build.rs +++ b/build.rs @@ -74,11 +74,6 @@ fn main() { use_feature_or_nothing("error_in_core"); } - // Feature needed for testing. - if use_static_assertions() { - use_feature("static_assertions"); - } - // WASI support can utilize wasi_ext if present. if os == "wasi" { use_feature_or_nothing("wasi_ext"); @@ -177,11 +172,6 @@ fn main() { println!("cargo:rerun-if-env-changed=CARGO_CFG_MIRI"); } -fn use_static_assertions() -> bool { - // `offset_from` was made const in Rust 1.65. - can_compile("const unsafe fn foo(p: *const u8) -> isize { p.offset_from(p) }") -} - fn use_thumb_mode() -> bool { // In thumb mode, r7 is reserved. !can_compile("pub unsafe fn f() { core::arch::asm!(\"udf #16\", in(\"r7\") 0); }") diff --git a/examples/termios.rs b/examples/termios.rs index cd2b7fd34..006acabd5 100644 --- a/examples/termios.rs +++ b/examples/termios.rs @@ -3,7 +3,7 @@ #[cfg(all(not(windows), feature = "termios"))] fn main() -> std::io::Result<()> { - use rustix::termios::{tcgetattr, tcsetattr, OptionalActions}; + use rustix::termios::{OptionalActions, tcgetattr, tcsetattr}; use std::io::{Read as _, Write as _}; let tty = std::io::stdin(); diff --git a/examples/time.rs b/examples/time.rs index c1ac01941..3abb3dadb 100644 --- a/examples/time.rs +++ b/examples/time.rs @@ -4,7 +4,7 @@ #[cfg(not(any(windows, target_os = "espidf")))] #[cfg(feature = "time")] fn main() { - use rustix::time::{clock_gettime, ClockId}; + use rustix::time::{ClockId, clock_gettime}; println!("Real time: {:?}", clock_gettime(ClockId::Realtime)); println!("Monotonic time: {:?}", clock_gettime(ClockId::Monotonic)); diff --git a/src/backend/libc/c.rs b/src/backend/libc/c.rs index 2f737c21c..81b29131d 100644 --- a/src/backend/libc/c.rs +++ b/src/backend/libc/c.rs @@ -105,8 +105,8 @@ pub(crate) const O_LARGEFILE: c_int = 0x2000; any(target_arch = "powerpc", target_arch = "powerpc64") ))] pub(crate) use { - termios as termios2, TCGETS as TCGETS2, TCSETS as TCSETS2, TCSETSF as TCSETSF2, - TCSETSW as TCSETSW2, + TCGETS as TCGETS2, TCSETS as TCSETS2, TCSETSF as TCSETSF2, TCSETSW as TCSETSW2, + termios as termios2, }; // And PowerPC doesn't define `CIBAUD`, but it does define `IBSHIFT`, so we can @@ -140,19 +140,19 @@ pub(super) use {blkcnt64_t as blkcnt_t, rlim64_t as rlim_t}; // to the upstream libc crate and implement rustix's `statat` etc. with them. #[cfg(target_os = "aix")] pub(super) use { - blksize64_t as blksize_t, fstat64 as fstat, fstatfs64 as fstatfs, fstatvfs64 as fstatvfs, - ftruncate64 as ftruncate, getrlimit64 as getrlimit, ino_t, lseek64 as lseek, mmap, - off64_t as off_t, openat, posix_fadvise64 as posix_fadvise, preadv, pwritev, - rlimit64 as rlimit, setrlimit64 as setrlimit, stat64at as fstatat, statfs64 as statfs, - statvfs64 as statvfs, RLIM_INFINITY, + RLIM_INFINITY, blksize64_t as blksize_t, fstat64 as fstat, fstatfs64 as fstatfs, + fstatvfs64 as fstatvfs, ftruncate64 as ftruncate, getrlimit64 as getrlimit, ino_t, + lseek64 as lseek, mmap, off64_t as off_t, openat, posix_fadvise64 as posix_fadvise, preadv, + pwritev, rlimit64 as rlimit, setrlimit64 as setrlimit, stat64at as fstatat, statfs64 as statfs, + statvfs64 as statvfs, }; #[cfg(any(linux_like, target_os = "hurd"))] pub(super) use { - fstat64 as fstat, fstatat64 as fstatat, fstatfs64 as fstatfs, fstatvfs64 as fstatvfs, - ftruncate64 as ftruncate, getrlimit64 as getrlimit, ino64_t as ino_t, lseek64 as lseek, - mmap64 as mmap, off64_t as off_t, openat64 as openat, posix_fadvise64 as posix_fadvise, - rlimit64 as rlimit, setrlimit64 as setrlimit, statfs64 as statfs, statvfs64 as statvfs, - RLIM64_INFINITY as RLIM_INFINITY, + RLIM64_INFINITY as RLIM_INFINITY, fstat64 as fstat, fstatat64 as fstatat, fstatfs64 as fstatfs, + fstatvfs64 as fstatvfs, ftruncate64 as ftruncate, getrlimit64 as getrlimit, ino64_t as ino_t, + lseek64 as lseek, mmap64 as mmap, off64_t as off_t, openat64 as openat, + posix_fadvise64 as posix_fadvise, rlimit64 as rlimit, setrlimit64 as setrlimit, + statfs64 as statfs, statvfs64 as statvfs, }; #[cfg(apple)] pub(super) use { @@ -186,17 +186,19 @@ pub(super) unsafe fn prlimit( new_limit: *const rlimit64, old_limit: *mut rlimit64, ) -> c_int { - // `prlimit64` wasn't supported in glibc until 2.13. - weak_or_syscall! { - fn prlimit64( - pid: pid_t, - resource: __rlimit_resource_t, - new_limit: *const rlimit64, - old_limit: *mut rlimit64 - ) via SYS_prlimit64 -> c_int - } + unsafe { + // `prlimit64` wasn't supported in glibc until 2.13. + weak_or_syscall! { + fn prlimit64( + pid: pid_t, + resource: __rlimit_resource_t, + new_limit: *const rlimit64, + old_limit: *mut rlimit64 + ) via SYS_prlimit64 -> c_int + } - prlimit64(pid, resource, new_limit, old_limit) + prlimit64(pid, resource, new_limit, old_limit) + } } #[cfg(all(target_os = "linux", target_env = "musl"))] @@ -339,37 +341,39 @@ mod readwrite_pv64v2 { offset: off64_t, flags: c_int, ) -> ssize_t { - // Older glibc lacks `preadv64v2`, so use the `weak!` mechanism to - // test for it, and call back to `syscall`. We don't use - // `weak_or_syscall` here because we need to pass the 64-bit offset - // specially. - weak! { - fn preadv64v2(c_int, *const iovec, c_int, off64_t, c_int) -> ssize_t - } - if let Some(fun) = preadv64v2.get() { - fun(fd, iov, iovcnt, offset, flags) - } else { - // Unlike the plain "p" functions, the "pv" functions pass their - // offset in an endian-independent way, and always in two - // registers. - syscall! { - fn preadv2( - fd: c_int, - iov: *const iovec, - iovcnt: c_int, - offset_lo: usize, - offset_hi: usize, - flags: c_int - ) via SYS_preadv2 -> ssize_t + unsafe { + // Older glibc lacks `preadv64v2`, so use the `weak!` mechanism to + // test for it, and call back to `syscall`. We don't use + // `weak_or_syscall` here because we need to pass the 64-bit offset + // specially. + weak! { + fn preadv64v2(c_int, *const iovec, c_int, off64_t, c_int) -> ssize_t + } + if let Some(fun) = preadv64v2.get() { + fun(fd, iov, iovcnt, offset, flags) + } else { + // Unlike the plain "p" functions, the "pv" functions pass their + // offset in an endian-independent way, and always in two + // registers. + syscall! { + fn preadv2( + fd: c_int, + iov: *const iovec, + iovcnt: c_int, + offset_lo: usize, + offset_hi: usize, + flags: c_int + ) via SYS_preadv2 -> ssize_t + } + preadv2( + fd, + iov, + iovcnt, + offset as usize, + (offset >> 32) as usize, + flags, + ) } - preadv2( - fd, - iov, - iovcnt, - offset as usize, - (offset >> 32) as usize, - flags, - ) } } pub(in super::super) unsafe fn pwritev64v2( @@ -379,34 +383,36 @@ mod readwrite_pv64v2 { offset: off64_t, flags: c_int, ) -> ssize_t { - // See the comments in `preadv64v2`. - weak! { - fn pwritev64v2(c_int, *const iovec, c_int, off64_t, c_int) -> ssize_t - } - if let Some(fun) = pwritev64v2.get() { - fun(fd, iov, iovcnt, offset, flags) - } else { - // Unlike the plain "p" functions, the "pv" functions pass their - // offset in an endian-independent way, and always in two - // registers. - syscall! { - fn pwritev2( - fd: c_int, - iov: *const iovec, - iovec: c_int, - offset_lo: usize, - offset_hi: usize, - flags: c_int - ) via SYS_pwritev2 -> ssize_t + unsafe { + // See the comments in `preadv64v2`. + weak! { + fn pwritev64v2(c_int, *const iovec, c_int, off64_t, c_int) -> ssize_t + } + if let Some(fun) = pwritev64v2.get() { + fun(fd, iov, iovcnt, offset, flags) + } else { + // Unlike the plain "p" functions, the "pv" functions pass their + // offset in an endian-independent way, and always in two + // registers. + syscall! { + fn pwritev2( + fd: c_int, + iov: *const iovec, + iovec: c_int, + offset_lo: usize, + offset_hi: usize, + flags: c_int + ) via SYS_pwritev2 -> ssize_t + } + pwritev2( + fd, + iov, + iovcnt, + offset as usize, + (offset >> 32) as usize, + flags, + ) } - pwritev2( - fd, - iov, - iovcnt, - offset as usize, - (offset >> 32) as usize, - flags, - ) } } } diff --git a/src/backend/libc/conv.rs b/src/backend/libc/conv.rs index 1cb1fc93a..e4896158f 100644 --- a/src/backend/libc/conv.rs +++ b/src/backend/libc/conv.rs @@ -129,10 +129,12 @@ pub(super) fn ret_pid_t(raw: c::pid_t) -> io::Result { /// which returns an owned file descriptor. #[inline] pub(super) unsafe fn ret_owned_fd(raw: LibcFd) -> io::Result { - if raw == !0 { - Err(io::Errno::last_os_error()) - } else { - Ok(OwnedFd::from_raw_fd(raw as RawFd)) + unsafe { + if raw == !0 { + Err(io::Errno::last_os_error()) + } else { + Ok(OwnedFd::from_raw_fd(raw as RawFd)) + } } } diff --git a/src/backend/libc/event/syscalls.rs b/src/backend/libc/event/syscalls.rs index 33d7c94ed..4dbfcb80c 100644 --- a/src/backend/libc/event/syscalls.rs +++ b/src/backend/libc/event/syscalls.rs @@ -6,8 +6,6 @@ use crate::backend::conv::ret; use crate::backend::conv::ret_c_int; #[cfg(any(linux_kernel, target_os = "illumos", target_os = "redox"))] use crate::backend::conv::ret_u32; -#[cfg(solarish)] -use crate::event::port::Event; #[cfg(any( linux_kernel, target_os = "freebsd", @@ -17,6 +15,8 @@ use crate::event::port::Event; use crate::event::EventfdFlags; #[cfg(any(bsd, linux_kernel, target_os = "wasi"))] use crate::event::FdSetElement; +#[cfg(solarish)] +use crate::event::port::Event; use crate::event::{PollFd, Timespec}; use crate::io; #[cfg(any(linux_kernel, target_os = "illumos", target_os = "redox"))] @@ -200,71 +200,73 @@ pub(crate) unsafe fn select( exceptfds: Option<&mut [FdSetElement]>, timeout: Option<&Timespec>, ) -> io::Result { - let len = crate::event::fd_set_num_elements_for_bitvector(nfds); + unsafe { + let len = crate::event::fd_set_num_elements_for_bitvector(nfds); - let readfds = match readfds { - Some(readfds) => { - assert!(readfds.len() >= len); - readfds.as_mut_ptr() - } - None => null_mut(), - }; - let writefds = match writefds { - Some(writefds) => { - assert!(writefds.len() >= len); - writefds.as_mut_ptr() - } - None => null_mut(), - }; - let exceptfds = match exceptfds { - Some(exceptfds) => { - assert!(exceptfds.len() >= len); - exceptfds.as_mut_ptr() - } - None => null_mut(), - }; + let readfds = match readfds { + Some(readfds) => { + assert!(readfds.len() >= len); + readfds.as_mut_ptr() + } + None => null_mut(), + }; + let writefds = match writefds { + Some(writefds) => { + assert!(writefds.len() >= len); + writefds.as_mut_ptr() + } + None => null_mut(), + }; + let exceptfds = match exceptfds { + Some(exceptfds) => { + assert!(exceptfds.len() >= len); + exceptfds.as_mut_ptr() + } + None => null_mut(), + }; - let timeout_data; - let timeout_ptr = match timeout { - Some(timeout) => { - // Convert from `Timespec` to `c::timeval`. - timeout_data = c::timeval { - tv_sec: timeout.tv_sec.try_into().map_err(|_| io::Errno::INVAL)?, - tv_usec: ((timeout.tv_nsec + 999) / 1000) as _, - }; - &timeout_data - } - None => null(), - }; + let timeout_data; + let timeout_ptr = match timeout { + Some(timeout) => { + // Convert from `Timespec` to `c::timeval`. + timeout_data = c::timeval { + tv_sec: timeout.tv_sec.try_into().map_err(|_| io::Errno::INVAL)?, + tv_usec: timeout.tv_nsec.div_ceil(1000) as _, + }; + &timeout_data + } + None => null(), + }; - // On Apple platforms, use the specially mangled `select` which doesn't - // have an `FD_SETSIZE` limitation. - #[cfg(apple)] - { - extern "C" { - #[link_name = "select$DARWIN_EXTSN$NOCANCEL"] - fn select( - nfds: c::c_int, - readfds: *mut FdSetElement, - writefds: *mut FdSetElement, - errorfds: *mut FdSetElement, - timeout: *const c::timeval, - ) -> c::c_int; - } + // On Apple platforms, use the specially mangled `select` which doesn't + // have an `FD_SETSIZE` limitation. + #[cfg(apple)] + { + extern "C" { + #[link_name = "select$DARWIN_EXTSN$NOCANCEL"] + fn select( + nfds: c::c_int, + readfds: *mut FdSetElement, + writefds: *mut FdSetElement, + errorfds: *mut FdSetElement, + timeout: *const c::timeval, + ) -> c::c_int; + } - ret_c_int(select(nfds, readfds, writefds, exceptfds, timeout_ptr)) - } + ret_c_int(select(nfds, readfds, writefds, exceptfds, timeout_ptr)) + } - // Otherwise just use the normal `select`. - #[cfg(not(apple))] - { - ret_c_int(c::select( - nfds, - readfds.cast(), - writefds.cast(), - exceptfds.cast(), - timeout_ptr as *mut c::timeval, - )) + // Otherwise just use the normal `select`. + #[cfg(not(apple))] + { + ret_c_int(c::select( + nfds, + readfds.cast(), + writefds.cast(), + exceptfds.cast(), + timeout_ptr as *mut c::timeval, + )) + } } } @@ -307,7 +309,7 @@ pub(crate) unsafe fn select( // Convert from `Timespec` to `c::timeval`. timeout_data = c::timeval { tv_sec: timeout.tv_sec.try_into().map_err(|_| io::Errno::INVAL)?, - tv_usec: ((timeout.tv_nsec + 999) / 1000) as _, + tv_usec: timeout.tv_nsec.div_ceil(1000) as _, }; &timeout_data } @@ -379,12 +381,11 @@ pub(crate) fn port_get(port: BorrowedFd<'_>, timeout: Option<&Timespec>) -> io:: let mut event = MaybeUninit::::uninit(); - // In Rust ≥ 1.65, the `as _` can be `.cast_mut()`. unsafe { ret(c::port_get( borrowed_fd(port), event.as_mut_ptr(), - timeout as _, + timeout.cast_mut(), ))?; } @@ -426,13 +427,12 @@ pub(crate) unsafe fn port_getn( return Ok(0); } - // In Rust ≥ 1.65, the `as _` can be `.cast_mut()`. ret(c::port_getn( borrowed_fd(port), events.0.cast(), events.1.try_into().unwrap_or(u32::MAX), &mut nget, - timeout as _, + timeout.cast_mut(), ))?; Ok(nget as usize) @@ -546,7 +546,7 @@ pub(crate) unsafe fn epoll_wait( target_env = "gnu", not(fix_y2038) ))] - { + unsafe { weak! { fn epoll_pwait2( c::c_int, @@ -569,7 +569,7 @@ pub(crate) unsafe fn epoll_wait( } } - // If we're on Linux ≥ 5.11, use `epoll_pwait2` via `libc::syscall`. + // If we're on Linux >= 5.11, use `epoll_pwait2` via `libc::syscall`. #[cfg(all(linux_kernel, feature = "linux_5_11"))] { syscall! { @@ -594,7 +594,7 @@ pub(crate) unsafe fn epoll_wait( // Otherwise just use `epoll_wait`. #[cfg(not(all(linux_kernel, feature = "linux_5_11")))] - { + unsafe { let timeout = match timeout { None => -1, Some(timeout) => timeout.as_c_int_millis().ok_or(io::Errno::INVAL)?, diff --git a/src/backend/libc/event/windows_syscalls.rs b/src/backend/libc/event/windows_syscalls.rs index 05394f55d..b13587078 100644 --- a/src/backend/libc/event/windows_syscalls.rs +++ b/src/backend/libc/event/windows_syscalls.rs @@ -60,7 +60,7 @@ pub(crate) fn select( .tv_sec .try_into() .map_err(|_| io::Errno::OPNOTSUPP)?, - tv_usec: ((timeout.tv_nsec + 999) / 1000) as _, + tv_usec: timeout.tv_nsec.div_ceil(1000) as _, }; &timeout_data } diff --git a/src/backend/libc/fs/dir.rs b/src/backend/libc/fs/dir.rs index cd7f232d3..c207fd8f3 100644 --- a/src/backend/libc/fs/dir.rs +++ b/src/backend/libc/fs/dir.rs @@ -10,9 +10,9 @@ use crate::backend::c; use crate::backend::conv::owned_fd; use crate::fd::{AsFd, BorrowedFd, OwnedFd}; use crate::ffi::{CStr, CString}; -use crate::fs::{fcntl_getfl, openat, Mode, OFlags}; +use crate::fs::{Mode, OFlags, fcntl_getfl, openat}; #[cfg(not(target_os = "vita"))] -use crate::fs::{fstat, Stat}; +use crate::fs::{Stat, fstat}; #[cfg(not(any( solarish, target_os = "haiku", @@ -23,7 +23,7 @@ use crate::fs::{fstat, Stat}; target_os = "vita", target_os = "wasi", )))] -use crate::fs::{fstatfs, StatFs}; +use crate::fs::{StatFs, fstatfs}; #[cfg(not(any( solarish, target_os = "haiku", @@ -31,7 +31,7 @@ use crate::fs::{fstatfs, StatFs}; target_os = "vita", target_os = "wasi" )))] -use crate::fs::{fstatvfs, StatVfs}; +use crate::fs::{StatVfs, fstatvfs}; use crate::io; #[cfg(not(any(target_os = "fuchsia", target_os = "vita", target_os = "wasi")))] #[cfg(feature = "process")] @@ -43,7 +43,7 @@ use c::readdir as libc_readdir; use c::readdir64 as libc_readdir; use core::fmt; use core::ptr::NonNull; -use libc_errno::{errno, set_errno, Errno}; +use libc_errno::{Errno, errno, set_errno}; /// `DIR*` pub struct Dir { @@ -296,7 +296,10 @@ impl fmt::Debug for Dir { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut s = f.debug_struct("Dir"); #[cfg(not(any(target_os = "horizon", target_os = "vita")))] - s.field("fd", unsafe { &c::dirfd(self.libc_dir.as_ptr()) }); + { + let fd = unsafe { c::dirfd(self.libc_dir.as_ptr()) }; + s.field("fd", &fd); + } s.finish() } } diff --git a/src/backend/libc/fs/syscalls.rs b/src/backend/libc/fs/syscalls.rs index ae7b7af61..4e1c217e1 100644 --- a/src/backend/libc/fs/syscalls.rs +++ b/src/backend/libc/fs/syscalls.rs @@ -73,7 +73,7 @@ use core::mem::MaybeUninit; #[cfg(apple)] use { crate::backend::conv::nonnegative_ret, - crate::fs::{copyfile_state_t, CloneFlags, CopyfileFlags}, + crate::fs::{CloneFlags, CopyfileFlags, copyfile_state_t}, }; #[cfg(not(any( apple, @@ -91,7 +91,7 @@ use {crate::fs::Advice, core::num::NonZeroU64}; use {crate::fs::XattrFlags, core::mem::size_of, core::ptr::null_mut}; #[cfg(linux_kernel)] use { - crate::fs::{ResolveFlags, Statx, StatxFlags, CWD}, + crate::fs::{CWD, ResolveFlags, Statx, StatxFlags}, core::ptr::null, }; @@ -294,7 +294,9 @@ pub(crate) unsafe fn readlinkat( path: &CStr, buf: (*mut u8, usize), ) -> io::Result { - ret_usize(c::readlinkat(borrowed_fd(dirfd), c_str(path), buf.0.cast(), buf.1) as isize) + unsafe { + ret_usize(c::readlinkat(borrowed_fd(dirfd), c_str(path), buf.0.cast(), buf.1) as isize) + } } pub(crate) fn mkdir(path: &CStr, mode: Mode) -> io::Result<()> { @@ -1355,7 +1357,7 @@ pub(crate) fn fcntl_add_seals(fd: BorrowedFd<'_>, seals: SealFlags) -> io::Resul )))] #[inline] pub(crate) fn fcntl_lock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::Result<()> { - use c::{flock, F_RDLCK, F_SETLK, F_SETLKW, F_UNLCK, F_WRLCK, SEEK_SET}; + use c::{F_RDLCK, F_SETLK, F_SETLKW, F_UNLCK, F_WRLCK, SEEK_SET, flock}; let (cmd, l_type) = match operation { FlockOperation::LockShared => (F_SETLKW, F_RDLCK), @@ -2016,7 +2018,7 @@ fn stat64_to_stat(s64: c::stat64) -> io::Result { #[cfg(linux_kernel)] #[allow(non_upper_case_globals)] mod sys { - use super::{c, ffi, BorrowedFd, Statx}; + use super::{BorrowedFd, Statx, c, ffi}; weak_or_syscall! { pub(super) fn statx( @@ -2351,33 +2353,35 @@ pub(crate) unsafe fn getxattr( name: &CStr, value: (*mut u8, usize), ) -> io::Result { - #[cfg(not(apple))] - { - ret_usize(c::getxattr( - path.as_ptr(), - name.as_ptr(), - value.0.cast::(), - value.1, - )) - } + unsafe { + #[cfg(not(apple))] + { + ret_usize(c::getxattr( + path.as_ptr(), + name.as_ptr(), + value.0.cast::(), + value.1, + )) + } - #[cfg(apple)] - { - // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS. - // Pass null instead. - let ptr = if value.1 == 0 { - core::ptr::null_mut() - } else { - value.0.cast::() - }; - ret_usize(c::getxattr( - path.as_ptr(), - name.as_ptr(), - ptr, - value.1, - 0, - 0, - )) + #[cfg(apple)] + { + // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS. + // Pass null instead. + let ptr = if value.1 == 0 { + core::ptr::null_mut() + } else { + value.0.cast::() + }; + ret_usize(c::getxattr( + path.as_ptr(), + name.as_ptr(), + ptr, + value.1, + 0, + 0, + )) + } } } @@ -2387,34 +2391,36 @@ pub(crate) unsafe fn lgetxattr( name: &CStr, value: (*mut u8, usize), ) -> io::Result { - #[cfg(not(apple))] - { - ret_usize(c::lgetxattr( - path.as_ptr(), - name.as_ptr(), - value.0.cast::(), - value.1, - )) - } + unsafe { + #[cfg(not(apple))] + { + ret_usize(c::lgetxattr( + path.as_ptr(), + name.as_ptr(), + value.0.cast::(), + value.1, + )) + } - #[cfg(apple)] - { - // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS. - // Pass null instead. - let ptr = if value.1 == 0 { - core::ptr::null_mut() - } else { - value.0.cast::() - }; + #[cfg(apple)] + { + // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS. + // Pass null instead. + let ptr = if value.1 == 0 { + core::ptr::null_mut() + } else { + value.0.cast::() + }; - ret_usize(c::getxattr( - path.as_ptr(), - name.as_ptr(), - ptr, - value.1, - 0, - c::XATTR_NOFOLLOW, - )) + ret_usize(c::getxattr( + path.as_ptr(), + name.as_ptr(), + ptr, + value.1, + 0, + c::XATTR_NOFOLLOW, + )) + } } } @@ -2424,33 +2430,35 @@ pub(crate) unsafe fn fgetxattr( name: &CStr, value: (*mut u8, usize), ) -> io::Result { - #[cfg(not(apple))] - { - ret_usize(c::fgetxattr( - borrowed_fd(fd), - name.as_ptr(), - value.0.cast::(), - value.1, - )) - } + unsafe { + #[cfg(not(apple))] + { + ret_usize(c::fgetxattr( + borrowed_fd(fd), + name.as_ptr(), + value.0.cast::(), + value.1, + )) + } - #[cfg(apple)] - { - // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS. - // Pass null instead. - let ptr = if value.1 == 0 { - core::ptr::null_mut() - } else { - value.0.cast::() - }; - ret_usize(c::fgetxattr( - borrowed_fd(fd), - name.as_ptr(), - ptr, - value.1, - 0, - 0, - )) + #[cfg(apple)] + { + // Passing an empty to slice to `getxattr` leads to `ERANGE` on macOS. + // Pass null instead. + let ptr = if value.1 == 0 { + core::ptr::null_mut() + } else { + value.0.cast::() + }; + ret_usize(c::fgetxattr( + borrowed_fd(fd), + name.as_ptr(), + ptr, + value.1, + 0, + 0, + )) + } } } @@ -2549,60 +2557,66 @@ pub(crate) fn fsetxattr( #[cfg(any(apple, linux_kernel, target_os = "hurd"))] pub(crate) unsafe fn listxattr(path: &CStr, list: (*mut u8, usize)) -> io::Result { - #[cfg(not(apple))] - { - ret_usize(c::listxattr( - path.as_ptr(), - list.0.cast::(), - list.1, - )) - } + unsafe { + #[cfg(not(apple))] + { + ret_usize(c::listxattr( + path.as_ptr(), + list.0.cast::(), + list.1, + )) + } - #[cfg(apple)] - { - ret_usize(c::listxattr( - path.as_ptr(), - list.0.cast::(), - list.1, - 0, - )) + #[cfg(apple)] + { + ret_usize(c::listxattr( + path.as_ptr(), + list.0.cast::(), + list.1, + 0, + )) + } } } #[cfg(any(apple, linux_kernel, target_os = "hurd"))] pub(crate) unsafe fn llistxattr(path: &CStr, list: (*mut u8, usize)) -> io::Result { - #[cfg(not(apple))] - { - ret_usize(c::llistxattr( - path.as_ptr(), - list.0.cast::(), - list.1, - )) - } + unsafe { + #[cfg(not(apple))] + { + ret_usize(c::llistxattr( + path.as_ptr(), + list.0.cast::(), + list.1, + )) + } - #[cfg(apple)] - { - ret_usize(c::listxattr( - path.as_ptr(), - list.0.cast::(), - list.1, - c::XATTR_NOFOLLOW, - )) + #[cfg(apple)] + { + ret_usize(c::listxattr( + path.as_ptr(), + list.0.cast::(), + list.1, + c::XATTR_NOFOLLOW, + )) + } } } #[cfg(any(apple, linux_kernel, target_os = "hurd"))] pub(crate) unsafe fn flistxattr(fd: BorrowedFd<'_>, list: (*mut u8, usize)) -> io::Result { - let fd = borrowed_fd(fd); + unsafe { + let fd = borrowed_fd(fd); - #[cfg(not(apple))] - { - ret_usize(c::flistxattr(fd, list.0.cast::(), list.1)) - } + #[cfg(not(apple))] + { + ret_usize(c::flistxattr(fd, list.0.cast::(), list.1)) + } - #[cfg(apple)] - { - ret_usize(c::flistxattr(fd, list.0.cast::(), list.1, 0)) + #[cfg(apple)] + { + ret_usize(c::flistxattr(fd, list.0.cast::(), list.1, 0)) + } } } diff --git a/src/backend/libc/io/syscalls.rs b/src/backend/libc/io/syscalls.rs index cdae88eca..9c1ac173f 100644 --- a/src/backend/libc/io/syscalls.rs +++ b/src/backend/libc/io/syscalls.rs @@ -25,11 +25,13 @@ use { }; pub(crate) unsafe fn read(fd: BorrowedFd<'_>, buf: (*mut u8, usize)) -> io::Result { - ret_usize(c::read( - borrowed_fd(fd), - buf.0.cast(), - min(buf.1, READ_LIMIT), - )) + unsafe { + ret_usize(c::read( + borrowed_fd(fd), + buf.0.cast(), + min(buf.1, READ_LIMIT), + )) + } } pub(crate) fn write(fd: BorrowedFd<'_>, buf: &[u8]) -> io::Result { @@ -47,16 +49,18 @@ pub(crate) unsafe fn pread( buf: (*mut u8, usize), offset: u64, ) -> io::Result { - let len = min(buf.1, READ_LIMIT); + unsafe { + let len = min(buf.1, READ_LIMIT); - // Silently cast; we'll get `EINVAL` if the value is negative. - let offset = offset as i64; + // Silently cast; we'll get `EINVAL` if the value is negative. + let offset = offset as i64; - // ESP-IDF and Vita don't support 64-bit offsets. - #[cfg(any(target_os = "espidf", target_os = "vita"))] - let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?; + // ESP-IDF and Vita don't support 64-bit offsets. + #[cfg(any(target_os = "espidf", target_os = "vita"))] + let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?; - ret_usize(c::pread(borrowed_fd(fd), buf.0.cast(), len, offset)) + ret_usize(c::pread(borrowed_fd(fd), buf.0.cast(), len, offset)) + } } pub(crate) fn pwrite(fd: BorrowedFd<'_>, buf: &[u8], offset: u64) -> io::Result { @@ -201,12 +205,14 @@ const READ_LIMIT: usize = c::c_int::MAX as usize - 1; const READ_LIMIT: usize = c::ssize_t::MAX as usize; pub(crate) unsafe fn close(raw_fd: RawFd) { - let _ = c::close(raw_fd as c::c_int); + unsafe { + let _ = c::close(raw_fd as c::c_int); + } } #[cfg(feature = "try_close")] pub(crate) unsafe fn try_close(raw_fd: RawFd) -> io::Result<()> { - ret(c::close(raw_fd as c::c_int)) + unsafe { ret(c::close(raw_fd as c::c_int)) } } #[inline] @@ -215,7 +221,7 @@ pub(crate) unsafe fn ioctl( request: Opcode, arg: *mut c::c_void, ) -> io::Result { - ret_c_int(c::ioctl(borrowed_fd(fd), request, arg)) + unsafe { ret_c_int(c::ioctl(borrowed_fd(fd), request, arg)) } } #[inline] @@ -224,7 +230,7 @@ pub(crate) unsafe fn ioctl_readonly( request: Opcode, arg: *mut c::c_void, ) -> io::Result { - ioctl(fd, request, arg) + unsafe { ioctl(fd, request, arg) } } pub(crate) fn fcntl_getfd(fd: BorrowedFd<'_>) -> io::Result { diff --git a/src/backend/libc/io_uring/syscalls.rs b/src/backend/libc/io_uring/syscalls.rs index 8bf1e987a..40f3de0a2 100644 --- a/src/backend/libc/io_uring/syscalls.rs +++ b/src/backend/libc/io_uring/syscalls.rs @@ -4,7 +4,7 @@ use crate::backend::c; use crate::backend::conv::{borrowed_fd, ret_owned_fd, ret_u32}; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io; -use crate::io_uring::{io_uring_params, IoringEnterFlags, IoringRegisterFlags, IoringRegisterOp}; +use crate::io_uring::{IoringEnterFlags, IoringRegisterFlags, IoringRegisterOp, io_uring_params}; #[inline] pub(crate) fn io_uring_setup(entries: u32, params: &mut io_uring_params) -> io::Result { @@ -24,20 +24,22 @@ pub(crate) unsafe fn io_uring_register( arg: *const c::c_void, nr_args: u32, ) -> io::Result { - syscall! { - fn io_uring_register( - fd: c::c_uint, - opcode: c::c_uint, - arg: *const c::c_void, - nr_args: c::c_uint - ) via SYS_io_uring_register -> c::c_int + unsafe { + syscall! { + fn io_uring_register( + fd: c::c_uint, + opcode: c::c_uint, + arg: *const c::c_void, + nr_args: c::c_uint + ) via SYS_io_uring_register -> c::c_int + } + ret_u32(io_uring_register( + borrowed_fd(fd) as _, + opcode as u32, + arg, + nr_args, + )) } - ret_u32(io_uring_register( - borrowed_fd(fd) as _, - opcode as u32, - arg, - nr_args, - )) } #[inline] @@ -48,20 +50,22 @@ pub(crate) unsafe fn io_uring_register_with( arg: *const c::c_void, nr_args: u32, ) -> io::Result { - syscall! { - fn io_uring_register( - fd: c::c_uint, - opcode: c::c_uint, - arg: *const c::c_void, - nr_args: c::c_uint - ) via SYS_io_uring_register -> c::c_int + unsafe { + syscall! { + fn io_uring_register( + fd: c::c_uint, + opcode: c::c_uint, + arg: *const c::c_void, + nr_args: c::c_uint + ) via SYS_io_uring_register -> c::c_int + } + ret_u32(io_uring_register( + borrowed_fd(fd) as _, + (opcode as u32) | bitflags_bits!(flags), + arg, + nr_args, + )) } - ret_u32(io_uring_register( - borrowed_fd(fd) as _, - (opcode as u32) | bitflags_bits!(flags), - arg, - nr_args, - )) } #[inline] @@ -73,22 +77,24 @@ pub(crate) unsafe fn io_uring_enter( arg: *const c::c_void, size: usize, ) -> io::Result { - syscall! { - fn io_uring_enter2( - fd: c::c_uint, - to_submit: c::c_uint, - min_complete: c::c_uint, - flags: c::c_uint, - arg: *const c::c_void, - size: usize - ) via SYS_io_uring_enter -> c::c_int + unsafe { + syscall! { + fn io_uring_enter2( + fd: c::c_uint, + to_submit: c::c_uint, + min_complete: c::c_uint, + flags: c::c_uint, + arg: *const c::c_void, + size: usize + ) via SYS_io_uring_enter -> c::c_int + } + ret_u32(io_uring_enter2( + borrowed_fd(fd) as _, + to_submit, + min_complete, + bitflags_bits!(flags), + arg, + size, + )) } - ret_u32(io_uring_enter2( - borrowed_fd(fd) as _, - to_submit, - min_complete, - bitflags_bits!(flags), - arg, - size, - )) } diff --git a/src/backend/libc/mm/syscalls.rs b/src/backend/libc/mm/syscalls.rs index 33bc9cac1..643c4992c 100644 --- a/src/backend/libc/mm/syscalls.rs +++ b/src/backend/libc/mm/syscalls.rs @@ -53,13 +53,15 @@ pub(crate) fn madvise(addr: *mut c::c_void, len: usize, advice: Advice) -> io::R } pub(crate) unsafe fn msync(addr: *mut c::c_void, len: usize, flags: MsyncFlags) -> io::Result<()> { - let err = c::msync(addr, len, bitflags_bits!(flags)); + unsafe { + let err = c::msync(addr, len, bitflags_bits!(flags)); - // `msync` returns its error status rather than using `errno`. - if err == 0 { - Ok(()) - } else { - Err(io::Errno(err)) + // `msync` returns its error status rather than using `errno`. + if err == 0 { + Ok(()) + } else { + Err(io::Errno(err)) + } } } @@ -75,18 +77,20 @@ pub(crate) unsafe fn mmap( fd: BorrowedFd<'_>, offset: u64, ) -> io::Result<*mut c::c_void> { - let res = c::mmap( - ptr, - len, - bitflags_bits!(prot), - bitflags_bits!(flags), - borrowed_fd(fd), - offset as i64, - ); - if res == c::MAP_FAILED { - Err(io::Errno::last_os_error()) - } else { - Ok(res) + unsafe { + let res = c::mmap( + ptr, + len, + bitflags_bits!(prot), + bitflags_bits!(flags), + borrowed_fd(fd), + offset as i64, + ); + if res == c::MAP_FAILED { + Err(io::Errno::last_os_error()) + } else { + Ok(res) + } } } @@ -100,18 +104,20 @@ pub(crate) unsafe fn mmap_anonymous( prot: ProtFlags, flags: MapFlags, ) -> io::Result<*mut c::c_void> { - let res = c::mmap( - ptr, - len, - bitflags_bits!(prot), - bitflags_bits!(flags | MapFlags::from_bits_retain(bitcast!(c::MAP_ANONYMOUS))), - no_fd(), - 0, - ); - if res == c::MAP_FAILED { - Err(io::Errno::last_os_error()) - } else { - Ok(res) + unsafe { + let res = c::mmap( + ptr, + len, + bitflags_bits!(prot), + bitflags_bits!(flags | MapFlags::from_bits_retain(bitcast!(c::MAP_ANONYMOUS))), + no_fd(), + 0, + ); + if res == c::MAP_FAILED { + Err(io::Errno::last_os_error()) + } else { + Ok(res) + } } } @@ -120,11 +126,11 @@ pub(crate) unsafe fn mprotect( len: usize, flags: MprotectFlags, ) -> io::Result<()> { - ret(c::mprotect(ptr, len, bitflags_bits!(flags))) + unsafe { ret(c::mprotect(ptr, len, bitflags_bits!(flags))) } } pub(crate) unsafe fn munmap(ptr: *mut c::c_void, len: usize) -> io::Result<()> { - ret(c::munmap(ptr, len)) + unsafe { ret(c::munmap(ptr, len)) } } /// # Safety @@ -138,11 +144,13 @@ pub(crate) unsafe fn mremap( new_size: usize, flags: MremapFlags, ) -> io::Result<*mut c::c_void> { - let res = c::mremap(old_address, old_size, new_size, bitflags_bits!(flags)); - if res == c::MAP_FAILED { - Err(io::Errno::last_os_error()) - } else { - Ok(res) + unsafe { + let res = c::mremap(old_address, old_size, new_size, bitflags_bits!(flags)); + if res == c::MAP_FAILED { + Err(io::Errno::last_os_error()) + } else { + Ok(res) + } } } @@ -159,17 +167,19 @@ pub(crate) unsafe fn mremap_fixed( flags: MremapFlags, new_address: *mut c::c_void, ) -> io::Result<*mut c::c_void> { - let res = c::mremap( - old_address, - old_size, - new_size, - bitflags_bits!(flags | MremapFlags::from_bits_retain(bitcast!(c::MAP_FIXED))), - new_address, - ); - if res == c::MAP_FAILED { - Err(io::Errno::last_os_error()) - } else { - Ok(res) + unsafe { + let res = c::mremap( + old_address, + old_size, + new_size, + bitflags_bits!(flags | MremapFlags::from_bits_retain(bitcast!(c::MAP_FIXED))), + new_address, + ); + if res == c::MAP_FAILED { + Err(io::Errno::last_os_error()) + } else { + Ok(res) + } } } @@ -179,7 +189,7 @@ pub(crate) unsafe fn mremap_fixed( /// boundaries. #[inline] pub(crate) unsafe fn mlock(addr: *mut c::c_void, length: usize) -> io::Result<()> { - ret(c::mlock(addr, length)) + unsafe { ret(c::mlock(addr, length)) } } /// # Safety @@ -193,15 +203,17 @@ pub(crate) unsafe fn mlock_with( length: usize, flags: MlockFlags, ) -> io::Result<()> { - weak_or_syscall! { - fn mlock2( - addr: *const c::c_void, - len: c::size_t, - flags: c::c_int - ) via SYS_mlock2 -> c::c_int - } + unsafe { + weak_or_syscall! { + fn mlock2( + addr: *const c::c_void, + len: c::size_t, + flags: c::c_int + ) via SYS_mlock2 -> c::c_int + } - ret(mlock2(addr, length, bitflags_bits!(flags))) + ret(mlock2(addr, length, bitflags_bits!(flags))) + } } /// # Safety @@ -210,17 +222,19 @@ pub(crate) unsafe fn mlock_with( /// boundaries. #[inline] pub(crate) unsafe fn munlock(addr: *mut c::c_void, length: usize) -> io::Result<()> { - ret(c::munlock(addr, length)) + unsafe { ret(c::munlock(addr, length)) } } #[cfg(linux_kernel)] pub(crate) unsafe fn userfaultfd(flags: UserfaultfdFlags) -> io::Result { - syscall! { - fn userfaultfd( - flags: c::c_int - ) via SYS_userfaultfd -> c::c_int + unsafe { + syscall! { + fn userfaultfd( + flags: c::c_int + ) via SYS_userfaultfd -> c::c_int + } + ret_owned_fd(userfaultfd(bitflags_bits!(flags))) } - ret_owned_fd(userfaultfd(bitflags_bits!(flags))) } /// Locks all pages mapped into the address space of the calling process. diff --git a/src/backend/libc/net/addr.rs b/src/backend/libc/net/addr.rs index 1699ffa99..ee06b9212 100644 --- a/src/backend/libc/net/addr.rs +++ b/src/backend/libc/net/addr.rs @@ -158,14 +158,16 @@ impl SocketAddrUnix { #[cfg(feature = "alloc")] #[cold] unsafe fn path_with_termination(bytes: &[u8]) -> Option> { - let mut owned = Vec::with_capacity(bytes.len() + 1); - owned.extend_from_slice(bytes); - owned.push(b'\0'); - // SAFETY: `from_vec_with_nul_unchecked` since the string is - // NUL-terminated and `bytes` does not contain any NULs. - Some(Cow::Owned( - CString::from_vec_with_nul_unchecked(owned).into(), - )) + unsafe { + let mut owned = Vec::with_capacity(bytes.len() + 1); + owned.extend_from_slice(bytes); + owned.push(b'\0'); + // SAFETY: `from_vec_with_nul_unchecked` since the string is + // NUL-terminated and `bytes` does not contain any NULs. + Some(Cow::Owned( + CString::from_vec_with_nul_unchecked(owned).into(), + )) + } } /// For a filesystem path address, return the path as a byte sequence, diff --git a/src/backend/libc/net/msghdr.rs b/src/backend/libc/net/msghdr.rs index fe5471b95..d2a925b71 100644 --- a/src/backend/libc/net/msghdr.rs +++ b/src/backend/libc/net/msghdr.rs @@ -107,28 +107,30 @@ pub(crate) unsafe fn with_recv_msghdr( control: &mut RecvAncillaryBuffer<'_>, f: impl FnOnce(&mut c::msghdr) -> io::Result, ) -> io::Result { - control.clear(); - - let mut msghdr = zero_msghdr(); - msghdr.msg_name = name.storage.as_mut_ptr().cast(); - msghdr.msg_namelen = name.len; - msghdr.msg_iov = iov.as_mut_ptr().cast(); - msghdr.msg_iovlen = msg_iov_len(iov.len()); - msghdr.msg_control = control.as_control_ptr().cast(); - msghdr.msg_controllen = msg_control_len(control.control_len()); - - let res = f(&mut msghdr); - - // Reset the control length. - if res.is_ok() { - // SAFETY: `f` returned `Ok`, so our safety condition requires `f` to - // have initialized `msg_controllen` bytes. - control.set_control_len(msghdr.msg_controllen as usize); - } + unsafe { + control.clear(); + + let mut msghdr = zero_msghdr(); + msghdr.msg_name = name.storage.as_mut_ptr().cast(); + msghdr.msg_namelen = name.len; + msghdr.msg_iov = iov.as_mut_ptr().cast(); + msghdr.msg_iovlen = msg_iov_len(iov.len()); + msghdr.msg_control = control.as_control_ptr().cast(); + msghdr.msg_controllen = msg_control_len(control.control_len()); + + let res = f(&mut msghdr); - name.len = msghdr.msg_namelen; + // Reset the control length. + if res.is_ok() { + // SAFETY: `f` returned `Ok`, so our safety condition requires `f` to + // have initialized `msg_controllen` bytes. + control.set_control_len(msghdr.msg_controllen as usize); + } - res + name.len = msghdr.msg_namelen; + + res + } } /// Create a message header intended to send without an address. @@ -163,19 +165,21 @@ pub(crate) unsafe fn with_msghdr( control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(&c::msghdr) -> R, ) -> R { - addr.with_sockaddr(|addr_ptr, addr_len| { - let mut h = zero_msghdr(); - h.msg_name = addr_ptr as *mut _; - h.msg_namelen = bitcast!(addr_len); - h.msg_iov = iov.as_ptr() as _; - h.msg_iovlen = msg_iov_len(iov.len()); - h.msg_control = control.as_control_ptr().cast(); - h.msg_controllen = msg_control_len(control.control_len()); - // Pass a reference to the `c::msghdr` instead of passing it by value - // because it may contain pointers to temporary objects that won't - // live beyond the call to `with_sockaddr`. - f(&h) - }) + unsafe { + addr.with_sockaddr(|addr_ptr, addr_len| { + let mut h = zero_msghdr(); + h.msg_name = addr_ptr as *mut _; + h.msg_namelen = bitcast!(addr_len); + h.msg_iov = iov.as_ptr() as _; + h.msg_iovlen = msg_iov_len(iov.len()); + h.msg_control = control.as_control_ptr().cast(); + h.msg_controllen = msg_control_len(control.control_len()); + // Pass a reference to the `c::msghdr` instead of passing it by value + // because it may contain pointers to temporary objects that won't + // live beyond the call to `with_sockaddr`. + f(&h) + }) + } } /// Create a zero-initialized message header struct value. diff --git a/src/backend/libc/net/netdevice.rs b/src/backend/libc/net/netdevice.rs index 887f768db..26b6c521a 100644 --- a/src/backend/libc/net/netdevice.rs +++ b/src/backend/libc/net/netdevice.rs @@ -10,7 +10,7 @@ use crate::fd::BorrowedFd; use crate::io; #[cfg(feature = "alloc")] use c::SIOCGIFNAME; -use c::{__c_anonymous_ifr_ifru, c_char, ifreq, IFNAMSIZ, SIOCGIFINDEX}; +use c::{__c_anonymous_ifr_ifru, IFNAMSIZ, SIOCGIFINDEX, c_char, ifreq}; pub(crate) fn name_to_index(fd: BorrowedFd<'_>, if_name: &str) -> io::Result { let if_name_bytes = if_name.as_bytes(); diff --git a/src/backend/libc/net/read_sockaddr.rs b/src/backend/libc/net/read_sockaddr.rs index 5f8c48ec7..d754636ed 100644 --- a/src/backend/libc/net/read_sockaddr.rs +++ b/src/backend/libc/net/read_sockaddr.rs @@ -3,7 +3,7 @@ #[cfg(unix)] use super::addr::SocketAddrUnix; -use super::ext::{in6_addr_s6_addr, in_addr_s_addr, sockaddr_in6_sin6_scope_id}; +use super::ext::{in_addr_s_addr, in6_addr_s6_addr, sockaddr_in6_sin6_scope_id}; use crate::backend::c; #[cfg(not(windows))] use crate::ffi::CStr; @@ -55,47 +55,49 @@ pub(crate) struct sockaddr_header { /// `storage` must point to a valid socket address returned from the OS. #[inline] pub(crate) unsafe fn read_sa_family(storage: *const c::sockaddr) -> u16 { - // Assert that we know the layout of `sockaddr`. - let _ = c::sockaddr { - #[cfg(any( - bsd, - target_os = "aix", - target_os = "espidf", - target_os = "haiku", - target_os = "hurd", - target_os = "nto", - target_os = "vita" - ))] - sa_len: 0_u8, - #[cfg(any( - bsd, - target_os = "aix", - target_os = "espidf", - target_os = "haiku", - target_os = "hurd", - target_os = "nto", - target_os = "vita" - ))] - sa_family: 0_u8, - #[cfg(not(any( - bsd, - target_os = "aix", - target_os = "espidf", - target_os = "haiku", - target_os = "hurd", - target_os = "nto", - target_os = "vita" - )))] - sa_family: 0_u16, - #[cfg(not(any(target_os = "haiku", target_os = "horizon")))] - sa_data: [0; 14], - #[cfg(target_os = "horizon")] - sa_data: [0; 26], - #[cfg(target_os = "haiku")] - sa_data: [0; 30], - }; + unsafe { + // Assert that we know the layout of `sockaddr`. + let _ = c::sockaddr { + #[cfg(any( + bsd, + target_os = "aix", + target_os = "espidf", + target_os = "haiku", + target_os = "hurd", + target_os = "nto", + target_os = "vita" + ))] + sa_len: 0_u8, + #[cfg(any( + bsd, + target_os = "aix", + target_os = "espidf", + target_os = "haiku", + target_os = "hurd", + target_os = "nto", + target_os = "vita" + ))] + sa_family: 0_u8, + #[cfg(not(any( + bsd, + target_os = "aix", + target_os = "espidf", + target_os = "haiku", + target_os = "hurd", + target_os = "nto", + target_os = "vita" + )))] + sa_family: 0_u16, + #[cfg(not(any(target_os = "haiku", target_os = "horizon")))] + sa_data: [0; 14], + #[cfg(target_os = "horizon")] + sa_data: [0; 26], + #[cfg(target_os = "haiku")] + sa_data: [0; 30], + }; - (*storage.cast::()).sa_family.into() + (*storage.cast::()).sa_family.into() + } } /// Read the first byte of the `sun_path` field, assuming we have an `AF_UNIX` @@ -117,24 +119,26 @@ unsafe fn read_sun_path0(storage: *const c::sockaddr) -> u8 { /// `storage` must point to a least an initialized `sockaddr_header`. #[inline] pub(crate) unsafe fn sockaddr_nonempty(storage: *const c::sockaddr, len: SocketAddrLen) -> bool { - if len == 0 { - return false; - } + unsafe { + if len == 0 { + return false; + } - assert!(len as usize >= size_of::()); - let family: c::c_int = read_sa_family(storage.cast::()).into(); - if family == c::AF_UNSPEC { - return false; - } + assert!(len as usize >= size_of::()); + let family: c::c_int = read_sa_family(storage.cast::()).into(); + if family == c::AF_UNSPEC { + return false; + } - // On macOS, if we get an `AF_UNIX` with an empty path, treat it as an - // absent address. - #[cfg(apple)] - if family == c::AF_UNIX && read_sun_path0(storage) == 0 { - return false; - } + // On macOS, if we get an `AF_UNIX` with an empty path, treat it as an + // absent address. + #[cfg(apple)] + if family == c::AF_UNIX && read_sun_path0(storage) == 0 { + return false; + } - true + true + } } /// Set the `sa_family` field of a socket address to `AF_UNSPEC`, so that we @@ -144,7 +148,9 @@ pub(crate) unsafe fn sockaddr_nonempty(storage: *const c::sockaddr, len: SocketA /// /// `storage` must point to a least an initialized `sockaddr_header`. pub(crate) unsafe fn initialize_family_to_unspec(storage: *mut c::sockaddr) { - (*storage.cast::()).sa_family = c::AF_UNSPEC as _; + unsafe { + (*storage.cast::()).sa_family = c::AF_UNSPEC as _; + } } #[inline] diff --git a/src/backend/libc/net/sockopt.rs b/src/backend/libc/net/sockopt.rs index 29ceaa84c..a19217554 100644 --- a/src/backend/libc/net/sockopt.rs +++ b/src/backend/libc/net/sockopt.rs @@ -1,6 +1,6 @@ //! libc syscalls supporting `rustix::net::sockopt`. -use super::ext::{in6_addr_new, in_addr_new}; +use super::ext::{in_addr_new, in6_addr_new}; use crate::backend::c; use crate::backend::conv::{borrowed_fd, ret}; use crate::fd::BorrowedFd; @@ -13,9 +13,6 @@ use crate::fd::BorrowedFd; ))] use crate::ffi::CStr; use crate::io; -use crate::net::sockopt::Timeout; -#[cfg(target_os = "linux")] -use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpRingOffset, XdpStatistics, XdpUmemReg}; #[cfg(not(any( apple, windows, @@ -50,6 +47,9 @@ use crate::net::Protocol; use crate::net::RawProtocol; #[cfg(any(linux_kernel, target_os = "fuchsia"))] use crate::net::SocketAddrV4; +use crate::net::sockopt::Timeout; +#[cfg(target_os = "linux")] +use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpRingOffset, XdpStatistics, XdpUmemReg}; use crate::net::{Ipv4Addr, Ipv6Addr, SocketType}; #[cfg(linux_kernel)] use crate::net::{SocketAddrV6, UCred}; @@ -74,7 +74,7 @@ use alloc::string::String; use c::TCP_KEEPALIVE as TCP_KEEPIDLE; #[cfg(not(any(apple, target_os = "haiku", target_os = "nto", target_os = "openbsd")))] use c::TCP_KEEPIDLE; -use core::mem::{size_of, MaybeUninit}; +use core::mem::{MaybeUninit, size_of}; use core::time::Duration; #[cfg(target_os = "linux")] use linux_raw_sys::xdp::{xdp_mmap_offsets, xdp_statistics, xdp_statistics_v1}; @@ -240,7 +240,7 @@ pub(crate) fn set_socket_timeout( // manually round up. let mut timeout = c::timeval { tv_sec, - tv_usec: ((timeout.subsec_nanos() + 999) / 1000) as _, + tv_usec: timeout.subsec_nanos().div_ceil(1000) as _, }; if timeout.tv_sec == 0 && timeout.tv_usec == 0 { timeout.tv_usec = 1; @@ -262,7 +262,9 @@ pub(crate) fn set_socket_timeout( // `as_millis` rounds down, so we use `as_nanos` and // manually round up. - let mut timeout: u32 = ((timeout.as_nanos() + 999_999) / 1_000_000) + let mut timeout: u32 = timeout + .as_nanos() + .div_ceil(1_000_000) .try_into() .map_err(|_convert_err| io::Errno::INVAL)?; if timeout == 0 { diff --git a/src/backend/libc/net/syscalls.rs b/src/backend/libc/net/syscalls.rs index aafea0025..1988bb401 100644 --- a/src/backend/libc/net/syscalls.rs +++ b/src/backend/libc/net/syscalls.rs @@ -8,14 +8,14 @@ use crate::backend::conv::ret_u32; use crate::backend::conv::{borrowed_fd, ret, ret_owned_fd, ret_send_recv, send_recv_len}; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io; -use crate::net::addr::SocketAddrArg; #[cfg(target_os = "linux")] use crate::net::MMsgHdr; +use crate::net::addr::SocketAddrArg; use crate::net::{ AddressFamily, Protocol, Shutdown, SocketAddrAny, SocketAddrBuf, SocketFlags, SocketType, }; use crate::utils::as_ptr; -use core::mem::{size_of, MaybeUninit}; +use core::mem::{MaybeUninit, size_of}; use core::ptr::null_mut; #[cfg(not(any( windows, @@ -36,12 +36,14 @@ pub(crate) unsafe fn recv( buf: (*mut u8, usize), flags: RecvFlags, ) -> io::Result { - ret_send_recv(c::recv( - borrowed_fd(fd), - buf.0.cast(), - send_recv_len(buf.1), - bitflags_bits!(flags), - )) + unsafe { + ret_send_recv(c::recv( + borrowed_fd(fd), + buf.0.cast(), + send_recv_len(buf.1), + bitflags_bits!(flags), + )) + } } pub(crate) fn send(fd: BorrowedFd<'_>, buf: &[u8], flags: SendFlags) -> io::Result { @@ -60,23 +62,25 @@ pub(crate) unsafe fn recvfrom( buf: (*mut u8, usize), flags: RecvFlags, ) -> io::Result<(usize, Option)> { - let mut addr = SocketAddrBuf::new(); + unsafe { + let mut addr = SocketAddrBuf::new(); - // `recvfrom` does not write to the storage if the socket is - // connection-oriented sockets, so we initialize the family field to - // `AF_UNSPEC` so that we can detect this case. - initialize_family_to_unspec(addr.storage.as_mut_ptr().cast::()); + // `recvfrom` does not write to the storage if the socket is + // connection-oriented sockets, so we initialize the family field to + // `AF_UNSPEC` so that we can detect this case. + initialize_family_to_unspec(addr.storage.as_mut_ptr().cast::()); - let nread = ret_send_recv(c::recvfrom( - borrowed_fd(fd), - buf.0.cast(), - send_recv_len(buf.1), - bitflags_bits!(flags), - addr.storage.as_mut_ptr().cast::(), - &mut addr.len, - ))?; + let nread = ret_send_recv(c::recvfrom( + borrowed_fd(fd), + buf.0.cast(), + send_recv_len(buf.1), + bitflags_bits!(flags), + addr.storage.as_mut_ptr().cast::(), + &mut addr.len, + ))?; - Ok((nread, addr.into_any_option())) + Ok((nread, addr.into_any_option())) + } } pub(crate) fn sendto( diff --git a/src/backend/libc/net/write_sockaddr.rs b/src/backend/libc/net/write_sockaddr.rs index 08f04646c..af3631354 100644 --- a/src/backend/libc/net/write_sockaddr.rs +++ b/src/backend/libc/net/write_sockaddr.rs @@ -1,7 +1,7 @@ //! The BSD sockets API requires us to read the `sa_family` field before we can //! interpret the rest of a `sockaddr` produced by the kernel. -use super::ext::{in6_addr_new, in_addr_new, sockaddr_in6_new}; +use super::ext::{in_addr_new, in6_addr_new, sockaddr_in6_new}; use crate::backend::c; use crate::net::{SocketAddrV4, SocketAddrV6}; diff --git a/src/backend/libc/pipe/syscalls.rs b/src/backend/libc/pipe/syscalls.rs index fe5249546..4bd8ba067 100644 --- a/src/backend/libc/pipe/syscalls.rs +++ b/src/backend/libc/pipe/syscalls.rs @@ -14,8 +14,8 @@ use crate::pipe::PipeFlags; use core::mem::MaybeUninit; #[cfg(linux_kernel)] use { - crate::backend::conv::{borrowed_fd, ret_c_int, ret_usize}, crate::backend::MAX_IOV, + crate::backend::conv::{borrowed_fd, ret_c_int, ret_usize}, crate::fd::BorrowedFd, crate::pipe::{IoSliceRaw, SpliceFlags}, crate::utils::option_as_mut_ptr, @@ -85,12 +85,14 @@ pub(crate) unsafe fn vmsplice( bufs: &[IoSliceRaw<'_>], flags: SpliceFlags, ) -> io::Result { - ret_usize(c::vmsplice( - borrowed_fd(fd), - bufs.as_ptr().cast::(), - min(bufs.len(), MAX_IOV), - flags.bits(), - )) + unsafe { + ret_usize(c::vmsplice( + borrowed_fd(fd), + bufs.as_ptr().cast::(), + min(bufs.len(), MAX_IOV), + flags.bits(), + )) + } } #[cfg(linux_kernel)] diff --git a/src/backend/libc/prctl/syscalls.rs b/src/backend/libc/prctl/syscalls.rs index 451cecc29..f53dbc58e 100644 --- a/src/backend/libc/prctl/syscalls.rs +++ b/src/backend/libc/prctl/syscalls.rs @@ -10,5 +10,5 @@ pub(crate) unsafe fn prctl( arg4: *mut c::c_void, arg5: *mut c::c_void, ) -> io::Result { - ret_c_int(c::prctl(option, arg2, arg3, arg4, arg5)) + unsafe { ret_c_int(c::prctl(option, arg2, arg3, arg4, arg5)) } } diff --git a/src/backend/libc/process/syscalls.rs b/src/backend/libc/process/syscalls.rs index 3c67f2c33..699e86952 100644 --- a/src/backend/libc/process/syscalls.rs +++ b/src/backend/libc/process/syscalls.rs @@ -520,18 +520,20 @@ fn _waitid_pidfd(fd: BorrowedFd<'_>, options: WaitIdOptions) -> io::Result) -> Option { - let status = status.assume_init(); - // `si_pid` is supposedly the better way to check that the struct has been - // filled, e.g. the Linux manual page says about the `WNOHANG` case “zero - // out the si_pid field before the call and check for a nonzero value”. - // But e.g. NetBSD/OpenBSD don't have it exposed in the libc crate for now, - // and some platforms don't have it at all. For simplicity, always check - // `si_signo`. We have zero-initialized the whole struct, and all kernels - // should set `SIGCHLD` here. - if status.si_signo == 0 { - None - } else { - Some(WaitIdStatus(status)) + unsafe { + let status = status.assume_init(); + // `si_pid` is supposedly the better way to check that the struct has been + // filled, e.g. the Linux manual page says about the `WNOHANG` case “zero + // out the si_pid field before the call and check for a nonzero value”. + // But e.g. NetBSD/OpenBSD don't have it exposed in the libc crate for now, + // and some platforms don't have it at all. For simplicity, always check + // `si_signo`. We have zero-initialized the whole struct, and all kernels + // should set `SIGCHLD` here. + if status.si_signo == 0 { + None + } else { + Some(WaitIdStatus(status)) + } } } diff --git a/src/backend/libc/rand/syscalls.rs b/src/backend/libc/rand/syscalls.rs index ce17c6aa5..9b54a2245 100644 --- a/src/backend/libc/rand/syscalls.rs +++ b/src/backend/libc/rand/syscalls.rs @@ -5,10 +5,12 @@ use {crate::backend::c, crate::backend::conv::ret_usize, crate::io, crate::rand: #[cfg(linux_kernel)] pub(crate) unsafe fn getrandom(buf: (*mut u8, usize), flags: GetRandomFlags) -> io::Result { - // `getrandom` wasn't supported in glibc until 2.25. - weak_or_syscall! { - fn getrandom(buf: *mut c::c_void, buflen: c::size_t, flags: c::c_uint) via SYS_getrandom -> c::ssize_t - } + unsafe { + // `getrandom` wasn't supported in glibc until 2.25. + weak_or_syscall! { + fn getrandom(buf: *mut c::c_void, buflen: c::size_t, flags: c::c_uint) via SYS_getrandom -> c::ssize_t + } - ret_usize(getrandom(buf.0.cast(), buf.1, flags.bits())) + ret_usize(getrandom(buf.0.cast(), buf.1, flags.bits())) + } } diff --git a/src/backend/libc/thread/cpu_set.rs b/src/backend/libc/thread/cpu_set.rs index 30473b708..f8ba36b67 100644 --- a/src/backend/libc/thread/cpu_set.rs +++ b/src/backend/libc/thread/cpu_set.rs @@ -2,7 +2,7 @@ #![allow(non_snake_case)] -use super::types::{RawCpuSet, CPU_SETSIZE}; +use super::types::{CPU_SETSIZE, RawCpuSet}; use crate::backend::c; #[inline] diff --git a/src/backend/libc/thread/syscalls.rs b/src/backend/libc/thread/syscalls.rs index 9198a7fbe..353b939e4 100644 --- a/src/backend/libc/thread/syscalls.rs +++ b/src/backend/libc/thread/syscalls.rs @@ -456,69 +456,71 @@ pub(crate) unsafe fn futex_val2( uaddr2: *const AtomicU32, val3: u32, ) -> io::Result { - // Pass `val2` in the least-significant bytes of the `timeout` argument. - // [“the kernel casts the timeout value first to unsigned long, then to - // uint32_t”], so we perform that exact conversion in reverse to create - // the pointer. - // - // [“the kernel casts the timeout value first to unsigned long, then to uint32_t”]: https://man7.org/linux/man-pages/man2/futex.2.html - let timeout = val2 as usize as *const Timespec; + unsafe { + // Pass `val2` in the least-significant bytes of the `timeout` argument. + // [“the kernel casts the timeout value first to unsigned long, then to + // uint32_t”], so we perform that exact conversion in reverse to create + // the pointer. + // + // [“the kernel casts the timeout value first to unsigned long, then to uint32_t”]: https://man7.org/linux/man-pages/man2/futex.2.html + let timeout = val2 as usize as *const Timespec; + + #[cfg(all( + target_pointer_width = "32", + not(any(target_arch = "aarch64", target_arch = "x86_64")) + ))] + { + // TODO: Upstream this to the libc crate. + #[allow(non_upper_case_globals)] + const SYS_futex_time64: i32 = linux_raw_sys::general::__NR_futex_time64 as i32; + + syscall! { + fn futex_time64( + uaddr: *const AtomicU32, + futex_op: c::c_int, + val: u32, + timeout: *const Timespec, + uaddr2: *const AtomicU32, + val3: u32 + ) via SYS_futex_time64 -> c::ssize_t + } - #[cfg(all( - target_pointer_width = "32", - not(any(target_arch = "aarch64", target_arch = "x86_64")) - ))] - { - // TODO: Upstream this to the libc crate. - #[allow(non_upper_case_globals)] - const SYS_futex_time64: i32 = linux_raw_sys::general::__NR_futex_time64 as i32; - - syscall! { - fn futex_time64( - uaddr: *const AtomicU32, - futex_op: c::c_int, - val: u32, - timeout: *const Timespec, - uaddr2: *const AtomicU32, - val3: u32 - ) via SYS_futex_time64 -> c::ssize_t + ret_usize(futex_time64( + uaddr, + op as i32 | flags.bits() as i32, + val, + timeout, + uaddr2, + val3, + )) } - ret_usize(futex_time64( - uaddr, - op as i32 | flags.bits() as i32, - val, - timeout, - uaddr2, - val3, - )) - } + #[cfg(any( + target_pointer_width = "64", + target_arch = "aarch64", + target_arch = "x86_64" + ))] + { + syscall! { + fn futex( + uaddr: *const AtomicU32, + futex_op: c::c_int, + val: u32, + timeout: *const Timespec, + uaddr2: *const AtomicU32, + val3: u32 + ) via SYS_futex -> c::c_long + } - #[cfg(any( - target_pointer_width = "64", - target_arch = "aarch64", - target_arch = "x86_64" - ))] - { - syscall! { - fn futex( - uaddr: *const AtomicU32, - futex_op: c::c_int, - val: u32, - timeout: *const Timespec, - uaddr2: *const AtomicU32, - val3: u32 - ) via SYS_futex -> c::c_long + ret_usize(futex( + uaddr, + op as i32 | flags.bits() as i32, + val, + timeout.cast(), + uaddr2, + val3, + ) as isize) } - - ret_usize(futex( - uaddr, - op as i32 | flags.bits() as i32, - val, - timeout.cast(), - uaddr2, - val3, - ) as isize) } } @@ -535,69 +537,71 @@ pub(crate) unsafe fn futex_timeout( uaddr2: *const AtomicU32, val3: u32, ) -> io::Result { - #[cfg(all( - target_pointer_width = "32", - not(any(target_arch = "aarch64", target_arch = "x86_64")) - ))] - { - // TODO: Upstream this to the libc crate. - #[allow(non_upper_case_globals)] - const SYS_futex_time64: i32 = linux_raw_sys::general::__NR_futex_time64 as i32; - - syscall! { - fn futex_time64( - uaddr: *const AtomicU32, - futex_op: c::c_int, - val: u32, - timeout: *const Timespec, - uaddr2: *const AtomicU32, - val3: u32 - ) via SYS_futex_time64 -> c::ssize_t + unsafe { + #[cfg(all( + target_pointer_width = "32", + not(any(target_arch = "aarch64", target_arch = "x86_64")) + ))] + { + // TODO: Upstream this to the libc crate. + #[allow(non_upper_case_globals)] + const SYS_futex_time64: i32 = linux_raw_sys::general::__NR_futex_time64 as i32; + + syscall! { + fn futex_time64( + uaddr: *const AtomicU32, + futex_op: c::c_int, + val: u32, + timeout: *const Timespec, + uaddr2: *const AtomicU32, + val3: u32 + ) via SYS_futex_time64 -> c::ssize_t + } + + ret_usize(futex_time64( + uaddr, + op as i32 | flags.bits() as i32, + val, + option_as_ptr(timeout), + uaddr2, + val3, + )) + .or_else(|err| { + // See the comments in `clock_gettime_via_syscall` about emulation. + if err == io::Errno::NOSYS { + futex_old_timespec(uaddr, op, flags, val, timeout, uaddr2, val3) + } else { + Err(err) + } + }) } - ret_usize(futex_time64( - uaddr, - op as i32 | flags.bits() as i32, - val, - option_as_ptr(timeout), - uaddr2, - val3, - )) - .or_else(|err| { - // See the comments in `clock_gettime_via_syscall` about emulation. - if err == io::Errno::NOSYS { - futex_old_timespec(uaddr, op, flags, val, timeout, uaddr2, val3) - } else { - Err(err) + #[cfg(any( + target_pointer_width = "64", + target_arch = "aarch64", + target_arch = "x86_64" + ))] + { + syscall! { + fn futex( + uaddr: *const AtomicU32, + futex_op: c::c_int, + val: u32, + timeout: *const Timespec, + uaddr2: *const AtomicU32, + val3: u32 + ) via SYS_futex -> c::c_long } - }) - } - #[cfg(any( - target_pointer_width = "64", - target_arch = "aarch64", - target_arch = "x86_64" - ))] - { - syscall! { - fn futex( - uaddr: *const AtomicU32, - futex_op: c::c_int, - val: u32, - timeout: *const Timespec, - uaddr2: *const AtomicU32, - val3: u32 - ) via SYS_futex -> c::c_long + ret_usize(futex( + uaddr, + op as i32 | flags.bits() as i32, + val, + option_as_ptr(timeout).cast(), + uaddr2, + val3, + ) as isize) } - - ret_usize(futex( - uaddr, - op as i32 | flags.bits() as i32, - val, - option_as_ptr(timeout).cast(), - uaddr2, - val3, - ) as isize) } } diff --git a/src/backend/libc/time/syscalls.rs b/src/backend/libc/time/syscalls.rs index c17a9d2f0..fa4c46d54 100644 --- a/src/backend/libc/time/syscalls.rs +++ b/src/backend/libc/time/syscalls.rs @@ -8,6 +8,9 @@ use crate::backend::time::types::LibcItimerspec; #[cfg(not(target_os = "wasi"))] use crate::clockid::{ClockId, DynamicClockId}; use crate::io; +#[cfg(all(target_env = "gnu", fix_y2038))] +use crate::timespec::LibcTimespec; +use crate::timespec::Timespec; #[cfg(not(fix_y2038))] use crate::timespec::as_libc_timespec_mut_ptr; #[cfg(not(fix_y2038))] @@ -17,9 +20,6 @@ use crate::timespec::as_libc_timespec_mut_ptr; all(apple, not(target_os = "macos")) )))] use crate::timespec::as_libc_timespec_ptr; -#[cfg(all(target_env = "gnu", fix_y2038))] -use crate::timespec::LibcTimespec; -use crate::timespec::Timespec; use core::mem::MaybeUninit; #[cfg(any(linux_kernel, target_os = "fuchsia"))] use { diff --git a/src/backend/libc/winsock_c.rs b/src/backend/libc/winsock_c.rs index c583e3317..fee782ac9 100644 --- a/src/backend/libc/winsock_c.rs +++ b/src/backend/libc/winsock_c.rs @@ -6,20 +6,11 @@ use windows_sys::Win32::Networking::WinSock; -// Define the basic C types. With Rust 1.64, we can use these from `core::ffi`. -pub(crate) type c_schar = i8; -pub(crate) type c_uchar = u8; -pub(crate) type c_short = i16; -pub(crate) type c_ushort = u16; -pub(crate) type c_int = i32; -pub(crate) type c_uint = u32; -pub(crate) type c_longlong = i64; -pub(crate) type c_ulonglong = u64; -pub(crate) type ssize_t = isize; -pub(crate) type c_char = i8; -pub(crate) type c_long = i32; -pub(crate) type c_ulong = u32; -pub(crate) use core::ffi::c_void; +// Define the basic C types. +pub(crate) use core::ffi::{ + c_char, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong, c_ulonglong, + c_ushort, c_void, ssize_t, +}; // windows-sys declares these constants as `u16`. For better compatibility with // Unix-family APIs, redeclare them as `i32`. @@ -33,29 +24,29 @@ pub(crate) const AF_UNSPEC: i32 = WinSock::AF_UNSPEC as _; // `WSAECANCELLED` will be removed in the future. // pub(crate) use WinSock::{ - closesocket as close, ioctlsocket as ioctl, WSAPoll as poll, ADDRESS_FAMILY as sa_family_t, - ADDRINFOA as addrinfo, IN6_ADDR as in6_addr, IN_ADDR as in_addr, IPV6_MREQ as ipv6_mreq, - IP_MREQ as ip_mreq, LINGER as linger, SD_BOTH as SHUT_RDWR, SD_RECEIVE as SHUT_RD, - SD_SEND as SHUT_WR, SOCKADDR as sockaddr, SOCKADDR_IN as sockaddr_in, - SOCKADDR_IN6 as sockaddr_in6, SOCKADDR_STORAGE as sockaddr_storage, WSAEACCES as EACCES, - WSAEADDRINUSE as EADDRINUSE, WSAEADDRNOTAVAIL as EADDRNOTAVAIL, - WSAEAFNOSUPPORT as EAFNOSUPPORT, WSAEALREADY as EALREADY, WSAEBADF as EBADF, - WSAECONNABORTED as ECONNABORTED, WSAECONNREFUSED as ECONNREFUSED, WSAECONNRESET as ECONNRESET, - WSAEDESTADDRREQ as EDESTADDRREQ, WSAEDISCON as EDISCON, WSAEDQUOT as EDQUOT, - WSAEFAULT as EFAULT, WSAEHOSTDOWN as EHOSTDOWN, WSAEHOSTUNREACH as EHOSTUNREACH, - WSAEINPROGRESS as EINPROGRESS, WSAEINTR as EINTR, WSAEINVAL as EINVAL, - WSAEINVALIDPROCTABLE as EINVALIDPROCTABLE, WSAEINVALIDPROVIDER as EINVALIDPROVIDER, - WSAEISCONN as EISCONN, WSAELOOP as ELOOP, WSAEMFILE as EMFILE, WSAEMSGSIZE as EMSGSIZE, - WSAENAMETOOLONG as ENAMETOOLONG, WSAENETDOWN as ENETDOWN, WSAENETRESET as ENETRESET, - WSAENETUNREACH as ENETUNREACH, WSAENOBUFS as ENOBUFS, WSAENOMORE as ENOMORE, - WSAENOPROTOOPT as ENOPROTOOPT, WSAENOTCONN as ENOTCONN, WSAENOTEMPTY as ENOTEMPTY, - WSAENOTSOCK as ENOTSOCK, WSAEOPNOTSUPP as EOPNOTSUPP, WSAEPFNOSUPPORT as EPFNOSUPPORT, - WSAEPROCLIM as EPROCLIM, WSAEPROTONOSUPPORT as EPROTONOSUPPORT, WSAEPROTOTYPE as EPROTOTYPE, + ADDRESS_FAMILY as sa_family_t, ADDRINFOA as addrinfo, IN_ADDR as in_addr, IN6_ADDR as in6_addr, + IP_MREQ as ip_mreq, IPV6_MREQ as ipv6_mreq, LINGER as linger, SD_BOTH as SHUT_RDWR, + SD_RECEIVE as SHUT_RD, SD_SEND as SHUT_WR, SOCKADDR as sockaddr, SOCKADDR_IN as sockaddr_in, + SOCKADDR_IN6 as sockaddr_in6, SOCKADDR_STORAGE as sockaddr_storage, + WSA_E_CANCELLED as ECANCELED, WSAEACCES as EACCES, WSAEADDRINUSE as EADDRINUSE, + WSAEADDRNOTAVAIL as EADDRNOTAVAIL, WSAEAFNOSUPPORT as EAFNOSUPPORT, WSAEALREADY as EALREADY, + WSAEBADF as EBADF, WSAECONNABORTED as ECONNABORTED, WSAECONNREFUSED as ECONNREFUSED, + WSAECONNRESET as ECONNRESET, WSAEDESTADDRREQ as EDESTADDRREQ, WSAEDISCON as EDISCON, + WSAEDQUOT as EDQUOT, WSAEFAULT as EFAULT, WSAEHOSTDOWN as EHOSTDOWN, + WSAEHOSTUNREACH as EHOSTUNREACH, WSAEINPROGRESS as EINPROGRESS, WSAEINTR as EINTR, + WSAEINVAL as EINVAL, WSAEINVALIDPROCTABLE as EINVALIDPROCTABLE, + WSAEINVALIDPROVIDER as EINVALIDPROVIDER, WSAEISCONN as EISCONN, WSAELOOP as ELOOP, + WSAEMFILE as EMFILE, WSAEMSGSIZE as EMSGSIZE, WSAENAMETOOLONG as ENAMETOOLONG, + WSAENETDOWN as ENETDOWN, WSAENETRESET as ENETRESET, WSAENETUNREACH as ENETUNREACH, + WSAENOBUFS as ENOBUFS, WSAENOMORE as ENOMORE, WSAENOPROTOOPT as ENOPROTOOPT, + WSAENOTCONN as ENOTCONN, WSAENOTEMPTY as ENOTEMPTY, WSAENOTSOCK as ENOTSOCK, + WSAEOPNOTSUPP as EOPNOTSUPP, WSAEPFNOSUPPORT as EPFNOSUPPORT, WSAEPROCLIM as EPROCLIM, + WSAEPROTONOSUPPORT as EPROTONOSUPPORT, WSAEPROTOTYPE as EPROTOTYPE, WSAEPROVIDERFAILEDINIT as EPROVIDERFAILEDINIT, WSAEREFUSED as EREFUSED, WSAEREMOTE as EREMOTE, WSAESHUTDOWN as ESHUTDOWN, WSAESOCKTNOSUPPORT as ESOCKTNOSUPPORT, WSAESTALE as ESTALE, WSAETIMEDOUT as ETIMEDOUT, WSAETOOMANYREFS as ETOOMANYREFS, WSAEUSERS as EUSERS, - WSAEWOULDBLOCK as EWOULDBLOCK, WSAEWOULDBLOCK as EAGAIN, WSAPOLLFD as pollfd, - WSA_E_CANCELLED as ECANCELED, *, + WSAEWOULDBLOCK as EWOULDBLOCK, WSAEWOULDBLOCK as EAGAIN, WSAPOLLFD as pollfd, WSAPoll as poll, + closesocket as close, ioctlsocket as ioctl, *, }; // Windows doesn't have `timespec`, just `timeval`. Rustix only uses `timespec` diff --git a/src/backend/linux_raw/arch/aarch64.rs b/src/backend/linux_raw/arch/aarch64.rs index cbe352882..634dce178 100644 --- a/src/backend/linux_raw/arch/aarch64.rs +++ b/src/backend/linux_raw/arch/aarch64.rs @@ -1,7 +1,7 @@ //! aarch64 Linux system calls. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/arm.rs b/src/backend/linux_raw/arch/arm.rs index 70f03000c..04cad0585 100644 --- a/src/backend/linux_raw/arch/arm.rs +++ b/src/backend/linux_raw/arch/arm.rs @@ -1,7 +1,7 @@ //! arm Linux system calls. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/mips.rs b/src/backend/linux_raw/arch/mips.rs index 3c2b62b4b..441e49b7c 100644 --- a/src/backend/linux_raw/arch/mips.rs +++ b/src/backend/linux_raw/arch/mips.rs @@ -7,7 +7,7 @@ //! however we use `__NR_pipe2` instead to avoid having to implement it. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, A6, R0, + A0, A1, A2, A3, A4, A5, A6, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/mips32r6.rs b/src/backend/linux_raw/arch/mips32r6.rs index 1b0b7dfbb..2671e3f1a 100644 --- a/src/backend/linux_raw/arch/mips32r6.rs +++ b/src/backend/linux_raw/arch/mips32r6.rs @@ -7,7 +7,7 @@ //! however we use `__NR_pipe2` instead to avoid having to implement it. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, A6, R0, + A0, A1, A2, A3, A4, A5, A6, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/mips64.rs b/src/backend/linux_raw/arch/mips64.rs index 870624698..f253ecdb4 100644 --- a/src/backend/linux_raw/arch/mips64.rs +++ b/src/backend/linux_raw/arch/mips64.rs @@ -7,7 +7,7 @@ //! however we use `__NR_pipe2` instead to avoid having to implement it. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/mips64r6.rs b/src/backend/linux_raw/arch/mips64r6.rs index 01eb495db..61cf8b0b4 100644 --- a/src/backend/linux_raw/arch/mips64r6.rs +++ b/src/backend/linux_raw/arch/mips64r6.rs @@ -11,7 +11,7 @@ //! explicit call of R6-only or R2-only instructions exist here. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/mod.rs b/src/backend/linux_raw/arch/mod.rs index 8d675adba..0c5e89fb3 100644 --- a/src/backend/linux_raw/arch/mod.rs +++ b/src/backend/linux_raw/arch/mod.rs @@ -79,14 +79,14 @@ macro_rules! syscall { )) }; - ($nr:ident, $a0:expr) => { + ($nr:ident, $a0:expr_2021) => { $crate::backend::arch::choose::syscall1( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), ) }; - ($nr:ident, $a0:expr, $a1:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021) => { $crate::backend::arch::choose::syscall2( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -94,7 +94,7 @@ macro_rules! syscall { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021) => { $crate::backend::arch::choose::syscall3( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -103,7 +103,7 @@ macro_rules! syscall { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021) => { $crate::backend::arch::choose::syscall4( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -113,7 +113,7 @@ macro_rules! syscall { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021) => { $crate::backend::arch::choose::syscall5( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -124,7 +124,7 @@ macro_rules! syscall { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021, $a5:expr_2021) => { $crate::backend::arch::choose::syscall6( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -136,7 +136,7 @@ macro_rules! syscall { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021, $a5:expr_2021, $a6:expr_2021) => { $crate::backend::arch::choose::syscall7( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -158,14 +158,14 @@ macro_rules! syscall_always_asm { $crate::backend::arch::asm::syscall0($crate::backend::reg::nr(linux_raw_sys::general::$nr)) }; - ($nr:ident, $a0:expr) => { + ($nr:ident, $a0:expr_2021) => { $crate::backend::arch::asm::syscall1( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), ) }; - ($nr:ident, $a0:expr, $a1:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021) => { $crate::backend::arch::asm::syscall2( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -173,7 +173,7 @@ macro_rules! syscall_always_asm { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021) => { $crate::backend::arch::asm::syscall3( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -182,7 +182,7 @@ macro_rules! syscall_always_asm { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021) => { $crate::backend::arch::asm::syscall4( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -192,7 +192,7 @@ macro_rules! syscall_always_asm { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021) => { $crate::backend::arch::asm::syscall5( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -203,7 +203,7 @@ macro_rules! syscall_always_asm { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021, $a5:expr_2021) => { $crate::backend::arch::asm::syscall6( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -215,7 +215,7 @@ macro_rules! syscall_always_asm { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021, $a5:expr_2021, $a6:expr_2021) => { $crate::backend::arch::asm::syscall7( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -238,14 +238,14 @@ macro_rules! syscall_readonly { )) }; - ($nr:ident, $a0:expr) => { + ($nr:ident, $a0:expr_2021) => { $crate::backend::arch::choose::syscall1_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), ) }; - ($nr:ident, $a0:expr, $a1:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021) => { $crate::backend::arch::choose::syscall2_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -253,7 +253,7 @@ macro_rules! syscall_readonly { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021) => { $crate::backend::arch::choose::syscall3_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -262,7 +262,7 @@ macro_rules! syscall_readonly { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021) => { $crate::backend::arch::choose::syscall4_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -272,7 +272,7 @@ macro_rules! syscall_readonly { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021) => { $crate::backend::arch::choose::syscall5_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -283,7 +283,7 @@ macro_rules! syscall_readonly { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021, $a5:expr_2021) => { $crate::backend::arch::choose::syscall6_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -295,7 +295,7 @@ macro_rules! syscall_readonly { ) }; - ($nr:ident, $a0:expr, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr) => { + ($nr:ident, $a0:expr_2021, $a1:expr_2021, $a2:expr_2021, $a3:expr_2021, $a4:expr_2021, $a5:expr_2021, $a6:expr_2021) => { $crate::backend::arch::choose::syscall7_readonly( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), @@ -312,7 +312,7 @@ macro_rules! syscall_readonly { /// Like `syscall`, but indicates that the syscall does not return. #[cfg(feature = "runtime")] macro_rules! syscall_noreturn { - ($nr:ident, $a0:expr) => { + ($nr:ident, $a0:expr_2021) => { $crate::backend::arch::choose::syscall1_noreturn( $crate::backend::reg::nr(linux_raw_sys::general::$nr), $a0.into(), diff --git a/src/backend/linux_raw/arch/powerpc.rs b/src/backend/linux_raw/arch/powerpc.rs index 2b3dd2909..3bafb353a 100644 --- a/src/backend/linux_raw/arch/powerpc.rs +++ b/src/backend/linux_raw/arch/powerpc.rs @@ -10,7 +10,7 @@ //! architectures. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/powerpc64.rs b/src/backend/linux_raw/arch/powerpc64.rs index 20c95f7d1..5975b257f 100644 --- a/src/backend/linux_raw/arch/powerpc64.rs +++ b/src/backend/linux_raw/arch/powerpc64.rs @@ -10,7 +10,7 @@ //! architectures. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/riscv64.rs b/src/backend/linux_raw/arch/riscv64.rs index f34fae721..460093464 100644 --- a/src/backend/linux_raw/arch/riscv64.rs +++ b/src/backend/linux_raw/arch/riscv64.rs @@ -1,7 +1,7 @@ //! riscv64 Linux system calls. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/s390x.rs b/src/backend/linux_raw/arch/s390x.rs index f83dde554..6a443b3d9 100644 --- a/src/backend/linux_raw/arch/s390x.rs +++ b/src/backend/linux_raw/arch/s390x.rs @@ -1,7 +1,7 @@ //! s390x Linux system calls. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/thumb.rs b/src/backend/linux_raw/arch/thumb.rs index 07e7bb994..7d0b7f5bf 100644 --- a/src/backend/linux_raw/arch/thumb.rs +++ b/src/backend/linux_raw/arch/thumb.rs @@ -5,7 +5,7 @@ //! into r7 inside the inline asm. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/x86.rs b/src/backend/linux_raw/arch/x86.rs index 5e02ea23a..c14b2d02b 100644 --- a/src/backend/linux_raw/arch/x86.rs +++ b/src/backend/linux_raw/arch/x86.rs @@ -13,7 +13,7 @@ #![allow(dead_code)] use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use crate::backend::vdso_wrappers::SyscallType; use core::arch::asm; diff --git a/src/backend/linux_raw/arch/x86_64.rs b/src/backend/linux_raw/arch/x86_64.rs index eba3fad3b..54fe3d69d 100644 --- a/src/backend/linux_raw/arch/x86_64.rs +++ b/src/backend/linux_raw/arch/x86_64.rs @@ -1,7 +1,7 @@ //! x86-64 Linux system calls. use crate::backend::reg::{ - ArgReg, FromAsm, RetReg, SyscallNumber, ToAsm as _, A0, A1, A2, A3, A4, A5, R0, + A0, A1, A2, A3, A4, A5, ArgReg, FromAsm, R0, RetReg, SyscallNumber, ToAsm as _, }; use core::arch::asm; @@ -10,29 +10,33 @@ compile_error!("x32 is not yet supported"); #[inline] pub(in crate::backend) unsafe fn syscall0_readonly(nr: SyscallNumber<'_>) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } #[inline] pub(in crate::backend) unsafe fn syscall1(nr: SyscallNumber<'_>, a0: ArgReg<'_, A0>) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -40,26 +44,30 @@ pub(in crate::backend) unsafe fn syscall1_readonly( nr: SyscallNumber<'_>, a0: ArgReg<'_, A0>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } #[inline] pub(in crate::backend) unsafe fn syscall1_noreturn(nr: SyscallNumber<'_>, a0: ArgReg<'_, A0>) -> ! { - asm!( - "syscall", - in("rax") nr.to_asm(), - in("rdi") a0.to_asm(), - options(nostack, noreturn) - ) + unsafe { + asm!( + "syscall", + in("rax") nr.to_asm(), + in("rdi") a0.to_asm(), + options(nostack, noreturn) + ) + } } #[inline] @@ -68,17 +76,19 @@ pub(in crate::backend) unsafe fn syscall2( a0: ArgReg<'_, A0>, a1: ArgReg<'_, A1>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -87,17 +97,19 @@ pub(in crate::backend) unsafe fn syscall2_readonly( a0: ArgReg<'_, A0>, a1: ArgReg<'_, A1>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -107,18 +119,20 @@ pub(in crate::backend) unsafe fn syscall3( a1: ArgReg<'_, A1>, a2: ArgReg<'_, A2>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -128,18 +142,20 @@ pub(in crate::backend) unsafe fn syscall3_readonly( a1: ArgReg<'_, A1>, a2: ArgReg<'_, A2>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -150,19 +166,21 @@ pub(in crate::backend) unsafe fn syscall4( a2: ArgReg<'_, A2>, a3: ArgReg<'_, A3>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - in("r10") a3.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + in("r10") a3.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -173,19 +191,21 @@ pub(in crate::backend) unsafe fn syscall4_readonly( a2: ArgReg<'_, A2>, a3: ArgReg<'_, A3>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - in("r10") a3.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + in("r10") a3.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -197,20 +217,22 @@ pub(in crate::backend) unsafe fn syscall5( a3: ArgReg<'_, A3>, a4: ArgReg<'_, A4>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - in("r10") a3.to_asm(), - in("r8") a4.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + in("r10") a3.to_asm(), + in("r8") a4.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -222,20 +244,22 @@ pub(in crate::backend) unsafe fn syscall5_readonly( a3: ArgReg<'_, A3>, a4: ArgReg<'_, A4>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - in("r10") a3.to_asm(), - in("r8") a4.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + in("r10") a3.to_asm(), + in("r8") a4.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -248,21 +272,23 @@ pub(in crate::backend) unsafe fn syscall6( a4: ArgReg<'_, A4>, a5: ArgReg<'_, A5>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - in("r10") a3.to_asm(), - in("r8") a4.to_asm(), - in("r9") a5.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + in("r10") a3.to_asm(), + in("r8") a4.to_asm(), + in("r9") a5.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags) + ); + FromAsm::from_asm(r0) + } } #[inline] @@ -275,19 +301,21 @@ pub(in crate::backend) unsafe fn syscall6_readonly( a4: ArgReg<'_, A4>, a5: ArgReg<'_, A5>, ) -> RetReg { - let r0; - asm!( - "syscall", - inlateout("rax") nr.to_asm() => r0, - in("rdi") a0.to_asm(), - in("rsi") a1.to_asm(), - in("rdx") a2.to_asm(), - in("r10") a3.to_asm(), - in("r8") a4.to_asm(), - in("r9") a5.to_asm(), - lateout("rcx") _, - lateout("r11") _, - options(nostack, preserves_flags, readonly) - ); - FromAsm::from_asm(r0) + unsafe { + let r0; + asm!( + "syscall", + inlateout("rax") nr.to_asm() => r0, + in("rdi") a0.to_asm(), + in("rsi") a1.to_asm(), + in("rdx") a2.to_asm(), + in("r10") a3.to_asm(), + in("r8") a4.to_asm(), + in("r9") a5.to_asm(), + lateout("rcx") _, + lateout("r11") _, + options(nostack, preserves_flags, readonly) + ); + FromAsm::from_asm(r0) + } } diff --git a/src/backend/linux_raw/c.rs b/src/backend/linux_raw/c.rs index 755dadcde..313ef1b84 100644 --- a/src/backend/linux_raw/c.rs +++ b/src/backend/linux_raw/c.rs @@ -9,7 +9,7 @@ pub(crate) type size_t = usize; pub(crate) use linux_raw_sys::ctypes::*; pub(crate) use linux_raw_sys::errno::{EBADF, EINVAL}; -pub(crate) use linux_raw_sys::general::{__kernel_fd_set as fd_set, __FD_SETSIZE as FD_SETSIZE}; +pub(crate) use linux_raw_sys::general::{__FD_SETSIZE as FD_SETSIZE, __kernel_fd_set as fd_set}; pub(crate) use linux_raw_sys::ioctl::{FIONBIO, FIONREAD}; // Import the kernel's `uid_t` and `gid_t` if they're 32-bit. #[cfg(feature = "thread")] @@ -17,8 +17,8 @@ pub(crate) use linux_raw_sys::general::futex_waitv; #[cfg(not(any(target_arch = "arm", target_arch = "sparc", target_arch = "x86")))] pub(crate) use linux_raw_sys::general::{__kernel_gid_t as gid_t, __kernel_uid_t as uid_t}; pub(crate) use linux_raw_sys::general::{ - __kernel_pid_t as pid_t, __kernel_time64_t as time_t, __kernel_timespec as timespec, iovec, - O_CLOEXEC, O_NOCTTY, O_NONBLOCK, O_RDWR, + __kernel_pid_t as pid_t, __kernel_time64_t as time_t, __kernel_timespec as timespec, O_CLOEXEC, + O_NOCTTY, O_NONBLOCK, O_RDWR, iovec, }; #[cfg(feature = "system")] pub(crate) use linux_raw_sys::system::sysinfo; @@ -39,7 +39,7 @@ pub(crate) use linux_raw_sys::general::epoll_event; #[cfg(feature = "mm")] mod mm { - pub(crate) use linux_raw_sys::general::{MAP_HUGETLB, MAP_HUGE_SHIFT}; + pub(crate) use linux_raw_sys::general::{MAP_HUGE_SHIFT, MAP_HUGETLB}; } #[cfg(feature = "mm")] pub(crate) use mm::*; @@ -64,10 +64,10 @@ pub(crate) use linux_raw_sys::general::{ }; pub(crate) use linux_raw_sys::ioctl::{BLKPBSZGET, BLKSSZGET, FICLONE}; -#[cfg(target_pointer_width = "32")] -pub(crate) use linux_raw_sys::ioctl::{FS_IOC32_GETFLAGS, FS_IOC32_SETFLAGS}; #[cfg(target_pointer_width = "64")] pub(crate) use linux_raw_sys::ioctl::{FS_IOC_GETFLAGS, FS_IOC_SETFLAGS}; +#[cfg(target_pointer_width = "32")] +pub(crate) use linux_raw_sys::ioctl::{FS_IOC32_GETFLAGS, FS_IOC32_SETFLAGS}; #[cfg(feature = "io_uring")] pub(crate) use linux_raw_sys::{general::open_how, io_uring::*}; @@ -79,38 +79,38 @@ pub(crate) use linux_raw_sys::{ if_ether::*, net::{ __kernel_sa_family_t as sa_family_t, __kernel_sockaddr_storage as sockaddr_storage, - cmsghdr, in6_addr, in_addr, ip_mreq, ip_mreq_source, ip_mreqn, ipv6_mreq, linger, mmsghdr, - msghdr, sockaddr, sockaddr_in, sockaddr_in6, sockaddr_un, socklen_t, AF_DECnet, AF_APPLETALK, AF_ASH, AF_ATMPVC, AF_ATMSVC, AF_AX25, AF_BLUETOOTH, AF_BRIDGE, AF_CAN, - AF_ECONET, AF_IEEE802154, AF_INET, AF_INET6, AF_IPX, AF_IRDA, AF_ISDN, AF_IUCV, AF_KEY, - AF_LLC, AF_NETBEUI, AF_NETLINK, AF_NETROM, AF_PACKET, AF_PHONET, AF_PPPOX, AF_RDS, AF_ROSE, - AF_RXRPC, AF_SECURITY, AF_SNA, AF_TIPC, AF_UNIX, AF_UNSPEC, AF_WANPIPE, AF_X25, AF_XDP, - IP6T_SO_ORIGINAL_DST, IPPROTO_FRAGMENT, IPPROTO_ICMPV6, IPPROTO_MH, IPPROTO_ROUTING, - IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_FREEBIND, IPV6_MULTICAST_HOPS, - IPV6_MULTICAST_LOOP, IPV6_RECVTCLASS, IPV6_TCLASS, IPV6_UNICAST_HOPS, IPV6_V6ONLY, - IP_ADD_MEMBERSHIP, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_DROP_SOURCE_MEMBERSHIP, - IP_FREEBIND, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_RECVTOS, IP_TOS, IP_TTL, - MSG_CMSG_CLOEXEC, MSG_CONFIRM, MSG_CTRUNC, MSG_DONTROUTE, MSG_DONTWAIT, MSG_EOR, - MSG_ERRQUEUE, MSG_MORE, MSG_NOSIGNAL, MSG_OOB, MSG_PEEK, MSG_TRUNC, MSG_WAITALL, - SCM_CREDENTIALS, SCM_RIGHTS, SHUT_RD, SHUT_RDWR, SHUT_WR, SOCK_DGRAM, SOCK_RAW, SOCK_RDM, - SOCK_SEQPACKET, SOCK_STREAM, SOL_SOCKET, SOL_XDP, SO_ACCEPTCONN, SO_BROADCAST, SO_COOKIE, - SO_DOMAIN, SO_ERROR, SO_INCOMING_CPU, SO_KEEPALIVE, SO_LINGER, SO_OOBINLINE, + AF_DECnet, AF_ECONET, AF_IEEE802154, AF_INET, AF_INET6, AF_IPX, AF_IRDA, AF_ISDN, AF_IUCV, + AF_KEY, AF_LLC, AF_NETBEUI, AF_NETLINK, AF_NETROM, AF_PACKET, AF_PHONET, AF_PPPOX, AF_RDS, + AF_ROSE, AF_RXRPC, AF_SECURITY, AF_SNA, AF_TIPC, AF_UNIX, AF_UNSPEC, AF_WANPIPE, AF_X25, + AF_XDP, IP_ADD_MEMBERSHIP, IP_ADD_SOURCE_MEMBERSHIP, IP_DROP_MEMBERSHIP, + IP_DROP_SOURCE_MEMBERSHIP, IP_FREEBIND, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_RECVTOS, + IP_TOS, IP_TTL, IP6T_SO_ORIGINAL_DST, IPPROTO_FRAGMENT, IPPROTO_ICMPV6, IPPROTO_MH, + IPPROTO_ROUTING, IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_FREEBIND, + IPV6_MULTICAST_HOPS, IPV6_MULTICAST_LOOP, IPV6_RECVTCLASS, IPV6_TCLASS, IPV6_UNICAST_HOPS, + IPV6_V6ONLY, MSG_CMSG_CLOEXEC, MSG_CONFIRM, MSG_CTRUNC, MSG_DONTROUTE, MSG_DONTWAIT, + MSG_EOR, MSG_ERRQUEUE, MSG_MORE, MSG_NOSIGNAL, MSG_OOB, MSG_PEEK, MSG_TRUNC, MSG_WAITALL, + SCM_CREDENTIALS, SCM_RIGHTS, SHUT_RD, SHUT_RDWR, SHUT_WR, SO_ACCEPTCONN, SO_BROADCAST, + SO_COOKIE, SO_DOMAIN, SO_ERROR, SO_INCOMING_CPU, SO_KEEPALIVE, SO_LINGER, SO_OOBINLINE, SO_ORIGINAL_DST, SO_PASSCRED, SO_PROTOCOL, SO_RCVBUF, SO_RCVBUFFORCE, SO_RCVTIMEO_NEW, SO_RCVTIMEO_NEW as SO_RCVTIMEO, SO_RCVTIMEO_OLD, SO_REUSEADDR, SO_REUSEPORT, SO_SNDBUF, SO_SNDBUFFORCE, SO_SNDTIMEO_NEW, SO_SNDTIMEO_NEW as SO_SNDTIMEO, SO_SNDTIMEO_OLD, SO_TYPE, + SOCK_DGRAM, SOCK_RAW, SOCK_RDM, SOCK_SEQPACKET, SOCK_STREAM, SOL_SOCKET, SOL_XDP, TCP_CONGESTION, TCP_CORK, TCP_KEEPCNT, TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_NODELAY, - TCP_QUICKACK, TCP_THIN_LINEAR_TIMEOUTS, TCP_USER_TIMEOUT, + TCP_QUICKACK, TCP_THIN_LINEAR_TIMEOUTS, TCP_USER_TIMEOUT, cmsghdr, in_addr, in6_addr, + ip_mreq, ip_mreq_source, ip_mreqn, ipv6_mreq, linger, mmsghdr, msghdr, sockaddr, + sockaddr_in, sockaddr_in6, sockaddr_un, socklen_t, }, netlink::*, xdp::{ - sockaddr_xdp, xdp_desc, xdp_mmap_offsets, xdp_mmap_offsets_v1, xdp_options, - xdp_ring_offset, xdp_ring_offset_v1, xdp_statistics, xdp_statistics_v1, xdp_umem_reg, - xdp_umem_reg_v1, XDP_COPY, XDP_MMAP_OFFSETS, XDP_OPTIONS, XDP_OPTIONS_ZEROCOPY, - XDP_PGOFF_RX_RING, XDP_PGOFF_TX_RING, XDP_PKT_CONTD, XDP_RING_NEED_WAKEUP, XDP_RX_RING, - XDP_SHARED_UMEM, XDP_STATISTICS, XDP_TX_RING, XDP_UMEM_COMPLETION_RING, XDP_UMEM_FILL_RING, + XDP_COPY, XDP_MMAP_OFFSETS, XDP_OPTIONS, XDP_OPTIONS_ZEROCOPY, XDP_PGOFF_RX_RING, + XDP_PGOFF_TX_RING, XDP_PKT_CONTD, XDP_RING_NEED_WAKEUP, XDP_RX_RING, XDP_SHARED_UMEM, + XDP_STATISTICS, XDP_TX_RING, XDP_UMEM_COMPLETION_RING, XDP_UMEM_FILL_RING, XDP_UMEM_PGOFF_COMPLETION_RING, XDP_UMEM_PGOFF_FILL_RING, XDP_UMEM_REG, XDP_UMEM_UNALIGNED_CHUNK_FLAG, XDP_USE_NEED_WAKEUP, XDP_USE_SG, XDP_ZEROCOPY, - XSK_UNALIGNED_BUF_ADDR_MASK, XSK_UNALIGNED_BUF_OFFSET_SHIFT, + XSK_UNALIGNED_BUF_ADDR_MASK, XSK_UNALIGNED_BUF_OFFSET_SHIFT, sockaddr_xdp, xdp_desc, + xdp_mmap_offsets, xdp_mmap_offsets_v1, xdp_options, xdp_ring_offset, xdp_ring_offset_v1, + xdp_statistics, xdp_statistics_v1, xdp_umem_reg, xdp_umem_reg_v1, }, }; @@ -195,11 +195,11 @@ pub(crate) use linux_raw_sys::{ #[cfg(feature = "process")] #[cfg(target_pointer_width = "32")] -pub(crate) use linux_raw_sys::general::{flock64 as flock, F_GETLK64}; +pub(crate) use linux_raw_sys::general::{F_GETLK64, flock64 as flock}; #[cfg(feature = "process")] #[cfg(target_pointer_width = "64")] -pub(crate) use linux_raw_sys::general::{flock, F_GETLK}; +pub(crate) use linux_raw_sys::general::{F_GETLK, flock}; #[cfg(feature = "pty")] pub(crate) use linux_raw_sys::ioctl::TIOCGPTPEER; @@ -207,19 +207,19 @@ pub(crate) use linux_raw_sys::ioctl::TIOCGPTPEER; #[cfg(feature = "termios")] pub(crate) use linux_raw_sys::{ general::{ - cc_t, speed_t, tcflag_t, termios, termios2, winsize, B0, B1000000, B110, B115200, B1152000, - B1200, B134, B150, B1500000, B1800, B19200, B200, B2000000, B230400, B2400, B2500000, B300, - B3000000, B3500000, B38400, B4000000, B460800, B4800, B50, B500000, B57600, B576000, B600, - B75, B921600, B9600, BOTHER, BRKINT, BS0, BS1, BSDLY, CBAUD, CBAUDEX, CIBAUD, CLOCAL, - CMSPAR, CR0, CR1, CR2, CR3, CRDLY, CREAD, CRTSCTS, CS5, CS6, CS7, CS8, CSIZE, CSTOPB, ECHO, - ECHOCTL, ECHOE, ECHOK, ECHOKE, ECHONL, ECHOPRT, EXTA, EXTB, EXTPROC, FF0, FF1, FFDLY, - FLUSHO, HUPCL, IBSHIFT, ICANON, ICRNL, IEXTEN, IGNBRK, IGNCR, IGNPAR, IMAXBEL, INLCR, - INPCK, ISIG, ISTRIP, IUCLC, IUTF8, IXANY, IXOFF, IXON, NCCS, NL0, NL1, NLDLY, NOFLSH, - OCRNL, OFDEL, OFILL, OLCUC, ONLCR, ONLRET, ONOCR, OPOST, PARENB, PARMRK, PARODD, PENDIN, - TAB0, TAB1, TAB2, TAB3, TABDLY, TCIFLUSH, TCIOFF, TCIOFLUSH, TCION, TCOFLUSH, TCOOFF, - TCOON, TCSADRAIN, TCSAFLUSH, TCSANOW, TOSTOP, VDISCARD, VEOF, VEOL, VEOL2, VERASE, VINTR, - VKILL, VLNEXT, VMIN, VQUIT, VREPRINT, VSTART, VSTOP, VSUSP, VSWTC, VT0, VT1, VTDLY, VTIME, - VWERASE, XCASE, XTABS, + B0, B50, B75, B110, B134, B150, B200, B300, B600, B1200, B1800, B2400, B4800, B9600, + B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, + B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000, BOTHER, BRKINT, BS0, + BS1, BSDLY, CBAUD, CBAUDEX, CIBAUD, CLOCAL, CMSPAR, CR0, CR1, CR2, CR3, CRDLY, CREAD, + CRTSCTS, CS5, CS6, CS7, CS8, CSIZE, CSTOPB, ECHO, ECHOCTL, ECHOE, ECHOK, ECHOKE, ECHONL, + ECHOPRT, EXTA, EXTB, EXTPROC, FF0, FF1, FFDLY, FLUSHO, HUPCL, IBSHIFT, ICANON, ICRNL, + IEXTEN, IGNBRK, IGNCR, IGNPAR, IMAXBEL, INLCR, INPCK, ISIG, ISTRIP, IUCLC, IUTF8, IXANY, + IXOFF, IXON, NCCS, NL0, NL1, NLDLY, NOFLSH, OCRNL, OFDEL, OFILL, OLCUC, ONLCR, ONLRET, + ONOCR, OPOST, PARENB, PARMRK, PARODD, PENDIN, TAB0, TAB1, TAB2, TAB3, TABDLY, TCIFLUSH, + TCIOFF, TCIOFLUSH, TCION, TCOFLUSH, TCOOFF, TCOON, TCSADRAIN, TCSAFLUSH, TCSANOW, TOSTOP, + VDISCARD, VEOF, VEOL, VEOL2, VERASE, VINTR, VKILL, VLNEXT, VMIN, VQUIT, VREPRINT, VSTART, + VSTOP, VSUSP, VSWTC, VT0, VT1, VTDLY, VTIME, VWERASE, XCASE, XTABS, cc_t, speed_t, + tcflag_t, termios, termios2, winsize, }, ioctl::{ TCFLSH, TCGETS, TCGETS2, TCSBRK, TCSETS, TCSETS2, TCSETSF2, TCSETSW2, TCXONC, TIOCEXCL, diff --git a/src/backend/linux_raw/conv.rs b/src/backend/linux_raw/conv.rs index 901451ae6..45d2fbf34 100644 --- a/src/backend/linux_raw/conv.rs +++ b/src/backend/linux_raw/conv.rs @@ -27,7 +27,7 @@ use super::io::errno::{ try_decode_c_int, try_decode_c_uint, try_decode_raw_fd, try_decode_usize, try_decode_void, try_decode_void_star, }; -use super::reg::{raw_arg, ArgNumber, ArgReg, RetReg, R0}; +use super::reg::{ArgNumber, ArgReg, R0, RetReg, raw_arg}; #[cfg(feature = "time")] use super::time::types::TimerfdClockId; #[cfg(any(feature = "thread", feature = "time"))] @@ -779,7 +779,7 @@ impl<'a, Num: ArgNumber> From<(crate::net::SocketType, crate::net::SocketFlags)> { #[inline] fn from(pair: (crate::net::SocketType, crate::net::SocketFlags)) -> Self { - c_uint(pair.0 .0 | pair.1.bits()) + c_uint(pair.0.0 | pair.1.bits()) } } @@ -867,7 +867,7 @@ impl<'a, Num: ArgNumber> From for ArgReg<'a, Num> { /// just returns 0 on success. #[inline] pub(super) unsafe fn ret(raw: RetReg) -> io::Result<()> { - try_decode_void(raw) + unsafe { try_decode_void(raw) } } /// Convert a `usize` returned from a syscall that doesn't return on success. @@ -879,7 +879,7 @@ pub(super) unsafe fn ret(raw: RetReg) -> io::Result<()> { #[cfg(any(feature = "event", feature = "runtime", feature = "system"))] #[inline] pub(super) unsafe fn ret_error(raw: RetReg) -> io::Errno { - try_decode_error(raw) + unsafe { try_decode_error(raw) } } /// Convert a `usize` returned from a syscall that effectively always returns @@ -891,12 +891,14 @@ pub(super) unsafe fn ret_error(raw: RetReg) -> io::Errno { /// always returns `()`. #[inline] pub(super) unsafe fn ret_infallible(raw: RetReg) { - #[cfg(debug_assertions)] - { - try_decode_void(raw).unwrap() + unsafe { + #[cfg(debug_assertions)] + { + try_decode_void(raw).unwrap() + } + #[cfg(not(debug_assertions))] + drop(raw); } - #[cfg(not(debug_assertions))] - drop(raw); } /// Convert a `usize` returned from a syscall that effectively returns a @@ -994,8 +996,10 @@ pub(super) unsafe fn ret_c_uint_infallible(raw: RetReg) -> c::c_uint { /// returns an owned file descriptor. #[inline] pub(super) unsafe fn ret_owned_fd(raw: RetReg) -> io::Result { - let raw_fd = try_decode_raw_fd(raw)?; - Ok(crate::backend::fd::OwnedFd::from_raw_fd(raw_fd)) + unsafe { + let raw_fd = try_decode_raw_fd(raw)?; + Ok(crate::backend::fd::OwnedFd::from_raw_fd(raw_fd)) + } } /// Convert the return value of `dup2` and `dup3`. @@ -1009,8 +1013,10 @@ pub(super) unsafe fn ret_owned_fd(raw: RetReg) -> io::Result { /// returns a file descriptor. #[inline] pub(super) unsafe fn ret_discarded_fd(raw: RetReg) -> io::Result<()> { - let _raw_fd = try_decode_raw_fd(raw)?; - Ok(()) + unsafe { + let _raw_fd = try_decode_raw_fd(raw)?; + Ok(()) + } } /// Convert a `usize` returned from a syscall that effectively returns a diff --git a/src/backend/linux_raw/event/syscalls.rs b/src/backend/linux_raw/event/syscalls.rs index 8a4e24bd6..404938a4c 100644 --- a/src/backend/linux_raw/event/syscalls.rs +++ b/src/backend/linux_raw/event/syscalls.rs @@ -9,11 +9,11 @@ use crate::backend::conv::{ by_ref, c_int, c_uint, opt_mut, opt_ref, pass_usize, ret, ret_c_int, ret_error, ret_owned_fd, ret_usize, size_of, slice_mut, zero, }; -use crate::event::{epoll, EventfdFlags, FdSetElement, PollFd, Timespec}; +use crate::event::{EventfdFlags, FdSetElement, PollFd, Timespec, epoll}; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io; use core::ptr::null_mut; -use linux_raw_sys::general::{kernel_sigset_t, EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD}; +use linux_raw_sys::general::{EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD, kernel_sigset_t}; #[inline] pub(crate) fn poll(fds: &mut [PollFd<'_>], timeout: Option<&Timespec>) -> io::Result { @@ -111,115 +111,117 @@ pub(crate) unsafe fn select( exceptfds: Option<&mut [FdSetElement]>, timeout: Option<&crate::timespec::Timespec>, ) -> io::Result { - let len = crate::event::fd_set_num_elements_for_bitvector(nfds); + unsafe { + let len = crate::event::fd_set_num_elements_for_bitvector(nfds); - let readfds = match readfds { - Some(readfds) => { - assert!(readfds.len() >= len); - readfds.as_mut_ptr() - } - None => null_mut(), - }; - let writefds = match writefds { - Some(writefds) => { - assert!(writefds.len() >= len); - writefds.as_mut_ptr() - } - None => null_mut(), - }; - let exceptfds = match exceptfds { - Some(exceptfds) => { - assert!(exceptfds.len() >= len); - exceptfds.as_mut_ptr() - } - None => null_mut(), - }; + let readfds = match readfds { + Some(readfds) => { + assert!(readfds.len() >= len); + readfds.as_mut_ptr() + } + None => null_mut(), + }; + let writefds = match writefds { + Some(writefds) => { + assert!(writefds.len() >= len); + writefds.as_mut_ptr() + } + None => null_mut(), + }; + let exceptfds = match exceptfds { + Some(exceptfds) => { + assert!(exceptfds.len() >= len); + exceptfds.as_mut_ptr() + } + None => null_mut(), + }; - #[cfg(target_pointer_width = "32")] - { - // If we don't have Linux 5.1, and the timeout fits in a - // `__kernel_old_timespec`, use plain `pselect6`. - // - // We do this unconditionally, rather than trying `pselect6_time64` and - // falling back on `Errno::NOSYS`, because seccomp configurations will - // sometimes abort the process on syscalls they don't recognize. - #[cfg(not(feature = "linux_5_1"))] + #[cfg(target_pointer_width = "32")] { - use linux_raw_sys::general::__kernel_old_timespec; + // If we don't have Linux 5.1, and the timeout fits in a + // `__kernel_old_timespec`, use plain `pselect6`. + // + // We do this unconditionally, rather than trying `pselect6_time64` and + // falling back on `Errno::NOSYS`, because seccomp configurations will + // sometimes abort the process on syscalls they don't recognize. + #[cfg(not(feature = "linux_5_1"))] + { + use linux_raw_sys::general::__kernel_old_timespec; - // If we don't have a timeout, or if we can convert the timeout to - // a `__kernel_old_timespec`, the use `__NR_pselect6`. - fn convert(timeout: &Timespec) -> Option<__kernel_old_timespec> { - Some(__kernel_old_timespec { - tv_sec: timeout.tv_sec.try_into().ok()?, - tv_nsec: timeout.tv_nsec.try_into().ok()?, - }) - } - let old_timeout = if let Some(timeout) = timeout { - match convert(timeout) { - // Could not convert timeout. - None => None, - // Could convert timeout. Ok! - Some(old_timeout) => Some(Some(old_timeout)), + // If we don't have a timeout, or if we can convert the timeout to + // a `__kernel_old_timespec`, the use `__NR_pselect6`. + fn convert(timeout: &Timespec) -> Option<__kernel_old_timespec> { + Some(__kernel_old_timespec { + tv_sec: timeout.tv_sec.try_into().ok()?, + tv_nsec: timeout.tv_nsec.try_into().ok()?, + }) + } + let old_timeout = if let Some(timeout) = timeout { + match convert(timeout) { + // Could not convert timeout. + None => None, + // Could convert timeout. Ok! + Some(old_timeout) => Some(Some(old_timeout)), + } + } else { + // No timeout. Ok! + Some(None) + }; + if let Some(mut old_timeout) = old_timeout { + // Call `pselect6`. + // + // Linux's `pselect6` mutates the timeout argument. Our public + // interface does not do this, because it's not portable to other + // platforms, so we create a temporary value to hide this behavior. + return ret_c_int(syscall!( + __NR_pselect6, + c_int(nfds), + readfds, + writefds, + exceptfds, + opt_mut(old_timeout.as_mut()), + zero() + )); } - } else { - // No timeout. Ok! - Some(None) - }; - if let Some(mut old_timeout) = old_timeout { - // Call `pselect6`. - // - // Linux's `pselect6` mutates the timeout argument. Our public - // interface does not do this, because it's not portable to other - // platforms, so we create a temporary value to hide this behavior. - return ret_c_int(syscall!( - __NR_pselect6, - c_int(nfds), - readfds, - writefds, - exceptfds, - opt_mut(old_timeout.as_mut()), - zero() - )); } - } - // We either have Linux 5.1 or the timeout didn't fit in - // `__kernel_old_timespec` so `__NR_pselect6_time64` will either - // succeed or fail due to our having no other options. + // We either have Linux 5.1 or the timeout didn't fit in + // `__kernel_old_timespec` so `__NR_pselect6_time64` will either + // succeed or fail due to our having no other options. - // Call `pselect6_time64`. - // - // Linux's `pselect6_time64` mutates the timeout argument. Our public - // interface does not do this, because it's not portable to other - // platforms, so we create a temporary value to hide this behavior. - ret_c_int(syscall!( - __NR_pselect6_time64, - c_int(nfds), - readfds, - writefds, - exceptfds, - opt_mut(timeout.copied().as_mut()), - zero() - )) - } + // Call `pselect6_time64`. + // + // Linux's `pselect6_time64` mutates the timeout argument. Our public + // interface does not do this, because it's not portable to other + // platforms, so we create a temporary value to hide this behavior. + ret_c_int(syscall!( + __NR_pselect6_time64, + c_int(nfds), + readfds, + writefds, + exceptfds, + opt_mut(timeout.copied().as_mut()), + zero() + )) + } - #[cfg(target_pointer_width = "64")] - { - // Call `pselect6`. - // - // Linux's `pselect6` mutates the timeout argument. Our public interface - // does not do this, because it's not portable to other platforms, so we - // create a temporary value to hide this behavior. - ret_c_int(syscall!( - __NR_pselect6, - c_int(nfds), - readfds, - writefds, - exceptfds, - opt_mut(timeout.copied().as_mut()), - zero() - )) + #[cfg(target_pointer_width = "64")] + { + // Call `pselect6`. + // + // Linux's `pselect6` mutates the timeout argument. Our public interface + // does not do this, because it's not portable to other platforms, so we + // create a temporary value to hide this behavior. + ret_c_int(syscall!( + __NR_pselect6, + c_int(nfds), + readfds, + writefds, + exceptfds, + opt_mut(timeout.copied().as_mut()), + zero() + )) + } } } @@ -288,49 +290,51 @@ pub(crate) unsafe fn epoll_wait( events: (*mut crate::event::epoll::Event, usize), timeout: Option<&Timespec>, ) -> io::Result { - // If we don't have Linux 5.1, and the timeout fits in an `i32`, use plain - // `epoll_pwait`. - // - // We do this unconditionally, rather than trying `epoll_pwait2` and - // falling back on `Errno::NOSYS`, because seccomp configurations will - // sometimes abort the process on syscalls they don't recognize. - #[cfg(not(feature = "linux_5_11"))] - { - // If we don't have a timeout, or if we can convert the timeout to an - // `i32`, the use `__NR_epoll_pwait`. - let old_timeout = if let Some(timeout) = timeout { - // Try to convert the timeout; if this is `Some`, we're ok! - timeout.as_c_int_millis() - } else { - // No timeout. Ok! - Some(-1) - }; - if let Some(old_timeout) = old_timeout { - // Call `epoll_pwait`. - return ret_usize(syscall!( - __NR_epoll_pwait, - epfd, - events.0, - pass_usize(events.1), - c_int(old_timeout), - zero() - )); + unsafe { + // If we don't have Linux 5.1, and the timeout fits in an `i32`, use plain + // `epoll_pwait`. + // + // We do this unconditionally, rather than trying `epoll_pwait2` and + // falling back on `Errno::NOSYS`, because seccomp configurations will + // sometimes abort the process on syscalls they don't recognize. + #[cfg(not(feature = "linux_5_11"))] + { + // If we don't have a timeout, or if we can convert the timeout to an + // `i32`, the use `__NR_epoll_pwait`. + let old_timeout = if let Some(timeout) = timeout { + // Try to convert the timeout; if this is `Some`, we're ok! + timeout.as_c_int_millis() + } else { + // No timeout. Ok! + Some(-1) + }; + if let Some(old_timeout) = old_timeout { + // Call `epoll_pwait`. + return ret_usize(syscall!( + __NR_epoll_pwait, + epfd, + events.0, + pass_usize(events.1), + c_int(old_timeout), + zero() + )); + } } - } - // Call `epoll_pwait2`. - // - // We either have Linux 5.1 or the timeout didn't fit in an `i32`, so - // `__NR_epoll_pwait2` will either succeed or fail due to our having no - // other options. - ret_usize(syscall!( - __NR_epoll_pwait2, - epfd, - events.0, - pass_usize(events.1), - opt_ref(timeout), - zero() - )) + // Call `epoll_pwait2`. + // + // We either have Linux 5.1 or the timeout didn't fit in an `i32`, so + // `__NR_epoll_pwait2` will either succeed or fail due to our having no + // other options. + ret_usize(syscall!( + __NR_epoll_pwait2, + epfd, + events.0, + pass_usize(events.1), + opt_ref(timeout), + zero() + )) + } } #[inline] diff --git a/src/backend/linux_raw/fs/dir.rs b/src/backend/linux_raw/fs/dir.rs index 31ebc5437..370eb4af0 100644 --- a/src/backend/linux_raw/fs/dir.rs +++ b/src/backend/linux_raw/fs/dir.rs @@ -1,7 +1,7 @@ use crate::fd::{AsFd, BorrowedFd, OwnedFd}; use crate::ffi::{CStr, CString}; use crate::fs::{ - fcntl_getfl, fstat, fstatfs, fstatvfs, openat, FileType, Mode, OFlags, Stat, StatFs, StatVfs, + FileType, Mode, OFlags, Stat, StatFs, StatVfs, fcntl_getfl, fstat, fstatfs, fstatvfs, openat, }; use crate::io; #[cfg(feature = "process")] @@ -11,7 +11,7 @@ use alloc::borrow::ToOwned as _; use alloc::vec::Vec; use core::fmt; use core::mem::size_of; -use linux_raw_sys::general::{linux_dirent64, SEEK_SET}; +use linux_raw_sys::general::{SEEK_SET, linux_dirent64}; /// `DIR*` pub struct Dir { @@ -251,11 +251,7 @@ impl Dir { }; self.buf.resize(nread, 0); self.pos = 0; - if nread == 0 { - None - } else { - Some(Ok(())) - } + if nread == 0 { None } else { Some(Ok(())) } } /// `fstat(self)` diff --git a/src/backend/linux_raw/fs/syscalls.rs b/src/backend/linux_raw/fs/syscalls.rs index 872dd8e35..6c92a1c10 100644 --- a/src/backend/linux_raw/fs/syscalls.rs +++ b/src/backend/linux_raw/fs/syscalls.rs @@ -27,9 +27,9 @@ use crate::ffi::CStr; #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))] use crate::fs::CWD; use crate::fs::{ - inotify, Access, Advice, AtFlags, FallocateFlags, FileType, FlockOperation, Fsid, Gid, - MemfdFlags, Mode, OFlags, RenameFlags, ResolveFlags, SealFlags, SeekFrom, Stat, StatFs, - StatVfs, StatVfsMountFlags, Statx, StatxFlags, Timestamps, Uid, XattrFlags, + Access, Advice, AtFlags, FallocateFlags, FileType, FlockOperation, Fsid, Gid, MemfdFlags, Mode, + OFlags, RenameFlags, ResolveFlags, SealFlags, SeekFrom, Stat, StatFs, StatVfs, + StatVfsMountFlags, Statx, StatxFlags, Timestamps, Uid, XattrFlags, inotify, }; use crate::io; use core::mem::MaybeUninit; @@ -37,8 +37,8 @@ use core::num::NonZeroU64; #[cfg(any(target_arch = "mips64", target_arch = "mips64r6"))] use linux_raw_sys::general::stat as linux_stat64; use linux_raw_sys::general::{ - open_how, AT_EACCESS, AT_FDCWD, AT_REMOVEDIR, AT_SYMLINK_NOFOLLOW, F_ADD_SEALS, F_GETFL, - F_GET_SEALS, F_SETFL, SEEK_CUR, SEEK_DATA, SEEK_END, SEEK_HOLE, SEEK_SET, STATX__RESERVED, + AT_EACCESS, AT_FDCWD, AT_REMOVEDIR, AT_SYMLINK_NOFOLLOW, F_ADD_SEALS, F_GET_SEALS, F_GETFL, + F_SETFL, SEEK_CUR, SEEK_DATA, SEEK_END, SEEK_HOLE, SEEK_SET, STATX__RESERVED, open_how, }; #[cfg(target_pointer_width = "32")] use { @@ -973,13 +973,15 @@ pub(crate) unsafe fn readlinkat( path: &CStr, buf: (*mut u8, usize), ) -> io::Result { - ret_usize(syscall!( - __NR_readlinkat, - dirfd, - path, - buf.0, - pass_usize(buf.1) - )) + unsafe { + ret_usize(syscall!( + __NR_readlinkat, + dirfd, + path, + buf.0, + pass_usize(buf.1) + )) + } } #[inline] @@ -1048,11 +1050,11 @@ pub(crate) fn fcntl_add_seals(fd: BorrowedFd<'_>, seals: SealFlags) -> io::Resul #[inline] pub(crate) fn fcntl_lock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::Result<()> { + use linux_raw_sys::general::{F_RDLCK, F_UNLCK, F_WRLCK}; #[cfg(target_pointer_width = "64")] - use linux_raw_sys::general::{flock, F_SETLK, F_SETLKW}; + use linux_raw_sys::general::{F_SETLK, F_SETLKW, flock}; #[cfg(target_pointer_width = "32")] - use linux_raw_sys::general::{flock64 as flock, F_SETLK64 as F_SETLK, F_SETLKW64 as F_SETLKW}; - use linux_raw_sys::general::{F_RDLCK, F_UNLCK, F_WRLCK}; + use linux_raw_sys::general::{F_SETLK64 as F_SETLK, F_SETLKW64 as F_SETLKW, flock64 as flock}; let (cmd, l_type) = match operation { FlockOperation::LockShared => (F_SETLKW, F_RDLCK), @@ -1528,13 +1530,15 @@ pub(crate) unsafe fn getxattr( name: &CStr, value: (*mut u8, usize), ) -> io::Result { - ret_usize(syscall!( - __NR_getxattr, - path, - name, - value.0, - pass_usize(value.1) - )) + unsafe { + ret_usize(syscall!( + __NR_getxattr, + path, + name, + value.0, + pass_usize(value.1) + )) + } } #[inline] @@ -1543,13 +1547,15 @@ pub(crate) unsafe fn lgetxattr( name: &CStr, value: (*mut u8, usize), ) -> io::Result { - ret_usize(syscall!( - __NR_lgetxattr, - path, - name, - value.0, - pass_usize(value.1) - )) + unsafe { + ret_usize(syscall!( + __NR_lgetxattr, + path, + name, + value.0, + pass_usize(value.1) + )) + } } #[inline] @@ -1558,13 +1564,15 @@ pub(crate) unsafe fn fgetxattr( name: &CStr, value: (*mut u8, usize), ) -> io::Result { - ret_usize(syscall!( - __NR_fgetxattr, - fd, - name, - value.0, - pass_usize(value.1) - )) + unsafe { + ret_usize(syscall!( + __NR_fgetxattr, + fd, + name, + value.0, + pass_usize(value.1) + )) + } } #[inline] @@ -1629,17 +1637,17 @@ pub(crate) fn fsetxattr( #[inline] pub(crate) unsafe fn listxattr(path: &CStr, list: (*mut u8, usize)) -> io::Result { - ret_usize(syscall!(__NR_listxattr, path, list.0, pass_usize(list.1))) + unsafe { ret_usize(syscall!(__NR_listxattr, path, list.0, pass_usize(list.1))) } } #[inline] pub(crate) unsafe fn llistxattr(path: &CStr, list: (*mut u8, usize)) -> io::Result { - ret_usize(syscall!(__NR_llistxattr, path, list.0, pass_usize(list.1))) + unsafe { ret_usize(syscall!(__NR_llistxattr, path, list.0, pass_usize(list.1))) } } #[inline] pub(crate) unsafe fn flistxattr(fd: BorrowedFd<'_>, list: (*mut u8, usize)) -> io::Result { - ret_usize(syscall!(__NR_flistxattr, fd, list.0, pass_usize(list.1))) + unsafe { ret_usize(syscall!(__NR_flistxattr, fd, list.0, pass_usize(list.1))) } } #[inline] diff --git a/src/backend/linux_raw/io/syscalls.rs b/src/backend/linux_raw/io/syscalls.rs index f40dfe5e2..93e61aa5f 100644 --- a/src/backend/linux_raw/io/syscalls.rs +++ b/src/backend/linux_raw/io/syscalls.rs @@ -24,7 +24,7 @@ use crate::backend::conv::{ }; #[cfg(target_pointer_width = "32")] use crate::backend::conv::{hi, lo}; -use crate::backend::{c, MAX_IOV}; +use crate::backend::{MAX_IOV, c}; use crate::fd::{AsFd as _, BorrowedFd, OwnedFd, RawFd}; use crate::io::{self, DupFlags, FdFlags, IoSlice, IoSliceMut, ReadWriteFlags}; use crate::ioctl::{IoctlOutput, Opcode}; @@ -33,7 +33,7 @@ use linux_raw_sys::general::{F_DUPFD_CLOEXEC, F_GETFD, F_SETFD}; #[inline] pub(crate) unsafe fn read(fd: BorrowedFd<'_>, buf: (*mut u8, usize)) -> io::Result { - ret_usize(syscall!(__NR_read, fd, buf.0, pass_usize(buf.1))) + unsafe { ret_usize(syscall!(__NR_read, fd, buf.0, pass_usize(buf.1))) } } #[inline] @@ -42,54 +42,56 @@ pub(crate) unsafe fn pread( buf: (*mut u8, usize), pos: u64, ) -> io::Result { - // - #[cfg(all( - target_pointer_width = "32", - any( - target_arch = "arm", - target_arch = "mips", - target_arch = "mips32r6", - target_arch = "powerpc" - ), - ))] - { - ret_usize(syscall!( - __NR_pread64, - fd, - buf.0, - pass_usize(buf.1), - zero(), - hi(pos), - lo(pos) - )) - } - #[cfg(all( - target_pointer_width = "32", - not(any( - target_arch = "arm", - target_arch = "mips", - target_arch = "mips32r6", - target_arch = "powerpc" - )), - ))] - { + unsafe { + // + #[cfg(all( + target_pointer_width = "32", + any( + target_arch = "arm", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "powerpc" + ), + ))] + { + ret_usize(syscall!( + __NR_pread64, + fd, + buf.0, + pass_usize(buf.1), + zero(), + hi(pos), + lo(pos) + )) + } + #[cfg(all( + target_pointer_width = "32", + not(any( + target_arch = "arm", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "powerpc" + )), + ))] + { + ret_usize(syscall!( + __NR_pread64, + fd, + buf.0, + pass_usize(buf.1), + hi(pos), + lo(pos) + )) + } + #[cfg(target_pointer_width = "64")] ret_usize(syscall!( __NR_pread64, fd, buf.0, pass_usize(buf.1), - hi(pos), - lo(pos) + loff_t_from_u64(pos) )) } - #[cfg(target_pointer_width = "64")] - ret_usize(syscall!( - __NR_pread64, - fd, - buf.0, - pass_usize(buf.1), - loff_t_from_u64(pos) - )) } #[inline] @@ -259,14 +261,16 @@ pub(crate) fn pwritev2( #[inline] pub(crate) unsafe fn close(fd: RawFd) { - // See the documentation for [`io::close`] for why errors are ignored. - syscall_readonly!(__NR_close, raw_fd(fd)).decode_void(); + unsafe { + // See the documentation for [`io::close`] for why errors are ignored. + syscall_readonly!(__NR_close, raw_fd(fd)).decode_void(); + } } #[cfg(feature = "try_close")] #[inline] pub(crate) unsafe fn try_close(fd: RawFd) -> io::Result<()> { - ret(syscall_readonly!(__NR_close, raw_fd(fd))) + unsafe { ret(syscall_readonly!(__NR_close, raw_fd(fd))) } } #[inline] @@ -275,7 +279,7 @@ pub(crate) unsafe fn ioctl( request: Opcode, arg: *mut c::c_void, ) -> io::Result { - ret_c_int(syscall!(__NR_ioctl, fd, c_uint(request), arg)) + unsafe { ret_c_int(syscall!(__NR_ioctl, fd, c_uint(request), arg)) } } #[inline] @@ -284,7 +288,7 @@ pub(crate) unsafe fn ioctl_readonly( request: Opcode, arg: *mut c::c_void, ) -> io::Result { - ret_c_int(syscall_readonly!(__NR_ioctl, fd, c_uint(request), arg)) + unsafe { ret_c_int(syscall_readonly!(__NR_ioctl, fd, c_uint(request), arg)) } } #[inline] diff --git a/src/backend/linux_raw/io_uring/syscalls.rs b/src/backend/linux_raw/io_uring/syscalls.rs index 3e61b7aa6..179441ee4 100644 --- a/src/backend/linux_raw/io_uring/syscalls.rs +++ b/src/backend/linux_raw/io_uring/syscalls.rs @@ -8,7 +8,7 @@ use crate::backend::conv::{by_mut, c_uint, pass_usize, ret_c_uint, ret_owned_fd}; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io; -use crate::io_uring::{io_uring_params, IoringEnterFlags, IoringRegisterFlags, IoringRegisterOp}; +use crate::io_uring::{IoringEnterFlags, IoringRegisterFlags, IoringRegisterOp, io_uring_params}; use core::ffi::c_void; #[inline] @@ -29,13 +29,15 @@ pub(crate) unsafe fn io_uring_register( arg: *const c_void, nr_args: u32, ) -> io::Result { - ret_c_uint(syscall_readonly!( - __NR_io_uring_register, - fd, - c_uint(opcode as u32), - arg, - c_uint(nr_args) - )) + unsafe { + ret_c_uint(syscall_readonly!( + __NR_io_uring_register, + fd, + c_uint(opcode as u32), + arg, + c_uint(nr_args) + )) + } } #[inline] @@ -46,13 +48,15 @@ pub(crate) unsafe fn io_uring_register_with( arg: *const c_void, nr_args: u32, ) -> io::Result { - ret_c_uint(syscall_readonly!( - __NR_io_uring_register, - fd, - c_uint((opcode as u32) | bitflags_bits!(flags)), - arg, - c_uint(nr_args) - )) + unsafe { + ret_c_uint(syscall_readonly!( + __NR_io_uring_register, + fd, + c_uint((opcode as u32) | bitflags_bits!(flags)), + arg, + c_uint(nr_args) + )) + } } #[inline] @@ -64,16 +68,18 @@ pub(crate) unsafe fn io_uring_enter( arg: *const c_void, size: usize, ) -> io::Result { - // This is not `_readonly` because `io_uring_enter` waits for I/O to - // complete, and I/O could involve writing to memory buffers, which - // could be a side effect depended on by the caller. - ret_c_uint(syscall!( - __NR_io_uring_enter, - fd, - c_uint(to_submit), - c_uint(min_complete), - flags, - arg, - pass_usize(size) - )) + unsafe { + // This is not `_readonly` because `io_uring_enter` waits for I/O to + // complete, and I/O could involve writing to memory buffers, which + // could be a side effect depended on by the caller. + ret_c_uint(syscall!( + __NR_io_uring_enter, + fd, + c_uint(to_submit), + c_uint(min_complete), + flags, + arg, + pass_usize(size) + )) + } } diff --git a/src/backend/linux_raw/mm/syscalls.rs b/src/backend/linux_raw/mm/syscalls.rs index 84881906f..2bae9149f 100644 --- a/src/backend/linux_raw/mm/syscalls.rs +++ b/src/backend/linux_raw/mm/syscalls.rs @@ -33,7 +33,7 @@ pub(crate) fn madvise(addr: *mut c_void, len: usize, advice: Advice) -> io::Resu #[inline] pub(crate) unsafe fn msync(addr: *mut c_void, len: usize, flags: MsyncFlags) -> io::Result<()> { - ret(syscall!(__NR_msync, addr, pass_usize(len), flags)) + unsafe { ret(syscall!(__NR_msync, addr, pass_usize(len), flags)) } } /// # Safety @@ -49,32 +49,34 @@ pub(crate) unsafe fn mmap( fd: BorrowedFd<'_>, offset: u64, ) -> io::Result<*mut c_void> { - #[cfg(target_pointer_width = "32")] - { - ret_void_star(syscall!( - __NR_mmap2, - addr, - pass_usize(length), - prot, - flags, - fd, - (offset / 4096) - .try_into() - .map(pass_usize) - .map_err(|_| io::Errno::INVAL)? - )) - } - #[cfg(target_pointer_width = "64")] - { - ret_void_star(syscall!( - __NR_mmap, - addr, - pass_usize(length), - prot, - flags, - fd, - loff_t_from_u64(offset) - )) + unsafe { + #[cfg(target_pointer_width = "32")] + { + ret_void_star(syscall!( + __NR_mmap2, + addr, + pass_usize(length), + prot, + flags, + fd, + (offset / 4096) + .try_into() + .map(pass_usize) + .map_err(|_| io::Errno::INVAL)? + )) + } + #[cfg(target_pointer_width = "64")] + { + ret_void_star(syscall!( + __NR_mmap, + addr, + pass_usize(length), + prot, + flags, + fd, + loff_t_from_u64(offset) + )) + } } } @@ -89,29 +91,31 @@ pub(crate) unsafe fn mmap_anonymous( prot: ProtFlags, flags: MapFlags, ) -> io::Result<*mut c_void> { - #[cfg(target_pointer_width = "32")] - { - ret_void_star(syscall!( - __NR_mmap2, - addr, - pass_usize(length), - prot, - c_uint(flags.bits() | MAP_ANONYMOUS), - no_fd(), - pass_usize(0) - )) - } - #[cfg(target_pointer_width = "64")] - { - ret_void_star(syscall!( - __NR_mmap, - addr, - pass_usize(length), - prot, - c_uint(flags.bits() | MAP_ANONYMOUS), - no_fd(), - loff_t_from_u64(0) - )) + unsafe { + #[cfg(target_pointer_width = "32")] + { + ret_void_star(syscall!( + __NR_mmap2, + addr, + pass_usize(length), + prot, + c_uint(flags.bits() | MAP_ANONYMOUS), + no_fd(), + pass_usize(0) + )) + } + #[cfg(target_pointer_width = "64")] + { + ret_void_star(syscall!( + __NR_mmap, + addr, + pass_usize(length), + prot, + c_uint(flags.bits() | MAP_ANONYMOUS), + no_fd(), + loff_t_from_u64(0) + )) + } } } @@ -121,7 +125,7 @@ pub(crate) unsafe fn mprotect( len: usize, flags: MprotectFlags, ) -> io::Result<()> { - ret(syscall!(__NR_mprotect, ptr, pass_usize(len), flags)) + unsafe { ret(syscall!(__NR_mprotect, ptr, pass_usize(len), flags)) } } /// # Safety @@ -130,7 +134,7 @@ pub(crate) unsafe fn mprotect( /// working with memory pointed to by raw pointers is unsafe. #[inline] pub(crate) unsafe fn munmap(addr: *mut c_void, length: usize) -> io::Result<()> { - ret(syscall!(__NR_munmap, addr, pass_usize(length))) + unsafe { ret(syscall!(__NR_munmap, addr, pass_usize(length))) } } /// # Safety @@ -144,13 +148,15 @@ pub(crate) unsafe fn mremap( new_size: usize, flags: MremapFlags, ) -> io::Result<*mut c_void> { - ret_void_star(syscall!( - __NR_mremap, - old_address, - pass_usize(old_size), - pass_usize(new_size), - flags - )) + unsafe { + ret_void_star(syscall!( + __NR_mremap, + old_address, + pass_usize(old_size), + pass_usize(new_size), + flags + )) + } } /// # Safety @@ -166,14 +172,16 @@ pub(crate) unsafe fn mremap_fixed( flags: MremapFlags, new_address: *mut c_void, ) -> io::Result<*mut c_void> { - ret_void_star(syscall!( - __NR_mremap, - old_address, - pass_usize(old_size), - pass_usize(new_size), - c_uint(flags.bits() | MREMAP_FIXED), - new_address - )) + unsafe { + ret_void_star(syscall!( + __NR_mremap, + old_address, + pass_usize(old_size), + pass_usize(new_size), + c_uint(flags.bits() | MREMAP_FIXED), + new_address + )) + } } /// # Safety @@ -182,7 +190,7 @@ pub(crate) unsafe fn mremap_fixed( /// boundaries. #[inline] pub(crate) unsafe fn mlock(addr: *mut c_void, length: usize) -> io::Result<()> { - ret(syscall!(__NR_mlock, addr, pass_usize(length))) + unsafe { ret(syscall!(__NR_mlock, addr, pass_usize(length))) } } /// # Safety @@ -195,7 +203,7 @@ pub(crate) unsafe fn mlock_with( length: usize, flags: MlockFlags, ) -> io::Result<()> { - ret(syscall!(__NR_mlock2, addr, pass_usize(length), flags)) + unsafe { ret(syscall!(__NR_mlock2, addr, pass_usize(length), flags)) } } /// # Safety @@ -204,12 +212,12 @@ pub(crate) unsafe fn mlock_with( /// boundaries. #[inline] pub(crate) unsafe fn munlock(addr: *mut c_void, length: usize) -> io::Result<()> { - ret(syscall!(__NR_munlock, addr, pass_usize(length))) + unsafe { ret(syscall!(__NR_munlock, addr, pass_usize(length))) } } #[inline] pub(crate) unsafe fn userfaultfd(flags: UserfaultfdFlags) -> io::Result { - ret_owned_fd(syscall_readonly!(__NR_userfaultfd, flags)) + unsafe { ret_owned_fd(syscall_readonly!(__NR_userfaultfd, flags)) } } /// Locks all pages mapped into the address space of the calling process. diff --git a/src/backend/linux_raw/net/addr.rs b/src/backend/linux_raw/net/addr.rs index 7138b5713..5232417e1 100644 --- a/src/backend/linux_raw/net/addr.rs +++ b/src/backend/linux_raw/net/addr.rs @@ -8,8 +8,8 @@ use crate::backend::c; use crate::ffi::CStr; -use crate::net::addr::SocketAddrLen; use crate::net::AddressFamily; +use crate::net::addr::SocketAddrLen; use crate::{io, path}; use core::cmp::Ordering; use core::hash::{Hash, Hasher}; @@ -120,14 +120,16 @@ impl SocketAddrUnix { #[cfg(feature = "alloc")] #[cold] unsafe fn path_with_termination(bytes: &[u8]) -> Option> { - let mut owned = Vec::with_capacity(bytes.len() + 1); - owned.extend_from_slice(bytes); - owned.push(b'\0'); - // SAFETY: `from_vec_with_nul_unchecked` since the string is - // NUL-terminated and `bytes` does not contain any NULs. - Some(Cow::Owned( - CString::from_vec_with_nul_unchecked(owned).into(), - )) + unsafe { + let mut owned = Vec::with_capacity(bytes.len() + 1); + owned.extend_from_slice(bytes); + owned.push(b'\0'); + // SAFETY: `from_vec_with_nul_unchecked` since the string is + // NUL-terminated and `bytes` does not contain any NULs. + Some(Cow::Owned( + CString::from_vec_with_nul_unchecked(owned).into(), + )) + } } /// For a filesystem path address, return the path as a byte sequence, diff --git a/src/backend/linux_raw/net/msghdr.rs b/src/backend/linux_raw/net/msghdr.rs index 0343e18c3..5f5b8d3c3 100644 --- a/src/backend/linux_raw/net/msghdr.rs +++ b/src/backend/linux_raw/net/msghdr.rs @@ -38,30 +38,32 @@ pub(crate) unsafe fn with_recv_msghdr( control: &mut RecvAncillaryBuffer<'_>, f: impl FnOnce(&mut c::msghdr) -> io::Result, ) -> io::Result { - control.clear(); - - let mut msghdr = c::msghdr { - msg_name: name.storage.as_mut_ptr().cast(), - msg_namelen: bitcast!(name.len), - msg_iov: iov.as_mut_ptr().cast(), - msg_iovlen: msg_iov_len(iov.len()), - msg_control: control.as_control_ptr().cast(), - msg_controllen: msg_control_len(control.control_len()), - msg_flags: 0, - }; - - let res = f(&mut msghdr); - - // Reset the control length. - if res.is_ok() { - // SAFETY: `f` returned `Ok`, so our safety condition requires `f` to - // have initialized `msg_controllen` bytes. - control.set_control_len(msghdr.msg_controllen as usize); + unsafe { + control.clear(); + + let mut msghdr = c::msghdr { + msg_name: name.storage.as_mut_ptr().cast(), + msg_namelen: bitcast!(name.len), + msg_iov: iov.as_mut_ptr().cast(), + msg_iovlen: msg_iov_len(iov.len()), + msg_control: control.as_control_ptr().cast(), + msg_controllen: msg_control_len(control.control_len()), + msg_flags: 0, + }; + + let res = f(&mut msghdr); + + // Reset the control length. + if res.is_ok() { + // SAFETY: `f` returned `Ok`, so our safety condition requires `f` to + // have initialized `msg_controllen` bytes. + control.set_control_len(msghdr.msg_controllen as usize); + } + + name.len = bitcast!(msghdr.msg_namelen); + + res } - - name.len = bitcast!(msghdr.msg_namelen); - - res } /// Create a message header intended to send without an address. @@ -99,16 +101,18 @@ pub(crate) unsafe fn with_msghdr( control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(&c::msghdr) -> R, ) -> R { - addr.with_sockaddr(|addr_ptr, addr_len| { - // Pass a reference to the `c::msghdr` instead of passing it by value - // because it may contain pointers to temporary objects that won't live - // beyond the call to `with_sockaddr`. - let mut msghdr = noaddr_msghdr(iov, control); - msghdr.msg_name = addr_ptr as _; - msghdr.msg_namelen = bitcast!(addr_len); - - f(&msghdr) - }) + unsafe { + addr.with_sockaddr(|addr_ptr, addr_len| { + // Pass a reference to the `c::msghdr` instead of passing it by value + // because it may contain pointers to temporary objects that won't live + // beyond the call to `with_sockaddr`. + let mut msghdr = noaddr_msghdr(iov, control); + msghdr.msg_name = addr_ptr as _; + msghdr.msg_namelen = bitcast!(addr_len); + + f(&msghdr) + }) + } } /// Create a zero-initialized message header struct value. diff --git a/src/backend/linux_raw/net/netdevice.rs b/src/backend/linux_raw/net/netdevice.rs index d3c2a9640..6fc10297f 100644 --- a/src/backend/linux_raw/net/netdevice.rs +++ b/src/backend/linux_raw/net/netdevice.rs @@ -11,7 +11,7 @@ use linux_raw_sys::ctypes::c_char; use linux_raw_sys::ioctl::SIOCGIFINDEX; #[cfg(feature = "alloc")] use linux_raw_sys::ioctl::SIOCGIFNAME; -use linux_raw_sys::net::{ifreq, ifreq__bindgen_ty_1, ifreq__bindgen_ty_2, IFNAMSIZ}; +use linux_raw_sys::net::{IFNAMSIZ, ifreq, ifreq__bindgen_ty_1, ifreq__bindgen_ty_2}; #[cfg(feature = "alloc")] use {alloc::borrow::ToOwned, alloc::string::String}; diff --git a/src/backend/linux_raw/net/read_sockaddr.rs b/src/backend/linux_raw/net/read_sockaddr.rs index f18cd4833..abcff9e05 100644 --- a/src/backend/linux_raw/net/read_sockaddr.rs +++ b/src/backend/linux_raw/net/read_sockaddr.rs @@ -27,20 +27,22 @@ pub(crate) struct sockaddr_header { /// `storage` must point to a least an initialized `sockaddr_header`. #[inline] pub(crate) const unsafe fn read_sa_family(storage: *const c::sockaddr) -> u16 { - // Assert that we know the layout of `sockaddr`. - let _ = c::sockaddr { - __storage: c::sockaddr_storage { - __bindgen_anon_1: linux_raw_sys::net::__kernel_sockaddr_storage__bindgen_ty_1 { - __bindgen_anon_1: - linux_raw_sys::net::__kernel_sockaddr_storage__bindgen_ty_1__bindgen_ty_1 { - ss_family: 0_u16, - __data: [0; 126_usize], - }, + unsafe { + // Assert that we know the layout of `sockaddr`. + let _ = c::sockaddr { + __storage: c::sockaddr_storage { + __bindgen_anon_1: linux_raw_sys::net::__kernel_sockaddr_storage__bindgen_ty_1 { + __bindgen_anon_1: + linux_raw_sys::net::__kernel_sockaddr_storage__bindgen_ty_1__bindgen_ty_1 { + ss_family: 0_u16, + __data: [0; 126_usize], + }, + }, }, - }, - }; + }; - (*storage.cast::()).sa_family + (*storage.cast::()).sa_family + } } /// Set the `sa_family` field of a socket address to `AF_UNSPEC`, so that we @@ -51,7 +53,9 @@ pub(crate) const unsafe fn read_sa_family(storage: *const c::sockaddr) -> u16 { /// `storage` must point to a least an initialized `sockaddr_header`. #[inline] pub(crate) unsafe fn initialize_family_to_unspec(storage: *mut c::sockaddr) { - (*storage.cast::()).sa_family = c::AF_UNSPEC as _; + unsafe { + (*storage.cast::()).sa_family = c::AF_UNSPEC as _; + } } /// Check if a socket address returned from the OS is considered non-empty. diff --git a/src/backend/linux_raw/net/sockopt.rs b/src/backend/linux_raw/net/sockopt.rs index 3e5ea1fd8..1fa680433 100644 --- a/src/backend/linux_raw/net/sockopt.rs +++ b/src/backend/linux_raw/net/sockopt.rs @@ -22,10 +22,10 @@ use crate::net::{ use alloc::borrow::ToOwned as _; #[cfg(feature = "alloc")] use alloc::string::String; -use core::mem::{size_of, MaybeUninit}; +use core::mem::{MaybeUninit, size_of}; use core::time::Duration; use linux_raw_sys::general::{__kernel_old_timeval, __kernel_sock_timeval}; -use linux_raw_sys::net::{IPV6_MTU, IPV6_MULTICAST_IF, IP_MTU, IP_MULTICAST_IF}; +use linux_raw_sys::net::{IP_MTU, IP_MULTICAST_IF, IPV6_MTU, IPV6_MULTICAST_IF}; #[cfg(target_os = "linux")] use linux_raw_sys::xdp::{xdp_mmap_offsets, xdp_statistics, xdp_statistics_v1}; #[cfg(target_arch = "x86")] @@ -233,7 +233,7 @@ pub(crate) fn socket_timeout(fd: BorrowedFd<'_>, id: Timeout) -> io::Result { - return socket_timeout_old(fd, id) + return socket_timeout_old(fd, id); } otherwise => otherwise?, }; @@ -283,7 +283,7 @@ fn duration_to_linux_sock_timeval(timeout: Option) -> io::Result<__ker // manually round up. let mut timeout = __kernel_sock_timeval { tv_sec: timeout.as_secs().try_into().unwrap_or(i64::MAX), - tv_usec: ((timeout.subsec_nanos() + 999) / 1000) as _, + tv_usec: timeout.subsec_nanos().div_ceil(1000) as _, }; if timeout.tv_sec == 0 && timeout.tv_usec == 0 { timeout.tv_usec = 1; @@ -310,7 +310,7 @@ fn duration_to_linux_old_timeval(timeout: Option) -> io::Result<__kern // manually round up. let mut timeout = __kernel_old_timeval { tv_sec: timeout.as_secs().try_into().unwrap_or(c::c_long::MAX), - tv_usec: ((timeout.subsec_nanos() + 999) / 1000) as _, + tv_usec: timeout.subsec_nanos().div_ceil(1000) as _, }; if timeout.tv_sec == 0 && timeout.tv_usec == 0 { timeout.tv_usec = 1; diff --git a/src/backend/linux_raw/net/syscalls.rs b/src/backend/linux_raw/net/syscalls.rs index 488e08f02..bc8b50e10 100644 --- a/src/backend/linux_raw/net/syscalls.rs +++ b/src/backend/linux_raw/net/syscalls.rs @@ -18,9 +18,9 @@ use crate::backend::conv::{ use crate::backend::reg::raw_arg; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io::{self, IoSlice, IoSliceMut}; -use crate::net::addr::SocketAddrArg; #[cfg(target_os = "linux")] use crate::net::MMsgHdr; +use crate::net::addr::SocketAddrArg; use crate::net::{ AddressFamily, Protocol, RecvAncillaryBuffer, RecvMsg, SendAncillaryBuffer, Shutdown, SocketAddrAny, SocketAddrBuf, SocketFlags, SocketType, @@ -480,49 +480,51 @@ pub(crate) unsafe fn recv( buf: (*mut u8, usize), flags: RecvFlags, ) -> io::Result { - #[cfg(not(any( - target_arch = "aarch64", - target_arch = "mips64", - target_arch = "mips64r6", - target_arch = "riscv64", - target_arch = "s390x", - target_arch = "x86", - target_arch = "x86_64", - )))] - { - ret_usize(syscall!(__NR_recv, fd, buf.0, pass_usize(buf.1), flags)) - } - #[cfg(any( - target_arch = "aarch64", - target_arch = "mips64", - target_arch = "mips64r6", - target_arch = "riscv64", - target_arch = "s390x", - target_arch = "x86_64", - ))] - { - ret_usize(syscall!( - __NR_recvfrom, - fd, - buf.0, - pass_usize(buf.1), - flags, - zero(), - zero() - )) - } - #[cfg(target_arch = "x86")] - { - ret_usize(syscall!( - __NR_socketcall, - x86_sys(SYS_RECV), - slice_just_addr::, _>(&[ - fd.into(), - buf.0.into(), + unsafe { + #[cfg(not(any( + target_arch = "aarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "x86", + target_arch = "x86_64", + )))] + { + ret_usize(syscall!(__NR_recv, fd, buf.0, pass_usize(buf.1), flags)) + } + #[cfg(any( + target_arch = "aarch64", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "x86_64", + ))] + { + ret_usize(syscall!( + __NR_recvfrom, + fd, + buf.0, pass_usize(buf.1), - flags.into(), - ]) - )) + flags, + zero(), + zero() + )) + } + #[cfg(target_arch = "x86")] + { + ret_usize(syscall!( + __NR_socketcall, + x86_sys(SYS_RECV), + slice_just_addr::, _>(&[ + fd.into(), + buf.0.into(), + pass_usize(buf.1), + flags.into(), + ]) + )) + } } } @@ -532,38 +534,40 @@ pub(crate) unsafe fn recvfrom( buf: (*mut u8, usize), flags: RecvFlags, ) -> io::Result<(usize, Option)> { - let mut addr = SocketAddrBuf::new(); + unsafe { + let mut addr = SocketAddrBuf::new(); - // `recvfrom` does not write to the storage if the socket is - // connection-oriented sockets, so we initialize the family field to - // `AF_UNSPEC` so that we can detect this case. - initialize_family_to_unspec(addr.storage.as_mut_ptr().cast::()); + // `recvfrom` does not write to the storage if the socket is + // connection-oriented sockets, so we initialize the family field to + // `AF_UNSPEC` so that we can detect this case. + initialize_family_to_unspec(addr.storage.as_mut_ptr().cast::()); - #[cfg(not(target_arch = "x86"))] - let nread = ret_usize(syscall!( - __NR_recvfrom, - fd, - buf.0, - pass_usize(buf.1), - flags, - &mut addr.storage, - by_mut(&mut addr.len) - ))?; - #[cfg(target_arch = "x86")] - let nread = ret_usize(syscall!( - __NR_socketcall, - x86_sys(SYS_RECVFROM), - slice_just_addr::, _>(&[ - fd.into(), - buf.0.into(), + #[cfg(not(target_arch = "x86"))] + let nread = ret_usize(syscall!( + __NR_recvfrom, + fd, + buf.0, pass_usize(buf.1), - flags.into(), - (&mut addr.storage).into(), - by_mut(&mut addr.len), - ]) - ))?; + flags, + &mut addr.storage, + by_mut(&mut addr.len) + ))?; + #[cfg(target_arch = "x86")] + let nread = ret_usize(syscall!( + __NR_socketcall, + x86_sys(SYS_RECVFROM), + slice_just_addr::, _>(&[ + fd.into(), + buf.0.into(), + pass_usize(buf.1), + flags.into(), + (&mut addr.storage).into(), + by_mut(&mut addr.len), + ]) + ))?; - Ok((nread, addr.into_any_option())) + Ok((nread, addr.into_any_option())) + } } #[inline] diff --git a/src/backend/linux_raw/param/auxv.rs b/src/backend/linux_raw/param/auxv.rs index d748219a9..7d97ccd7e 100644 --- a/src/backend/linux_raw/param/auxv.rs +++ b/src/backend/linux_raw/param/auxv.rs @@ -15,7 +15,7 @@ use crate::utils::{as_ptr, check_raw_pointer}; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::mem::size_of; -use core::ptr::{null_mut, read_unaligned, NonNull}; +use core::ptr::{NonNull, null_mut, read_unaligned}; #[cfg(feature = "runtime")] use core::sync::atomic::AtomicU8; use core::sync::atomic::Ordering::Relaxed; @@ -365,110 +365,112 @@ fn init_from_auxv_file(auxv: OwnedFd) -> Option<()> { #[cold] #[must_use] unsafe fn init_from_aux_iter(aux_iter: impl Iterator) -> Option<()> { - let mut pagesz = 0; - let mut clktck = 0; - let mut hwcap = 0; - let mut hwcap2 = 0; - let mut minsigstksz = 0; - let mut execfn = null_mut(); - let mut sysinfo_ehdr = null_mut(); - #[cfg(feature = "runtime")] - let mut secure = 0; - #[cfg(feature = "runtime")] - let mut phdr = null_mut(); - #[cfg(feature = "runtime")] - let mut phnum = 0; - #[cfg(feature = "runtime")] - let mut phent = 0; - #[cfg(feature = "runtime")] - let mut entry = 0; - #[cfg(feature = "runtime")] - let mut uid = None; - #[cfg(feature = "runtime")] - let mut euid = None; - #[cfg(feature = "runtime")] - let mut gid = None; - #[cfg(feature = "runtime")] - let mut egid = None; - #[cfg(feature = "runtime")] - let mut random = null_mut(); - - for Elf_auxv_t { a_type, a_val } in aux_iter { - match a_type as _ { - AT_PAGESZ => pagesz = a_val as usize, - AT_CLKTCK => clktck = a_val as usize, - AT_HWCAP => hwcap = a_val as usize, - AT_HWCAP2 => hwcap2 = a_val as usize, - AT_MINSIGSTKSZ => minsigstksz = a_val as usize, - AT_EXECFN => execfn = check_raw_pointer::(a_val as *mut _)?.as_ptr(), - AT_SYSINFO_EHDR => sysinfo_ehdr = check_elf_base(a_val as *mut _)?.as_ptr(), - - AT_BASE => { - // The `AT_BASE` value can be null in a static executable that - // doesn't use a dynamic linker. If so, ignore it. - if !a_val.is_null() { - let _ = check_elf_base(a_val.cast())?; + unsafe { + let mut pagesz = 0; + let mut clktck = 0; + let mut hwcap = 0; + let mut hwcap2 = 0; + let mut minsigstksz = 0; + let mut execfn = null_mut(); + let mut sysinfo_ehdr = null_mut(); + #[cfg(feature = "runtime")] + let mut secure = 0; + #[cfg(feature = "runtime")] + let mut phdr = null_mut(); + #[cfg(feature = "runtime")] + let mut phnum = 0; + #[cfg(feature = "runtime")] + let mut phent = 0; + #[cfg(feature = "runtime")] + let mut entry = 0; + #[cfg(feature = "runtime")] + let mut uid = None; + #[cfg(feature = "runtime")] + let mut euid = None; + #[cfg(feature = "runtime")] + let mut gid = None; + #[cfg(feature = "runtime")] + let mut egid = None; + #[cfg(feature = "runtime")] + let mut random = null_mut(); + + for Elf_auxv_t { a_type, a_val } in aux_iter { + match a_type as _ { + AT_PAGESZ => pagesz = a_val as usize, + AT_CLKTCK => clktck = a_val as usize, + AT_HWCAP => hwcap = a_val as usize, + AT_HWCAP2 => hwcap2 = a_val as usize, + AT_MINSIGSTKSZ => minsigstksz = a_val as usize, + AT_EXECFN => execfn = check_raw_pointer::(a_val as *mut _)?.as_ptr(), + AT_SYSINFO_EHDR => sysinfo_ehdr = check_elf_base(a_val as *mut _)?.as_ptr(), + + AT_BASE => { + // The `AT_BASE` value can be null in a static executable that + // doesn't use a dynamic linker. If so, ignore it. + if !a_val.is_null() { + let _ = check_elf_base(a_val.cast())?; + } } - } - #[cfg(feature = "runtime")] - AT_SECURE => secure = (a_val as usize != 0) as u8 + 1, - #[cfg(feature = "runtime")] - AT_UID => uid = Some(a_val), - #[cfg(feature = "runtime")] - AT_EUID => euid = Some(a_val), - #[cfg(feature = "runtime")] - AT_GID => gid = Some(a_val), - #[cfg(feature = "runtime")] - AT_EGID => egid = Some(a_val), - #[cfg(feature = "runtime")] - AT_PHDR => phdr = check_raw_pointer::(a_val as *mut _)?.as_ptr(), - #[cfg(feature = "runtime")] - AT_PHNUM => phnum = a_val as usize, - #[cfg(feature = "runtime")] - AT_PHENT => phent = a_val as usize, - #[cfg(feature = "runtime")] - AT_ENTRY => entry = a_val as usize, - #[cfg(feature = "runtime")] - AT_RANDOM => random = check_raw_pointer::<[u8; 16]>(a_val as *mut _)?.as_ptr(), - - AT_NULL => break, - _ => (), + #[cfg(feature = "runtime")] + AT_SECURE => secure = (a_val as usize != 0) as u8 + 1, + #[cfg(feature = "runtime")] + AT_UID => uid = Some(a_val), + #[cfg(feature = "runtime")] + AT_EUID => euid = Some(a_val), + #[cfg(feature = "runtime")] + AT_GID => gid = Some(a_val), + #[cfg(feature = "runtime")] + AT_EGID => egid = Some(a_val), + #[cfg(feature = "runtime")] + AT_PHDR => phdr = check_raw_pointer::(a_val as *mut _)?.as_ptr(), + #[cfg(feature = "runtime")] + AT_PHNUM => phnum = a_val as usize, + #[cfg(feature = "runtime")] + AT_PHENT => phent = a_val as usize, + #[cfg(feature = "runtime")] + AT_ENTRY => entry = a_val as usize, + #[cfg(feature = "runtime")] + AT_RANDOM => random = check_raw_pointer::<[u8; 16]>(a_val as *mut _)?.as_ptr(), + + AT_NULL => break, + _ => (), + } } - } - #[cfg(feature = "runtime")] - assert_eq!(phent, size_of::()); + #[cfg(feature = "runtime")] + assert_eq!(phent, size_of::()); - // If we're running set-uid or set-gid, enable “secure execution” mode, - // which doesn't do much, but users may be depending on the things that - // it does do. - #[cfg(feature = "runtime")] - if uid != euid || gid != egid { - secure = 2; - } + // If we're running set-uid or set-gid, enable “secure execution” mode, + // which doesn't do much, but users may be depending on the things that + // it does do. + #[cfg(feature = "runtime")] + if uid != euid || gid != egid { + secure = 2; + } - // The base and sysinfo_ehdr (if present) matches our platform. Accept the - // aux values. - PAGE_SIZE.store(pagesz, Relaxed); - CLOCK_TICKS_PER_SECOND.store(clktck, Relaxed); - HWCAP.store(hwcap, Relaxed); - HWCAP2.store(hwcap2, Relaxed); - MINSIGSTKSZ.store(minsigstksz, Relaxed); - EXECFN.store(execfn, Relaxed); - SYSINFO_EHDR.store(sysinfo_ehdr, Relaxed); - #[cfg(feature = "runtime")] - SECURE.store(secure, Relaxed); - #[cfg(feature = "runtime")] - PHDR.store(phdr, Relaxed); - #[cfg(feature = "runtime")] - PHNUM.store(phnum, Relaxed); - #[cfg(feature = "runtime")] - ENTRY.store(entry, Relaxed); - #[cfg(feature = "runtime")] - RANDOM.store(random, Relaxed); - - Some(()) + // The base and sysinfo_ehdr (if present) matches our platform. Accept the + // aux values. + PAGE_SIZE.store(pagesz, Relaxed); + CLOCK_TICKS_PER_SECOND.store(clktck, Relaxed); + HWCAP.store(hwcap, Relaxed); + HWCAP2.store(hwcap2, Relaxed); + MINSIGSTKSZ.store(minsigstksz, Relaxed); + EXECFN.store(execfn, Relaxed); + SYSINFO_EHDR.store(sysinfo_ehdr, Relaxed); + #[cfg(feature = "runtime")] + SECURE.store(secure, Relaxed); + #[cfg(feature = "runtime")] + PHDR.store(phdr, Relaxed); + #[cfg(feature = "runtime")] + PHNUM.store(phnum, Relaxed); + #[cfg(feature = "runtime")] + ENTRY.store(entry, Relaxed); + #[cfg(feature = "runtime")] + RANDOM.store(random, Relaxed); + + Some(()) + } } /// Check that `base` is a valid pointer to the kernel-provided vDSO. @@ -479,63 +481,65 @@ unsafe fn init_from_aux_iter(aux_iter: impl Iterator) -> Opti #[cold] #[must_use] unsafe fn check_elf_base(base: *const Elf_Ehdr) -> Option> { - // If we're reading a 64-bit auxv on a 32-bit platform, we'll see a zero - // `a_val` because `AT_*` values are never greater than `u32::MAX`. Zero is - // used by libc's `getauxval` to indicate errors, so it should never be a - // valid value. - if base.is_null() { - return None; - } + unsafe { + // If we're reading a 64-bit auxv on a 32-bit platform, we'll see a zero + // `a_val` because `AT_*` values are never greater than `u32::MAX`. Zero is + // used by libc's `getauxval` to indicate errors, so it should never be a + // valid value. + if base.is_null() { + return None; + } - let hdr = check_raw_pointer::(base as *mut _)?; + let hdr = check_raw_pointer::(base as *mut _)?; - let hdr = hdr.as_ref(); - if hdr.e_ident[..SELFMAG] != ELFMAG { - return None; // Wrong ELF magic - } - if !matches!(hdr.e_ident[EI_OSABI], ELFOSABI_SYSV | ELFOSABI_LINUX) { - return None; // Unrecognized ELF OS ABI - } - if hdr.e_ident[EI_ABIVERSION] != ELFABIVERSION { - return None; // Unrecognized ELF ABI version - } - if hdr.e_type != ET_DYN { - return None; // Wrong ELF type - } + let hdr = hdr.as_ref(); + if hdr.e_ident[..SELFMAG] != ELFMAG { + return None; // Wrong ELF magic + } + if !matches!(hdr.e_ident[EI_OSABI], ELFOSABI_SYSV | ELFOSABI_LINUX) { + return None; // Unrecognized ELF OS ABI + } + if hdr.e_ident[EI_ABIVERSION] != ELFABIVERSION { + return None; // Unrecognized ELF ABI version + } + if hdr.e_type != ET_DYN { + return None; // Wrong ELF type + } - // If ELF is extended, we'll need to adjust. - if hdr.e_ident[EI_VERSION] != EV_CURRENT - || hdr.e_ehsize as usize != size_of::() - || hdr.e_phentsize as usize != size_of::() - { - return None; - } - // We don't currently support extra-large numbers of segments. - if hdr.e_phnum == PN_XNUM { - return None; - } + // If ELF is extended, we'll need to adjust. + if hdr.e_ident[EI_VERSION] != EV_CURRENT + || hdr.e_ehsize as usize != size_of::() + || hdr.e_phentsize as usize != size_of::() + { + return None; + } + // We don't currently support extra-large numbers of segments. + if hdr.e_phnum == PN_XNUM { + return None; + } - // If `e_phoff` is zero, it's more likely that we're looking at memory that - // has been zeroed than that the kernel has somehow aliased the `Ehdr` and - // the `Phdr`. - if hdr.e_phoff < size_of::() { - return None; - } + // If `e_phoff` is zero, it's more likely that we're looking at memory that + // has been zeroed than that the kernel has somehow aliased the `Ehdr` and + // the `Phdr`. + if hdr.e_phoff < size_of::() { + return None; + } - // Verify that the `EI_CLASS`/`EI_DATA`/`e_machine` fields match the - // architecture we're running as. This helps catch cases where we're - // running under QEMU. - if hdr.e_ident[EI_CLASS] != ELFCLASS { - return None; // Wrong ELF class - } - if hdr.e_ident[EI_DATA] != ELFDATA { - return None; // Wrong ELF data - } - if hdr.e_machine != EM_CURRENT { - return None; // Wrong machine type - } + // Verify that the `EI_CLASS`/`EI_DATA`/`e_machine` fields match the + // architecture we're running as. This helps catch cases where we're + // running under QEMU. + if hdr.e_ident[EI_CLASS] != ELFCLASS { + return None; // Wrong ELF class + } + if hdr.e_ident[EI_DATA] != ELFDATA { + return None; // Wrong ELF data + } + if hdr.e_machine != EM_CURRENT { + return None; // Wrong machine type + } - Some(NonNull::new_unchecked(as_ptr(hdr) as *mut _)) + Some(NonNull::new_unchecked(as_ptr(hdr) as *mut _)) + } } // Aux reading utilities diff --git a/src/backend/linux_raw/param/init.rs b/src/backend/linux_raw/param/init.rs index de1e59492..851adfad0 100644 --- a/src/backend/linux_raw/param/init.rs +++ b/src/backend/linux_raw/param/init.rs @@ -9,7 +9,7 @@ use crate::backend::c; #[cfg(feature = "param")] use crate::ffi::CStr; use core::ffi::c_void; -use core::ptr::{null_mut, read, NonNull}; +use core::ptr::{NonNull, null_mut, read}; #[cfg(feature = "runtime")] use core::sync::atomic::AtomicBool; use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; diff --git a/src/backend/linux_raw/param/libc_auxv.rs b/src/backend/linux_raw/param/libc_auxv.rs index d77d3a840..ac71e5465 100644 --- a/src/backend/linux_raw/param/libc_auxv.rs +++ b/src/backend/linux_raw/param/libc_auxv.rs @@ -20,7 +20,7 @@ weak!(fn getauxval(c::c_ulong) -> *mut c::c_void); // With the "runtime" feature, go ahead and depend on `getauxval` existing so // that we never fail. #[cfg(feature = "runtime")] -extern "C" { +unsafe extern "C" { fn getauxval(type_: c::c_ulong) -> *mut c::c_void; } @@ -43,7 +43,7 @@ const AT_MINSIGSTKSZ: c::c_ulong = 51; // Declare `sysconf` ourselves so that we don't depend on all of libc just for // this. -extern "C" { +unsafe extern "C" { fn sysconf(name: c::c_int) -> c::c_long; } diff --git a/src/backend/linux_raw/pipe/syscalls.rs b/src/backend/linux_raw/pipe/syscalls.rs index 86fe08553..14dc849f7 100644 --- a/src/backend/linux_raw/pipe/syscalls.rs +++ b/src/backend/linux_raw/pipe/syscalls.rs @@ -6,7 +6,7 @@ #![allow(unsafe_code, clippy::undocumented_unsafe_blocks)] use crate::backend::conv::{c_int, c_uint, opt_mut, pass_usize, ret, ret_usize, slice}; -use crate::backend::{c, MAX_IOV}; +use crate::backend::{MAX_IOV, c}; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io; use crate::pipe::{IoSliceRaw, PipeFlags, SpliceFlags}; @@ -84,8 +84,10 @@ pub(crate) unsafe fn vmsplice( bufs: &[IoSliceRaw<'_>], flags: SpliceFlags, ) -> io::Result { - let (bufs_addr, bufs_len) = slice(&bufs[..cmp::min(bufs.len(), MAX_IOV)]); - ret_usize(syscall!(__NR_vmsplice, fd, bufs_addr, bufs_len, flags)) + unsafe { + let (bufs_addr, bufs_len) = slice(&bufs[..cmp::min(bufs.len(), MAX_IOV)]); + ret_usize(syscall!(__NR_vmsplice, fd, bufs_addr, bufs_len, flags)) + } } #[inline] diff --git a/src/backend/linux_raw/prctl/syscalls.rs b/src/backend/linux_raw/prctl/syscalls.rs index 1410d5128..1fe385bb9 100644 --- a/src/backend/linux_raw/prctl/syscalls.rs +++ b/src/backend/linux_raw/prctl/syscalls.rs @@ -17,5 +17,5 @@ pub(crate) unsafe fn prctl( arg4: *mut c::c_void, arg5: *mut c::c_void, ) -> io::Result { - ret_c_int(syscall!(__NR_prctl, c_int(option), arg2, arg3, arg4, arg5)) + unsafe { ret_c_int(syscall!(__NR_prctl, c_int(option), arg2, arg3, arg4, arg5)) } } diff --git a/src/backend/linux_raw/process/syscalls.rs b/src/backend/linux_raw/process/syscalls.rs index c9c1fd824..62f35b0d6 100644 --- a/src/backend/linux_raw/process/syscalls.rs +++ b/src/backend/linux_raw/process/syscalls.rs @@ -24,7 +24,7 @@ use crate::process::{ use crate::signal::Signal; use core::mem::MaybeUninit; use core::ptr::{null, null_mut}; -use linux_raw_sys::general::{rlimit64, PRIO_PGRP, PRIO_PROCESS, PRIO_USER, RLIM64_INFINITY}; +use linux_raw_sys::general::{PRIO_PGRP, PRIO_PROCESS, PRIO_USER, RLIM64_INFINITY, rlimit64}; #[cfg(feature = "fs")] use {crate::backend::conv::ret_c_uint_infallible, crate::fs::Mode}; #[cfg(feature = "alloc")] @@ -407,18 +407,20 @@ fn _waitid_pidfd(fd: BorrowedFd<'_>, options: WaitIdOptions) -> io::Result) -> Option { - let status = status.assume_init(); - if status - .__bindgen_anon_1 - .__bindgen_anon_1 - ._sifields - ._sigchld - ._pid - == 0 - { - None - } else { - Some(WaitIdStatus(status)) + unsafe { + let status = status.assume_init(); + if status + .__bindgen_anon_1 + .__bindgen_anon_1 + ._sifields + ._sigchld + ._pid + == 0 + { + None + } else { + Some(WaitIdStatus(status)) + } } } diff --git a/src/backend/linux_raw/process/wait.rs b/src/backend/linux_raw/process/wait.rs index 89b3eadb5..ff308d332 100644 --- a/src/backend/linux_raw/process/wait.rs +++ b/src/backend/linux_raw/process/wait.rs @@ -3,7 +3,7 @@ use crate::ffi::c_int; pub(crate) use linux_raw_sys::general::{ - siginfo_t, WCONTINUED, WEXITED, WNOHANG, WNOWAIT, WSTOPPED, WUNTRACED, + WCONTINUED, WEXITED, WNOHANG, WNOWAIT, WSTOPPED, WUNTRACED, siginfo_t, }; #[inline] @@ -78,11 +78,13 @@ impl SiginfoExt for siginfo_t { /// `waitid` call). #[inline] unsafe fn si_status(&self) -> c_int { - self.__bindgen_anon_1 - .__bindgen_anon_1 - ._sifields - ._sigchld - ._status + unsafe { + self.__bindgen_anon_1 + .__bindgen_anon_1 + ._sifields + ._sigchld + ._status + } } } diff --git a/src/backend/linux_raw/rand/syscalls.rs b/src/backend/linux_raw/rand/syscalls.rs index acea3968c..a4f1268f9 100644 --- a/src/backend/linux_raw/rand/syscalls.rs +++ b/src/backend/linux_raw/rand/syscalls.rs @@ -11,5 +11,5 @@ use crate::rand::GetRandomFlags; #[inline] pub(crate) unsafe fn getrandom(buf: (*mut u8, usize), flags: GetRandomFlags) -> io::Result { - ret_usize(syscall!(__NR_getrandom, buf.0, pass_usize(buf.1), flags)) + unsafe { ret_usize(syscall!(__NR_getrandom, buf.0, pass_usize(buf.1), flags)) } } diff --git a/src/backend/linux_raw/runtime/syscalls.rs b/src/backend/linux_raw/runtime/syscalls.rs index 1e00030c1..63f19ec77 100644 --- a/src/backend/linux_raw/runtime/syscalls.rs +++ b/src/backend/linux_raw/runtime/syscalls.rs @@ -33,49 +33,51 @@ use linux_raw_sys::general::ARCH_SET_FS; #[inline] pub(crate) unsafe fn kernel_fork() -> io::Result { - let mut child_pid = MaybeUninit::::uninit(); + unsafe { + let mut child_pid = MaybeUninit::::uninit(); - // Unix `fork` only returns the child PID in the parent; we'd like it in - // the child too, so set `CLONE_CHILD_SETTID` and pass in the address of a - // memory location to store it to in the child. - // - // Architectures differ on the order of the parameters. - #[cfg(target_arch = "x86_64")] - let pid = ret_c_int(syscall!( - __NR_clone, - c_int(c::SIGCHLD | c::CLONE_CHILD_SETTID), - zero(), - zero(), - &mut child_pid, - zero() - ))?; - #[cfg(any( - target_arch = "aarch64", - target_arch = "arm", - target_arch = "mips", - target_arch = "mips32r6", - target_arch = "mips64", - target_arch = "mips64r6", - target_arch = "powerpc", - target_arch = "powerpc64", - target_arch = "riscv64", - target_arch = "s390x", - target_arch = "x86" - ))] - let pid = ret_c_int(syscall!( - __NR_clone, - c_int(c::SIGCHLD | c::CLONE_CHILD_SETTID), - zero(), - zero(), - zero(), - &mut child_pid - ))?; + // Unix `fork` only returns the child PID in the parent; we'd like it in + // the child too, so set `CLONE_CHILD_SETTID` and pass in the address of a + // memory location to store it to in the child. + // + // Architectures differ on the order of the parameters. + #[cfg(target_arch = "x86_64")] + let pid = ret_c_int(syscall!( + __NR_clone, + c_int(c::SIGCHLD | c::CLONE_CHILD_SETTID), + zero(), + zero(), + &mut child_pid, + zero() + ))?; + #[cfg(any( + target_arch = "aarch64", + target_arch = "arm", + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc", + target_arch = "powerpc64", + target_arch = "riscv64", + target_arch = "s390x", + target_arch = "x86" + ))] + let pid = ret_c_int(syscall!( + __NR_clone, + c_int(c::SIGCHLD | c::CLONE_CHILD_SETTID), + zero(), + zero(), + zero(), + &mut child_pid + ))?; - Ok(if let Some(pid) = Pid::from_raw(pid) { - Fork::ParentOf(pid) - } else { - Fork::Child(Pid::from_raw_unchecked(child_pid.assume_init())) - }) + Ok(if let Some(pid) = Pid::from_raw(pid) { + Fork::ParentOf(pid) + } else { + Fork::Child(Pid::from_raw_unchecked(child_pid.assume_init())) + }) + } } #[cfg(feature = "fs")] @@ -86,14 +88,16 @@ pub(crate) unsafe fn execveat( env_vars: *const *const u8, flags: AtFlags, ) -> io::Errno { - ret_error(syscall_readonly!( - __NR_execveat, - dirfd, - path, - args, - env_vars, - flags - )) + unsafe { + ret_error(syscall_readonly!( + __NR_execveat, + dirfd, + path, + args, + env_vars, + flags + )) + } } pub(crate) unsafe fn execve( @@ -101,7 +105,7 @@ pub(crate) unsafe fn execve( args: *const *const u8, env_vars: *const *const u8, ) -> io::Errno { - ret_error(syscall_readonly!(__NR_execve, path, args, env_vars)) + unsafe { ret_error(syscall_readonly!(__NR_execve, path, args, env_vars)) } } pub(crate) mod tls { @@ -124,20 +128,24 @@ pub(crate) mod tls { #[cfg(target_arch = "x86_64")] #[inline] pub(crate) unsafe fn set_fs(data: *mut c::c_void) { - ret_infallible(syscall_readonly!( - __NR_arch_prctl, - c_uint(ARCH_SET_FS), - data, - zero(), - zero(), - zero() - )) + unsafe { + ret_infallible(syscall_readonly!( + __NR_arch_prctl, + c_uint(ARCH_SET_FS), + data, + zero(), + zero(), + zero() + )) + } } #[inline] pub(crate) unsafe fn set_tid_address(data: *mut c::c_void) -> Pid { - let tid: i32 = ret_c_int_infallible(syscall_readonly!(__NR_set_tid_address, data)); - Pid::from_raw_unchecked(tid) + unsafe { + let tid: i32 = ret_c_int_infallible(syscall_readonly!(__NR_set_tid_address, data)); + Pid::from_raw_unchecked(tid) + } } #[inline] @@ -151,29 +159,33 @@ pub(crate) unsafe fn kernel_sigaction( signal: Signal, new: Option, ) -> io::Result { - let mut old = MaybeUninit::::uninit(); - let new = opt_ref(new.as_ref()); - ret(syscall!( - __NR_rt_sigaction, - signal, - new, - &mut old, - size_of::() - ))?; - Ok(old.assume_init()) + unsafe { + let mut old = MaybeUninit::::uninit(); + let new = opt_ref(new.as_ref()); + ret(syscall!( + __NR_rt_sigaction, + signal, + new, + &mut old, + size_of::() + ))?; + Ok(old.assume_init()) + } } #[inline] pub(crate) unsafe fn kernel_sigaltstack(new: Option) -> io::Result { - let mut old = MaybeUninit::::uninit(); - let new = opt_ref(new.as_ref()); - ret(syscall!(__NR_sigaltstack, new, &mut old))?; - Ok(old.assume_init()) + unsafe { + let mut old = MaybeUninit::::uninit(); + let new = opt_ref(new.as_ref()); + ret(syscall!(__NR_sigaltstack, new, &mut old))?; + Ok(old.assume_init()) + } } #[inline] pub(crate) unsafe fn tkill(tid: Pid, sig: Signal) -> io::Result<()> { - ret(syscall_readonly!(__NR_tkill, tid, sig)) + unsafe { ret(syscall_readonly!(__NR_tkill, tid, sig)) } } #[inline] @@ -181,16 +193,18 @@ pub(crate) unsafe fn kernel_sigprocmask( how: How, new: Option<&KernelSigSet>, ) -> io::Result { - let mut old = MaybeUninit::::uninit(); - let new = opt_ref(new); - ret(syscall!( - __NR_rt_sigprocmask, - how, - new, - &mut old, - size_of::() - ))?; - Ok(old.assume_init()) + unsafe { + let mut old = MaybeUninit::::uninit(); + let new = opt_ref(new); + ret(syscall!( + __NR_rt_sigprocmask, + how, + new, + &mut old, + size_of::() + ))?; + Ok(old.assume_init()) + } } #[inline] @@ -219,26 +233,30 @@ pub(crate) fn kernel_sigsuspend(set: &KernelSigSet) -> io::Result<()> { #[inline] pub(crate) unsafe fn kernel_sigwait(set: &KernelSigSet) -> io::Result { - Ok(Signal::from_raw_unchecked(ret_c_int(syscall_readonly!( - __NR_rt_sigtimedwait, - by_ref(set), - zero(), - zero(), - size_of::() - ))?)) + unsafe { + Ok(Signal::from_raw_unchecked(ret_c_int(syscall_readonly!( + __NR_rt_sigtimedwait, + by_ref(set), + zero(), + zero(), + size_of::() + ))?)) + } } #[inline] pub(crate) unsafe fn kernel_sigwaitinfo(set: &KernelSigSet) -> io::Result { - let mut info = MaybeUninit::::uninit(); - let _signum = ret_c_int(syscall!( - __NR_rt_sigtimedwait, - by_ref(set), - &mut info, - zero(), - size_of::() - ))?; - Ok(info.assume_init()) + unsafe { + let mut info = MaybeUninit::::uninit(); + let _signum = ret_c_int(syscall!( + __NR_rt_sigtimedwait, + by_ref(set), + &mut info, + zero(), + size_of::() + ))?; + Ok(info.assume_init()) + } } #[inline] @@ -246,91 +264,93 @@ pub(crate) unsafe fn kernel_sigtimedwait( set: &KernelSigSet, timeout: Option<&Timespec>, ) -> io::Result { - let mut info = MaybeUninit::::uninit(); + unsafe { + let mut info = MaybeUninit::::uninit(); - // `rt_sigtimedwait_time64` was introduced in Linux 5.1. The old - // `rt_sigtimedwait` syscall is not y2038-compatible on 32-bit - // architectures. - #[cfg(target_pointer_width = "32")] - { - // If we don't have Linux 5.1, and the timeout fits in a - // `__kernel_old_timespec`, use plain `rt_sigtimedwait`. - // - // We do this unconditionally, rather than trying - // `rt_sigtimedwait_time64` and falling back on `Errno::NOSYS`, because - // seccomp configurations will sometimes abort the process on syscalls - // they don't recognize. - #[cfg(not(feature = "linux_5_1"))] + // `rt_sigtimedwait_time64` was introduced in Linux 5.1. The old + // `rt_sigtimedwait` syscall is not y2038-compatible on 32-bit + // architectures. + #[cfg(target_pointer_width = "32")] { - // If we don't have a timeout, or if we can convert the timeout to - // a `__kernel_old_timespec`, the use `__NR_futex`. - fn convert(timeout: &Timespec) -> Option<__kernel_old_timespec> { - Some(__kernel_old_timespec { - tv_sec: timeout.tv_sec.try_into().ok()?, - tv_nsec: timeout.tv_nsec.try_into().ok()?, - }) - } - let old_timeout = if let Some(timeout) = timeout { - match convert(timeout) { - // Could not convert timeout. - None => None, - // Could convert timeout. Ok! - Some(old_timeout) => Some(Some(old_timeout)), + // If we don't have Linux 5.1, and the timeout fits in a + // `__kernel_old_timespec`, use plain `rt_sigtimedwait`. + // + // We do this unconditionally, rather than trying + // `rt_sigtimedwait_time64` and falling back on `Errno::NOSYS`, because + // seccomp configurations will sometimes abort the process on syscalls + // they don't recognize. + #[cfg(not(feature = "linux_5_1"))] + { + // If we don't have a timeout, or if we can convert the timeout to + // a `__kernel_old_timespec`, the use `__NR_futex`. + fn convert(timeout: &Timespec) -> Option<__kernel_old_timespec> { + Some(__kernel_old_timespec { + tv_sec: timeout.tv_sec.try_into().ok()?, + tv_nsec: timeout.tv_nsec.try_into().ok()?, + }) + } + let old_timeout = if let Some(timeout) = timeout { + match convert(timeout) { + // Could not convert timeout. + None => None, + // Could convert timeout. Ok! + Some(old_timeout) => Some(Some(old_timeout)), + } + } else { + // No timeout. Ok! + Some(None) + }; + if let Some(old_timeout) = old_timeout { + return ret_c_int(syscall!( + __NR_rt_sigtimedwait, + by_ref(set), + &mut info, + opt_ref(old_timeout.as_ref()), + size_of::() + )) + .map(|sig| { + debug_assert_eq!( + sig, + info.assume_init_ref() + .__bindgen_anon_1 + .__bindgen_anon_1 + .si_signo + ); + info.assume_init() + }); } - } else { - // No timeout. Ok! - Some(None) - }; - if let Some(old_timeout) = old_timeout { - return ret_c_int(syscall!( - __NR_rt_sigtimedwait, - by_ref(set), - &mut info, - opt_ref(old_timeout.as_ref()), - size_of::() - )) - .map(|sig| { - debug_assert_eq!( - sig, - info.assume_init_ref() - .__bindgen_anon_1 - .__bindgen_anon_1 - .si_signo - ); - info.assume_init() - }); } - } - ret_c_int(syscall!( - __NR_rt_sigtimedwait_time64, - by_ref(set), - &mut info, - opt_ref(timeout), - size_of::() - )) - .map(|sig| { - debug_assert_eq!( - sig, - info.assume_init_ref() - .__bindgen_anon_1 - .__bindgen_anon_1 - .si_signo - ); - info.assume_init() - }) - } + ret_c_int(syscall!( + __NR_rt_sigtimedwait_time64, + by_ref(set), + &mut info, + opt_ref(timeout), + size_of::() + )) + .map(|sig| { + debug_assert_eq!( + sig, + info.assume_init_ref() + .__bindgen_anon_1 + .__bindgen_anon_1 + .si_signo + ); + info.assume_init() + }) + } - #[cfg(target_pointer_width = "64")] - { - let _signum = ret_c_int(syscall!( - __NR_rt_sigtimedwait, - by_ref(set), - &mut info, - opt_ref(timeout), - size_of::() - ))?; - Ok(info.assume_init()) + #[cfg(target_pointer_width = "64")] + { + let _signum = ret_c_int(syscall!( + __NR_rt_sigtimedwait, + by_ref(set), + &mut info, + opt_ref(timeout), + size_of::() + ))?; + Ok(info.assume_init()) + } } } @@ -341,6 +361,8 @@ pub(crate) fn exit_group(code: c::c_int) -> ! { #[inline] pub(crate) unsafe fn kernel_brk(addr: *mut c::c_void) -> io::Result<*mut c_void> { - // This is non-`readonly`, to prevent loads from being reordered past it. - ret_void_star(syscall!(__NR_brk, addr)) + unsafe { + // This is non-`readonly`, to prevent loads from being reordered past it. + ret_void_star(syscall!(__NR_brk, addr)) + } } diff --git a/src/backend/linux_raw/termios/syscalls.rs b/src/backend/linux_raw/termios/syscalls.rs index 07c3a3d95..953f50f8c 100644 --- a/src/backend/linux_raw/termios/syscalls.rs +++ b/src/backend/linux_raw/termios/syscalls.rs @@ -13,8 +13,8 @@ use crate::ffi::CStr; use crate::io; use crate::pid::Pid; use crate::termios::{ - speed, Action, ControlModes, InputModes, LocalModes, OptionalActions, OutputModes, - QueueSelector, SpecialCodeIndex, Termios, Winsize, + Action, ControlModes, InputModes, LocalModes, OptionalActions, OutputModes, QueueSelector, + SpecialCodeIndex, Termios, Winsize, speed, }; #[cfg(feature = "alloc")] #[cfg(feature = "fs")] diff --git a/src/backend/linux_raw/thread/syscalls.rs b/src/backend/linux_raw/thread/syscalls.rs index 352e06150..1c6b36287 100644 --- a/src/backend/linux_raw/thread/syscalls.rs +++ b/src/backend/linux_raw/thread/syscalls.rs @@ -15,14 +15,14 @@ use crate::fd::BorrowedFd; use crate::io; use crate::pid::Pid; use crate::thread::{ - futex, ClockId, Cpuid, MembarrierCommand, MembarrierQuery, NanosleepRelativeResult, Timespec, + ClockId, Cpuid, MembarrierCommand, MembarrierQuery, NanosleepRelativeResult, Timespec, futex, }; use crate::utils::as_mut_ptr; use core::mem::MaybeUninit; use core::sync::atomic::AtomicU32; #[cfg(target_pointer_width = "32")] use linux_raw_sys::general::timespec as __kernel_old_timespec; -use linux_raw_sys::general::{membarrier_cmd, membarrier_cmd_flag, TIMER_ABSTIME}; +use linux_raw_sys::general::{TIMER_ABSTIME, membarrier_cmd, membarrier_cmd_flag}; #[inline] pub(crate) fn clock_nanosleep_relative(id: ClockId, req: &Timespec) -> NanosleepRelativeResult { @@ -213,57 +213,59 @@ pub(crate) unsafe fn futex_val2( uaddr2: *const AtomicU32, val3: u32, ) -> io::Result { - // Pass `val2` in the least-significant bytes of the `timeout` argument. - // [“the kernel casts the timeout value first to unsigned long, then to - // uint32_t”], so we perform that exact conversion in reverse to create - // the pointer. - // - // [“the kernel casts the timeout value first to unsigned long, then to uint32_t”]: https://man7.org/linux/man-pages/man2/futex.2.html - let timeout = val2 as usize as *const Timespec; + unsafe { + // Pass `val2` in the least-significant bytes of the `timeout` argument. + // [“the kernel casts the timeout value first to unsigned long, then to + // uint32_t”], so we perform that exact conversion in reverse to create + // the pointer. + // + // [“the kernel casts the timeout value first to unsigned long, then to uint32_t”]: https://man7.org/linux/man-pages/man2/futex.2.html + let timeout = val2 as usize as *const Timespec; - #[cfg(target_pointer_width = "32")] - { - // Linux 5.1 added `futex_time64`; if we have that, use it. We don't - // need it here, because `timeout` is just passing `val2` and not a - // real timeout, but it's nice to use `futex_time64` for consistency - // with the other futex calls that do. - #[cfg(feature = "linux_5_1")] + #[cfg(target_pointer_width = "32")] { - ret_usize(syscall!( - __NR_futex_time64, - uaddr, - (op, flags), - c_uint(val), - timeout, - uaddr2, - c_uint(val3) - )) - } + // Linux 5.1 added `futex_time64`; if we have that, use it. We don't + // need it here, because `timeout` is just passing `val2` and not a + // real timeout, but it's nice to use `futex_time64` for consistency + // with the other futex calls that do. + #[cfg(feature = "linux_5_1")] + { + ret_usize(syscall!( + __NR_futex_time64, + uaddr, + (op, flags), + c_uint(val), + timeout, + uaddr2, + c_uint(val3) + )) + } - // If we don't have Linux 5.1, use plain `futex`. - #[cfg(not(feature = "linux_5_1"))] - { - ret_usize(syscall!( - __NR_futex, - uaddr, - (op, flags), - c_uint(val), - timeout, - uaddr2, - c_uint(val3) - )) + // If we don't have Linux 5.1, use plain `futex`. + #[cfg(not(feature = "linux_5_1"))] + { + ret_usize(syscall!( + __NR_futex, + uaddr, + (op, flags), + c_uint(val), + timeout, + uaddr2, + c_uint(val3) + )) + } } + #[cfg(target_pointer_width = "64")] + ret_usize(syscall!( + __NR_futex, + uaddr, + (op, flags), + c_uint(val), + timeout, + uaddr2, + c_uint(val3) + )) } - #[cfg(target_pointer_width = "64")] - ret_usize(syscall!( - __NR_futex, - uaddr, - (op, flags), - c_uint(val), - timeout, - uaddr2, - c_uint(val3) - )) } /// # Safety @@ -279,53 +281,65 @@ pub(crate) unsafe fn futex_timeout( uaddr2: *const AtomicU32, val3: u32, ) -> io::Result { - #[cfg(target_pointer_width = "32")] - { - // If we don't have Linux 5.1, and the timeout fits in a - // `__kernel_old_timespec`, use plain `futex`. - // - // We do this unconditionally, rather than trying `futex_time64` and - // falling back on `Errno::NOSYS`, because seccomp configurations will - // sometimes abort the process on syscalls they don't recognize. - #[cfg(not(feature = "linux_5_1"))] + unsafe { + #[cfg(target_pointer_width = "32")] { - // If we don't have a timeout, or if we can convert the timeout to - // a `__kernel_old_timespec`, the use `__NR_futex`. - fn convert(timeout: &Timespec) -> Option<__kernel_old_timespec> { - Some(__kernel_old_timespec { - tv_sec: timeout.tv_sec.try_into().ok()?, - tv_nsec: timeout.tv_nsec.try_into().ok()?, - }) - } - let old_timeout = if let Some(timeout) = timeout { - match convert(timeout) { - // Could not convert timeout. - None => None, - // Could convert timeout. Ok! - Some(old_timeout) => Some(Some(old_timeout)), + // If we don't have Linux 5.1, and the timeout fits in a + // `__kernel_old_timespec`, use plain `futex`. + // + // We do this unconditionally, rather than trying `futex_time64` and + // falling back on `Errno::NOSYS`, because seccomp configurations will + // sometimes abort the process on syscalls they don't recognize. + #[cfg(not(feature = "linux_5_1"))] + { + // If we don't have a timeout, or if we can convert the timeout to + // a `__kernel_old_timespec`, the use `__NR_futex`. + fn convert(timeout: &Timespec) -> Option<__kernel_old_timespec> { + Some(__kernel_old_timespec { + tv_sec: timeout.tv_sec.try_into().ok()?, + tv_nsec: timeout.tv_nsec.try_into().ok()?, + }) + } + let old_timeout = if let Some(timeout) = timeout { + match convert(timeout) { + // Could not convert timeout. + None => None, + // Could convert timeout. Ok! + Some(old_timeout) => Some(Some(old_timeout)), + } + } else { + // No timeout. Ok! + Some(None) + }; + if let Some(old_timeout) = old_timeout { + return ret_usize(syscall!( + __NR_futex, + uaddr, + (op, flags), + c_uint(val), + opt_ref(old_timeout.as_ref()), + uaddr2, + c_uint(val3) + )); } - } else { - // No timeout. Ok! - Some(None) - }; - if let Some(old_timeout) = old_timeout { - return ret_usize(syscall!( - __NR_futex, - uaddr, - (op, flags), - c_uint(val), - opt_ref(old_timeout.as_ref()), - uaddr2, - c_uint(val3) - )); } - } - // We either have Linux 5.1 or the timeout didn't fit in - // `__kernel_old_timespec` so `__NR_futex_time64` will either succeed - // or fail due to our having no other options. + // We either have Linux 5.1 or the timeout didn't fit in + // `__kernel_old_timespec` so `__NR_futex_time64` will either succeed + // or fail due to our having no other options. + ret_usize(syscall!( + __NR_futex_time64, + uaddr, + (op, flags), + c_uint(val), + opt_ref(timeout), + uaddr2, + c_uint(val3) + )) + } + #[cfg(target_pointer_width = "64")] ret_usize(syscall!( - __NR_futex_time64, + __NR_futex, uaddr, (op, flags), c_uint(val), @@ -334,16 +348,6 @@ pub(crate) unsafe fn futex_timeout( c_uint(val3) )) } - #[cfg(target_pointer_width = "64")] - ret_usize(syscall!( - __NR_futex, - uaddr, - (op, flags), - c_uint(val), - opt_ref(timeout), - uaddr2, - c_uint(val3) - )) } #[inline] diff --git a/src/backend/linux_raw/vdso.rs b/src/backend/linux_raw/vdso.rs index 4fa1d1ccf..a5ea46588 100644 --- a/src/backend/linux_raw/vdso.rs +++ b/src/backend/linux_raw/vdso.rs @@ -253,47 +253,49 @@ impl Vdso { /// /// The raw pointers inside `self` must be valid. unsafe fn match_version(&self, mut ver: u16, name: &CStr, hash: u32) -> bool { - // This is a helper function to check if the version indexed by - // ver matches name (which hashes to hash). - // - // The version definition table is a mess, and I don't know how - // to do this in better than linear time without allocating memory - // to build an index. I also don't know why the table has - // variable size entries in the first place. - // - // For added fun, I can't find a comprehensible specification of how - // to parse all the weird flags in the table. - // - // So I just parse the whole table every time. - - // First step: find the version definition - ver &= 0x7fff; // Apparently bit 15 means "hidden" - let mut def = self.verdef; - loop { - if (*def).vd_version != VER_DEF_CURRENT { - return false; // Failed - } + unsafe { + // This is a helper function to check if the version indexed by + // ver matches name (which hashes to hash). + // + // The version definition table is a mess, and I don't know how + // to do this in better than linear time without allocating memory + // to build an index. I also don't know why the table has + // variable size entries in the first place. + // + // For added fun, I can't find a comprehensible specification of how + // to parse all the weird flags in the table. + // + // So I just parse the whole table every time. + + // First step: find the version definition + ver &= 0x7fff; // Apparently bit 15 means "hidden" + let mut def = self.verdef; + loop { + if (*def).vd_version != VER_DEF_CURRENT { + return false; // Failed + } - if ((*def).vd_flags & VER_FLG_BASE) == 0 && ((*def).vd_ndx & 0x7fff) == ver { - break; - } + if ((*def).vd_flags & VER_FLG_BASE) == 0 && ((*def).vd_ndx & 0x7fff) == ver { + break; + } - if (*def).vd_next == 0 { - return false; // No definition. + if (*def).vd_next == 0 { + return false; // No definition. + } + + def = def + .cast::() + .add((*def).vd_next as usize) + .cast::(); } - def = def - .cast::() - .add((*def).vd_next as usize) - .cast::(); + // Now figure out whether it matches. + let aux = &*(def.cast::()) + .add((*def).vd_aux as usize) + .cast::(); + (*def).vd_hash == hash + && (name == CStr::from_ptr(self.symstrings.add(aux.vda_name as usize).cast())) } - - // Now figure out whether it matches. - let aux = &*(def.cast::()) - .add((*def).vd_aux as usize) - .cast::(); - (*def).vd_hash == hash - && (name == CStr::from_ptr(self.symstrings.add(aux.vda_name as usize).cast())) } /// Check to see if the symbol is the one we're looking for. @@ -309,31 +311,33 @@ impl Vdso { version: &CStr, ver_hash: u32, ) -> bool { - // Check for a defined global or weak function w/ right name. - // - // Accept `STT_NOTYPE` in addition to `STT_FUNC` for the symbol - // type, for compatibility with some versions of Linux on - // PowerPC64. See [this commit] in Linux for more background. - // - // [this commit]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/tools/testing/selftests/vDSO/parse_vdso.c?id=0161bd38c24312853ed5ae9a425a1c41c4ac674a - if ELF_ST_TYPE(sym.st_info) != STT_FUNC && ELF_ST_TYPE(sym.st_info) != STT_NOTYPE { - return false; - } - if ELF_ST_BIND(sym.st_info) != STB_GLOBAL && ELF_ST_BIND(sym.st_info) != STB_WEAK { - return false; - } - if name != CStr::from_ptr(self.symstrings.add(sym.st_name as usize).cast()) { - return false; - } + unsafe { + // Check for a defined global or weak function w/ right name. + // + // Accept `STT_NOTYPE` in addition to `STT_FUNC` for the symbol + // type, for compatibility with some versions of Linux on + // PowerPC64. See [this commit] in Linux for more background. + // + // [this commit]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/tools/testing/selftests/vDSO/parse_vdso.c?id=0161bd38c24312853ed5ae9a425a1c41c4ac674a + if ELF_ST_TYPE(sym.st_info) != STT_FUNC && ELF_ST_TYPE(sym.st_info) != STT_NOTYPE { + return false; + } + if ELF_ST_BIND(sym.st_info) != STB_GLOBAL && ELF_ST_BIND(sym.st_info) != STB_WEAK { + return false; + } + if name != CStr::from_ptr(self.symstrings.add(sym.st_name as usize).cast()) { + return false; + } - // Check symbol version. - if !self.versym.is_null() - && !self.match_version(*self.versym.add(i as usize), version, ver_hash) - { - return false; - } + // Check symbol version. + if !self.versym.is_null() + && !self.match_version(*self.versym.add(i as usize), version, ver_hash) + { + return false; + } - true + true + } } /// Look up a symbol in the vDSO. @@ -408,15 +412,17 @@ impl Vdso { /// Add the given address to the vDSO base address. unsafe fn base_plus(&self, offset: usize) -> Option<*const c_void> { - // Check for overflow. - let _ = (self.load_addr as usize).checked_add(offset)?; - // Add the offset to the base. - Some(self.load_addr.cast::().add(offset).cast()) + unsafe { + // Check for overflow. + let _ = (self.load_addr as usize).checked_add(offset)?; + // Add the offset to the base. + Some(self.load_addr.cast::().add(offset).cast()) + } } /// Translate an ELF-address-space address into a usable virtual address. unsafe fn addr_from_elf(&self, elf_addr: usize) -> Option<*const c_void> { - self.base_plus(elf_addr.wrapping_add(self.pv_offset)) + unsafe { self.base_plus(elf_addr.wrapping_add(self.pv_offset)) } } } diff --git a/src/backend/linux_raw/vdso_wrappers.rs b/src/backend/linux_raw/vdso_wrappers.rs index 338f4548e..72cb64974 100644 --- a/src/backend/linux_raw/vdso_wrappers.rs +++ b/src/backend/linux_raw/vdso_wrappers.rs @@ -11,7 +11,7 @@ #![allow(clippy::missing_transmute_annotations)] #[cfg(target_arch = "x86")] -use super::reg::{ArgReg, RetReg, SyscallNumber, A0, A1, A2, A3, A4, A5, R0}; +use super::reg::{A0, A1, A2, A3, A4, A5, ArgReg, R0, RetReg, SyscallNumber}; use super::vdso; #[cfg(target_arch = "x86")] use core::arch::global_asm; @@ -145,7 +145,7 @@ pub(crate) fn sched_getcpu() -> usize { #[cfg(target_arch = "x86")] pub(super) mod x86_via_vdso { - use super::{transmute, ArgReg, Relaxed, RetReg, SyscallNumber, A0, A1, A2, A3, A4, A5, R0}; + use super::{A0, A1, A2, A3, A4, A5, ArgReg, R0, Relaxed, RetReg, SyscallNumber, transmute}; use crate::backend::arch::asm; #[inline] @@ -346,9 +346,11 @@ static SYSCALL: AtomicPtr = AtomicPtr::new(null_mut()); #[cfg(feature = "time")] #[must_use] unsafe extern "C" fn clock_gettime_via_syscall(clockid: c::c_int, res: *mut Timespec) -> c::c_int { - match _clock_gettime_via_syscall(clockid, res) { - Ok(()) => 0, - Err(err) => err.raw_os_error().wrapping_neg(), + unsafe { + match _clock_gettime_via_syscall(clockid, res) { + Ok(()) => 0, + Err(err) => err.raw_os_error().wrapping_neg(), + } } } @@ -387,7 +389,7 @@ unsafe fn _clock_gettime_via_syscall_old(clockid: c::c_int, res: *mut Timespec) #[cfg(feature = "time")] #[cfg(target_pointer_width = "64")] unsafe fn _clock_gettime_via_syscall(clockid: c::c_int, res: *mut Timespec) -> io::Result<()> { - ret(syscall!(__NR_clock_gettime, c_int(clockid), res)) + unsafe { ret(syscall!(__NR_clock_gettime, c_int(clockid), res)) } } #[cfg(feature = "thread")] @@ -404,9 +406,11 @@ unsafe extern "C" fn getcpu_via_syscall( node: *mut u32, unused: *mut c_void, ) -> c::c_int { - match ret(syscall!(__NR_getcpu, cpu, node, unused)) { - Ok(()) => 0, - Err(err) => err.raw_os_error().wrapping_neg(), + unsafe { + match ret(syscall!(__NR_getcpu, cpu, node, unused)) { + Ok(()) => 0, + Err(err) => err.raw_os_error().wrapping_neg(), + } } } diff --git a/src/bitcast.rs b/src/bitcast.rs index db17c7cb1..95ea7542a 100644 --- a/src/bitcast.rs +++ b/src/bitcast.rs @@ -5,7 +5,7 @@ // Ensure that the source and destination types are both primitive integer // types and the same size, and then bitcast. macro_rules! bitcast { - ($x:expr) => {{ + ($x:expr_2021) => {{ if false { // Ensure the source and destinations are primitive integer types. let _ = !$x; @@ -33,7 +33,5 @@ macro_rules! bitcast { /// Return a [`bitcast`] of the value of `$x.bits()`, where `$x` is a /// `bitflags` type. macro_rules! bitflags_bits { - ($x:expr) => {{ - bitcast!($x.bits()) - }}; + ($x:expr_2021) => {{ bitcast!($x.bits()) }}; } diff --git a/src/buffer.rs b/src/buffer.rs index 6c86826f0..9437e39af 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -164,12 +164,14 @@ impl<'a, T> private::Sealed for &'a mut [MaybeUninit] { #[inline] unsafe fn assume_init(self, len: usize) -> Self::Output { - let (init, uninit) = self.split_at_mut(len); + unsafe { + let (init, uninit) = self.split_at_mut(len); - // SAFETY: The user asserts that the slice is now initialized. - let init = slice::from_raw_parts_mut(init.as_mut_ptr().cast::(), init.len()); + // SAFETY: The user asserts that the slice is now initialized. + let init = slice::from_raw_parts_mut(init.as_mut_ptr().cast::(), init.len()); - (init, uninit) + (init, uninit) + } } } @@ -183,12 +185,14 @@ impl<'a, T, const N: usize> private::Sealed for &'a mut [MaybeUninit; N] { #[inline] unsafe fn assume_init(self, len: usize) -> Self::Output { - let (init, uninit) = self.split_at_mut(len); + unsafe { + let (init, uninit) = self.split_at_mut(len); - // SAFETY: The user asserts that the slice is now initialized. - let init = slice::from_raw_parts_mut(init.as_mut_ptr().cast::(), init.len()); + // SAFETY: The user asserts that the slice is now initialized. + let init = slice::from_raw_parts_mut(init.as_mut_ptr().cast::(), init.len()); - (init, uninit) + (init, uninit) + } } } @@ -203,12 +207,14 @@ impl<'a, T> private::Sealed for &'a mut Vec> { #[inline] unsafe fn assume_init(self, len: usize) -> Self::Output { - let (init, uninit) = self.split_at_mut(len); + unsafe { + let (init, uninit) = self.split_at_mut(len); - // SAFETY: The user asserts that the slice is now initialized. - let init = slice::from_raw_parts_mut(init.as_mut_ptr().cast::(), init.len()); + // SAFETY: The user asserts that the slice is now initialized. + let init = slice::from_raw_parts_mut(init.as_mut_ptr().cast::(), init.len()); - (init, uninit) + (init, uninit) + } } } @@ -280,9 +286,11 @@ impl<'a, T> private::Sealed for SpareCapacity<'a, T> { #[inline] unsafe fn assume_init(self, len: usize) -> Self::Output { - // We initialized `len` elements; extend the `Vec` to include them. - self.0.set_len(self.0.len() + len); - len + unsafe { + // We initialized `len` elements; extend the `Vec` to include them. + self.0.set_len(self.0.len() + len); + len + } } } diff --git a/src/event/mod.rs b/src/event/mod.rs index 29dfc2272..96d1e0845 100644 --- a/src/event/mod.rs +++ b/src/event/mod.rs @@ -26,9 +26,9 @@ pub use crate::timespec::{Nsecs, Secs, Timespec}; target_os = "illumos", target_os = "espidf" ))] -pub use eventfd::{eventfd, EventfdFlags}; +pub use eventfd::{EventfdFlags, eventfd}; #[cfg(not(any(windows, target_os = "redox", target_os = "wasi")))] pub use pause::*; -pub use poll::{poll, PollFd, PollFlags}; +pub use poll::{PollFd, PollFlags, poll}; #[cfg(any(bsd, linux_kernel, windows, target_os = "wasi"))] pub use select::*; diff --git a/src/event/select.rs b/src/event/select.rs index 6bb93b538..9790019a0 100644 --- a/src/event/select.rs +++ b/src/event/select.rs @@ -122,7 +122,7 @@ pub unsafe fn select( exceptfds: Option<&mut [FdSetElement]>, timeout: Option<&Timespec>, ) -> io::Result { - backend::event::syscalls::select(nfds, readfds, writefds, exceptfds, timeout) + unsafe { backend::event::syscalls::select(nfds, readfds, writefds, exceptfds, timeout) } } #[cfg(not(any(windows, target_os = "wasi")))] @@ -260,11 +260,7 @@ pub(crate) fn fd_set_num_elements_for_bitvector(nfds: RawFd) -> usize { fn div_ceil(lhs: usize, rhs: usize) -> usize { let d = lhs / rhs; let r = lhs % rhs; - if r > 0 { - d + 1 - } else { - d - } + if r > 0 { d + 1 } else { d } } /// An iterator over the fds in a set. diff --git a/src/ffi.rs b/src/ffi.rs index 073b6b120..7c5bb2b63 100644 --- a/src/ffi.rs +++ b/src/ffi.rs @@ -1,23 +1,10 @@ //! Utilities related to FFI bindings. -// If we have std, use it. #[cfg(not(windows))] -#[cfg(feature = "std")] -pub use std::ffi::{CStr, CString, FromBytesWithNulError, NulError}; -#[cfg(feature = "std")] -pub use std::os::raw::{ - c_char, c_int, c_long, c_longlong, c_short, c_uint, c_ulong, c_ulonglong, c_ushort, c_void, -}; - -// If we don't have std, we can depend on core and alloc having these features -// in Rust 1.64+. -#[cfg(not(windows))] -#[cfg(all(feature = "alloc", not(feature = "std")))] +#[cfg(feature = "alloc")] pub use alloc::ffi::{CString, NulError}; -#[cfg(not(feature = "std"))] +#[cfg(not(windows))] +pub use core::ffi::{CStr, FromBytesWithNulError}; pub use core::ffi::{ c_char, c_int, c_long, c_longlong, c_short, c_uint, c_ulong, c_ulonglong, c_ushort, c_void, }; -#[cfg(not(windows))] -#[cfg(not(feature = "std"))] -pub use core::ffi::{CStr, FromBytesWithNulError}; diff --git a/src/fs/inotify.rs b/src/fs/inotify.rs index ad03dfa6b..6889aa723 100644 --- a/src/fs/inotify.rs +++ b/src/fs/inotify.rs @@ -47,8 +47,8 @@ use crate::backend::fs::syscalls; use crate::fd::{AsFd, OwnedFd}; use crate::ffi::CStr; use crate::io; -use crate::io::{read, Errno}; -use core::mem::{align_of, size_of, MaybeUninit}; +use crate::io::{Errno, read}; +use core::mem::{MaybeUninit, align_of, size_of}; use linux_raw_sys::general::inotify_event; /// `inotify_init1(flags)`—Creates a new inotify object. diff --git a/src/fs/raw_dir.rs b/src/fs/raw_dir.rs index 7fec6fd71..2fcf63a0a 100644 --- a/src/fs/raw_dir.rs +++ b/src/fs/raw_dir.rs @@ -6,7 +6,7 @@ use crate::ffi::CStr; use crate::fs::FileType; use crate::io; use core::fmt; -use core::mem::{align_of, MaybeUninit}; +use core::mem::{MaybeUninit, align_of}; use linux_raw_sys::general::linux_dirent64; /// A directory iterator implemented with getdents. @@ -88,8 +88,7 @@ impl<'buf, Fd: AsFd> RawDir<'buf, Fd> { /// Heap allocated growing buffer for supporting directory entries with /// arbitrarily large file names: /// - /// ```ignore - /// # // The `ignore` above can be removed when we can depend on Rust 1.65. + /// ``` /// # use std::mem::MaybeUninit; /// # use rustix::fs::{CWD, Mode, OFlags, openat, RawDir}; /// # use rustix::io::Errno; diff --git a/src/io/close.rs b/src/io/close.rs index 9317edfec..81ac5935e 100644 --- a/src/io/close.rs +++ b/src/io/close.rs @@ -52,7 +52,7 @@ use backend::fd::RawFd; /// not valid after the call. #[inline] pub unsafe fn close(raw_fd: RawFd) { - backend::io::syscalls::close(raw_fd) + unsafe { backend::io::syscalls::close(raw_fd) } } /// `close(raw_fd)`—Closes a `RawFd` directly, and report any errors returned @@ -67,5 +67,5 @@ pub unsafe fn close(raw_fd: RawFd) { /// not valid after the call, even if it fails. #[cfg(feature = "try_close")] pub unsafe fn try_close(raw_fd: RawFd) -> crate::io::Result<()> { - backend::io::syscalls::try_close(raw_fd) + unsafe { backend::io::syscalls::try_close(raw_fd) } } diff --git a/src/io/mod.rs b/src/io/mod.rs index a2994d74a..afa44ae2f 100644 --- a/src/io/mod.rs +++ b/src/io/mod.rs @@ -17,7 +17,7 @@ mod read_write; pub use close::*; #[cfg(not(windows))] pub use dup::*; -pub use errno::{retry_on_intr, Errno, Result}; +pub use errno::{Errno, Result, retry_on_intr}; #[cfg(not(windows))] pub use fcntl::*; pub use ioctl::*; diff --git a/src/io_uring/bindgen_types.rs b/src/io_uring/bindgen_types.rs index c45aefb67..39b41f777 100644 --- a/src/io_uring/bindgen_types.rs +++ b/src/io_uring/bindgen_types.rs @@ -28,12 +28,12 @@ impl IncompleteArrayField { #[inline] pub unsafe fn as_slice(&self, len: usize) -> &[T] { - ::core::slice::from_raw_parts(self.as_ptr(), len) + unsafe { ::core::slice::from_raw_parts(self.as_ptr(), len) } } #[inline] pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { - ::core::slice::from_raw_parts_mut(self.as_mut_ptr(), len) + unsafe { ::core::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } } @@ -57,12 +57,12 @@ impl UnionField { #[inline] pub unsafe fn as_ref(&self) -> &T { - ::core::mem::transmute(self) + unsafe { ::core::mem::transmute(self) } } #[inline] pub unsafe fn as_mut(&mut self) -> &mut T { - ::core::mem::transmute(self) + unsafe { ::core::mem::transmute(self) } } } diff --git a/src/io_uring/mod.rs b/src/io_uring/mod.rs index 5e3756812..cfbd4b7c6 100644 --- a/src/io_uring/mod.rs +++ b/src/io_uring/mod.rs @@ -117,7 +117,7 @@ pub unsafe fn io_uring_register( arg: *const c_void, nr_args: u32, ) -> io::Result { - backend::io_uring::syscalls::io_uring_register(fd.as_fd(), opcode, arg, nr_args) + unsafe { backend::io_uring::syscalls::io_uring_register(fd.as_fd(), opcode, arg, nr_args) } } /// `io_uring_register_with(fd, opcode, flags, arg, nr_args)`—Register files or @@ -141,7 +141,9 @@ pub unsafe fn io_uring_register_with( arg: *const c_void, nr_args: u32, ) -> io::Result { - backend::io_uring::syscalls::io_uring_register_with(fd.as_fd(), opcode, flags, arg, nr_args) + unsafe { + backend::io_uring::syscalls::io_uring_register_with(fd.as_fd(), opcode, flags, arg, nr_args) + } } /// `io_uring_enter(fd, to_submit, min_complete, flags, 0, 0)`—Initiate @@ -173,17 +175,19 @@ pub unsafe fn io_uring_enter( min_complete: u32, flags: IoringEnterFlags, ) -> io::Result { - debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG)); - debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG_REG)); - - backend::io_uring::syscalls::io_uring_enter( - fd.as_fd(), - to_submit, - min_complete, - flags, - null_mut(), - 0, - ) + unsafe { + debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG)); + debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG_REG)); + + backend::io_uring::syscalls::io_uring_enter( + fd.as_fd(), + to_submit, + min_complete, + flags, + null_mut(), + 0, + ) + } } /// `io_uring_enter(fd, to_submit, min_complete, flags, sigmask, @@ -215,17 +219,19 @@ pub unsafe fn io_uring_enter_sigmask( flags: IoringEnterFlags, sigmask: Option<&KernelSigSet>, ) -> io::Result { - debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG)); - debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG_REG)); - - backend::io_uring::syscalls::io_uring_enter( - fd.as_fd(), - to_submit, - min_complete, - flags, - option_as_ptr(sigmask).cast::(), - size_of::(), - ) + unsafe { + debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG)); + debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG_REG)); + + backend::io_uring::syscalls::io_uring_enter( + fd.as_fd(), + to_submit, + min_complete, + flags, + option_as_ptr(sigmask).cast::(), + size_of::(), + ) + } } /// `io_uring_enter2(fd, to_submit, min_complete, flags, arg, sizeof(*arg))`— @@ -258,17 +264,19 @@ pub unsafe fn io_uring_enter_arg( flags: IoringEnterFlags, arg: Option<&io_uring_getevents_arg>, ) -> io::Result { - debug_assert!(flags.contains(IoringEnterFlags::EXT_ARG)); - debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG_REG)); - - backend::io_uring::syscalls::io_uring_enter( - fd.as_fd(), - to_submit, - min_complete, - flags, - option_as_ptr(arg).cast::(), - size_of::(), - ) + unsafe { + debug_assert!(flags.contains(IoringEnterFlags::EXT_ARG)); + debug_assert!(!flags.contains(IoringEnterFlags::EXT_ARG_REG)); + + backend::io_uring::syscalls::io_uring_enter( + fd.as_fd(), + to_submit, + min_complete, + flags, + option_as_ptr(arg).cast::(), + size_of::(), + ) + } } // TODO: Uncomment this when we support `IoringRegisterOp::CQWAIT_REG`. @@ -1314,8 +1322,7 @@ impl io_uring_user_data { /// Create a zero-initialized `Self`. pub const fn zeroed() -> Self { // Initialize the `u64_` field, which is the size of the full union. - // This can use `core::mem::zeroed` in Rust 1.75. - Self { u64_: 0 } + unsafe { core::mem::zeroed() } } /// Return the `u64` value. diff --git a/src/ioctl/linux.rs b/src/ioctl/linux.rs index 7215228a7..87bfacd78 100644 --- a/src/ioctl/linux.rs +++ b/src/ioctl/linux.rs @@ -11,9 +11,7 @@ pub(super) const fn compose_opcode( size: Opcode, ) -> Opcode { macro_rules! mask_and_shift { - ($val:expr, $shift:expr, $mask:expr) => {{ - ($val & $mask) << $shift - }}; + ($val:expr_2021, $shift:expr_2021, $mask:expr_2021) => {{ ($val & $mask) << $shift }}; } let dir = match dir { diff --git a/src/ioctl/mod.rs b/src/ioctl/mod.rs index e3e8f8e1b..5f1a28b31 100644 --- a/src/ioctl/mod.rs +++ b/src/ioctl/mod.rs @@ -89,25 +89,27 @@ use bsd as platform; /// [illumos]: https://illumos.org/man/2/ioctl #[inline] pub unsafe fn ioctl(fd: F, mut ioctl: I) -> Result { - let fd = fd.as_fd(); - let request = ioctl.opcode(); - let arg = ioctl.as_ptr(); - - // SAFETY: The variant of `Ioctl` asserts that this is a valid IOCTL call - // to make. - let output = if I::IS_MUTATING { - _ioctl(fd, request, arg)? - } else { - _ioctl_readonly(fd, request, arg)? - }; - - // SAFETY: The variant of `Ioctl` asserts that this is a valid pointer to - // the output data. - I::output_from_ptr(output, arg) + unsafe { + let fd = fd.as_fd(); + let request = ioctl.opcode(); + let arg = ioctl.as_ptr(); + + // SAFETY: The variant of `Ioctl` asserts that this is a valid IOCTL call + // to make. + let output = if I::IS_MUTATING { + _ioctl(fd, request, arg)? + } else { + _ioctl_readonly(fd, request, arg)? + }; + + // SAFETY: The variant of `Ioctl` asserts that this is a valid pointer to + // the output data. + I::output_from_ptr(output, arg) + } } unsafe fn _ioctl(fd: BorrowedFd<'_>, request: Opcode, arg: *mut c::c_void) -> Result { - crate::backend::io::syscalls::ioctl(fd, request, arg) + unsafe { crate::backend::io::syscalls::ioctl(fd, request, arg) } } unsafe fn _ioctl_readonly( @@ -115,7 +117,7 @@ unsafe fn _ioctl_readonly( request: Opcode, arg: *mut c::c_void, ) -> Result { - crate::backend::io::syscalls::ioctl_readonly(fd, request, arg) + unsafe { crate::backend::io::syscalls::ioctl_readonly(fd, request, arg) } } /// A trait defining the properties of an `ioctl` command. diff --git a/src/ioctl/patterns.rs b/src/ioctl/patterns.rs index a08aae74e..6a158821a 100644 --- a/src/ioctl/patterns.rs +++ b/src/ioctl/patterns.rs @@ -102,7 +102,7 @@ unsafe impl Ioctl for Getter { } unsafe fn output_from_ptr(_: IoctlOutput, ptr: *mut c::c_void) -> Result { - Ok(ptr.cast::().read()) + unsafe { Ok(ptr.cast::().read()) } } } diff --git a/src/kernel_sigset.rs b/src/kernel_sigset.rs index 706bcb8cb..2090f1173 100644 --- a/src/kernel_sigset.rs +++ b/src/kernel_sigset.rs @@ -6,7 +6,7 @@ use crate::backend::c; use crate::signal::Signal; use core::fmt; -use linux_raw_sys::general::{kernel_sigset_t, _NSIG}; +use linux_raw_sys::general::{_NSIG, kernel_sigset_t}; /// `kernel_sigset_t`—A set of signal numbers, as used by some syscalls. /// diff --git a/src/lib.rs b/src/lib.rs index 1621262ed..a683f2c10 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -116,6 +116,7 @@ )] #![cfg_attr(asm_experimental_arch, feature(asm_experimental_arch))] #![cfg_attr(not(feature = "all-apis"), allow(dead_code))] +#![feature(int_roundings)] // It is common in Linux and libc APIs for types to vary between platforms. #![allow(clippy::unnecessary_cast)] // It is common in Linux and libc APIs for types to vary between platforms. @@ -147,15 +148,10 @@ extern crate rustc_std_workspace_alloc as alloc; #[cfg(all(feature = "alloc", not(feature = "rustc-dep-of-std")))] extern crate alloc; -// Use `static_assertions` macros if we have them, or a polyfill otherwise. -#[cfg(all(test, static_assertions))] +#[cfg(test)] #[macro_use] #[allow(unused_imports)] extern crate static_assertions; -#[cfg(all(test, not(static_assertions)))] -#[macro_use] -#[allow(unused_imports)] -mod static_assertions; pub mod buffer; #[cfg(not(windows))] diff --git a/src/mm/mmap.rs b/src/mm/mmap.rs index ec5a6d7cd..72b6883d4 100644 --- a/src/mm/mmap.rs +++ b/src/mm/mmap.rs @@ -92,7 +92,7 @@ pub unsafe fn mmap( fd: Fd, offset: u64, ) -> io::Result<*mut c_void> { - backend::mm::syscalls::mmap(ptr, len, prot, flags, fd.as_fd(), offset) + unsafe { backend::mm::syscalls::mmap(ptr, len, prot, flags, fd.as_fd(), offset) } } /// `mmap(ptr, len, prot, MAP_ANONYMOUS | flags, -1, 0)`—Create an anonymous @@ -135,7 +135,7 @@ pub unsafe fn mmap_anonymous( prot: ProtFlags, flags: MapFlags, ) -> io::Result<*mut c_void> { - backend::mm::syscalls::mmap_anonymous(ptr, len, prot, flags) + unsafe { backend::mm::syscalls::mmap_anonymous(ptr, len, prot, flags) } } /// `munmap(ptr, len)`—Remove a memory mapping. @@ -169,7 +169,7 @@ pub unsafe fn mmap_anonymous( /// [glibc]: https://sourceware.org/glibc/manual/latest/html_node/Memory_002dmapped-I_002fO.html#index-munmap #[inline] pub unsafe fn munmap(ptr: *mut c_void, len: usize) -> io::Result<()> { - backend::mm::syscalls::munmap(ptr, len) + unsafe { backend::mm::syscalls::munmap(ptr, len) } } /// `mremap(old_address, old_size, new_size, flags)`—Resize, modify, and/or @@ -202,7 +202,7 @@ pub unsafe fn mremap( new_size: usize, flags: MremapFlags, ) -> io::Result<*mut c_void> { - backend::mm::syscalls::mremap(old_address, old_size, new_size, flags) + unsafe { backend::mm::syscalls::mremap(old_address, old_size, new_size, flags) } } /// `mremap(old_address, old_size, new_size, MREMAP_FIXED | flags)`—Resize, @@ -238,7 +238,9 @@ pub unsafe fn mremap_fixed( flags: MremapFlags, new_address: *mut c_void, ) -> io::Result<*mut c_void> { - backend::mm::syscalls::mremap_fixed(old_address, old_size, new_size, flags, new_address) + unsafe { + backend::mm::syscalls::mremap_fixed(old_address, old_size, new_size, flags, new_address) + } } /// `mprotect(ptr, len, flags)`—Change the protection flags of a region of @@ -270,7 +272,7 @@ pub unsafe fn mremap_fixed( /// [illumos]: https://illumos.org/man/2/mprotect #[inline] pub unsafe fn mprotect(ptr: *mut c_void, len: usize, flags: MprotectFlags) -> io::Result<()> { - backend::mm::syscalls::mprotect(ptr, len, flags) + unsafe { backend::mm::syscalls::mprotect(ptr, len, flags) } } /// `mlock(ptr, len)`—Lock memory into RAM. @@ -310,7 +312,7 @@ pub unsafe fn mprotect(ptr: *mut c_void, len: usize, flags: MprotectFlags) -> io /// [glibc]: https://sourceware.org/glibc/manual/latest/html_node/Page-Lock-Functions.html#index-mlock #[inline] pub unsafe fn mlock(ptr: *mut c_void, len: usize) -> io::Result<()> { - backend::mm::syscalls::mlock(ptr, len) + unsafe { backend::mm::syscalls::mlock(ptr, len) } } /// `mlock2(ptr, len, flags)`—Lock memory into RAM, with flags. @@ -337,7 +339,7 @@ pub unsafe fn mlock(ptr: *mut c_void, len: usize) -> io::Result<()> { #[inline] #[doc(alias = "mlock2")] pub unsafe fn mlock_with(ptr: *mut c_void, len: usize, flags: MlockFlags) -> io::Result<()> { - backend::mm::syscalls::mlock_with(ptr, len, flags) + unsafe { backend::mm::syscalls::mlock_with(ptr, len, flags) } } /// `munlock(ptr, len)`—Unlock memory. @@ -374,7 +376,7 @@ pub unsafe fn mlock_with(ptr: *mut c_void, len: usize, flags: MlockFlags) -> io: /// [glibc]: https://sourceware.org/glibc/manual/latest/html_node/Page-Lock-Functions.html#index-munlock #[inline] pub unsafe fn munlock(ptr: *mut c_void, len: usize) -> io::Result<()> { - backend::mm::syscalls::munlock(ptr, len) + unsafe { backend::mm::syscalls::munlock(ptr, len) } } /// Locks all pages mapped into the address space of the calling process. diff --git a/src/mm/mod.rs b/src/mm/mod.rs index 7505cac0a..c23bbd777 100644 --- a/src/mm/mod.rs +++ b/src/mm/mod.rs @@ -8,8 +8,8 @@ mod msync; mod userfaultfd; #[cfg(not(target_os = "redox"))] -pub use madvise::{madvise, Advice}; +pub use madvise::{Advice, madvise}; pub use mmap::*; -pub use msync::{msync, MsyncFlags}; +pub use msync::{MsyncFlags, msync}; #[cfg(linux_kernel)] -pub use userfaultfd::{userfaultfd, UserfaultfdFlags}; +pub use userfaultfd::{UserfaultfdFlags, userfaultfd}; diff --git a/src/mm/msync.rs b/src/mm/msync.rs index c6723436a..59044cc0c 100644 --- a/src/mm/msync.rs +++ b/src/mm/msync.rs @@ -42,5 +42,5 @@ pub use backend::mm::types::MsyncFlags; /// [glibc]: https://sourceware.org/glibc/manual/latest/html_node/Memory_002dmapped-I_002fO.html#index-msync #[inline] pub unsafe fn msync(addr: *mut c_void, len: usize, flags: MsyncFlags) -> io::Result<()> { - backend::mm::syscalls::msync(addr, len, flags) + unsafe { backend::mm::syscalls::msync(addr, len, flags) } } diff --git a/src/mm/userfaultfd.rs b/src/mm/userfaultfd.rs index 46ab07ebd..dea54b876 100644 --- a/src/mm/userfaultfd.rs +++ b/src/mm/userfaultfd.rs @@ -26,5 +26,5 @@ pub use backend::mm::types::UserfaultfdFlags; /// [Linux userfaultfd]: https://www.kernel.org/doc/Documentation/vm/userfaultfd.txt #[inline] pub unsafe fn userfaultfd(flags: UserfaultfdFlags) -> io::Result { - backend::mm::syscalls::userfaultfd(flags) + unsafe { backend::mm::syscalls::userfaultfd(flags) } } diff --git a/src/net/addr.rs b/src/net/addr.rs index 13e5c24ff..f63f3330c 100644 --- a/src/net/addr.rs +++ b/src/net/addr.rs @@ -5,7 +5,7 @@ //! [the parent module][`super`]. #![allow(unsafe_code)] -use core::mem::{size_of, MaybeUninit}; +use core::mem::{MaybeUninit, size_of}; use core::ptr; use crate::backend::net::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6}; @@ -91,11 +91,13 @@ pub unsafe trait SocketAddrArg { /// `storage` must be valid to write up to `size_of()` /// bytes to. unsafe fn write_sockaddr(&self, storage: *mut SocketAddrStorage) -> SocketAddrLen { - // The closure dereferences exactly `len` bytes at `ptr`. - self.with_sockaddr(|ptr, len| { - ptr::copy_nonoverlapping(ptr.cast::(), storage.cast::(), len as usize); - len - }) + unsafe { + // The closure dereferences exactly `len` bytes at `ptr`. + self.with_sockaddr(|ptr, len| { + ptr::copy_nonoverlapping(ptr.cast::(), storage.cast::(), len as usize); + len + }) + } } } @@ -121,9 +123,11 @@ unsafe impl SocketAddrArg for SocketAddr { &self, f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, ) -> R { - match self { - Self::V4(v4) => v4.with_sockaddr(f), - Self::V6(v6) => v6.with_sockaddr(f), + unsafe { + match self { + Self::V4(v4) => v4.with_sockaddr(f), + Self::V6(v6) => v6.with_sockaddr(f), + } } } } @@ -135,7 +139,7 @@ unsafe impl SocketAddrArg for SocketAddrV4 { &self, f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, ) -> R { - call_with_sockaddr(&encode_sockaddr_v4(self), f) + unsafe { call_with_sockaddr(&encode_sockaddr_v4(self), f) } } } @@ -146,7 +150,7 @@ unsafe impl SocketAddrArg for SocketAddrV6 { &self, f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, ) -> R { - call_with_sockaddr(&encode_sockaddr_v6(self), f) + unsafe { call_with_sockaddr(&encode_sockaddr_v6(self), f) } } } diff --git a/src/net/send_recv/mod.rs b/src/net/send_recv/mod.rs index 0aac6d2eb..bad3eb3d3 100644 --- a/src/net/send_recv/mod.rs +++ b/src/net/send_recv/mod.rs @@ -3,8 +3,8 @@ #![allow(unsafe_code)] use crate::buffer::Buffer; -use crate::net::addr::SocketAddrArg; use crate::net::SocketAddrAny; +use crate::net::addr::SocketAddrArg; use crate::{backend, io}; use backend::fd::AsFd; use core::cmp::min; diff --git a/src/net/send_recv/msg.rs b/src/net/send_recv/msg.rs index 7df60a5e7..99cdb273d 100644 --- a/src/net/send_recv/msg.rs +++ b/src/net/send_recv/msg.rs @@ -7,12 +7,12 @@ use crate::backend::net::msghdr::noaddr_msghdr; use crate::backend::{self, c}; use crate::fd::{AsFd, BorrowedFd, OwnedFd}; use crate::io::{self, IoSlice, IoSliceMut}; -use crate::net::addr::SocketAddrArg; #[cfg(linux_kernel)] use crate::net::UCred; +use crate::net::addr::SocketAddrArg; use core::iter::FusedIterator; use core::marker::PhantomData; -use core::mem::{align_of, size_of, size_of_val, take, MaybeUninit}; +use core::mem::{MaybeUninit, align_of, size_of, size_of_val, take}; #[cfg(linux_kernel)] use core::ptr::addr_of; use core::{ptr, slice}; @@ -56,19 +56,19 @@ use super::{RecvFlags, ReturnFlags, SendFlags, SocketAddrAny}; #[macro_export] macro_rules! cmsg_space { // Base Rules - (ScmRights($len:expr)) => { + (ScmRights($len:expr_2021)) => { $crate::net::__cmsg_space( $len * ::core::mem::size_of::<$crate::fd::BorrowedFd<'static>>(), ) }; - (ScmCredentials($len:expr)) => { + (ScmCredentials($len:expr_2021)) => { $crate::net::__cmsg_space( $len * ::core::mem::size_of::<$crate::net::UCred>(), ) }; // Combo Rules - ($firstid:ident($firstex:expr), $($restid:ident($restex:expr)),*) => {{ + ($firstid:ident($firstex:expr_2021), $($restid:ident($restex:expr_2021)),*) => {{ // We only have to add `cmsghdr` alignment once; all other times we can // use `cmsg_aligned_space`. let sum = $crate::cmsg_space!($firstid($firstex)); @@ -84,19 +84,19 @@ macro_rules! cmsg_space { #[macro_export] macro_rules! cmsg_aligned_space { // Base Rules - (ScmRights($len:expr)) => { + (ScmRights($len:expr_2021)) => { $crate::net::__cmsg_aligned_space( $len * ::core::mem::size_of::<$crate::fd::BorrowedFd<'static>>(), ) }; - (ScmCredentials($len:expr)) => { + (ScmCredentials($len:expr_2021)) => { $crate::net::__cmsg_aligned_space( $len * ::core::mem::size_of::<$crate::net::UCred>(), ) }; // Combo Rules - ($firstid:ident($firstex:expr), $($restid:ident($restex:expr)),*) => {{ + ($firstid:ident($firstex:expr_2021), $($restid:ident($restex:expr_2021)),*) => {{ let sum = cmsg_aligned_space!($firstid($firstex)); $( let sum = sum + cmsg_aligned_space!($restid($restex)); @@ -297,7 +297,7 @@ impl<'buf, 'slice, 'fd> SendAncillaryBuffer<'buf, 'slice, 'fd> { /// Pushes an ancillary message to the buffer. fn push_ancillary(&mut self, source: &[u8], cmsg_level: c::c_int, cmsg_type: c::c_int) -> bool { macro_rules! leap { - ($e:expr) => {{ + ($e:expr_2021) => {{ match ($e) { Some(x) => x, None => return false, diff --git a/src/net/socket.rs b/src/net/socket.rs index fff302ad9..25ccb8c2b 100644 --- a/src/net/socket.rs +++ b/src/net/socket.rs @@ -1,6 +1,6 @@ use crate::fd::OwnedFd; -use crate::net::addr::SocketAddrArg; use crate::net::SocketAddrAny; +use crate::net::addr::SocketAddrArg; use crate::{backend, io}; use backend::fd::AsFd; diff --git a/src/net/socket_addr_any.rs b/src/net/socket_addr_any.rs index 7a9530444..637d6d249 100644 --- a/src/net/socket_addr_any.rs +++ b/src/net/socket_addr_any.rs @@ -5,12 +5,12 @@ use crate::backend::c; use crate::backend::net::read_sockaddr; use crate::io::Errno; -use crate::net::addr::{SocketAddrArg, SocketAddrLen, SocketAddrOpaque, SocketAddrStorage}; #[cfg(unix)] use crate::net::SocketAddrUnix; +use crate::net::addr::{SocketAddrArg, SocketAddrLen, SocketAddrOpaque, SocketAddrStorage}; use crate::net::{AddressFamily, SocketAddr, SocketAddrV4, SocketAddrV6}; use core::fmt; -use core::mem::{size_of, MaybeUninit}; +use core::mem::{MaybeUninit, size_of}; use core::num::NonZeroU32; /// Temporary buffer for creating a `SocketAddrAny` from a syscall that writes @@ -40,7 +40,7 @@ impl SocketAddrBuf { /// length written into `self.len`. #[inline] pub(crate) unsafe fn into_any(self) -> SocketAddrAny { - SocketAddrAny::new(self.storage, bitcast!(self.len)) + unsafe { SocketAddrAny::new(self.storage, bitcast!(self.len)) } } /// Convert the buffer into [`Option`]. @@ -54,11 +54,13 @@ impl SocketAddrBuf { /// length written into `self.len`, or `self.len` must have been set to 0. #[inline] pub(crate) unsafe fn into_any_option(self) -> Option { - let len = bitcast!(self.len); - if read_sockaddr::sockaddr_nonempty(self.storage.as_ptr().cast(), len) { - Some(SocketAddrAny::new(self.storage, len)) - } else { - None + unsafe { + let len = bitcast!(self.len); + if read_sockaddr::sockaddr_nonempty(self.storage.as_ptr().cast(), len) { + Some(SocketAddrAny::new(self.storage, len)) + } else { + None + } } } } @@ -97,10 +99,12 @@ impl SocketAddrAny { /// - `len` bytes must be initialized. #[inline] pub const unsafe fn new(storage: MaybeUninit, len: SocketAddrLen) -> Self { - assert!(len as usize >= size_of::()); - assert!(len as usize <= size_of::()); - let len = NonZeroU32::new_unchecked(len); - Self { storage, len } + unsafe { + assert!(len as usize >= size_of::()); + assert!(len as usize <= size_of::()); + let len = NonZeroU32::new_unchecked(len); + Self { storage, len } + } } /// Creates a socket address from reading from `ptr`, which points at `len` @@ -116,16 +120,18 @@ impl SocketAddrAny { /// - `ptr` must be a pointer to memory containing a valid socket address. /// - `len` bytes must be initialized. pub unsafe fn read(ptr: *const SocketAddrStorage, len: SocketAddrLen) -> Self { - assert!(len as usize >= size_of::()); - assert!(len as usize <= size_of::()); - let mut storage = MaybeUninit::::uninit(); - core::ptr::copy_nonoverlapping( - ptr.cast::(), - storage.as_mut_ptr().cast::(), - len as usize, - ); - let len = NonZeroU32::new_unchecked(len); - Self { storage, len } + unsafe { + assert!(len as usize >= size_of::()); + assert!(len as usize <= size_of::()); + let mut storage = MaybeUninit::::uninit(); + core::ptr::copy_nonoverlapping( + ptr.cast::(), + storage.as_mut_ptr().cast::(), + len as usize, + ); + let len = NonZeroU32::new_unchecked(len); + Self { storage, len } + } } /// Gets the initialized part of the storage as bytes. diff --git a/src/net/sockopt.rs b/src/net/sockopt.rs index 3379fb028..3acb014f9 100644 --- a/src/net/sockopt.rs +++ b/src/net/sockopt.rs @@ -143,8 +143,6 @@ #![doc(alias = "getsockopt")] #![doc(alias = "setsockopt")] -#[cfg(target_os = "linux")] -use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpStatistics, XdpUmemReg}; #[cfg(not(any( apple, windows, @@ -172,6 +170,8 @@ use crate::net::Protocol; use crate::net::SocketAddrV4; #[cfg(linux_kernel)] use crate::net::SocketAddrV6; +#[cfg(target_os = "linux")] +use crate::net::xdp::{XdpMmapOffsets, XdpOptionsFlags, XdpStatistics, XdpUmemReg}; use crate::net::{Ipv4Addr, Ipv6Addr, SocketType}; use crate::{backend, io}; #[cfg(feature = "alloc")] diff --git a/src/net/types.rs b/src/net/types.rs index 057f944d0..0006c9c08 100644 --- a/src/net/types.rs +++ b/src/net/types.rs @@ -803,7 +803,7 @@ pub struct Protocol(pub(crate) RawProtocol); /// /// For `IPPROTO_IP`, pass `None` as the `protocol` argument. pub mod ipproto { - use super::{new_raw_protocol, Protocol}; + use super::{Protocol, new_raw_protocol}; use crate::backend::c; /// `IPPROTO_ICMP` @@ -1119,7 +1119,7 @@ pub mod ipproto { pub mod sysproto { #[cfg(apple)] use { - super::{new_raw_protocol, Protocol}, + super::{Protocol, new_raw_protocol}, crate::backend::c, }; @@ -1138,12 +1138,12 @@ pub mod sysproto { pub mod netlink { #[cfg(linux_kernel)] use { - super::{new_raw_protocol, Protocol}, + super::{Protocol, new_raw_protocol}, crate::backend::c, crate::backend::net::read_sockaddr::read_sockaddr_netlink, crate::net::{ - addr::{call_with_sockaddr, SocketAddrArg, SocketAddrLen, SocketAddrOpaque}, SocketAddrAny, + addr::{SocketAddrArg, SocketAddrLen, SocketAddrOpaque, call_with_sockaddr}, }, core::mem, }; @@ -1273,11 +1273,13 @@ pub mod netlink { &self, f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, ) -> R { - let mut addr: c::sockaddr_nl = mem::zeroed(); - addr.nl_family = c::AF_NETLINK as _; - addr.nl_pid = self.pid; - addr.nl_groups = self.groups; - call_with_sockaddr(&addr, f) + unsafe { + let mut addr: c::sockaddr_nl = mem::zeroed(); + addr.nl_family = c::AF_NETLINK as _; + addr.nl_pid = self.pid; + addr.nl_groups = self.groups; + call_with_sockaddr(&addr, f) + } } } @@ -1307,7 +1309,7 @@ pub mod netlink { pub mod eth { #[cfg(linux_kernel)] use { - super::{new_raw_protocol, Protocol}, + super::{Protocol, new_raw_protocol}, crate::backend::c, }; @@ -1727,8 +1729,8 @@ bitflags! { pub mod xdp { use crate::backend::net::read_sockaddr::read_sockaddr_xdp; use crate::fd::{AsRawFd, BorrowedFd}; - use crate::net::addr::{call_with_sockaddr, SocketAddrArg, SocketAddrLen, SocketAddrOpaque}; use crate::net::SocketAddrAny; + use crate::net::addr::{SocketAddrArg, SocketAddrLen, SocketAddrOpaque, call_with_sockaddr}; use super::{bitflags, c}; @@ -1861,15 +1863,17 @@ pub mod xdp { &self, f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, ) -> R { - let addr = c::sockaddr_xdp { - sxdp_family: c::AF_XDP as _, - sxdp_flags: self.flags().bits(), - sxdp_ifindex: self.interface_index(), - sxdp_queue_id: self.queue_id(), - sxdp_shared_umem_fd: !0, - }; - - call_with_sockaddr(&addr, f) + unsafe { + let addr = c::sockaddr_xdp { + sxdp_family: c::AF_XDP as _, + sxdp_flags: self.flags().bits(), + sxdp_ifindex: self.interface_index(), + sxdp_queue_id: self.queue_id(), + sxdp_shared_umem_fd: !0, + }; + + call_with_sockaddr(&addr, f) + } } } @@ -1909,15 +1913,17 @@ pub mod xdp { &self, f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, ) -> R { - let addr = c::sockaddr_xdp { - sxdp_family: c::AF_XDP as _, - sxdp_flags: self.addr.flags().bits(), - sxdp_ifindex: self.addr.interface_index(), - sxdp_queue_id: self.addr.queue_id(), - sxdp_shared_umem_fd: self.shared_umem_fd.as_raw_fd() as u32, - }; - - call_with_sockaddr(&addr, f) + unsafe { + let addr = c::sockaddr_xdp { + sxdp_family: c::AF_XDP as _, + sxdp_flags: self.addr.flags().bits(), + sxdp_ifindex: self.addr.interface_index(), + sxdp_queue_id: self.addr.queue_id(), + sxdp_shared_umem_fd: self.shared_umem_fd.as_raw_fd() as u32, + }; + + call_with_sockaddr(&addr, f) + } } } diff --git a/src/net/wsa.rs b/src/net/wsa.rs index 0ad4db5eb..4c6350aa4 100644 --- a/src/net/wsa.rs +++ b/src/net/wsa.rs @@ -1,6 +1,6 @@ use crate::io; use core::mem::MaybeUninit; -use windows_sys::Win32::Networking::WinSock::{WSACleanup, WSAGetLastError, WSAStartup, WSADATA}; +use windows_sys::Win32::Networking::WinSock::{WSACleanup, WSADATA, WSAGetLastError, WSAStartup}; /// `WSAStartup()`—Initialize process-wide Windows support for sockets. /// diff --git a/src/path/mod.rs b/src/path/mod.rs index 627716d85..fefab8091 100644 --- a/src/path/mod.rs +++ b/src/path/mod.rs @@ -3,7 +3,7 @@ mod arg; mod dec_int; -pub use arg::{option_into_with_c_str, Arg}; +pub use arg::{Arg, option_into_with_c_str}; pub use dec_int::{DecInt, Integer}; pub(crate) const SMALL_PATH_BUFFER_SIZE: usize = 256; diff --git a/src/pid.rs b/src/pid.rs index c998a2082..1842dd5fe 100644 --- a/src/pid.rs +++ b/src/pid.rs @@ -51,8 +51,10 @@ impl Pid { /// The caller must guarantee `raw` is positive. #[inline] pub const unsafe fn from_raw_unchecked(raw: RawPid) -> Self { - debug_assert!(raw > 0); - Self(NonZeroI32::new_unchecked(raw)) + unsafe { + debug_assert!(raw > 0); + Self(NonZeroI32::new_unchecked(raw)) + } } /// Creates a `Pid` holding the ID of the given child process. diff --git a/src/pipe.rs b/src/pipe.rs index 267c99d51..9418bda18 100644 --- a/src/pipe.rs +++ b/src/pipe.rs @@ -173,7 +173,7 @@ pub unsafe fn vmsplice( bufs: &[IoSliceRaw<'_>], flags: SpliceFlags, ) -> io::Result { - backend::pipe::syscalls::vmsplice(fd.as_fd(), bufs, flags) + unsafe { backend::pipe::syscalls::vmsplice(fd.as_fd(), bufs, flags) } } /// `tee(fd_in, fd_out, len, flags)`—Copy data between pipes without diff --git a/src/prctl.rs b/src/prctl.rs index 1a31a8cc4..660a1447f 100644 --- a/src/prctl.rs +++ b/src/prctl.rs @@ -33,14 +33,18 @@ bitflags! { #[inline] pub(crate) unsafe fn prctl_1arg(option: c_int) -> io::Result { - const NULL: *mut c_void = null_mut(); - syscalls::prctl(option, NULL, NULL, NULL, NULL) + unsafe { + const NULL: *mut c_void = null_mut(); + syscalls::prctl(option, NULL, NULL, NULL, NULL) + } } #[inline] pub(crate) unsafe fn prctl_2args(option: c_int, arg2: *mut c_void) -> io::Result { - const NULL: *mut c_void = null_mut(); - syscalls::prctl(option, arg2, NULL, NULL, NULL) + unsafe { + const NULL: *mut c_void = null_mut(); + syscalls::prctl(option, arg2, NULL, NULL, NULL) + } } #[inline] @@ -49,14 +53,16 @@ pub(crate) unsafe fn prctl_3args( arg2: *mut c_void, arg3: *mut c_void, ) -> io::Result { - syscalls::prctl(option, arg2, arg3, null_mut(), null_mut()) + unsafe { syscalls::prctl(option, arg2, arg3, null_mut(), null_mut()) } } #[inline] pub(crate) unsafe fn prctl_get_at_arg2_optional

(option: i32) -> io::Result

{ - let mut value: MaybeUninit

= MaybeUninit::uninit(); - prctl_2args(option, value.as_mut_ptr().cast())?; - Ok(value.assume_init()) + unsafe { + let mut value: MaybeUninit

= MaybeUninit::uninit(); + prctl_2args(option, value.as_mut_ptr().cast())?; + Ok(value.assume_init()) + } } #[inline] @@ -65,7 +71,9 @@ where P: Default, T: TryFrom, { - let mut value: P = Default::default(); - prctl_2args(option, as_mut_ptr(&mut value).cast())?; - TryFrom::try_from(value) + unsafe { + let mut value: P = Default::default(); + prctl_2args(option, as_mut_ptr(&mut value).cast())?; + TryFrom::try_from(value) + } } diff --git a/src/process/prctl.rs b/src/process/prctl.rs index 8b08409c1..8e7fcb14c 100644 --- a/src/process/prctl.rs +++ b/src/process/prctl.rs @@ -7,13 +7,13 @@ use core::mem::size_of; use core::num::NonZeroI32; -use core::ptr::{null, null_mut, NonNull}; +use core::ptr::{NonNull, null, null_mut}; use bitflags::bitflags; use crate::backend::prctl::syscalls; use crate::fd::{AsRawFd as _, BorrowedFd, RawFd}; -use crate::ffi::{c_int, c_uint, c_void, CStr}; +use crate::ffi::{CStr, c_int, c_uint, c_void}; use crate::io; use crate::prctl::*; use crate::process::{Pid, RawPid}; @@ -429,7 +429,7 @@ const PR_SET_ENDIAN: c_int = 20; #[inline] #[doc(alias = "PR_SET_ENDIAN")] pub unsafe fn set_endian_mode(mode: EndianMode) -> io::Result<()> { - prctl_2args(PR_SET_ENDIAN, mode as usize as *mut _).map(|_r| ()) + unsafe { prctl_2args(PR_SET_ENDIAN, mode as usize as *mut _).map(|_r| ()) } } // @@ -569,8 +569,8 @@ impl TryFrom for MachineCheckMemoryCorruptionKillPolicy { /// [`prctl(PR_MCE_KILL_GET,…)`]: https://man7.org/linux/man-pages/man2/prctl.2.html #[inline] #[doc(alias = "PR_MCE_KILL_GET")] -pub fn machine_check_memory_corruption_kill_policy( -) -> io::Result { +pub fn machine_check_memory_corruption_kill_policy() +-> io::Result { let r = unsafe { prctl_1arg(PR_MCE_KILL_GET)? } as c_uint; MachineCheckMemoryCorruptionKillPolicy::try_from(r) } @@ -671,8 +671,10 @@ pub unsafe fn set_virtual_memory_map_address( option: VirtualMemoryMapAddress, address: Option>, ) -> io::Result<()> { - let address = address.map_or_else(null_mut, NonNull::as_ptr); - prctl_3args(PR_SET_MM, option as usize as *mut _, address).map(|_r| ()) + unsafe { + let address = address.map_or_else(null_mut, NonNull::as_ptr); + prctl_3args(PR_SET_MM, option as usize as *mut _, address).map(|_r| ()) + } } /// Supersede the `/proc/pid/exe` symbolic link with a new one pointing to a @@ -705,14 +707,16 @@ pub fn set_executable_file(fd: BorrowedFd<'_>) -> io::Result<()> { #[doc(alias = "PR_SET_MM")] #[doc(alias = "PR_SET_MM_AUXV")] pub unsafe fn set_auxiliary_vector(auxv: &[*const c_void]) -> io::Result<()> { - syscalls::prctl( - PR_SET_MM, - PR_SET_MM_AUXV as *mut _, - auxv.as_ptr() as *mut _, - auxv.len() as *mut _, - null_mut(), - ) - .map(|_r| ()) + unsafe { + syscalls::prctl( + PR_SET_MM, + PR_SET_MM_AUXV as *mut _, + auxv.as_ptr() as *mut _, + auxv.len() as *mut _, + null_mut(), + ) + .map(|_r| ()) + } } /// Get the size of the [`PrctlMmMap`] the kernel expects. @@ -784,14 +788,16 @@ pub struct PrctlMmMap { #[doc(alias = "PR_SET_MM")] #[doc(alias = "PR_SET_MM_MAP")] pub unsafe fn configure_virtual_memory_map(config: &PrctlMmMap) -> io::Result<()> { - syscalls::prctl( - PR_SET_MM, - PR_SET_MM_MAP as *mut _, - as_ptr(config) as *mut _, - size_of::() as *mut _, - null_mut(), - ) - .map(|_r| ()) + unsafe { + syscalls::prctl( + PR_SET_MM, + PR_SET_MM_MAP as *mut _, + as_ptr(config) as *mut _, + size_of::() as *mut _, + null_mut(), + ) + .map(|_r| ()) + } } // @@ -1108,30 +1114,32 @@ pub unsafe fn configure_pointer_authentication_keys< >( config: Config, ) -> io::Result<()> { - let mut affected_keys: u32 = 0; - let mut enabled_keys: u32 = 0; - - for (key, enable) in config { - let key = key.bits(); - affected_keys |= key; + unsafe { + let mut affected_keys: u32 = 0; + let mut enabled_keys: u32 = 0; + + for (key, enable) in config { + let key = key.bits(); + affected_keys |= key; + + if enable { + enabled_keys |= key; + } else { + enabled_keys &= !key; + } + } - if enable { - enabled_keys |= key; - } else { - enabled_keys &= !key; + if affected_keys == 0 { + return Ok(()); // Nothing to do. } - } - if affected_keys == 0 { - return Ok(()); // Nothing to do. + prctl_3args( + PR_PAC_SET_ENABLED_KEYS, + affected_keys as usize as *mut _, + enabled_keys as usize as *mut _, + ) + .map(|_r| ()) } - - prctl_3args( - PR_PAC_SET_ENABLED_KEYS, - affected_keys as usize as *mut _, - enabled_keys as usize as *mut _, - ) - .map(|_r| ()) } // diff --git a/src/process/types.rs b/src/process/types.rs index 0adb47ec6..e275d20c8 100644 --- a/src/process/types.rs +++ b/src/process/types.rs @@ -30,12 +30,14 @@ pub struct Flock { #[cfg(not(target_os = "horizon"))] impl Flock { pub(crate) const unsafe fn from_raw_unchecked(raw_fl: c::flock) -> Self { - Self { - start: raw_fl.l_start as _, - length: raw_fl.l_len as _, - pid: Pid::from_raw(raw_fl.l_pid), - typ: transmute::(raw_fl.l_type), - offset_type: transmute::(raw_fl.l_whence), + unsafe { + Self { + start: raw_fl.l_start as _, + length: raw_fl.l_len as _, + pid: Pid::from_raw(raw_fl.l_pid), + typ: transmute::(raw_fl.l_type), + offset_type: transmute::(raw_fl.l_whence), + } } } diff --git a/src/pty.rs b/src/pty.rs index 560dfc136..1976714fb 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -92,7 +92,7 @@ pub fn openpt(flags: OpenptFlags) -> io::Result { // On Linux, open the device ourselves so that we can support `CLOEXEC`. #[cfg(linux_kernel)] { - use crate::fs::{open, Mode}; + use crate::fs::{Mode, open}; match open(cstr!("/dev/ptmx"), flags.into(), Mode::empty()) { // Match libc `openat` behavior with `ENOSPC`. Err(io::Errno::NOSPC) => Err(io::Errno::AGAIN), @@ -218,6 +218,6 @@ unsafe impl ioctl::Ioctl for Tiocgptpeer { ret: ioctl::IoctlOutput, _arg: *mut c::c_void, ) -> io::Result { - Ok(OwnedFd::from_raw_fd(ret)) + unsafe { Ok(OwnedFd::from_raw_fd(ret)) } } } diff --git a/src/rand/mod.rs b/src/rand/mod.rs index e767c590d..58740cf23 100644 --- a/src/rand/mod.rs +++ b/src/rand/mod.rs @@ -4,4 +4,4 @@ mod getrandom; #[cfg(linux_kernel)] -pub use getrandom::{getrandom, GetRandomFlags}; +pub use getrandom::{GetRandomFlags, getrandom}; diff --git a/src/runtime.rs b/src/runtime.rs index 9b612b8ba..516f6055b 100644 --- a/src/runtime.rs +++ b/src/runtime.rs @@ -217,7 +217,7 @@ pub unsafe fn arm_set_tls(data: *mut c_void) -> io::Result<()> { #[cfg(target_arch = "x86_64")] #[inline] pub unsafe fn set_fs(data: *mut c_void) { - backend::runtime::syscalls::tls::set_fs(data) + unsafe { backend::runtime::syscalls::tls::set_fs(data) } } /// Set the x86-64 thread ID address. @@ -228,7 +228,7 @@ pub unsafe fn set_fs(data: *mut c_void) { /// See the references links above. #[inline] pub unsafe fn set_tid_address(data: *mut c_void) -> Pid { - backend::runtime::syscalls::tls::set_tid_address(data) + unsafe { backend::runtime::syscalls::tls::set_tid_address(data) } } #[cfg(target_arch = "x86")] @@ -417,7 +417,7 @@ pub fn random() -> *const [u8; 16] { /// [Linux]: https://man7.org/linux/man-pages/man2/fork.2.html /// [async-signal-safe]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/V2_chap02.html#tag_15_04_03 pub unsafe fn kernel_fork() -> io::Result { - backend::runtime::syscalls::kernel_fork() + unsafe { backend::runtime::syscalls::kernel_fork() } } /// Regular Unix `fork` doesn't tell the child its own PID because it assumes @@ -460,7 +460,7 @@ pub unsafe fn execveat( envp: *const *const u8, flags: AtFlags, ) -> io::Errno { - backend::runtime::syscalls::execveat(dirfd.as_fd(), path, argv, envp, flags) + unsafe { backend::runtime::syscalls::execveat(dirfd.as_fd(), path, argv, envp, flags) } } /// `execve(path.as_c_str(), argv, envp)`—Execute a new command using the @@ -482,7 +482,7 @@ pub unsafe fn execveat( #[inline] #[must_use] pub unsafe fn execve(path: &CStr, argv: *const *const u8, envp: *const *const u8) -> io::Errno { - backend::runtime::syscalls::execve(path, argv, envp) + unsafe { backend::runtime::syscalls::execve(path, argv, envp) } } /// `sigaction(signal, &new, &old)`—Modify and/or query a signal handler. @@ -504,7 +504,7 @@ pub unsafe fn kernel_sigaction( signal: Signal, new: Option, ) -> io::Result { - backend::runtime::syscalls::kernel_sigaction(signal, new) + unsafe { backend::runtime::syscalls::kernel_sigaction(signal, new) } } /// `sigaltstack(new, old)`—Modify and/or query a signal stack. @@ -541,7 +541,7 @@ pub unsafe fn kernel_sigaction( /// [Linux]: https://man7.org/linux/man-pages/man2/sigaltstack.2.html #[inline] pub unsafe fn kernel_sigaltstack(new: Option) -> io::Result { - backend::runtime::syscalls::kernel_sigaltstack(new) + unsafe { backend::runtime::syscalls::kernel_sigaltstack(new) } } /// `tkill(tid, sig)`—Send a signal to a thread. @@ -563,7 +563,7 @@ pub unsafe fn kernel_sigaltstack(new: Option) -> io::Result { /// [Linux]: https://man7.org/linux/man-pages/man2/tkill.2.html #[inline] pub unsafe fn tkill(tid: Pid, sig: Signal) -> io::Result<()> { - backend::runtime::syscalls::tkill(tid, sig) + unsafe { backend::runtime::syscalls::tkill(tid, sig) } } /// `rt_sigprocmask(how, set, oldset)`—Adjust the process signal mask. @@ -594,7 +594,7 @@ pub unsafe fn tkill(tid: Pid, sig: Signal) -> io::Result<()> { #[doc(alias = "pthread_sigmask")] #[doc(alias = "rt_sigprocmask")] pub unsafe fn kernel_sigprocmask(how: How, set: Option<&KernelSigSet>) -> io::Result { - backend::runtime::syscalls::kernel_sigprocmask(how, set) + unsafe { backend::runtime::syscalls::kernel_sigprocmask(how, set) } } /// `sigpending()`—Query the pending signals. @@ -649,7 +649,7 @@ pub fn kernel_sigsuspend(set: &KernelSigSet) -> io::Result<()> { /// [Linux]: https://man7.org/linux/man-pages/man3/sigwait.3.html #[inline] pub unsafe fn kernel_sigwait(set: &KernelSigSet) -> io::Result { - backend::runtime::syscalls::kernel_sigwait(set) + unsafe { backend::runtime::syscalls::kernel_sigwait(set) } } /// `sigwaitinfo(set)`—Wait for signals, returning a [`Siginfo`]. @@ -676,7 +676,7 @@ pub unsafe fn kernel_sigwait(set: &KernelSigSet) -> io::Result { /// [Linux]: https://man7.org/linux/man-pages/man2/sigwaitinfo.2.html #[inline] pub unsafe fn kernel_sigwaitinfo(set: &KernelSigSet) -> io::Result { - backend::runtime::syscalls::kernel_sigwaitinfo(set) + unsafe { backend::runtime::syscalls::kernel_sigwaitinfo(set) } } /// `sigtimedwait(set)`—Wait for signals, optionally with a timeout. @@ -706,7 +706,7 @@ pub unsafe fn kernel_sigtimedwait( set: &KernelSigSet, timeout: Option<&Timespec>, ) -> io::Result { - backend::runtime::syscalls::kernel_sigtimedwait(set, timeout) + unsafe { backend::runtime::syscalls::kernel_sigtimedwait(set, timeout) } } /// `getauxval(AT_SECURE)`—Returns the Linux “secure execution” mode. @@ -738,7 +738,7 @@ pub fn linux_secure() -> bool { /// (perhaps because you yourself are implementing a libc). #[inline] pub unsafe fn kernel_brk(addr: *mut c_void) -> io::Result<*mut c_void> { - backend::runtime::syscalls::kernel_brk(addr) + unsafe { backend::runtime::syscalls::kernel_brk(addr) } } /// `SIGRTMIN`—The start of the raw OS “real-time” signal range. diff --git a/src/signal.rs b/src/signal.rs index 264f227e9..2a4652ce2 100644 --- a/src/signal.rs +++ b/src/signal.rs @@ -51,40 +51,40 @@ pub struct Signal(NonZeroI32); #[rustfmt::skip] impl Signal { /// `SIGHUP` - pub const HUP: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGHUP) }); + pub const HUP: Self = Self( NonZeroI32::new(c::SIGHUP).unwrap() ); /// `SIGINT` - pub const INT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGINT) }); + pub const INT: Self = Self( NonZeroI32::new(c::SIGINT).unwrap() ); /// `SIGQUIT` - pub const QUIT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGQUIT) }); + pub const QUIT: Self = Self( NonZeroI32::new(c::SIGQUIT).unwrap() ); /// `SIGILL` - pub const ILL: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGILL) }); + pub const ILL: Self = Self( NonZeroI32::new(c::SIGILL).unwrap() ); /// `SIGTRAP` - pub const TRAP: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGTRAP) }); + pub const TRAP: Self = Self( NonZeroI32::new(c::SIGTRAP).unwrap() ); /// `SIGABRT`, aka `SIGIOT` #[doc(alias = "IOT")] #[doc(alias = "ABRT")] - pub const ABORT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGABRT) }); + pub const ABORT: Self = Self( NonZeroI32::new(c::SIGABRT).unwrap() ); /// `SIGBUS` - pub const BUS: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGBUS) }); + pub const BUS: Self = Self( NonZeroI32::new(c::SIGBUS).unwrap() ); /// `SIGFPE` - pub const FPE: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGFPE) }); + pub const FPE: Self = Self( NonZeroI32::new(c::SIGFPE).unwrap() ); /// `SIGKILL` - pub const KILL: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGKILL) }); + pub const KILL: Self = Self( NonZeroI32::new(c::SIGKILL).unwrap() ); /// `SIGUSR1` #[cfg(not(target_os = "vita"))] - pub const USR1: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGUSR1) }); + pub const USR1: Self = Self( NonZeroI32::new(c::SIGUSR1).unwrap() ); /// `SIGSEGV` - pub const SEGV: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGSEGV) }); + pub const SEGV: Self = Self( NonZeroI32::new(c::SIGSEGV).unwrap() ); /// `SIGUSR2` #[cfg(not(target_os = "vita"))] - pub const USR2: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGUSR2) }); + pub const USR2: Self = Self( NonZeroI32::new(c::SIGUSR2).unwrap() ); /// `SIGPIPE` - pub const PIPE: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGPIPE) }); + pub const PIPE: Self = Self( NonZeroI32::new(c::SIGPIPE).unwrap() ); /// `SIGALRM` #[doc(alias = "ALRM")] - pub const ALARM: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGALRM) }); + pub const ALARM: Self = Self( NonZeroI32::new(c::SIGALRM).unwrap() ); /// `SIGTERM` - pub const TERM: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGTERM) }); + pub const TERM: Self = Self( NonZeroI32::new(c::SIGTERM).unwrap() ); /// `SIGSTKFLT` #[cfg(not(any( bsd, @@ -108,49 +108,49 @@ impl Signal { ), ), )))] - pub const STKFLT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGSTKFLT) }); + pub const STKFLT: Self = Self( NonZeroI32::new(c::SIGSTKFLT).unwrap() ); /// `SIGCHLD` #[cfg(not(target_os = "vita"))] #[doc(alias = "CHLD")] - pub const CHILD: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGCHLD) }); + pub const CHILD: Self = Self( NonZeroI32::new(c::SIGCHLD).unwrap() ); /// `SIGCONT` #[cfg(not(target_os = "vita"))] - pub const CONT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGCONT) }); + pub const CONT: Self = Self( NonZeroI32::new(c::SIGCONT).unwrap() ); /// `SIGSTOP` #[cfg(not(target_os = "vita"))] - pub const STOP: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGSTOP) }); + pub const STOP: Self = Self( NonZeroI32::new(c::SIGSTOP).unwrap() ); /// `SIGTSTP` #[cfg(not(target_os = "vita"))] - pub const TSTP: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGTSTP) }); + pub const TSTP: Self = Self( NonZeroI32::new(c::SIGTSTP).unwrap() ); /// `SIGTTIN` #[cfg(not(target_os = "vita"))] - pub const TTIN: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGTTIN) }); + pub const TTIN: Self = Self( NonZeroI32::new(c::SIGTTIN).unwrap() ); /// `SIGTTOU` #[cfg(not(target_os = "vita"))] - pub const TTOU: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGTTOU) }); + pub const TTOU: Self = Self( NonZeroI32::new(c::SIGTTOU).unwrap() ); /// `SIGURG` #[cfg(not(target_os = "vita"))] - pub const URG: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGURG) }); + pub const URG: Self = Self( NonZeroI32::new(c::SIGURG).unwrap() ); /// `SIGXCPU` #[cfg(not(target_os = "vita"))] - pub const XCPU: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGXCPU) }); + pub const XCPU: Self = Self( NonZeroI32::new(c::SIGXCPU).unwrap() ); /// `SIGXFSZ` #[cfg(not(target_os = "vita"))] - pub const XFSZ: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGXFSZ) }); + pub const XFSZ: Self = Self( NonZeroI32::new(c::SIGXFSZ).unwrap() ); /// `SIGVTALRM` #[cfg(not(target_os = "vita"))] #[doc(alias = "VTALRM")] - pub const VTALARM: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGVTALRM) }); + pub const VTALARM: Self = Self( NonZeroI32::new(c::SIGVTALRM).unwrap() ); /// `SIGPROF` #[cfg(not(target_os = "vita"))] - pub const PROF: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGPROF) }); + pub const PROF: Self = Self( NonZeroI32::new(c::SIGPROF).unwrap() ); /// `SIGWINCH` #[cfg(not(target_os = "vita"))] - pub const WINCH: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGWINCH) }); + pub const WINCH: Self = Self( NonZeroI32::new(c::SIGWINCH).unwrap() ); /// `SIGIO`, aka `SIGPOLL` #[doc(alias = "POLL")] #[cfg(not(any(target_os = "haiku", target_os = "vita")))] - pub const IO: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGIO) }); + pub const IO: Self = Self( NonZeroI32::new(c::SIGIO).unwrap() ); /// `SIGPWR` #[cfg(not(any( bsd, @@ -160,10 +160,10 @@ impl Signal { target_os = "vita" )))] #[doc(alias = "PWR")] - pub const POWER: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGPWR) }); + pub const POWER: Self = Self( NonZeroI32::new(c::SIGPWR).unwrap() ); /// `SIGSYS`, aka `SIGUNUSED` #[doc(alias = "UNUSED")] - pub const SYS: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGSYS) }); + pub const SYS: Self = Self( NonZeroI32::new(c::SIGSYS).unwrap() ); /// `SIGEMT` #[cfg(any( bsd, @@ -182,17 +182,17 @@ impl Signal { ) ) ))] - pub const EMT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGEMT) }); + pub const EMT: Self = Self( NonZeroI32::new(c::SIGEMT).unwrap() ); /// `SIGINFO` #[cfg(bsd)] - pub const INFO: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGINFO) }); + pub const INFO: Self = Self( NonZeroI32::new(c::SIGINFO).unwrap() ); /// `SIGTHR` #[cfg(target_os = "freebsd")] #[doc(alias = "LWP")] - pub const THR: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGTHR) }); + pub const THR: Self = Self( NonZeroI32::new(c::SIGTHR).unwrap() ); /// `SIGLIBRT` #[cfg(target_os = "freebsd")] - pub const LIBRT: Self = Self(unsafe { NonZeroI32::new_unchecked(c::SIGLIBRT) }); + pub const LIBRT: Self = Self( NonZeroI32::new(c::SIGLIBRT).unwrap() ); } impl Signal { @@ -230,7 +230,7 @@ impl Signal { /// [`SIGRTMAX`]: https://docs.rs/libc/*/libc/fn.SIGRTMAX.html #[inline] pub const unsafe fn from_raw_unchecked(sig: i32) -> Self { - Self::from_raw_nonzero_unchecked(NonZeroI32::new_unchecked(sig)) + unsafe { Self::from_raw_nonzero_unchecked(NonZeroI32::new_unchecked(sig)) } } /// Convert a raw non-zero signal number into a `Signal` without checks. diff --git a/src/static_assertions.rs b/src/static_assertions.rs deleted file mode 100644 index 3d0711811..000000000 --- a/src/static_assertions.rs +++ /dev/null @@ -1,36 +0,0 @@ -//! Workarounds for Rust 1.63 where some things in the `static_assertions` -//! crate do things that don't work in const contexts. We want to call them in -//! const contexts in Rust versions where that's supported so that problems are -//! caught at compile time, and fall back to dynamic asserts in Rust 1.63. - -#![allow(unused_macros)] - -macro_rules! assert_eq_size { - ($x:ty, $y:ty) => { - assert_eq!(core::mem::size_of::<$x>(), core::mem::size_of::<$y>()); - }; -} - -macro_rules! assert_eq_align { - ($x:ty, $y:ty) => { - assert_eq!(core::mem::align_of::<$x>(), core::mem::align_of::<$y>()); - }; -} - -macro_rules! const_assert_eq { - ($x:expr, $y:expr) => { - assert_eq!($x, $y); - }; -} - -macro_rules! const_assert_ne { - ($x:expr, $y:expr) => { - assert_ne!($x, $y); - }; -} - -macro_rules! const_assert { - ($x:expr) => { - assert!($x); - }; -} diff --git a/src/stdio.rs b/src/stdio.rs index e5ea0d4f4..5f3fe777c 100644 --- a/src/stdio.rs +++ b/src/stdio.rs @@ -144,7 +144,7 @@ pub const unsafe fn stdin() -> BorrowedFd<'static> { #[doc(alias = "STDIN_FILENO")] #[inline] pub unsafe fn take_stdin() -> OwnedFd { - backend::fd::OwnedFd::from_raw_fd(c::STDIN_FILENO as RawFd) + unsafe { backend::fd::OwnedFd::from_raw_fd(c::STDIN_FILENO as RawFd) } } /// `STDOUT_FILENO`—Standard output, borrowed. @@ -266,7 +266,7 @@ pub const unsafe fn stdout() -> BorrowedFd<'static> { #[doc(alias = "STDOUT_FILENO")] #[inline] pub unsafe fn take_stdout() -> OwnedFd { - backend::fd::OwnedFd::from_raw_fd(c::STDOUT_FILENO as RawFd) + unsafe { backend::fd::OwnedFd::from_raw_fd(c::STDOUT_FILENO as RawFd) } } /// `STDERR_FILENO`—Standard error, borrowed. @@ -381,7 +381,7 @@ pub const unsafe fn stderr() -> BorrowedFd<'static> { #[doc(alias = "STDERR_FILENO")] #[inline] pub unsafe fn take_stderr() -> OwnedFd { - backend::fd::OwnedFd::from_raw_fd(c::STDERR_FILENO as RawFd) + unsafe { backend::fd::OwnedFd::from_raw_fd(c::STDERR_FILENO as RawFd) } } /// `STDIN_FILENO`—Standard input, raw. diff --git a/src/thread/futex.rs b/src/thread/futex.rs index 7ac49e69f..532d34c5f 100644 --- a/src/thread/futex.rs +++ b/src/thread/futex.rs @@ -39,7 +39,7 @@ use crate::{backend, io}; pub use crate::clockid::ClockId; pub use crate::timespec::{Nsecs, Secs, Timespec}; -pub use backend::thread::futex::{Flags, WaitFlags, OWNER_DIED, WAITERS}; +pub use backend::thread::futex::{Flags, OWNER_DIED, WAITERS, WaitFlags}; /// `syscall(SYS_futex, uaddr, FUTEX_WAIT, val, timeout, NULL, 0)` /// diff --git a/src/thread/mod.rs b/src/thread/mod.rs index e32b5945c..ffbad9150 100644 --- a/src/thread/mod.rs +++ b/src/thread/mod.rs @@ -23,7 +23,7 @@ pub use clock::*; #[cfg(linux_kernel)] pub use id::*; #[cfg(linux_kernel)] -pub use libcap::{capabilities, set_capabilities, CapabilityFlags, CapabilitySets}; +pub use libcap::{CapabilityFlags, CapabilitySets, capabilities, set_capabilities}; #[cfg(linux_kernel)] pub use membarrier::*; #[cfg(linux_kernel)] diff --git a/src/thread/prctl.rs b/src/thread/prctl.rs index 4719b1eb4..24a4b0cf5 100644 --- a/src/thread/prctl.rs +++ b/src/thread/prctl.rs @@ -19,11 +19,11 @@ use bitflags::bitflags; use crate::backend::prctl::syscalls; #[cfg(feature = "alloc")] use crate::ffi::CString; -use crate::ffi::{c_int, c_uint, c_void, CStr}; +use crate::ffi::{CStr, c_int, c_uint, c_void}; use crate::io; use crate::pid::Pid; use crate::prctl::{ - prctl_1arg, prctl_2args, prctl_3args, prctl_get_at_arg2_optional, PointerAuthenticationKeys, + PointerAuthenticationKeys, prctl_1arg, prctl_2args, prctl_3args, prctl_get_at_arg2_optional, }; use crate::utils::as_ptr; @@ -701,20 +701,22 @@ pub unsafe fn set_sve_vector_length_configuration( vector_length_inherited_across_execve: bool, defer_change_to_next_execve: bool, ) -> io::Result<()> { - let vector_length_in_bytes = - u32::try_from(vector_length_in_bytes).map_err(|_r| io::Errno::RANGE)?; + unsafe { + let vector_length_in_bytes = + u32::try_from(vector_length_in_bytes).map_err(|_r| io::Errno::RANGE)?; - let mut bits = vector_length_in_bytes & PR_SVE_VL_LEN_MASK; + let mut bits = vector_length_in_bytes & PR_SVE_VL_LEN_MASK; - if vector_length_inherited_across_execve { - bits |= PR_SVE_VL_INHERIT; - } + if vector_length_inherited_across_execve { + bits |= PR_SVE_VL_INHERIT; + } - if defer_change_to_next_execve { - bits |= PR_SVE_SET_VL_ONEXEC; - } + if defer_change_to_next_execve { + bits |= PR_SVE_SET_VL_ONEXEC; + } - prctl_2args(PR_SVE_SET_VL, bits as usize as *mut _).map(|_r| ()) + prctl_2args(PR_SVE_SET_VL, bits as usize as *mut _).map(|_r| ()) + } } // @@ -739,8 +741,10 @@ const PR_PAC_RESET_KEYS: c_int = 54; pub unsafe fn reset_pointer_authentication_keys( keys: Option, ) -> io::Result<()> { - let keys = keys.as_ref().map_or(0_u32, PointerAuthenticationKeys::bits); - prctl_2args(PR_PAC_RESET_KEYS, keys as usize as *mut _).map(|_r| ()) + unsafe { + let keys = keys.as_ref().map_or(0_u32, PointerAuthenticationKeys::bits); + prctl_2args(PR_PAC_RESET_KEYS, keys as usize as *mut _).map(|_r| ()) + } } // @@ -803,9 +807,11 @@ pub unsafe fn set_current_tagged_address_mode( mode: Option, mte_tag: u32, ) -> io::Result<()> { - let config = mode.as_ref().map_or(0_u32, TaggedAddressMode::bits) - | ((mte_tag << PR_MTE_TAG_SHIFT) & PR_MTE_TAG_MASK); - prctl_2args(PR_SET_TAGGED_ADDR_CTRL, config as usize as *mut _).map(|_r| ()) + unsafe { + let config = mode.as_ref().map_or(0_u32, TaggedAddressMode::bits) + | ((mte_tag << PR_MTE_TAG_SHIFT) & PR_MTE_TAG_MASK); + prctl_2args(PR_SET_TAGGED_ADDR_CTRL, config as usize as *mut _).map(|_r| ()) + } } // @@ -829,7 +835,7 @@ const PR_SYS_DISPATCH_OFF: usize = 0; /// [`prctl(PR_SET_SYSCALL_USER_DISPATCH,PR_SYS_DISPATCH_OFF,…)`]: https://man7.org/linux/man-pages/man2/prctl.2.html #[inline] pub unsafe fn disable_syscall_user_dispatch() -> io::Result<()> { - prctl_2args(PR_SET_SYSCALL_USER_DISPATCH, PR_SYS_DISPATCH_OFF as *mut _).map(|_r| ()) + unsafe { prctl_2args(PR_SET_SYSCALL_USER_DISPATCH, PR_SYS_DISPATCH_OFF as *mut _).map(|_r| ()) } } const PR_SYS_DISPATCH_ON: usize = 1; @@ -878,14 +884,16 @@ pub unsafe fn enable_syscall_user_dispatch( always_allowed_region: &[u8], fast_switch_flag: &AtomicU8, ) -> io::Result<()> { - syscalls::prctl( - PR_SET_SYSCALL_USER_DISPATCH, - PR_SYS_DISPATCH_ON as *mut _, - always_allowed_region.as_ptr() as *mut _, - always_allowed_region.len() as *mut _, - as_ptr(fast_switch_flag) as *mut _, - ) - .map(|_r| ()) + unsafe { + syscalls::prctl( + PR_SET_SYSCALL_USER_DISPATCH, + PR_SYS_DISPATCH_ON as *mut _, + always_allowed_region.as_ptr() as *mut _, + always_allowed_region.len() as *mut _, + as_ptr(fast_switch_flag) as *mut _, + ) + .map(|_r| ()) + } } // diff --git a/src/timespec.rs b/src/timespec.rs index f5404ba42..fcbca9d14 100644 --- a/src/timespec.rs +++ b/src/timespec.rs @@ -198,8 +198,7 @@ impl Timespec { secs.checked_mul(1000) .and_then(|millis| { // Add the nanoseconds, converted to milliseconds, rounding up. - // With Rust 1.73.0 this can use `div_ceil`. - millis.checked_add((i64::from(self.tv_nsec) + 999_999) / 1_000_000) + millis.checked_add(i64::from(self.tv_nsec).div_ceil(1_000_000)) }) .and_then(|millis| c::c_int::try_from(millis).ok()) } diff --git a/src/utils.rs b/src/utils.rs index 77eb26c14..296fe4244 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -5,7 +5,7 @@ use core::ffi::c_void; use core::mem::{align_of, size_of}; -use core::ptr::{null, null_mut, NonNull}; +use core::ptr::{NonNull, null, null_mut}; /// Convert a `&T` into a `*const T` without using an `as`. #[inline] diff --git a/src/weak.rs b/src/weak.rs index 036ddeea4..10487582b 100644 --- a/src/weak.rs +++ b/src/weak.rs @@ -102,13 +102,15 @@ impl Weak { // Cold because it should only happen during first-time initialization. #[cold] unsafe fn initialize(&self) -> Option { - let val = fetch(self.name); - // This synchronizes with the acquire fence in `get`. - self.addr.store(val, Ordering::Release); + unsafe { + let val = fetch(self.name); + // This synchronizes with the acquire fence in `get`. + self.addr.store(val, Ordering::Release); - match val { - NULL => None, - addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)), + match val { + NULL => None, + addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)), + } } } } @@ -126,7 +128,7 @@ mod libc { #[cfg(not(all(target_os = "android", target_pointer_width = "32")))] pub(super) const RTLD_DEFAULT: *mut c_void = ptr::null_mut(); - extern "C" { + unsafe extern "C" { pub(super) fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void; } @@ -137,11 +139,13 @@ mod libc { } unsafe fn fetch(name: &str) -> *mut c_void { - let name = match CStr::from_bytes_with_nul(name.as_bytes()) { - Ok(c_str) => c_str, - Err(..) => return null_mut(), - }; - libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast()) + unsafe { + let name = match CStr::from_bytes_with_nul(name.as_bytes()) { + Ok(c_str) => c_str, + Err(..) => return null_mut(), + }; + libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr().cast()) + } } #[cfg(not(linux_kernel))] @@ -163,7 +167,7 @@ macro_rules! syscall { #[cfg(linux_kernel)] macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => ( - unsafe fn $name($($arg_name:$t),*) -> $ret { + unsafe fn $name($($arg_name:$t),*) -> $ret { unsafe { // This looks like a hack, but `concat_idents` only accepts idents // (not paths). use libc::*; @@ -247,7 +251,7 @@ macro_rules! syscall { */ syscall($sys_name, $($arg_name.into_syscall_arg()),*) as $ret - } + }} ) } @@ -272,7 +276,7 @@ macro_rules! weakcall { /// available, and fall back to `libc::syscall` otherwise. macro_rules! weak_or_syscall { ($vis:vis fn $name:ident($($arg_name:ident: $t:ty),*) via $sys_name:ident -> $ret:ty) => ( - $vis unsafe fn $name($($arg_name: $t),*) -> $ret { + $vis unsafe fn $name($($arg_name: $t),*) -> $ret { unsafe { weak! { fn $name($($t),*) -> $ret } // Use a weak symbol from libc when possible, allowing `LD_PRELOAD` @@ -283,6 +287,6 @@ macro_rules! weak_or_syscall { syscall! { fn $name($($arg_name: $t),*) via $sys_name -> $ret } $name($($arg_name),*) } - } + }} ) } diff --git a/tests/event/epoll.rs b/tests/event/epoll.rs index 3d5e963d7..382c47f55 100644 --- a/tests/event/epoll.rs +++ b/tests/event/epoll.rs @@ -2,8 +2,8 @@ use rustix::buffer::spare_capacity; use rustix::event::epoll; use rustix::io::{ioctl_fionbio, read, write}; use rustix::net::{ - accept, bind, connect, getsockname, listen, socket, AddressFamily, Ipv4Addr, SocketAddrV4, - SocketType, + AddressFamily, Ipv4Addr, SocketAddrV4, SocketType, accept, bind, connect, getsockname, listen, + socket, }; use std::collections::HashMap; use std::ffi::c_void; diff --git a/tests/event/epoll_timeout.rs b/tests/event/epoll_timeout.rs index 3328a5feb..0573b6010 100644 --- a/tests/event/epoll_timeout.rs +++ b/tests/event/epoll_timeout.rs @@ -1,5 +1,5 @@ use rustix::buffer::spare_capacity; -use rustix::event::{epoll, Timespec}; +use rustix::event::{Timespec, epoll}; use std::time::Instant; #[test] diff --git a/tests/event/eventfd.rs b/tests/event/eventfd.rs index 95c68ca62..4e71b5861 100644 --- a/tests/event/eventfd.rs +++ b/tests/event/eventfd.rs @@ -1,7 +1,7 @@ #[cfg(any(linux_kernel, target_os = "freebsd", target_os = "illumos"))] #[test] fn test_eventfd() { - use rustix::event::{eventfd, EventfdFlags}; + use rustix::event::{EventfdFlags, eventfd}; use rustix::io::{read, write}; use std::mem::size_of; use std::thread; diff --git a/tests/event/main.rs b/tests/event/main.rs index ad29a36f3..9a0a8ad05 100644 --- a/tests/event/main.rs +++ b/tests/event/main.rs @@ -21,8 +21,7 @@ mod select; #[cfg(windows)] mod windows { - // With Rust 1.70 this can be `std::sync::OnceLock`. - use once_cell::sync::OnceCell as OnceLock; + use std::sync::OnceLock; pub struct Thing; diff --git a/tests/event/select.rs b/tests/event/select.rs index 6bdec54a0..8b88c61d7 100644 --- a/tests/event/select.rs +++ b/tests/event/select.rs @@ -1,6 +1,6 @@ use rustix::event::{ - fd_set_bound, fd_set_insert, fd_set_num_elements, fd_set_remove, select, FdSetElement, - FdSetIter, Timespec, + FdSetElement, FdSetIter, Timespec, fd_set_bound, fd_set_insert, fd_set_num_elements, + fd_set_remove, select, }; use rustix::fd::{AsRawFd as _, RawFd}; #[cfg(feature = "pipe")] @@ -90,7 +90,7 @@ fn test_select_with_great_fds() { use core::cmp::max; use rustix::io::{read, write}; use rustix::pipe::pipe; - use rustix::process::{getrlimit, setrlimit, Resource}; + use rustix::process::{Resource, getrlimit, setrlimit}; // Create a pipe. let (reader, writer) = pipe().unwrap(); @@ -180,7 +180,7 @@ fn test_select_with_great_fds() { #[test] #[serial] // for `crate::init` fn test_select_with_sockets() { - use rustix::net::{recv, send, AddressFamily, RecvFlags, SendFlags, SocketType}; + use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType, recv, send}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; crate::init(); @@ -277,8 +277,8 @@ fn test_select_with_sockets() { #[test] #[serial] // for `setrlimit` usage, and `crate::init` fn test_select_with_maxfd_sockets() { - use rustix::net::{recv, send, AddressFamily, RecvFlags, SendFlags, SocketType}; - use rustix::process::{getrlimit, setrlimit, Resource}; + use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketType, recv, send}; + use rustix::process::{Resource, getrlimit, setrlimit}; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; crate::init(); diff --git a/tests/fs/chmodat.rs b/tests/fs/chmodat.rs index 7567ed7fd..2eb237ab1 100644 --- a/tests/fs/chmodat.rs +++ b/tests/fs/chmodat.rs @@ -1,7 +1,7 @@ #[cfg(not(any(target_os = "cygwin", target_os = "wasi")))] #[test] fn test_chmod() { - use rustix::fs::{chmod, open, stat, symlink, Mode, OFlags}; + use rustix::fs::{Mode, OFlags, chmod, open, stat, symlink}; let tmp = tempfile::tempdir().unwrap(); @@ -30,7 +30,7 @@ fn test_chmod() { #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_chmodat() { - use rustix::fs::{chmodat, openat, statat, symlinkat, AtFlags, Mode, OFlags, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, OFlags, chmodat, openat, statat, symlinkat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::RWXU).unwrap(); diff --git a/tests/fs/fcntl.rs b/tests/fs/fcntl.rs index e2c4414b7..8bcd10fce 100644 --- a/tests/fs/fcntl.rs +++ b/tests/fs/fcntl.rs @@ -19,7 +19,7 @@ fn test_fcntl_dupfd_cloexec() { #[cfg(apple)] #[test] fn test_fcntl_apple() { - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/fcntl_lock.rs b/tests/fs/fcntl_lock.rs index 166275627..d3f9f6e15 100644 --- a/tests/fs/fcntl_lock.rs +++ b/tests/fs/fcntl_lock.rs @@ -1,6 +1,6 @@ #[test] fn test_fcntl_lock() { - use rustix::fs::{fcntl_lock, FlockOperation}; + use rustix::fs::{FlockOperation, fcntl_lock}; let f = tempfile::tempfile().unwrap(); fcntl_lock(&f, FlockOperation::LockExclusive).unwrap(); diff --git a/tests/fs/flock.rs b/tests/fs/flock.rs index c90da58fb..046110f1d 100644 --- a/tests/fs/flock.rs +++ b/tests/fs/flock.rs @@ -1,7 +1,7 @@ #[cfg(not(any(target_os = "redox", target_os = "solaris")))] #[test] fn test_flock() { - use rustix::fs::{flock, openat, FlockOperation, Mode, OFlags, CWD}; + use rustix::fs::{CWD, FlockOperation, Mode, OFlags, flock, openat}; let f = openat(CWD, "Cargo.toml", OFlags::RDONLY, Mode::empty()).unwrap(); flock(&f, FlockOperation::LockExclusive).unwrap(); diff --git a/tests/fs/futimens.rs b/tests/fs/futimens.rs index 963b57f39..10975a75c 100644 --- a/tests/fs/futimens.rs +++ b/tests/fs/futimens.rs @@ -1,7 +1,7 @@ #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_futimens() { - use rustix::fs::{fstat, futimens, openat, Mode, OFlags, Timespec, Timestamps, CWD}; + use rustix::fs::{CWD, Mode, OFlags, Timespec, Timestamps, fstat, futimens, openat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/inotify.rs b/tests/fs/inotify.rs index 6b4992ad2..7c6d0f5dc 100644 --- a/tests/fs/inotify.rs +++ b/tests/fs/inotify.rs @@ -1,7 +1,7 @@ use rustix::fs::inotify::{self, CreateFlags, WatchFlags}; use rustix::io::Errno; use std::fmt::Write as _; -use std::fs::{create_dir_all, remove_file, rename, File}; +use std::fs::{File, create_dir_all, remove_file, rename}; use std::mem::MaybeUninit; #[test] diff --git a/tests/fs/invalid_offset.rs b/tests/fs/invalid_offset.rs index cf84c9912..fc5740412 100644 --- a/tests/fs/invalid_offset.rs +++ b/tests/fs/invalid_offset.rs @@ -13,7 +13,7 @@ use rustix::fs::SeekFrom; #[test] fn invalid_offset_seek() { - use rustix::fs::{openat, seek, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat, seek}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); let file = openat( @@ -40,7 +40,7 @@ fn invalid_offset_seek() { )))] #[test] fn invalid_offset_fallocate() { - use rustix::fs::{fallocate, openat, FallocateFlags, Mode, OFlags, CWD}; + use rustix::fs::{CWD, FallocateFlags, Mode, OFlags, fallocate, openat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); let file = openat( @@ -69,7 +69,7 @@ fn invalid_offset_fallocate() { #[test] fn invalid_offset_fadvise() { use core::num::NonZeroU64; - use rustix::fs::{fadvise, openat, Advice, Mode, OFlags, CWD}; + use rustix::fs::{Advice, CWD, Mode, OFlags, fadvise, openat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); let file = openat( @@ -142,7 +142,7 @@ fn invalid_offset_fadvise() { #[test] fn invalid_offset_pread() { - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::io::pread; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); @@ -162,7 +162,7 @@ fn invalid_offset_pread() { #[cfg(not(any(apple, target_os = "cygwin")))] #[test] fn invalid_offset_pwrite() { - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::io::pwrite; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); @@ -182,7 +182,7 @@ fn invalid_offset_pwrite() { #[cfg(linux_kernel)] #[test] fn invalid_offset_copy_file_range() { - use rustix::fs::{copy_file_range, openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, copy_file_range, openat}; use rustix::io::write; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/linkat.rs b/tests/fs/linkat.rs index 42ad21177..e2160d570 100644 --- a/tests/fs/linkat.rs +++ b/tests/fs/linkat.rs @@ -1,6 +1,6 @@ #[test] fn test_link() { - use rustix::fs::{link, open, readlink, stat, Mode, OFlags}; + use rustix::fs::{Mode, OFlags, link, open, readlink, stat}; let tmp = tempfile::tempdir().unwrap(); @@ -32,7 +32,7 @@ fn test_link() { #[cfg(not(target_os = "redox"))] #[test] fn test_linkat() { - use rustix::fs::{linkat, openat, readlinkat, statat, AtFlags, Mode, OFlags, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, OFlags, linkat, openat, readlinkat, statat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/long_paths.rs b/tests/fs/long_paths.rs index 099ffe1b8..80b92d24c 100644 --- a/tests/fs/long_paths.rs +++ b/tests/fs/long_paths.rs @@ -1,7 +1,7 @@ #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_long_paths() { - use rustix::fs::{mkdirat, openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, mkdirat, openat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/mkdirat.rs b/tests/fs/mkdirat.rs index f405490b5..ceb6161b1 100644 --- a/tests/fs/mkdirat.rs +++ b/tests/fs/mkdirat.rs @@ -1,6 +1,6 @@ #[test] fn test_mkdir() { - use rustix::fs::{access, mkdir, rmdir, stat, unlink, Access, FileType, Mode}; + use rustix::fs::{Access, FileType, Mode, access, mkdir, rmdir, stat, unlink}; let tmp = tempfile::tempdir().unwrap(); @@ -19,7 +19,7 @@ fn test_mkdir() { #[test] fn test_mkdirat() { use rustix::fs::{ - accessat, mkdirat, openat, statat, unlinkat, Access, AtFlags, FileType, Mode, OFlags, CWD, + Access, AtFlags, CWD, FileType, Mode, OFlags, accessat, mkdirat, openat, statat, unlinkat, }; let tmp = tempfile::tempdir().unwrap(); @@ -40,7 +40,7 @@ fn test_mkdirat() { #[test] fn test_mkdirat_with_o_path() { use rustix::fs::{ - accessat, mkdirat, openat, statat, unlinkat, Access, AtFlags, FileType, Mode, OFlags, CWD, + Access, AtFlags, CWD, FileType, Mode, OFlags, accessat, mkdirat, openat, statat, unlinkat, }; let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/fs/mknodat.rs b/tests/fs/mknodat.rs index cf35b95ea..9cf0adaf6 100644 --- a/tests/fs/mknodat.rs +++ b/tests/fs/mknodat.rs @@ -2,7 +2,7 @@ #[test] fn test_mknodat() { use rustix::fs::{ - accessat, mknodat, openat, statat, unlinkat, Access, AtFlags, FileType, Mode, OFlags, CWD, + Access, AtFlags, CWD, FileType, Mode, OFlags, accessat, mknodat, openat, statat, unlinkat, }; let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/fs/negative_timestamp.rs b/tests/fs/negative_timestamp.rs index b367fbb30..352cf7393 100644 --- a/tests/fs/negative_timestamp.rs +++ b/tests/fs/negative_timestamp.rs @@ -3,8 +3,8 @@ #[test] fn negative_file_timestamp() { use rustix::fs::{ - fstat, futimens, lstat, open, stat, statat, AtFlags, Mode, OFlags, Timespec, Timestamps, - CWD, + AtFlags, CWD, Mode, OFlags, Timespec, Timestamps, fstat, futimens, lstat, open, stat, + statat, }; let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/fs/openat.rs b/tests/fs/openat.rs index e3395c4c4..8d4e79f26 100644 --- a/tests/fs/openat.rs +++ b/tests/fs/openat.rs @@ -1,6 +1,6 @@ use std::fs::File; -use rustix::fs::{open, openat, Mode, OFlags, CWD}; +use rustix::fs::{CWD, Mode, OFlags, open, openat}; use std::io::Write as _; #[test] diff --git a/tests/fs/openat2.rs b/tests/fs/openat2.rs index 4303be925..270b776c5 100644 --- a/tests/fs/openat2.rs +++ b/tests/fs/openat2.rs @@ -1,5 +1,5 @@ use rustix::fd::{AsFd, AsRawFd as _, OwnedFd}; -use rustix::fs::{mkdirat, openat, openat2, symlinkat, Mode, OFlags, ResolveFlags, CWD}; +use rustix::fs::{CWD, Mode, OFlags, ResolveFlags, mkdirat, openat, openat2, symlinkat}; use rustix::{io, path}; /// Like `openat2`, but keep retrying until it fails or succeeds. diff --git a/tests/fs/readlinkat.rs b/tests/fs/readlinkat.rs index dab847a25..b7ad92071 100644 --- a/tests/fs/readlinkat.rs +++ b/tests/fs/readlinkat.rs @@ -1,6 +1,6 @@ #[test] fn test_readlink() { - use rustix::fs::{open, readlink, symlink, Mode, OFlags}; + use rustix::fs::{Mode, OFlags, open, readlink, symlink}; let tmp = tempfile::tempdir().unwrap(); @@ -29,7 +29,7 @@ fn test_readlink() { #[cfg(not(target_os = "redox"))] #[test] fn test_readlinkat() { - use rustix::fs::{openat, readlinkat, symlinkat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat, readlinkat, symlinkat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); @@ -55,7 +55,7 @@ fn test_readlinkat() { #[test] fn test_readlinkat_raw() { use core::mem::MaybeUninit; - use rustix::fs::{openat, readlinkat_raw, symlinkat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat, readlinkat_raw, symlinkat}; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt as _; diff --git a/tests/fs/renameat.rs b/tests/fs/renameat.rs index 128950965..4c529b8e3 100644 --- a/tests/fs/renameat.rs +++ b/tests/fs/renameat.rs @@ -11,7 +11,7 @@ const DIR_OPEN_FLAGS: OFlags = OFlags::RDONLY; #[test] fn test_rename() { - use rustix::fs::{access, open, rename, stat, Access, Mode}; + use rustix::fs::{Access, Mode, access, open, rename, stat}; let tmp = tempfile::tempdir().unwrap(); @@ -37,7 +37,7 @@ fn test_rename() { #[cfg(any(linux_kernel, apple))] #[test] fn test_renameat() { - use rustix::fs::{accessat, openat, renameat, statat, Access, AtFlags, Mode, CWD}; + use rustix::fs::{Access, AtFlags, CWD, Mode, accessat, openat, renameat, statat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), DIR_OPEN_FLAGS, Mode::empty()).unwrap(); @@ -61,7 +61,7 @@ fn test_renameat() { #[cfg(any(linux_kernel, apple))] #[test] fn test_renameat_overwrite() { - use rustix::fs::{openat, renameat, statat, AtFlags, Mode, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, openat, renameat, statat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), DIR_OPEN_FLAGS, Mode::empty()).unwrap(); @@ -77,7 +77,7 @@ fn test_renameat_overwrite() { #[cfg(any(linux_kernel, apple))] #[test] fn test_renameat_with() { - use rustix::fs::{openat, renameat_with, statat, AtFlags, Mode, RenameFlags, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, RenameFlags, openat, renameat_with, statat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), DIR_OPEN_FLAGS, Mode::empty()).unwrap(); diff --git a/tests/fs/seals.rs b/tests/fs/seals.rs index 5e5530a39..b83469fb4 100644 --- a/tests/fs/seals.rs +++ b/tests/fs/seals.rs @@ -1,7 +1,7 @@ #[test] fn test_seals() { use rustix::fs::{ - fcntl_add_seals, fcntl_get_seals, ftruncate, memfd_create, MemfdFlags, SealFlags, + MemfdFlags, SealFlags, fcntl_add_seals, fcntl_get_seals, ftruncate, memfd_create, }; use std::fs::File; use std::io::Write as _; diff --git a/tests/fs/seek.rs b/tests/fs/seek.rs index 03d753d1d..c517bc29c 100644 --- a/tests/fs/seek.rs +++ b/tests/fs/seek.rs @@ -2,7 +2,7 @@ #[cfg(any(apple, freebsdlike, linux_kernel, solarish))] #[test] fn test_seek_holes() { - use rustix::fs::{fstat, openat, seek, Mode, OFlags, SeekFrom, CWD}; + use rustix::fs::{CWD, Mode, OFlags, SeekFrom, fstat, openat, seek}; use std::io::Write as _; let tmp = tempfile::tempdir().unwrap(); @@ -58,7 +58,7 @@ fn test_seek_holes() { #[test] fn test_seek_offsets() { - use rustix::fs::{open, seek, Mode, OFlags, SeekFrom}; + use rustix::fs::{Mode, OFlags, SeekFrom, open, seek}; let f = open("Cargo.toml", OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/special.rs b/tests/fs/special.rs index de72b027e..c0ece3862 100644 --- a/tests/fs/special.rs +++ b/tests/fs/special.rs @@ -2,7 +2,7 @@ #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_special_fds() { - use rustix::fs::{fstat, open, openat, Mode, OFlags, Stat, ABS, CWD}; + use rustix::fs::{ABS, CWD, Mode, OFlags, Stat, fstat, open, openat}; use rustix::process::getcwd; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt as _; diff --git a/tests/fs/statfs.rs b/tests/fs/statfs.rs index c3ff160ce..55bd6a652 100644 --- a/tests/fs/statfs.rs +++ b/tests/fs/statfs.rs @@ -1,7 +1,7 @@ #[cfg(linux_kernel)] #[test] fn test_statfs_abi() { - use rustix::fs::{FsWord, StatFs, NFS_SUPER_MAGIC, PROC_SUPER_MAGIC}; + use rustix::fs::{FsWord, NFS_SUPER_MAGIC, PROC_SUPER_MAGIC, StatFs}; // Ensure these all have consistent types. let t: StatFs = unsafe { std::mem::zeroed() }; diff --git a/tests/fs/symlinkat.rs b/tests/fs/symlinkat.rs index 740b9c898..f9bb1e89e 100644 --- a/tests/fs/symlinkat.rs +++ b/tests/fs/symlinkat.rs @@ -1,6 +1,6 @@ #[test] fn test_symlink() { - use rustix::fs::{lstat, open, readlink, symlink, Mode, OFlags}; + use rustix::fs::{Mode, OFlags, lstat, open, readlink, symlink}; let tmp = tempfile::tempdir().unwrap(); @@ -24,7 +24,7 @@ fn test_symlink() { #[cfg(not(target_os = "redox"))] #[test] fn test_symlinkat() { - use rustix::fs::{openat, readlinkat, statat, symlinkat, AtFlags, Mode, OFlags, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, OFlags, openat, readlinkat, statat, symlinkat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); diff --git a/tests/fs/utimensat.rs b/tests/fs/utimensat.rs index 2da161286..932aeffd2 100644 --- a/tests/fs/utimensat.rs +++ b/tests/fs/utimensat.rs @@ -1,7 +1,7 @@ #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_utimensat() { - use rustix::fs::{openat, statat, utimensat, AtFlags, Mode, OFlags, Timespec, Timestamps, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, OFlags, Timespec, Timestamps, openat, statat, utimensat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat( @@ -49,7 +49,7 @@ fn test_utimensat() { #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_utimensat_noent() { - use rustix::fs::{openat, utimensat, AtFlags, Mode, OFlags, Timespec, Timestamps, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, OFlags, Timespec, Timestamps, openat, utimensat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat( @@ -79,7 +79,7 @@ fn test_utimensat_noent() { #[cfg(not(any(target_os = "redox", target_os = "wasi")))] #[test] fn test_utimensat_notdir() { - use rustix::fs::{openat, utimensat, AtFlags, Mode, OFlags, Timespec, Timestamps, CWD}; + use rustix::fs::{AtFlags, CWD, Mode, OFlags, Timespec, Timestamps, openat, utimensat}; let tmp = tempfile::tempdir().unwrap(); let dir = openat( diff --git a/tests/fs/y2038.rs b/tests/fs/y2038.rs index 749dd043f..e13ae0202 100644 --- a/tests/fs/y2038.rs +++ b/tests/fs/y2038.rs @@ -10,7 +10,7 @@ #[test] fn test_y2038_with_utimensat() { use rustix::fs::{ - fstat, openat, statat, utimensat, AtFlags, Mode, OFlags, Timespec, Timestamps, CWD, + AtFlags, CWD, Mode, OFlags, Timespec, Timestamps, fstat, openat, statat, utimensat, }; let tmp = tempfile::tempdir().unwrap(); @@ -86,7 +86,7 @@ fn test_y2038_with_utimensat() { #[test] fn test_y2038_with_futimens() { use rustix::fs::{ - fstat, futimens, openat, statat, AtFlags, Mode, OFlags, Timespec, Timestamps, CWD, + AtFlags, CWD, Mode, OFlags, Timespec, Timestamps, fstat, futimens, openat, statat, }; let tmp = tempfile::tempdir().unwrap(); @@ -160,7 +160,7 @@ fn test_y2038_with_futimens() { #[cfg(not(target_os = "cygwin"))] #[test] fn test_y2038_with_futimens_and_stat() { - use rustix::fs::{fstat, futimens, open, stat, Mode, OFlags, Timespec, Timestamps}; + use rustix::fs::{Mode, OFlags, Timespec, Timestamps, fstat, futimens, open, stat}; let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/io/ioctl.rs b/tests/io/ioctl.rs index 40573ffef..ff78f3e83 100644 --- a/tests/io/ioctl.rs +++ b/tests/io/ioctl.rs @@ -13,8 +13,8 @@ fn test_ioctls() { #[cfg(all(target_os = "linux", feature = "fs"))] #[test] fn test_int_setter() { - use rustix::fs::{open, Mode, OFlags}; - use rustix::ioctl::{ioctl, IntegerSetter, Opcode}; + use rustix::fs::{Mode, OFlags, open}; + use rustix::ioctl::{IntegerSetter, Opcode, ioctl}; const TUNSETOFFLOAD: Opcode = 0x4004_54D0; diff --git a/tests/io/read_write.rs b/tests/io/read_write.rs index 6d6daa93a..5ed1b42de 100644 --- a/tests/io/read_write.rs +++ b/tests/io/read_write.rs @@ -8,7 +8,7 @@ use std::io::{IoSlice, IoSliceMut}; #[cfg(not(target_os = "cygwin"))] // no preadv/pwritev #[test] fn test_readwrite_pv() { - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::io::{preadv, pwritev}; let tmp = tempfile::tempdir().unwrap(); @@ -47,7 +47,7 @@ fn test_readwrite_pv() { #[cfg(feature = "fs")] #[test] fn test_readwrite_p() { - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::io::{pread, pwrite}; let tmp = tempfile::tempdir().unwrap(); @@ -73,7 +73,7 @@ fn test_readwrite_p() { #[test] fn test_readwrite_p_uninit() { use core::mem::MaybeUninit; - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::io::{pread, pwrite}; let tmp = tempfile::tempdir().unwrap(); @@ -99,7 +99,7 @@ fn test_readwrite_p_uninit() { #[cfg(feature = "fs")] #[test] fn test_readwrite_v() { - use rustix::fs::{openat, seek, Mode, OFlags, SeekFrom, CWD}; + use rustix::fs::{CWD, Mode, OFlags, SeekFrom, openat, seek}; use rustix::io::{readv, writev}; let tmp = tempfile::tempdir().unwrap(); @@ -125,7 +125,7 @@ fn test_readwrite_v() { #[cfg(feature = "fs")] #[test] fn test_readwrite() { - use rustix::fs::{openat, seek, Mode, OFlags, SeekFrom, CWD}; + use rustix::fs::{CWD, Mode, OFlags, SeekFrom, openat, seek}; use rustix::io::{read, write}; let tmp = tempfile::tempdir().unwrap(); @@ -152,7 +152,7 @@ fn test_readwrite() { #[test] fn test_readwrite_uninit() { use core::mem::MaybeUninit; - use rustix::fs::{openat, seek, Mode, OFlags, SeekFrom, CWD}; + use rustix::fs::{CWD, Mode, OFlags, SeekFrom, openat, seek}; use rustix::io::{read, write}; let tmp = tempfile::tempdir().unwrap(); @@ -206,8 +206,8 @@ fn test_rwf_values() { #[cfg(feature = "fs")] #[test] fn test_pwritev2() { - use rustix::fs::{openat, seek, Mode, OFlags, SeekFrom, CWD}; - use rustix::io::{preadv2, pwritev2, writev, ReadWriteFlags}; + use rustix::fs::{CWD, Mode, OFlags, SeekFrom, openat, seek}; + use rustix::io::{ReadWriteFlags, preadv2, pwritev2, writev}; let tmp = tempfile::tempdir().unwrap(); let dir = openat(CWD, tmp.path(), OFlags::RDONLY, Mode::empty()).unwrap(); @@ -260,8 +260,8 @@ fn test_pwritev2() { #[cfg(all(feature = "net", feature = "pipe"))] #[test] fn test_preadv2_nowait() { - use rustix::io::{preadv2, ReadWriteFlags}; - use rustix::net::{socketpair, AddressFamily, SocketFlags, SocketType}; + use rustix::io::{ReadWriteFlags, preadv2}; + use rustix::net::{AddressFamily, SocketFlags, SocketType, socketpair}; use rustix::pipe::pipe; let mut buf = [0_u8; 5]; @@ -305,10 +305,10 @@ fn test_preadv2_nowait() { #[cfg(not(target_os = "haiku"))] // no preadv/pwritev #[test] fn test_p_offsets() { - use rustix::fs::{openat, Mode, OFlags, CWD}; - use rustix::io::{pread, preadv, pwrite, pwritev}; + use rustix::fs::{CWD, Mode, OFlags, openat}; #[cfg(linux_kernel)] - use rustix::io::{preadv2, pwritev2, ReadWriteFlags}; + use rustix::io::{ReadWriteFlags, preadv2, pwritev2}; + use rustix::io::{pread, preadv, pwrite, pwritev}; let mut buf = [0_u8; 5]; diff --git a/tests/io_uring/register.rs b/tests/io_uring/register.rs index 71e779570..72d3bdd7d 100644 --- a/tests/io_uring/register.rs +++ b/tests/io_uring/register.rs @@ -4,9 +4,9 @@ use libc::c_void; use rustix::fd::{AsFd, AsRawFd, BorrowedFd}; use rustix::io::{Errno, Result}; use rustix::io_uring::{ - io_uring_buf, io_uring_buf_reg, io_uring_buf_ring, io_uring_params, io_uring_ptr, - io_uring_register_with, io_uring_rsrc_update, io_uring_setup, IoringFeatureFlags, - IoringRegisterFlags, IoringRegisterOp, + IoringFeatureFlags, IoringRegisterFlags, IoringRegisterOp, io_uring_buf, io_uring_buf_reg, + io_uring_buf_ring, io_uring_params, io_uring_ptr, io_uring_register_with, io_uring_rsrc_update, + io_uring_setup, }; #[cfg(feature = "mm")] use rustix::mm::{MapFlags, ProtFlags}; diff --git a/tests/mm/mmap.rs b/tests/mm/mmap.rs index 79133dfb9..30c04a2a6 100644 --- a/tests/mm/mmap.rs +++ b/tests/mm/mmap.rs @@ -2,9 +2,9 @@ #[cfg(not(target_os = "redox"))] #[test] fn test_mmap() { - use rustix::fs::{openat, Mode, OFlags, CWD}; + use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::io::write; - use rustix::mm::{mmap, munmap, MapFlags, ProtFlags}; + use rustix::mm::{MapFlags, ProtFlags, mmap, munmap}; use std::ptr::null_mut; use std::slice; @@ -58,7 +58,7 @@ fn test_mmap() { #[test] fn test_mmap_anonymous() { - use rustix::mm::{mmap_anonymous, munmap, MapFlags, ProtFlags}; + use rustix::mm::{MapFlags, ProtFlags, mmap_anonymous, munmap}; use std::ptr::null_mut; use std::slice; @@ -73,7 +73,7 @@ fn test_mmap_anonymous() { #[test] fn test_mprotect() { - use rustix::mm::{mmap_anonymous, mprotect, munmap, MapFlags, MprotectFlags, ProtFlags}; + use rustix::mm::{MapFlags, MprotectFlags, ProtFlags, mmap_anonymous, mprotect, munmap}; use std::ptr::null_mut; use std::slice; @@ -92,9 +92,9 @@ fn test_mprotect() { #[test] fn test_mlock() { - use rustix::mm::{mlock, mmap_anonymous, munlock, munmap, MapFlags, ProtFlags}; + use rustix::mm::{MapFlags, ProtFlags, mlock, mmap_anonymous, munlock, munmap}; #[cfg(linux_kernel)] - use rustix::mm::{mlock_with, MlockFlags}; + use rustix::mm::{MlockFlags, mlock_with}; use std::ptr::null_mut; unsafe { @@ -135,7 +135,7 @@ fn test_mlock() { #[cfg(not(target_os = "redox"))] #[test] fn test_madvise() { - use rustix::mm::{madvise, mmap_anonymous, munmap, Advice, MapFlags, ProtFlags}; + use rustix::mm::{Advice, MapFlags, ProtFlags, madvise, mmap_anonymous, munmap}; use std::ptr::null_mut; unsafe { @@ -153,7 +153,7 @@ fn test_madvise() { #[test] fn test_msync() { - use rustix::mm::{mmap_anonymous, msync, munmap, MapFlags, MsyncFlags, ProtFlags}; + use rustix::mm::{MapFlags, MsyncFlags, ProtFlags, mmap_anonymous, msync, munmap}; use std::ptr::null_mut; unsafe { @@ -169,7 +169,7 @@ fn test_msync() { #[cfg(any(target_os = "emscripten", target_os = "linux"))] #[test] fn test_mremap() { - use rustix::mm::{mmap_anonymous, mremap, munmap, MapFlags, MremapFlags, ProtFlags}; + use rustix::mm::{MapFlags, MremapFlags, ProtFlags, mmap_anonymous, mremap, munmap}; use std::ptr::null_mut; unsafe { diff --git a/tests/net/addr.rs b/tests/net/addr.rs index 4abe2a4dd..6a136daf8 100644 --- a/tests/net/addr.rs +++ b/tests/net/addr.rs @@ -50,10 +50,12 @@ fn test_unix_addr() { #[cfg(linux_kernel)] { - assert!(SocketAddrUnix::new("foo") - .unwrap() - .abstract_name() - .is_none()); + assert!( + SocketAddrUnix::new("foo") + .unwrap() + .abstract_name() + .is_none() + ); assert_eq!( SocketAddrUnix::new_abstract_name(b"test") @@ -77,9 +79,11 @@ fn test_unix_addr() { b"this\0that" ); SocketAddrUnix::new_abstract_name(&[b'a'; 500]).unwrap_err(); - assert!(SocketAddrUnix::new_abstract_name(b"test") - .unwrap() - .path() - .is_none()); + assert!( + SocketAddrUnix::new_abstract_name(b"test") + .unwrap() + .path() + .is_none() + ); } } diff --git a/tests/net/main.rs b/tests/net/main.rs index c4bdef4b8..e418df001 100644 --- a/tests/net/main.rs +++ b/tests/net/main.rs @@ -26,8 +26,7 @@ mod v6; #[cfg(windows)] mod windows { - // With Rust 1.70 this can be `std::sync::OnceLock`. - use once_cell::sync::OnceCell as OnceLock; + use std::sync::OnceLock; pub struct Thing; diff --git a/tests/net/netlink.rs b/tests/net/netlink.rs index 9c891c2f0..9959ac8d3 100644 --- a/tests/net/netlink.rs +++ b/tests/net/netlink.rs @@ -1,7 +1,7 @@ use rustix::net::netlink::{self, SocketAddrNetlink}; use rustix::net::{ - bind, getsockname, recvfrom, sendto, socket_with, AddressFamily, RecvFlags, SendFlags, - SocketAddrAny, SocketFlags, SocketType, + AddressFamily, RecvFlags, SendFlags, SocketAddrAny, SocketFlags, SocketType, bind, getsockname, + recvfrom, sendto, socket_with, }; #[test] diff --git a/tests/net/poll.rs b/tests/net/poll.rs index c52015c0a..a6e180383 100644 --- a/tests/net/poll.rs +++ b/tests/net/poll.rs @@ -2,10 +2,10 @@ #![cfg(not(target_os = "wasi"))] -use rustix::event::{poll, PollFd, PollFlags}; +use rustix::event::{PollFd, PollFlags, poll}; use rustix::net::{ - accept, bind, connect, getsockname, listen, recv, send, socket, AddressFamily, Ipv6Addr, - RecvFlags, SendFlags, SocketAddrV6, SocketType, + AddressFamily, Ipv6Addr, RecvFlags, SendFlags, SocketAddrV6, SocketType, accept, bind, connect, + getsockname, listen, recv, send, socket, }; use std::sync::{Arc, Condvar, Mutex}; use std::thread; diff --git a/tests/net/sockopt.rs b/tests/net/sockopt.rs index a668afad9..8e89e2761 100644 --- a/tests/net/sockopt.rs +++ b/tests/net/sockopt.rs @@ -9,16 +9,18 @@ use rustix::io; target_env = "newlib" ))] use rustix::net::ipproto; -use rustix::net::{sockopt, AddressFamily, SocketType}; +use rustix::net::{AddressFamily, SocketType, sockopt}; use std::net::Ipv4Addr; use std::time::Duration; // Test `socket` socket options. fn test_sockopts_socket(s: &OwnedFd) { // On a new socket we shouldn't have a timeout yet. - assert!(sockopt::socket_timeout(s, sockopt::Timeout::Recv) - .unwrap() - .is_none()); + assert!( + sockopt::socket_timeout(s, sockopt::Timeout::Recv) + .unwrap() + .is_none() + ); assert_eq!(sockopt::socket_type(s).unwrap(), SocketType::STREAM); #[cfg(any( linux_kernel, diff --git a/tests/net/unix.rs b/tests/net/unix.rs index e1341aa50..53ce3715e 100644 --- a/tests/net/unix.rs +++ b/tests/net/unix.rs @@ -7,10 +7,10 @@ #![cfg(not(any(apple, target_os = "espidf", target_os = "redox", target_os = "wasi")))] #![cfg(feature = "fs")] -use rustix::fs::{unlinkat, AtFlags, CWD}; +use rustix::fs::{AtFlags, CWD, unlinkat}; use rustix::io::{read, write}; use rustix::net::{ - accept, bind, connect, listen, socket, AddressFamily, SocketAddrUnix, SocketType, + AddressFamily, SocketAddrUnix, SocketType, accept, bind, connect, listen, socket, }; use rustix::path::DecInt; use std::mem::MaybeUninit; @@ -130,7 +130,7 @@ fn test_unix() { #[cfg(not(any(target_os = "espidf", target_os = "redox", target_os = "wasi")))] fn do_test_unix_msg(addr: SocketAddrUnix) { use rustix::io::{IoSlice, IoSliceMut}; - use rustix::net::{recvmsg, sendmsg, RecvFlags, ReturnFlags, SendFlags}; + use rustix::net::{RecvFlags, ReturnFlags, SendFlags, recvmsg, sendmsg}; let server = { let connection_socket = socket(AddressFamily::UNIX, SocketType::SEQPACKET, None).unwrap(); @@ -260,7 +260,7 @@ fn do_test_unix_msg(addr: SocketAddrUnix) { #[cfg(not(any(target_os = "espidf", target_os = "redox", target_os = "wasi")))] fn do_test_unix_msg_unconnected(addr: SocketAddrUnix) { use rustix::io::{IoSlice, IoSliceMut}; - use rustix::net::{recvmsg, sendmsg_addr, RecvFlags, ReturnFlags, SendFlags}; + use rustix::net::{RecvFlags, ReturnFlags, SendFlags, recvmsg, sendmsg_addr}; let server = { let runs: &[i32] = &[3, 184, 187, 0]; @@ -452,8 +452,8 @@ fn test_unix_msg_with_scm_rights() { use rustix::fd::AsFd as _; use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, - SendAncillaryBuffer, SendAncillaryMessage, SendFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, + SendAncillaryMessage, SendFlags, recvmsg, sendmsg, }; use rustix::pipe::pipe; use std::string::ToString as _; @@ -629,8 +629,8 @@ fn test_unix_peercred_explicit() { use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, sockopt, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, - ReturnFlags, SendAncillaryBuffer, SendAncillaryMessage, SendFlags, SocketFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, + SendAncillaryMessage, SendFlags, SocketFlags, recvmsg, sendmsg, sockopt, }; let (send_sock, recv_sock) = rustix::net::socketpair( @@ -687,8 +687,8 @@ fn test_unix_peercred_implicit() { use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, sockopt, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, - ReturnFlags, SendAncillaryBuffer, SendFlags, SocketFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, + SendFlags, SocketFlags, recvmsg, sendmsg, sockopt, }; use rustix::process::{getgid, getpid, getuid}; @@ -748,8 +748,8 @@ fn test_unix_msg_with_combo() { use rustix::fd::AsFd as _; use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, - SendAncillaryBuffer, SendAncillaryMessage, SendFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, + SendAncillaryMessage, SendFlags, recvmsg, sendmsg, }; use rustix::pipe::pipe; use std::string::ToString as _; diff --git a/tests/net/unix_alloc.rs b/tests/net/unix_alloc.rs index 3e0774e7d..68d31abd7 100644 --- a/tests/net/unix_alloc.rs +++ b/tests/net/unix_alloc.rs @@ -5,10 +5,10 @@ #![cfg(not(any(apple, target_os = "espidf", target_os = "redox", target_os = "wasi")))] #![cfg(feature = "fs")] -use rustix::fs::{unlinkat, AtFlags, CWD}; +use rustix::fs::{AtFlags, CWD, unlinkat}; use rustix::io::{read, write}; use rustix::net::{ - accept, bind, connect, listen, socket, AddressFamily, SocketAddrUnix, SocketType, + AddressFamily, SocketAddrUnix, SocketType, accept, bind, connect, listen, socket, }; use rustix::path::DecInt; use std::path::Path; @@ -127,7 +127,7 @@ fn test_unix() { #[cfg(not(any(target_os = "espidf", target_os = "redox", target_os = "wasi")))] fn do_test_unix_msg(addr: SocketAddrUnix) { use rustix::io::{IoSlice, IoSliceMut}; - use rustix::net::{recvmsg, sendmsg, RecvFlags, ReturnFlags, SendFlags}; + use rustix::net::{RecvFlags, ReturnFlags, SendFlags, recvmsg, sendmsg}; let server = { let connection_socket = socket(AddressFamily::UNIX, SocketType::SEQPACKET, None).unwrap(); @@ -256,7 +256,7 @@ fn do_test_unix_msg(addr: SocketAddrUnix) { #[cfg(not(any(target_os = "espidf", target_os = "redox", target_os = "wasi")))] fn do_test_unix_msg_unconnected(addr: SocketAddrUnix) { use rustix::io::{IoSlice, IoSliceMut}; - use rustix::net::{recvmsg, sendmsg_addr, RecvFlags, ReturnFlags, SendFlags}; + use rustix::net::{RecvFlags, ReturnFlags, SendFlags, recvmsg, sendmsg_addr}; let server = { let runs: &[i32] = &[3, 184, 187, 0]; @@ -449,8 +449,8 @@ fn test_unix_msg_with_scm_rights() { use rustix::fd::AsFd as _; use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, - SendAncillaryBuffer, SendAncillaryMessage, SendFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, + SendAncillaryMessage, SendFlags, recvmsg, sendmsg, }; use rustix::pipe::pipe; use std::string::ToString as _; @@ -626,8 +626,8 @@ fn test_unix_peercred() { use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, sockopt, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, - SendAncillaryBuffer, SendAncillaryMessage, SendFlags, SocketFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, SendAncillaryBuffer, + SendAncillaryMessage, SendFlags, SocketFlags, recvmsg, sendmsg, sockopt, }; use rustix::process::{getgid, getpid, getuid}; @@ -688,8 +688,8 @@ fn test_unix_msg_with_combo() { use rustix::fd::AsFd as _; use rustix::io::{IoSlice, IoSliceMut}; use rustix::net::{ - recvmsg, sendmsg, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, - SendAncillaryBuffer, SendAncillaryMessage, SendFlags, + RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags, ReturnFlags, SendAncillaryBuffer, + SendAncillaryMessage, SendFlags, recvmsg, sendmsg, }; use rustix::pipe::pipe; use std::string::ToString as _; diff --git a/tests/net/v4.rs b/tests/net/v4.rs index bb11a5293..ea4afedb2 100644 --- a/tests/net/v4.rs +++ b/tests/net/v4.rs @@ -7,8 +7,8 @@ #[cfg(not(any(windows, target_os = "espidf", target_os = "redox", target_os = "wasi")))] use rustix::net::ReturnFlags; use rustix::net::{ - accept, bind, connect, getsockname, listen, recv, send, socket, AddressFamily, Ipv4Addr, - RecvFlags, SendFlags, SocketAddrV4, SocketType, + AddressFamily, Ipv4Addr, RecvFlags, SendFlags, SocketAddrV4, SocketType, accept, bind, connect, + getsockname, listen, recv, send, socket, }; use std::sync::{Arc, Condvar, Mutex}; use std::thread; @@ -206,7 +206,7 @@ fn test_v4_sendmmsg() { use rustix::io::IoSlice; use rustix::net::addr::SocketAddrArg as _; - use rustix::net::{sendmmsg, MMsgHdr}; + use rustix::net::{MMsgHdr, sendmmsg}; fn server(ready: Arc<(Mutex, Condvar)>) { let connection_socket = socket(AddressFamily::INET, SocketType::STREAM, None).unwrap(); diff --git a/tests/net/v6.rs b/tests/net/v6.rs index 4016c18ad..dc04721f8 100644 --- a/tests/net/v6.rs +++ b/tests/net/v6.rs @@ -7,8 +7,8 @@ #[cfg(not(any(windows, target_os = "espidf", target_os = "redox", target_os = "wasi")))] use rustix::net::ReturnFlags; use rustix::net::{ - accept, bind, connect, getsockname, listen, recv, send, socket, AddressFamily, Ipv6Addr, - RecvFlags, SendFlags, SocketAddrV6, SocketType, + AddressFamily, Ipv6Addr, RecvFlags, SendFlags, SocketAddrV6, SocketType, accept, bind, connect, + getsockname, listen, recv, send, socket, }; use std::sync::{Arc, Condvar, Mutex}; use std::thread; @@ -205,7 +205,7 @@ fn test_v6_sendmmsg() { use rustix::io::IoSlice; use rustix::net::addr::SocketAddrArg as _; - use rustix::net::{sendmmsg, MMsgHdr}; + use rustix::net::{MMsgHdr, sendmmsg}; fn server(ready: Arc<(Mutex, Condvar)>) { let connection_socket = socket(AddressFamily::INET6, SocketType::STREAM, None).unwrap(); diff --git a/tests/param/weak.rs b/tests/param/weak.rs index f8d1c354a..616f7a79d 100644 --- a/tests/param/weak.rs +++ b/tests/param/weak.rs @@ -99,23 +99,27 @@ impl Weak { // Cold because it should only happen during first-time initialization. #[cold] unsafe fn initialize(&self) -> Option { - let val = fetch(self.name); - // This synchronizes with the acquire fence in `get`. - self.addr.store(val, Ordering::Release); + unsafe { + let val = fetch(self.name); + // This synchronizes with the acquire fence in `get`. + self.addr.store(val, Ordering::Release); - match val { - NULL => None, - addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)), + match val { + NULL => None, + addr => Some(mem::transmute_copy::<*mut c_void, F>(&addr)), + } } } } unsafe fn fetch(name: &str) -> *mut c_void { - let name = match CStr::from_bytes_with_nul(name.as_bytes()) { - Ok(c_str) => c_str, - Err(..) => return null_mut(), - }; - libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) + unsafe { + let name = match CStr::from_bytes_with_nul(name.as_bytes()) { + Ok(c_str) => c_str, + Err(..) => return null_mut(), + }; + libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) + } } #[cfg(not(linux_kernel))] diff --git a/tests/path/dec_int.rs b/tests/path/dec_int.rs index 9c16cdd3c..138b8aea0 100644 --- a/tests/path/dec_int.rs +++ b/tests/path/dec_int.rs @@ -1,7 +1,7 @@ use rustix::path::DecInt; macro_rules! check { - ($i:expr) => { + ($i:expr_2021) => { let i = $i; assert_eq!( DecInt::new(i).as_c_str().to_bytes_with_nul(), diff --git a/tests/pipe/basic.rs b/tests/pipe/basic.rs index 6dbbdaf7e..53891f9ac 100644 --- a/tests/pipe/basic.rs +++ b/tests/pipe/basic.rs @@ -30,7 +30,7 @@ fn test_basic_pipes() { #[test] fn test_basic_pipes_with() { use rustix::io::{read, write}; - use rustix::pipe::{pipe_with, PipeFlags}; + use rustix::pipe::{PipeFlags, pipe_with}; let message = b"Hello, tee!"; diff --git a/tests/pipe/splice.rs b/tests/pipe/splice.rs index aa41af927..cddc0063e 100644 --- a/tests/pipe/splice.rs +++ b/tests/pipe/splice.rs @@ -2,7 +2,7 @@ #[cfg(linux_kernel)] #[test] fn test_splice_cursor() { - use rustix::pipe::{pipe, splice, SpliceFlags}; + use rustix::pipe::{SpliceFlags, pipe, splice}; use std::io::{Read as _, Seek as _, SeekFrom, Write as _}; let mut src = tempfile::tempfile().unwrap(); @@ -27,7 +27,7 @@ fn test_splice_cursor() { #[cfg(linux_kernel)] #[test] fn test_splice_offset() { - use rustix::pipe::{pipe, splice, SpliceFlags}; + use rustix::pipe::{SpliceFlags, pipe, splice}; use std::io::{Read as _, Write as _}; let mut src = tempfile::tempfile().unwrap(); @@ -69,7 +69,7 @@ fn test_splice_offset() { #[test] fn test_splice_pipe2pipe() { use rustix::io::{read, write}; - use rustix::pipe::{pipe, splice, SpliceFlags}; + use rustix::pipe::{SpliceFlags, pipe, splice}; let (read_p1, write_p1) = pipe().unwrap(); let (read_p2, write_p2) = pipe().unwrap(); @@ -87,7 +87,7 @@ fn test_splice_pipe2pipe() { #[test] fn test_vmsplice_write() { use rustix::io::read; - use rustix::pipe::{pipe, vmsplice, IoSliceRaw, SpliceFlags}; + use rustix::pipe::{IoSliceRaw, SpliceFlags, pipe, vmsplice}; let (read_p, write_p) = pipe().unwrap(); let mut output = [0; 11]; @@ -108,7 +108,7 @@ fn test_vmsplice_write() { #[test] fn test_vmsplice_read() { use rustix::io::write; - use rustix::pipe::{pipe, vmsplice, IoSliceRaw, SpliceFlags}; + use rustix::pipe::{IoSliceRaw, SpliceFlags, pipe, vmsplice}; let (read_p, write_p) = pipe().unwrap(); let mut outputs = ([0; 5], [0; 1], [0; 5]); diff --git a/tests/pipe/tee.rs b/tests/pipe/tee.rs index fbb863140..81acb327d 100644 --- a/tests/pipe/tee.rs +++ b/tests/pipe/tee.rs @@ -3,7 +3,7 @@ #[test] fn test_tee() { use rustix::io::{read, write}; - use rustix::pipe::{pipe, tee, SpliceFlags}; + use rustix::pipe::{SpliceFlags, pipe, tee}; let message = b"Hello, tee!"; assert!(message.len() <= rustix::pipe::PIPE_BUF); diff --git a/tests/process/fcntl_getlk.rs b/tests/process/fcntl_getlk.rs index 971721134..9b5e89acb 100644 --- a/tests/process/fcntl_getlk.rs +++ b/tests/process/fcntl_getlk.rs @@ -1,6 +1,6 @@ use rustix::fd::{AsRawFd as _, BorrowedFd}; -use rustix::fs::{fcntl_lock, FlockOperation}; -use rustix::process::{fcntl_getlk, getppid, Flock, FlockType}; +use rustix::fs::{FlockOperation, fcntl_lock}; +use rustix::process::{Flock, FlockType, fcntl_getlk, getppid}; use serial_test::serial; use std::fs::File; use std::os::unix::process::CommandExt as _; @@ -49,15 +49,17 @@ unsafe fn child_process(file: &File, f: F) where F: Fn(BorrowedFd<'static>) + Send + Sync + 'static, { - let fd = BorrowedFd::borrow_raw(file.as_raw_fd()); - let output = Command::new("true") - .pre_exec(move || { - f(fd); - Ok(()) - }) - .output() - .unwrap(); - if !output.status.success() { - panic!("{}", std::str::from_utf8(&output.stderr).unwrap()); + unsafe { + let fd = BorrowedFd::borrow_raw(file.as_raw_fd()); + let output = Command::new("true") + .pre_exec(move || { + f(fd); + Ok(()) + }) + .output() + .unwrap(); + if !output.status.success() { + panic!("{}", std::str::from_utf8(&output.stderr).unwrap()); + } } } diff --git a/tests/process/pidfd.rs b/tests/process/pidfd.rs index e4a7b0bf9..6b4c2ca1a 100644 --- a/tests/process/pidfd.rs +++ b/tests/process/pidfd.rs @@ -1,6 +1,6 @@ //! Tests for the `pidfd` type. -use libc::{kill, SIGCONT, SIGINT, SIGSTOP}; +use libc::{SIGCONT, SIGINT, SIGSTOP, kill}; #[cfg(feature = "event")] use rustix::event; use rustix::fd::AsFd as _; diff --git a/tests/process/wait.rs b/tests/process/wait.rs index cd2dc27e0..44ddd058e 100644 --- a/tests/process/wait.rs +++ b/tests/process/wait.rs @@ -1,5 +1,5 @@ #[allow(unused_imports)] -use libc::{kill, SIGCONT, SIGKILL, SIGSTOP}; +use libc::{SIGCONT, SIGKILL, SIGSTOP, kill}; use rustix::process; use serial_test::serial; use std::process::{Command, Stdio}; diff --git a/tests/process/working_directory.rs b/tests/process/working_directory.rs index afa7fe584..cc248adaa 100644 --- a/tests/process/working_directory.rs +++ b/tests/process/working_directory.rs @@ -1,6 +1,6 @@ #[cfg(not(any(target_os = "fuchsia", target_os = "macos")))] use rustix::fs::{Mode, OFlags}; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; #[allow(unused)] fn tmpdir() -> TempDir { diff --git a/tests/pty/openpty.rs b/tests/pty/openpty.rs index b5a9a4aa8..5c6b6a081 100644 --- a/tests/pty/openpty.rs +++ b/tests/pty/openpty.rs @@ -2,7 +2,7 @@ #![allow(unused_mut, unused_imports)] -use rustix::fs::{openat, Mode, OFlags, CWD}; +use rustix::fs::{CWD, Mode, OFlags, openat}; use rustix::pty::*; use std::fs::File; use std::io::{Read as _, Write as _}; diff --git a/tests/rand/getrandom.rs b/tests/rand/getrandom.rs index 4a30bdc86..4cb3696bb 100644 --- a/tests/rand/getrandom.rs +++ b/tests/rand/getrandom.rs @@ -1,5 +1,5 @@ use core::mem::MaybeUninit; -use rustix::rand::{getrandom, GetRandomFlags}; +use rustix::rand::{GetRandomFlags, getrandom}; #[test] fn test_getrandom() { diff --git a/tests/stdio/dup2_to_replace_stdio.rs b/tests/stdio/dup2_to_replace_stdio.rs index 12fa450e8..1c99bb1c4 100644 --- a/tests/stdio/dup2_to_replace_stdio.rs +++ b/tests/stdio/dup2_to_replace_stdio.rs @@ -6,13 +6,15 @@ use std::process::Command; fn dup2_to_replace_stdio() { // This test modifies the stdio file descriptors, so we run it in a // separate process so that it doesn't interfere with the test harness. - assert!(Command::new(env::var("CARGO").unwrap()) - .arg("run") - .arg("--example") - .arg("dup2_to_replace_stdio") - .arg("--features") - .arg("pipe,stdio") - .status() - .unwrap() - .success()); + assert!( + Command::new(env::var("CARGO").unwrap()) + .arg("run") + .arg("--example") + .arg("dup2_to_replace_stdio") + .arg("--features") + .arg("pipe,stdio") + .status() + .unwrap() + .success() + ); } diff --git a/tests/termios/isatty.rs b/tests/termios/isatty.rs index 40476bd12..38b30deb2 100644 --- a/tests/termios/isatty.rs +++ b/tests/termios/isatty.rs @@ -1,6 +1,6 @@ use rustix::fd::AsRawFd as _; use rustix::termios::{isatty, tcgetwinsize}; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; #[allow(unused)] fn tmpdir() -> TempDir { diff --git a/tests/termios/pgrp.rs b/tests/termios/pgrp.rs index 80b8cc3c7..5feddbb7d 100644 --- a/tests/termios/pgrp.rs +++ b/tests/termios/pgrp.rs @@ -1,5 +1,5 @@ use rustix::io::Errno; -use rustix::termios::{tcgetpgrp, tcsetpgrp, Pid}; +use rustix::termios::{Pid, tcgetpgrp, tcsetpgrp}; use tempfile::tempdir; #[cfg(feature = "fs")] diff --git a/tests/termios/ttyname.rs b/tests/termios/ttyname.rs index 065251b70..49fd3adc1 100644 --- a/tests/termios/ttyname.rs +++ b/tests/termios/ttyname.rs @@ -14,10 +14,12 @@ fn test_ttyname_ok() { let name = ttyname(&file, Vec::new()).unwrap().into_string().unwrap(); assert!(name.starts_with("/dev/")); assert!(!name.ends_with('/')); - assert!(std::fs::metadata(&name) - .unwrap() - .file_type() - .is_char_device()); + assert!( + std::fs::metadata(&name) + .unwrap() + .file_type() + .is_char_device() + ); } } diff --git a/tests/thread/clocks.rs b/tests/thread/clocks.rs index 915f3e35e..a990c12c0 100644 --- a/tests/thread/clocks.rs +++ b/tests/thread/clocks.rs @@ -7,11 +7,11 @@ target_os = "redox", target_os = "wasi", )))] -use rustix::thread::{clock_nanosleep_absolute, clock_nanosleep_relative, ClockId}; +use rustix::thread::{ClockId, clock_nanosleep_absolute, clock_nanosleep_relative}; #[cfg(not(target_os = "redox"))] use { rustix::io, - rustix::thread::{nanosleep, NanosleepRelativeResult, Timespec}, + rustix::thread::{NanosleepRelativeResult, Timespec, nanosleep}, }; #[cfg(not(target_os = "redox"))] diff --git a/tests/thread/futex.rs b/tests/thread/futex.rs index 8e0de96aa..731f159ad 100644 --- a/tests/thread/futex.rs +++ b/tests/thread/futex.rs @@ -70,10 +70,7 @@ fn test_waitv_wake() { let lock = std::sync::Arc::new(AtomicU32::new(0)); let mut wait = futex::Wait::new(); - // In Rust 1.70, use `AtomicU32::as_ptr`. - wait.uaddr = (&*lock as *const AtomicU32 as *mut u32) - .cast::() - .into(); + wait.uaddr = lock.as_ptr().cast::().into(); wait.flags = futex::WaitFlags::SIZE_U32; wait.val = 1; match futex::waitv( @@ -100,10 +97,7 @@ fn test_waitv_wake() { std::thread::sleep(std::time::Duration::from_millis(50)); let mut wait = futex::Wait::new(); - // In Rust 1.70, use `AtomicU32::as_ptr`. - wait.uaddr = (&*lock as *const AtomicU32 as *mut u32) - .cast::() - .into(); + wait.uaddr = lock.as_ptr().cast::().into(); wait.flags = futex::WaitFlags::SIZE_U32; wait.val = 1; match futex::waitv( @@ -122,10 +116,7 @@ fn test_waitv_wake() { }); let mut wait = futex::Wait::new(); - // In Rust 1.70, use `AtomicU32::as_ptr`. - wait.uaddr = (&*lock as *const AtomicU32 as *mut u32) - .cast::() - .into(); + wait.uaddr = lock.as_ptr().cast::().into(); wait.flags = futex::WaitFlags::SIZE_U32; wait.val = 0; match futex::waitv( @@ -199,10 +190,7 @@ fn test_waitv_timeout() { let lock = AtomicU32::new(0); let mut wait = futex::Wait::new(); - // In Rust 1.70, use `AtomicU32::as_ptr`. - wait.uaddr = (&lock as *const AtomicU32 as *mut u32) - .cast::() - .into(); + wait.uaddr = lock.as_ptr().cast::().into(); wait.flags = futex::WaitFlags::SIZE_U32; wait.val = 0; diff --git a/tests/thread/membarrier.rs b/tests/thread/membarrier.rs index 7d40bc736..381f1363b 100644 --- a/tests/thread/membarrier.rs +++ b/tests/thread/membarrier.rs @@ -1,6 +1,6 @@ #[test] fn test_membarrier() { - use rustix::thread::{membarrier, membarrier_query, MembarrierCommand, MembarrierQuery}; + use rustix::thread::{MembarrierCommand, MembarrierQuery, membarrier, membarrier_query}; let query: MembarrierQuery = membarrier_query(); diff --git a/tests/time/clocks.rs b/tests/time/clocks.rs index d7ed39f56..e942f550b 100644 --- a/tests/time/clocks.rs +++ b/tests/time/clocks.rs @@ -3,7 +3,7 @@ #![cfg(not(any(apple, target_os = "wasi")))] #[cfg(not(any(solarish, target_os = "netbsd", target_os = "redox")))] -use rustix::time::{clock_gettime, ClockId}; +use rustix::time::{ClockId, clock_gettime}; /// Attempt to test that the boot clock is monotonic. Time may or may not /// advance, but it shouldn't regress. @@ -15,7 +15,7 @@ use rustix::time::{clock_gettime, ClockId}; ))] #[test] fn test_boottime_clock() { - use rustix::time::{clock_gettime_dynamic, DynamicClockId}; + use rustix::time::{DynamicClockId, clock_gettime_dynamic}; let monotonic = clock_gettime(ClockId::Monotonic); @@ -61,7 +61,7 @@ fn test_boottime_clock() { #[cfg(any(linux_kernel, target_os = "fuchsia"))] #[test] fn test_boottime_alarm_clock() { - use rustix::time::{clock_gettime_dynamic, DynamicClockId}; + use rustix::time::{DynamicClockId, clock_gettime_dynamic}; let monotonic = clock_gettime(ClockId::Monotonic); @@ -156,7 +156,7 @@ fn test_realtime_coarse_clock() { #[cfg(linux_kernel)] #[test] fn test_realtime_alarm_clock() { - use rustix::time::{clock_gettime_dynamic, DynamicClockId}; + use rustix::time::{DynamicClockId, clock_gettime_dynamic}; if let Ok(a) = clock_gettime_dynamic(DynamicClockId::RealtimeAlarm) { // Test that the timespec is valid; there's not much else we can say. @@ -177,7 +177,7 @@ fn test_realtime_alarm_clock() { #[cfg(linux_kernel)] #[test] fn test_tai_clock() { - use rustix::time::{clock_gettime_dynamic, DynamicClockId}; + use rustix::time::{DynamicClockId, clock_gettime_dynamic}; let realtime = clock_gettime(ClockId::Realtime); diff --git a/tests/time/dynamic_clocks.rs b/tests/time/dynamic_clocks.rs index fed2ff6e0..b255cbdf3 100644 --- a/tests/time/dynamic_clocks.rs +++ b/tests/time/dynamic_clocks.rs @@ -1,5 +1,5 @@ use rustix::fd::AsFd as _; -use rustix::time::{clock_gettime_dynamic, ClockId, DynamicClockId}; +use rustix::time::{ClockId, DynamicClockId, clock_gettime_dynamic}; #[test] fn test_known_clocks() { diff --git a/tests/time/monotonic.rs b/tests/time/monotonic.rs index d0f50216b..582657d77 100644 --- a/tests/time/monotonic.rs +++ b/tests/time/monotonic.rs @@ -1,6 +1,6 @@ #[cfg(feature = "thread")] use rustix::thread::nanosleep; -use rustix::time::{clock_gettime, ClockId, Timespec}; +use rustix::time::{ClockId, Timespec, clock_gettime}; /// Attempt to test that the monotonic clock is monotonic. Time may or may not /// advance, but it shouldn't regress. diff --git a/tests/time/settime.rs b/tests/time/settime.rs index d20c0ebb0..8ef80f49c 100644 --- a/tests/time/settime.rs +++ b/tests/time/settime.rs @@ -1,5 +1,5 @@ use rustix::io; -use rustix::time::{clock_settime, ClockId, Timespec}; +use rustix::time::{ClockId, Timespec, clock_settime}; #[test] fn test_settime() { diff --git a/tests/time/timerfd.rs b/tests/time/timerfd.rs index 6ad4dd72e..89cb3a414 100644 --- a/tests/time/timerfd.rs +++ b/tests/time/timerfd.rs @@ -1,6 +1,6 @@ use rustix::time::{ - timerfd_create, timerfd_gettime, timerfd_settime, Itimerspec, TimerfdClockId, TimerfdFlags, - TimerfdTimerFlags, Timespec, + Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags, Timespec, timerfd_create, + timerfd_gettime, timerfd_settime, }; #[test] diff --git a/tests/time/wall.rs b/tests/time/wall.rs index ceab007b5..c931ff0ea 100644 --- a/tests/time/wall.rs +++ b/tests/time/wall.rs @@ -1,4 +1,4 @@ -use rustix::time::{clock_gettime, ClockId, Timespec}; +use rustix::time::{ClockId, Timespec, clock_gettime}; #[test] fn test_wall_clock() { diff --git a/tests/time/y2038.rs b/tests/time/y2038.rs index 0ff960f73..5467a13f4 100644 --- a/tests/time/y2038.rs +++ b/tests/time/y2038.rs @@ -38,8 +38,8 @@ fn test_y2038() { #[test] fn test_y2038_with_timerfd() { use rustix::time::{ - timerfd_create, timerfd_gettime, timerfd_settime, Itimerspec, TimerfdClockId, TimerfdFlags, - TimerfdTimerFlags, Timespec, + Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags, Timespec, timerfd_create, + timerfd_gettime, timerfd_settime, }; let fd = timerfd_create(TimerfdClockId::Monotonic, TimerfdFlags::CLOEXEC).unwrap();