diff --git a/examples/stdio.rs b/examples/stdio.rs index 67ce576ad..7a5197858 100644 --- a/examples/stdio.rs +++ b/examples/stdio.rs @@ -111,7 +111,8 @@ fn show(fd: Fd) -> io::Result<()> { print!(" IMAXBEL"); } #[cfg(not(any( - bsd, + freebsdlike, + netbsdlike, solarish, target_os = "aix", target_os = "emscripten", @@ -127,7 +128,13 @@ fn show(fd: Fd) -> io::Result<()> { if (term.c_oflag & OPOST) != 0 { print!(" OPOST"); } - #[cfg(not(any(bsd, target_os = "aix", target_os = "redox")))] + #[cfg(not(any( + apple, + freebsdlike, + target_os = "aix", + target_os = "netbsd", + target_os = "redox" + )))] if (term.c_oflag & OLCUC) != 0 { print!(" OLCUC"); } diff --git a/src/backend/libc/fs/syscalls.rs b/src/backend/libc/fs/syscalls.rs index 3cd2f081c..d9105f423 100644 --- a/src/backend/libc/fs/syscalls.rs +++ b/src/backend/libc/fs/syscalls.rs @@ -2,8 +2,6 @@ use super::super::c; use super::super::conv::{borrowed_fd, c_str, ret, ret_c_int, ret_off_t, ret_owned_fd, ret_usize}; -#[cfg(any(target_os = "android", target_os = "linux"))] -use super::super::conv::{syscall_ret, syscall_ret_owned_fd, syscall_ret_usize}; #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] use super::super::offset::libc_fallocate; #[cfg(not(any( @@ -83,10 +81,6 @@ use crate::fs::SealFlags; target_os = "wasi", )))] use crate::fs::StatFs; -#[cfg(any(apple, target_os = "android", target_os = "linux"))] -use crate::fs::XattrFlags; -#[cfg(any(target_os = "android", target_os = "linux"))] -use crate::fs::{cwd, RenameFlags, ResolveFlags, Statx, StatxFlags}; use crate::fs::{Access, Mode, OFlags, Stat, Timestamps}; #[cfg(not(any(apple, target_os = "redox", target_os = "wasi")))] use crate::fs::{Dev, FileType}; @@ -100,21 +94,25 @@ use crate::process::{Gid, Uid}; target_env = "gnu", )))] use crate::utils::as_ptr; +#[cfg(apple)] +use alloc::vec; use core::convert::TryInto; -#[cfg(any(apple, target_os = "android", target_os = "linux"))] -use core::mem::size_of; use core::mem::MaybeUninit; -#[cfg(any(target_os = "android", target_os = "linux"))] -use core::ptr::null; -#[cfg(any(apple, target_os = "android", target_os = "linux"))] -use core::ptr::null_mut; #[cfg(apple)] use { super::super::conv::nonnegative_ret, crate::fs::{copyfile_state_t, CloneFlags, CopyfileFlags}, }; +#[cfg(any(target_os = "android", target_os = "linux"))] +use { + super::super::conv::{syscall_ret, syscall_ret_owned_fd, syscall_ret_usize}, + crate::fs::{cwd, RenameFlags, ResolveFlags, Statx, StatxFlags}, + core::ptr::null, +}; #[cfg(not(target_os = "redox"))] use {super::super::offset::libc_openat, crate::fs::AtFlags}; +#[cfg(any(apple, target_os = "android", target_os = "linux"))] +use {crate::fs::XattrFlags, core::mem::size_of, core::ptr::null_mut}; #[cfg(all( any(target_arch = "arm", target_arch = "mips", target_arch = "x86"), @@ -1635,7 +1633,7 @@ pub(crate) fn getpath(fd: BorrowedFd<'_>) -> io::Result { // `F_GETPATH` in terms of `MAXPATHLEN`, and there are no // alternatives. If a better method is invented, it should be used // instead. - let mut buf = alloc::vec![0; c::PATH_MAX as usize]; + let mut buf = vec![0; c::PATH_MAX as usize]; // From the [macOS `fcntl` manual page]: // `F_GETPATH` - Get the path of the file descriptor `Fildes`. The argument diff --git a/src/backend/libc/io/syscalls.rs b/src/backend/libc/io/syscalls.rs index bc642bdd5..1f91e35c3 100644 --- a/src/backend/libc/io/syscalls.rs +++ b/src/backend/libc/io/syscalls.rs @@ -1,8 +1,6 @@ //! libc syscalls supporting `rustix::io`. use super::super::c; -#[cfg(any(target_os = "android", target_os = "linux"))] -use super::super::conv::syscall_ret_owned_fd; #[cfg(any( target_os = "android", all(target_os = "linux", not(target_env = "gnu")), @@ -15,10 +13,6 @@ use super::super::offset::{libc_preadv, libc_pwritev}; #[cfg(all(target_os = "linux", target_env = "gnu"))] use super::super::offset::{libc_preadv2, libc_pwritev2}; use crate::fd::{AsFd, BorrowedFd, OwnedFd, RawFd}; -#[cfg(bsd)] -use crate::io::kqueue::Event; -#[cfg(solarish)] -use crate::io::port::Event; #[cfg(not(any(target_os = "aix", target_os = "wasi")))] use crate::io::DupFlags; #[cfg(any( @@ -31,15 +25,21 @@ use crate::io::EventfdFlags; #[cfg(not(any(apple, target_os = "aix", target_os = "haiku", target_os = "wasi")))] use crate::io::PipeFlags; use crate::io::{self, FdFlags, IoSlice, IoSliceMut, PollFd}; -#[cfg(any(target_os = "android", target_os = "linux"))] -use crate::io::{IoSliceRaw, ReadWriteFlags, SpliceFlags}; use core::cmp::min; use core::convert::TryInto; use core::mem::MaybeUninit; -#[cfg(any(target_os = "android", target_os = "linux"))] -use core::ptr; #[cfg(all(feature = "fs", feature = "net"))] use libc_errno::errno; +#[cfg(any(target_os = "android", target_os = "linux"))] +use { + super::super::conv::syscall_ret_owned_fd, + crate::io::{IoSliceRaw, ReadWriteFlags, SpliceFlags}, + core::ptr, +}; +#[cfg(bsd)] +use {crate::io::kqueue::Event, crate::utils::as_ptr, core::ptr::null}; +#[cfg(solarish)] +use {crate::io::port::Event, crate::utils::as_mut_ptr, core::ptr::null_mut}; pub(crate) fn read(fd: BorrowedFd<'_>, buf: &mut [u8]) -> io::Result { unsafe { @@ -531,17 +531,17 @@ pub(crate) unsafe fn kevent( ) -> io::Result { ret_c_int(c::kevent( borrowed_fd(kq), - changelist.as_ptr() as *const _, + changelist.as_ptr().cast(), changelist .len() .try_into() .map_err(|_| io::Errno::OVERFLOW)?, - eventlist.as_mut_ptr() as *mut _, + eventlist.as_mut_ptr().cast(), eventlist .len() .try_into() .map_err(|_| io::Errno::OVERFLOW)?, - timeout.map_or(core::ptr::null(), |t| t as *const _), + timeout.map_or(null(), as_ptr), )) } @@ -658,7 +658,7 @@ pub(crate) fn port_get( timeout: Option<&mut c::timespec>, ) -> io::Result { let mut event = MaybeUninit::::uninit(); - let timeout = timeout.map_or(core::ptr::null_mut(), |t| t as *mut _); + let timeout = timeout.map_or(null_mut(), as_mut_ptr); unsafe { ret(c::port_get(borrowed_fd(port), event.as_mut_ptr(), timeout))?; @@ -675,7 +675,7 @@ pub(crate) fn port_getn( events: &mut Vec, mut nget: u32, ) -> io::Result<()> { - let timeout = timeout.map_or(core::ptr::null_mut(), |t| t as *mut _); + let timeout = timeout.map_or(null_mut(), as_mut_ptr); unsafe { ret(c::port_getn( borrowed_fd(port), diff --git a/src/backend/libc/net/addr.rs b/src/backend/libc/net/addr.rs index d00a48626..e454ee494 100644 --- a/src/backend/libc/net/addr.rs +++ b/src/backend/libc/net/addr.rs @@ -1,18 +1,18 @@ -//! IPv4, IPv6, and Socket addresses. +//! Socket address utilities. use super::super::c; -#[cfg(unix)] -use crate::ffi::CStr; -#[cfg(unix)] -use crate::io; -#[cfg(unix)] -use crate::path; #[cfg(not(windows))] use core::convert::TryInto; #[cfg(unix)] -use core::fmt; -#[cfg(unix)] -use core::slice; +use { + crate::ffi::CStr, + crate::io, + crate::path, + core::cmp::Ordering, + core::fmt, + core::hash::{Hash, Hasher}, + core::slice, +}; /// `struct sockaddr_un` #[cfg(unix)] @@ -159,7 +159,7 @@ impl Eq for SocketAddrUnix {} #[cfg(unix)] impl PartialOrd for SocketAddrUnix { #[inline] - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { let self_len = self.len() - offsetof_sun_path(); let other_len = other.len() - offsetof_sun_path(); self.unix.sun_path[..self_len].partial_cmp(&other.unix.sun_path[..other_len]) @@ -169,7 +169,7 @@ impl PartialOrd for SocketAddrUnix { #[cfg(unix)] impl Ord for SocketAddrUnix { #[inline] - fn cmp(&self, other: &Self) -> core::cmp::Ordering { + fn cmp(&self, other: &Self) -> Ordering { let self_len = self.len() - offsetof_sun_path(); let other_len = other.len() - offsetof_sun_path(); self.unix.sun_path[..self_len].cmp(&other.unix.sun_path[..other_len]) @@ -177,9 +177,9 @@ impl Ord for SocketAddrUnix { } #[cfg(unix)] -impl core::hash::Hash for SocketAddrUnix { +impl Hash for SocketAddrUnix { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { let self_len = self.len() - offsetof_sun_path(); self.unix.sun_path[..self_len].hash(state) } diff --git a/src/backend/libc/net/msghdr.rs b/src/backend/libc/net/msghdr.rs index e2a6981fa..d316a5a34 100644 --- a/src/backend/libc/net/msghdr.rs +++ b/src/backend/libc/net/msghdr.rs @@ -7,8 +7,8 @@ use super::super::c; use super::super::conv::{msg_control_len, msg_iov_len}; use super::super::net::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6}; -use crate::io; -use crate::net::{SocketAddrV4, SocketAddrV6}; +use crate::io::{IoSlice, IoSliceMut}; +use crate::net::{RecvAncillaryBuffer, SendAncillaryBuffer, SocketAddrV4, SocketAddrV6}; use crate::utils::as_ptr; use core::convert::TryInto; @@ -17,8 +17,8 @@ use core::mem::{size_of, zeroed, MaybeUninit}; /// Create a message header intended to receive a datagram. pub(crate) fn with_recv_msghdr( name: &mut MaybeUninit, - iov: &mut [io::IoSliceMut<'_>], - control: &mut crate::net::RecvAncillaryBuffer<'_>, + iov: &mut [IoSliceMut<'_>], + control: &mut RecvAncillaryBuffer<'_>, f: impl FnOnce(&mut c::msghdr) -> R, ) -> R { let namelen = size_of::() as c::socklen_t; @@ -45,8 +45,8 @@ pub(crate) fn with_recv_msghdr( /// Create a message header intended to send without an address. pub(crate) fn with_noaddr_msghdr( - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { f({ @@ -62,8 +62,8 @@ pub(crate) fn with_noaddr_msghdr( /// Create a message header intended to send with an IPv4 address. pub(crate) fn with_v4_msghdr( addr: &SocketAddrV4, - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { let encoded = unsafe { encode_sockaddr_v4(addr) }; @@ -83,8 +83,8 @@ pub(crate) fn with_v4_msghdr( /// Create a message header intended to send with an IPv6 address. pub(crate) fn with_v6_msghdr( addr: &SocketAddrV6, - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { let encoded = unsafe { encode_sockaddr_v6(addr) }; @@ -105,8 +105,8 @@ pub(crate) fn with_v6_msghdr( #[cfg(all(unix, not(target_os = "redox")))] pub(crate) fn with_unix_msghdr( addr: &crate::net::SocketAddrUnix, - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { f({ diff --git a/src/backend/libc/net/syscalls.rs b/src/backend/libc/net/syscalls.rs index 50b3baf68..9a7dd6b6c 100644 --- a/src/backend/libc/net/syscalls.rs +++ b/src/backend/libc/net/syscalls.rs @@ -5,31 +5,26 @@ use super::super::conv::{borrowed_fd, ret, ret_owned_fd, ret_send_recv, send_rec #[cfg(unix)] use super::addr::SocketAddrUnix; use super::ext::{in6_addr_new, in_addr_new}; -#[cfg(not(any(windows, target_os = "redox", target_os = "wasi")))] -use super::msghdr::{with_noaddr_msghdr, with_recv_msghdr, with_v4_msghdr, with_v6_msghdr}; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use super::read_sockaddr::initialize_family_to_unspec; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use super::read_sockaddr::{maybe_read_sockaddr_os, read_sockaddr_os}; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use super::send_recv::{RecvFlags, SendFlags}; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use super::types::{AddressFamily, Protocol, Shutdown, SocketFlags, SocketType}; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use super::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6}; use crate::fd::{BorrowedFd, OwnedFd}; use crate::io; use crate::net::{SocketAddrAny, SocketAddrV4, SocketAddrV6}; use crate::utils::as_ptr; use core::convert::TryInto; use core::mem::{size_of, MaybeUninit}; -#[cfg(not(any(target_os = "redox", target_os = "wasi")))] -use core::ptr::null_mut; #[cfg(not(any(windows, target_os = "redox", target_os = "wasi")))] use { + super::msghdr::{with_noaddr_msghdr, with_recv_msghdr, with_v4_msghdr, with_v6_msghdr}, crate::io::{IoSlice, IoSliceMut}, crate::net::{RecvAncillaryBuffer, RecvMsgReturn, SendAncillaryBuffer}, }; +#[cfg(not(any(target_os = "redox", target_os = "wasi")))] +use { + super::read_sockaddr::{initialize_family_to_unspec, maybe_read_sockaddr_os, read_sockaddr_os}, + super::send_recv::{RecvFlags, SendFlags}, + super::types::{AddressFamily, Protocol, Shutdown, SocketFlags, SocketType}, + super::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6}, + core::ptr::null_mut, +}; #[cfg(not(any(target_os = "redox", target_os = "wasi")))] pub(crate) fn recv(fd: BorrowedFd<'_>, buf: &mut [u8], flags: RecvFlags) -> io::Result { diff --git a/src/backend/libc/termios/syscalls.rs b/src/backend/libc/termios/syscalls.rs index dba73c960..9705044a2 100644 --- a/src/backend/libc/termios/syscalls.rs +++ b/src/backend/libc/termios/syscalls.rs @@ -10,13 +10,13 @@ use crate::fd::BorrowedFd; #[cfg(feature = "procfs")] #[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))] use crate::ffi::CStr; -#[cfg(not(target_os = "wasi"))] -use crate::io; -#[cfg(not(target_os = "wasi"))] -use crate::process::{Pid, RawNonZeroPid}; -#[cfg(not(target_os = "wasi"))] -use crate::termios::{Action, OptionalActions, QueueSelector, Speed, Termios, Winsize}; use core::mem::MaybeUninit; +#[cfg(not(target_os = "wasi"))] +use { + crate::io, + crate::process::{Pid, RawNonZeroPid}, + crate::termios::{Action, OptionalActions, QueueSelector, Speed, Termios, Winsize}, +}; #[cfg(not(target_os = "wasi"))] pub(crate) fn tcgetattr(fd: BorrowedFd<'_>) -> io::Result { diff --git a/src/backend/libc/termios/types.rs b/src/backend/libc/termios/types.rs index 99fd9753a..1f65ff74d 100644 --- a/src/backend/libc/termios/types.rs +++ b/src/backend/libc/termios/types.rs @@ -127,16 +127,7 @@ pub const VTIME: usize = c::VTIME as usize; pub const VMIN: usize = c::VMIN as usize; /// `VSWTC` -#[cfg(not(any( - apple, - solarish, - target_os = "aix", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "haiku", - target_os = "netbsd", - target_os = "openbsd", -)))] +#[cfg(not(any(bsd, solarish, target_os = "aix", target_os = "haiku")))] pub const VSWTC: usize = c::VSWTC as usize; /// `VSTART` @@ -217,14 +208,12 @@ pub const IMAXBEL: Tcflag = c::IMAXBEL; /// `IUTF8` #[cfg(not(any( + freebsdlike, + netbsdlike, solarish, target_os = "aix", - target_os = "dragonfly", target_os = "emscripten", - target_os = "freebsd", target_os = "haiku", - target_os = "netbsd", - target_os = "openbsd", target_os = "redox", )))] pub const IUTF8: Tcflag = c::IUTF8; @@ -235,9 +224,8 @@ pub const OPOST: Tcflag = c::OPOST; /// `OLCUC` #[cfg(not(any( apple, + freebsdlike, target_os = "aix", - target_os = "dragonfly", - target_os = "freebsd", target_os = "netbsd", target_os = "redox", )))] diff --git a/src/backend/libc/thread/syscalls.rs b/src/backend/libc/thread/syscalls.rs index adf4bb700..c995bb007 100644 --- a/src/backend/libc/thread/syscalls.rs +++ b/src/backend/libc/thread/syscalls.rs @@ -2,17 +2,17 @@ use super::super::c; use super::super::conv::ret; -#[cfg(any(target_os = "android", target_os = "linux"))] -use super::super::conv::{borrowed_fd, ret_c_int, syscall_ret}; use super::super::time::types::LibcTimespec; -#[cfg(any(target_os = "android", target_os = "linux"))] -use crate::fd::BorrowedFd; use crate::io; -#[cfg(any(target_os = "android", target_os = "linux"))] -use crate::process::{Pid, RawNonZeroPid}; #[cfg(not(target_os = "redox"))] use crate::thread::{NanosleepRelativeResult, Timespec}; use core::mem::MaybeUninit; +#[cfg(any(target_os = "android", target_os = "linux"))] +use { + super::super::conv::{borrowed_fd, ret_c_int, syscall_ret}, + crate::fd::BorrowedFd, + crate::process::{Pid, RawNonZeroPid}, +}; #[cfg(not(any( apple, freebsdlike, diff --git a/src/backend/linux_raw/fs/dir.rs b/src/backend/linux_raw/fs/dir.rs index cfa347d03..66b3101b1 100644 --- a/src/backend/linux_raw/fs/dir.rs +++ b/src/backend/linux_raw/fs/dir.rs @@ -100,8 +100,7 @@ impl Dir { .iter() .position(|x| *x == b'\0') .unwrap(); - let name = - CStr::from_bytes_with_nul(&self.buf[name_start..name_start + name_len + 1]).unwrap(); + let name = CStr::from_bytes_with_nul(&self.buf[name_start..][..name_len + 1]).unwrap(); let name = name.to_owned(); assert!(name.as_bytes().len() <= self.buf.len() - name_start); diff --git a/src/backend/linux_raw/fs/syscalls.rs b/src/backend/linux_raw/fs/syscalls.rs index e2f1863e0..146c2dbf5 100644 --- a/src/backend/linux_raw/fs/syscalls.rs +++ b/src/backend/linux_raw/fs/syscalls.rs @@ -32,7 +32,7 @@ use crate::io::{self, SeekFrom}; use crate::process::{Gid, Uid}; #[cfg(any(target_pointer_width = "32", target_arch = "mips64"))] use core::convert::TryInto; -use core::mem::MaybeUninit; +use core::mem::{transmute, zeroed, MaybeUninit}; #[cfg(target_arch = "mips64")] use linux_raw_sys::general::stat as linux_stat64; use linux_raw_sys::general::{ @@ -1077,7 +1077,7 @@ pub(crate) fn fcntl_lock(fd: BorrowedFd<'_>, operation: FlockOperation) -> io::R l_start: 0, l_len: 0, - ..core::mem::zeroed() + ..zeroed() }; #[cfg(target_pointer_width = "32")] @@ -1308,7 +1308,7 @@ fn _utimensat( flags: AtFlags, ) -> io::Result<()> { // Assert that `Timestamps` has the expected layout. - let _ = unsafe { core::mem::transmute::(times.clone()) }; + let _ = unsafe { transmute::(times.clone()) }; #[cfg(target_pointer_width = "32")] unsafe { diff --git a/src/backend/linux_raw/io/epoll.rs b/src/backend/linux_raw/io/epoll.rs index 3fc6462a2..970e1493e 100644 --- a/src/backend/linux_raw/io/epoll.rs +++ b/src/backend/linux_raw/io/epoll.rs @@ -76,6 +76,7 @@ use crate::fd::{AsFd, AsRawFd, OwnedFd}; use crate::io; use alloc::vec::Vec; use bitflags::bitflags; +use core::slice; bitflags! { /// `EPOLL_*` for use with [`Epoll::new`]. @@ -247,7 +248,7 @@ pub fn epoll_wait( /// An iterator over the `Event`s in an `EventVec`. pub struct Iter<'a> { - iter: core::slice::Iter<'a, Event>, + iter: slice::Iter<'a, Event>, } impl<'a> Iterator for Iter<'a> { diff --git a/src/backend/linux_raw/net/addr.rs b/src/backend/linux_raw/net/addr.rs index b69c6deca..7153fe1bc 100644 --- a/src/backend/linux_raw/net/addr.rs +++ b/src/backend/linux_raw/net/addr.rs @@ -1,14 +1,17 @@ -//! IPv4, IPv6, and Socket addresses. +//! Socket address utilities. //! //! # Safety //! -//! Linux's IPv6 type contains a union. +//! This file casts between `&[c_char]` used in C APIs and `&[u8]` used in Rust +//! APIs. #![allow(unsafe_code)] use super::super::c; use crate::ffi::CStr; use crate::{io, path}; +use core::cmp::Ordering; use core::convert::TryInto; +use core::hash::{Hash, Hasher}; use core::{fmt, slice}; /// `struct sockaddr_un` @@ -122,7 +125,7 @@ impl Eq for SocketAddrUnix {} impl PartialOrd for SocketAddrUnix { #[inline] - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { let self_len = self.len() - offsetof_sun_path(); let other_len = other.len() - offsetof_sun_path(); self.unix.sun_path[..self_len].partial_cmp(&other.unix.sun_path[..other_len]) @@ -131,16 +134,16 @@ impl PartialOrd for SocketAddrUnix { impl Ord for SocketAddrUnix { #[inline] - fn cmp(&self, other: &Self) -> core::cmp::Ordering { + fn cmp(&self, other: &Self) -> Ordering { let self_len = self.len() - offsetof_sun_path(); let other_len = other.len() - offsetof_sun_path(); self.unix.sun_path[..self_len].cmp(&other.unix.sun_path[..other_len]) } } -impl core::hash::Hash for SocketAddrUnix { +impl Hash for SocketAddrUnix { #[inline] - fn hash(&self, state: &mut H) { + fn hash(&self, state: &mut H) { let self_len = self.len() - offsetof_sun_path(); self.unix.sun_path[..self_len].hash(state) } diff --git a/src/backend/linux_raw/net/msghdr.rs b/src/backend/linux_raw/net/msghdr.rs index 161553c55..a5259ec94 100644 --- a/src/backend/linux_raw/net/msghdr.rs +++ b/src/backend/linux_raw/net/msghdr.rs @@ -8,8 +8,8 @@ use super::super::c; use super::super::net::write_sockaddr::{encode_sockaddr_v4, encode_sockaddr_v6}; -use crate::io; -use crate::net::{SocketAddrV4, SocketAddrV6}; +use crate::io::{IoSlice, IoSliceMut}; +use crate::net::{RecvAncillaryBuffer, SendAncillaryBuffer, SocketAddrV4, SocketAddrV6}; use crate::utils::as_ptr; use core::convert::TryInto; @@ -29,8 +29,8 @@ pub(crate) fn msg_control_len(len: usize) -> c::size_t { /// Create a message header intended to receive a datagram. pub(crate) fn with_recv_msghdr( name: &mut MaybeUninit, - iov: &mut [io::IoSliceMut<'_>], - control: &mut crate::net::RecvAncillaryBuffer<'_>, + iov: &mut [IoSliceMut<'_>], + control: &mut RecvAncillaryBuffer<'_>, f: impl FnOnce(&mut c::msghdr) -> R, ) -> R { let namelen = size_of::() as c::c_int; @@ -58,8 +58,8 @@ pub(crate) fn with_recv_msghdr( /// Create a message header intended to send without an address. pub(crate) fn with_noaddr_msghdr( - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { f(c::msghdr { @@ -78,8 +78,8 @@ pub(crate) fn with_noaddr_msghdr( /// Create a message header intended to send with an IPv4 address. pub(crate) fn with_v4_msghdr( addr: &SocketAddrV4, - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { let encoded = unsafe { encode_sockaddr_v4(addr) }; @@ -100,8 +100,8 @@ pub(crate) fn with_v4_msghdr( /// Create a message header intended to send with an IPv6 address. pub(crate) fn with_v6_msghdr( addr: &SocketAddrV6, - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { let encoded = unsafe { encode_sockaddr_v6(addr) }; @@ -122,8 +122,8 @@ pub(crate) fn with_v6_msghdr( /// Create a message header intended to send with a Unix address. pub(crate) fn with_unix_msghdr( addr: &crate::net::SocketAddrUnix, - iov: &[io::IoSlice<'_>], - control: &mut crate::net::SendAncillaryBuffer<'_, '_, '_>, + iov: &[IoSlice<'_>], + control: &mut SendAncillaryBuffer<'_, '_, '_>, f: impl FnOnce(c::msghdr) -> R, ) -> R { f(c::msghdr { diff --git a/src/backend/linux_raw/param/libc_auxv.rs b/src/backend/linux_raw/param/libc_auxv.rs index a8e291ff6..b8f2c06c8 100644 --- a/src/backend/linux_raw/param/libc_auxv.rs +++ b/src/backend/linux_raw/param/libc_auxv.rs @@ -8,6 +8,7 @@ use super::super::elf::*; #[cfg(feature = "param")] use crate::ffi::CStr; +use core::ptr::null; #[cfg(feature = "runtime")] use core::slice; @@ -78,6 +79,6 @@ pub(in super::super) fn sysinfo_ehdr() -> *const Elf_Ehdr { if let Some(libc_getauxval) = getauxval.get() { unsafe { libc_getauxval(linux_raw_sys::general::AT_SYSINFO_EHDR.into()) as *const Elf_Ehdr } } else { - core::ptr::null() + null() } } diff --git a/src/backend/linux_raw/reg.rs b/src/backend/linux_raw/reg.rs index afe99c5f4..206031dde 100644 --- a/src/backend/linux_raw/reg.rs +++ b/src/backend/linux_raw/reg.rs @@ -16,6 +16,7 @@ use super::c; use super::fd::RawFd; use core::marker::PhantomData; +use core::ops::Range; pub(super) trait ToAsm: private::Sealed { /// Convert `self` to a `usize` ready to be passed to a syscall @@ -188,7 +189,7 @@ impl RetReg { } #[inline] - pub(super) fn is_in_range(&self, range: core::ops::Range) -> bool { + pub(super) fn is_in_range(&self, range: Range) -> bool { range.contains(&(self.raw as isize)) } } diff --git a/src/backend/linux_raw/thread/syscalls.rs b/src/backend/linux_raw/thread/syscalls.rs index 1895c8c6d..03ae53c89 100644 --- a/src/backend/linux_raw/thread/syscalls.rs +++ b/src/backend/linux_raw/thread/syscalls.rs @@ -17,9 +17,7 @@ use crate::thread::{ClockId, FutexFlags, FutexOperation, NanosleepRelativeResult use core::mem::MaybeUninit; use linux_raw_sys::general::{__kernel_pid_t, __kernel_timespec, TIMER_ABSTIME}; #[cfg(target_pointer_width = "32")] -use { - core::convert::TryInto, core::ptr, linux_raw_sys::general::timespec as __kernel_old_timespec, -}; +use {core::convert::TryInto, linux_raw_sys::general::timespec as __kernel_old_timespec}; #[inline] pub(crate) fn clock_nanosleep_relative( @@ -87,13 +85,10 @@ unsafe fn clock_nanosleep_relative_old( ))?; let old_rem = old_rem.assume_init(); // TODO: With Rust 1.55, we can use MaybeUninit::write here. - ptr::write( - rem.as_mut_ptr(), - __kernel_timespec { - tv_sec: old_rem.tv_sec.into(), - tv_nsec: old_rem.tv_nsec.into(), - }, - ); + rem.as_mut_ptr().write(__kernel_timespec { + tv_sec: old_rem.tv_sec.into(), + tv_nsec: old_rem.tv_nsec.into(), + }); Ok(()) } @@ -195,13 +190,10 @@ unsafe fn nanosleep_old( ret(syscall!(__NR_nanosleep, by_ref(&old_req), &mut old_rem))?; let old_rem = old_rem.assume_init(); // TODO: With Rust 1.55, we can use MaybeUninit::write here. - ptr::write( - rem.as_mut_ptr(), - __kernel_timespec { - tv_sec: old_rem.tv_sec.into(), - tv_nsec: old_rem.tv_nsec.into(), - }, - ); + rem.as_mut_ptr().write(__kernel_timespec { + tv_sec: old_rem.tv_sec.into(), + tv_nsec: old_rem.tv_nsec.into(), + }); Ok(()) } diff --git a/src/backend/linux_raw/time/syscalls.rs b/src/backend/linux_raw/time/syscalls.rs index c039393ef..09a6dc37a 100644 --- a/src/backend/linux_raw/time/syscalls.rs +++ b/src/backend/linux_raw/time/syscalls.rs @@ -6,24 +6,22 @@ #![allow(unsafe_code)] #![allow(clippy::undocumented_unsafe_blocks)] -#[cfg(feature = "time")] -use super::super::conv::{by_ref, ret_owned_fd}; use super::super::conv::{ret, ret_infallible}; use super::types::ClockId; -#[cfg(feature = "time")] -use crate::fd::BorrowedFd; -#[cfg(feature = "time")] -use crate::fd::OwnedFd; use crate::io; -#[cfg(feature = "time")] -use crate::time::{Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags}; use core::mem::MaybeUninit; use linux_raw_sys::general::__kernel_timespec; -#[cfg(feature = "time")] #[cfg(target_pointer_width = "32")] +use linux_raw_sys::general::timespec as __kernel_old_timespec; +#[cfg(feature = "time")] +use { + super::super::conv::{by_ref, ret_owned_fd}, + crate::fd::BorrowedFd, + crate::fd::OwnedFd, + crate::time::{Itimerspec, TimerfdClockId, TimerfdFlags, TimerfdTimerFlags}, +}; +#[cfg(all(feature = "time", target_pointer_width = "32"))] use {core::convert::TryInto, linux_raw_sys::general::itimerspec as __kernel_old_itimerspec}; -#[cfg(target_pointer_width = "32")] -use {core::ptr, linux_raw_sys::general::timespec as __kernel_old_timespec}; // `clock_gettime` has special optimizations via the vDSO. #[cfg(feature = "time")] @@ -56,13 +54,10 @@ unsafe fn clock_getres_old(which_clock: ClockId, result: &mut MaybeUninit<__kern ret_infallible(syscall!(__NR_clock_getres, which_clock, &mut old_result)); let old_result = old_result.assume_init(); // TODO: With Rust 1.55, we can use MaybeUninit::write here. - ptr::write( - result.as_mut_ptr(), - __kernel_timespec { - tv_sec: old_result.tv_sec.into(), - tv_nsec: old_result.tv_nsec.into(), - }, - ); + result.as_mut_ptr().write(__kernel_timespec { + tv_sec: old_result.tv_sec.into(), + tv_nsec: old_result.tv_nsec.into(), + }); } #[cfg(feature = "time")] @@ -201,19 +196,16 @@ unsafe fn timerfd_settime_old( ))?; let old_result = old_result.assume_init(); // TODO: With Rust 1.55, we can use MaybeUninit::write here. - ptr::write( - result.as_mut_ptr(), - Itimerspec { - it_interval: __kernel_timespec { - tv_sec: old_result.it_interval.tv_sec.into(), - tv_nsec: old_result.it_interval.tv_nsec.into(), - }, - it_value: __kernel_timespec { - tv_sec: old_result.it_value.tv_sec.into(), - tv_nsec: old_result.it_value.tv_nsec.into(), - }, + result.as_mut_ptr().write(Itimerspec { + it_interval: __kernel_timespec { + tv_sec: old_result.it_interval.tv_sec.into(), + tv_nsec: old_result.it_interval.tv_nsec.into(), }, - ); + it_value: __kernel_timespec { + tv_sec: old_result.it_value.tv_sec.into(), + tv_nsec: old_result.it_value.tv_nsec.into(), + }, + }); Ok(()) } @@ -253,18 +245,15 @@ unsafe fn timerfd_gettime_old( ret(syscall!(__NR_timerfd_gettime, fd, &mut old_result))?; let old_result = old_result.assume_init(); // TODO: With Rust 1.55, we can use MaybeUninit::write here. - ptr::write( - result.as_mut_ptr(), - Itimerspec { - it_interval: __kernel_timespec { - tv_sec: old_result.it_interval.tv_sec.into(), - tv_nsec: old_result.it_interval.tv_nsec.into(), - }, - it_value: __kernel_timespec { - tv_sec: old_result.it_value.tv_sec.into(), - tv_nsec: old_result.it_value.tv_nsec.into(), - }, + result.as_mut_ptr().write(Itimerspec { + it_interval: __kernel_timespec { + tv_sec: old_result.it_interval.tv_sec.into(), + tv_nsec: old_result.it_interval.tv_nsec.into(), + }, + it_value: __kernel_timespec { + tv_sec: old_result.it_value.tv_sec.into(), + tv_nsec: old_result.it_value.tv_nsec.into(), }, - ); + }); Ok(()) } diff --git a/src/fs/fd.rs b/src/fs/fd.rs index 81e56d909..b356b54e9 100644 --- a/src/fs/fd.rs +++ b/src/fs/fd.rs @@ -2,6 +2,7 @@ #[cfg(not(target_os = "wasi"))] use crate::fs::Mode; +use crate::fs::{OFlags, Timespec}; use crate::io::SeekFrom; #[cfg(not(target_os = "wasi"))] use crate::process::{Gid, Uid}; @@ -47,10 +48,10 @@ pub use backend::fs::types::FsWord; #[derive(Clone, Debug)] pub struct Timestamps { /// The timestamp of the last access to a filesystem object. - pub last_access: crate::fs::Timespec, + pub last_access: Timespec, /// The timestamp of the last modification of a filesystem object. - pub last_modification: crate::fs::Timespec, + pub last_modification: Timespec, } /// The filesystem magic number for procfs. @@ -143,7 +144,7 @@ pub fn fchown(fd: Fd, owner: Option, group: Option) -> io::R /// /// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/fstat.html /// [Linux]: https://man7.org/linux/man-pages/man2/fstat.2.html -/// [`Mode::from_raw_mode`]: crate::fs::Mode::from_raw_mode +/// [`Mode::from_raw_mode`]: Mode::from_raw_mode /// [`FileType::from_raw_mode`]: crate::fs::FileType::from_raw_mode #[inline] pub fn fstat(fd: Fd) -> io::Result { @@ -253,16 +254,16 @@ pub(crate) fn _is_file_read_write(fd: BorrowedFd<'_>) -> io::Result<(bool, bool) target_os = "linux", target_os = "emscripten", ))] - if mode.contains(crate::fs::OFlags::PATH) { + if mode.contains(OFlags::PATH) { return Ok((false, false)); } // Use `RWMODE` rather than `ACCMODE` as `ACCMODE` may include `O_PATH`. // We handled `O_PATH` above. - match mode & crate::fs::OFlags::RWMODE { - crate::fs::OFlags::RDONLY => Ok((true, false)), - crate::fs::OFlags::RDWR => Ok((true, true)), - crate::fs::OFlags::WRONLY => Ok((false, true)), + match mode & OFlags::RWMODE { + OFlags::RDONLY => Ok((true, false)), + OFlags::RDWR => Ok((true, true)), + OFlags::WRONLY => Ok((false, true)), _ => unreachable!(), } } diff --git a/src/fs/mod.rs b/src/fs/mod.rs index e28ddab6f..16bb554db 100644 --- a/src/fs/mod.rs +++ b/src/fs/mod.rs @@ -61,8 +61,8 @@ pub use cwd::cwd; pub use dir::{Dir, DirEntry}; #[cfg(not(any( apple, - solarish, netbsdlike, + solarish, target_os = "dragonfly", target_os = "haiku", target_os = "redox", diff --git a/src/io/kqueue.rs b/src/io/kqueue.rs index 55d2acabf..d6ff60933 100644 --- a/src/io/kqueue.rs +++ b/src/io/kqueue.rs @@ -1,12 +1,15 @@ //! An API for interfacing with `kqueue`. use crate::fd::{AsFd, AsRawFd, OwnedFd, RawFd}; +#[cfg(feature = "process")] +use crate::process::{Pid, Signal}; use crate::{backend, io}; use backend::c::{self, intptr_t, kevent as kevent_t, uintptr_t}; use backend::io::syscalls; use alloc::vec::Vec; +use core::mem::zeroed; use core::ptr::slice_from_raw_parts_mut; use core::time::Duration; @@ -31,12 +34,9 @@ impl Event { (vnode.as_raw_fd() as _, 0, c::EVFILT_VNODE, flags.bits()) } #[cfg(feature = "process")] - EventFilter::Proc { pid, flags } => ( - crate::process::Pid::as_raw(Some(pid)) as _, - 0, - c::EVFILT_PROC, - flags.bits(), - ), + EventFilter::Proc { pid, flags } => { + (Pid::as_raw(Some(pid)) as _, 0, c::EVFILT_PROC, flags.bits()) + } #[cfg(feature = "process")] EventFilter::Signal { signal, times: _ } => (signal as _, 0, c::EVFILT_SIGNAL, 0), EventFilter::Timer { ident, timer } => { @@ -85,7 +85,7 @@ impl Event { // TODO: Strict provenance, prevent int-to-ptr cast. udata as _ }, - ..unsafe { core::mem::zeroed() } + ..unsafe { zeroed() } }, } } @@ -116,12 +116,12 @@ impl Event { }, #[cfg(feature = "process")] c::EVFILT_PROC => EventFilter::Proc { - pid: unsafe { crate::process::Pid::from_raw(self.inner.ident as _) }.unwrap(), + pid: unsafe { Pid::from_raw(self.inner.ident as _) }.unwrap(), flags: ProcessEvents::from_bits_truncate(self.inner.fflags), }, #[cfg(feature = "process")] c::EVFILT_SIGNAL => EventFilter::Signal { - signal: crate::process::Signal::from_raw(self.inner.ident as _).unwrap(), + signal: Signal::from_raw(self.inner.ident as _).unwrap(), times: self.inner.data as _, }, c::EVFILT_TIMER => EventFilter::Timer { @@ -184,7 +184,7 @@ pub enum EventFilter { #[cfg(feature = "process")] Proc { /// The process ID we waited on. - pid: crate::process::Pid, + pid: Pid, /// The flags for this event. flags: ProcessEvents, @@ -194,7 +194,7 @@ pub enum EventFilter { #[cfg(feature = "process")] Signal { /// The signal number we waited on. - signal: crate::process::Signal, + signal: Signal, /// The number of times the signal has been /// received since the last call to kevent. @@ -405,15 +405,14 @@ pub unsafe fn kevent( eventlist: &mut Vec, timeout: Option, ) -> io::Result { - let timeout = timeout.map(|timeout| crate::backend::c::timespec { + let timeout = timeout.map(|timeout| backend::c::timespec { tv_sec: timeout.as_secs() as _, tv_nsec: timeout.subsec_nanos() as _, }); // Populate the event list with events. eventlist.set_len(0); - let out_slice = - slice_from_raw_parts_mut(eventlist.as_mut_ptr() as *mut _, eventlist.capacity()); + let out_slice = slice_from_raw_parts_mut(eventlist.as_mut_ptr().cast(), eventlist.capacity()); let res = syscalls::kevent( kqueue.as_fd(), changelist, diff --git a/src/io/pipe.rs b/src/io/pipe.rs index 40acc814d..d51c3ec5f 100644 --- a/src/io/pipe.rs +++ b/src/io/pipe.rs @@ -149,7 +149,7 @@ pub fn splice( #[inline] pub unsafe fn vmsplice( fd: PipeFd, - bufs: &[io::IoSliceRaw], + bufs: &[IoSliceRaw], flags: SpliceFlags, ) -> io::Result { backend::io::syscalls::vmsplice(fd.as_fd(), bufs, flags) diff --git a/src/io/stdio.rs b/src/io/stdio.rs index adfb776d5..ce70f4b2c 100644 --- a/src/io/stdio.rs +++ b/src/io/stdio.rs @@ -13,9 +13,7 @@ use crate::fd::OwnedFd; use backend::fd::{BorrowedFd, FromRawFd, RawFd}; #[cfg(not(any(windows, target_os = "wasi")))] -use crate::io; -#[cfg(not(any(windows, target_os = "wasi")))] -use backend::fd::AsFd; +use {crate::io, backend::fd::AsFd, core::mem::forget}; /// `STDIN_FILENO`—Standard input, borrowed. /// @@ -480,7 +478,7 @@ pub fn dup2_stdin(fd: Fd) -> io::Result<()> { // dropped. let mut target = unsafe { io::take_stdin() }; backend::io::syscalls::dup2(fd.as_fd(), &mut target)?; - core::mem::forget(target); + forget(target); Ok(()) } @@ -492,7 +490,7 @@ pub fn dup2_stdout(fd: Fd) -> io::Result<()> { // dropped. let mut target = unsafe { io::take_stdout() }; backend::io::syscalls::dup2(fd.as_fd(), &mut target)?; - core::mem::forget(target); + forget(target); Ok(()) } @@ -504,6 +502,6 @@ pub fn dup2_stderr(fd: Fd) -> io::Result<()> { // dropped. let mut target = unsafe { io::take_stderr() }; backend::io::syscalls::dup2(fd.as_fd(), &mut target)?; - core::mem::forget(target); + forget(target); Ok(()) } diff --git a/src/io_uring.rs b/src/io_uring.rs index b94b458f5..629e4d175 100644 --- a/src/io_uring.rs +++ b/src/io_uring.rs @@ -5,6 +5,8 @@ //! `Result`, `OwnedFd`, `AsFd`, `RawFd`, and `*mut c_void` in place of plain //! integers. //! +//! For a higher-level API built on top of this, see the [rustix-uring] crate. +//! //! # Safety //! //! io_uring operates on raw pointers and raw file descriptors. Rustix does not @@ -19,12 +21,14 @@ //! [Linux]: https://man.archlinux.org/man/io_uring.7.en //! [io_uring]: https://en.wikipedia.org/wiki/Io_uring //! [io_uring header]: https://github.com/torvalds/linux/blob/master/include/uapi/linux/io_uring.h +//! [rustix-uring]: https://crates.io/crates/rustix-uring #![allow(unsafe_code)] use crate::fd::{AsFd, BorrowedFd, OwnedFd, RawFd}; use crate::{backend, io}; use core::ffi::c_void; -use core::ptr::null_mut; +use core::mem::{zeroed, MaybeUninit}; +use core::ptr::{null_mut, write_bytes}; use linux_raw_sys::general as sys; /// `io_uring_setup(entries, params)`—Setup a context for performing @@ -863,10 +867,10 @@ impl io_uring_user_data { impl Default for io_uring_user_data { #[inline] fn default() -> Self { - let mut s = ::core::mem::MaybeUninit::::uninit(); + let mut s = MaybeUninit::::uninit(); // SAFETY: All of Linux's io_uring structs may be zero-initialized. unsafe { - ::core::ptr::write_bytes(s.as_mut_ptr(), 0, 1); + write_bytes(s.as_mut_ptr(), 0, 1); s.assume_init() } } @@ -1213,7 +1217,7 @@ impl Default for ioprio_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1221,7 +1225,7 @@ impl Default for len_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1229,7 +1233,7 @@ impl Default for off_or_addr2_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1237,7 +1241,7 @@ impl Default for addr_or_splice_off_in_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1245,7 +1249,7 @@ impl Default for addr3_or_cmd_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1253,7 +1257,7 @@ impl Default for op_flags_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1261,7 +1265,7 @@ impl Default for buf_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1269,7 +1273,7 @@ impl Default for splice_fd_in_or_file_index_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } @@ -1277,7 +1281,7 @@ impl Default for register_or_sqe_op_or_sqe_flags_union { #[inline] fn default() -> Self { // SAFETY: All of Linux's io_uring structs may be zero-initialized. - unsafe { ::core::mem::zeroed::() } + unsafe { zeroed::() } } } diff --git a/src/net/send_recv/msg.rs b/src/net/send_recv/msg.rs index 1575befc6..e63af3a34 100644 --- a/src/net/send_recv/msg.rs +++ b/src/net/send_recv/msg.rs @@ -4,12 +4,13 @@ use crate::backend::{self, c}; use crate::fd::{AsFd, BorrowedFd, OwnedFd}; -use crate::io; +use crate::io::{self, IoSlice, IoSliceMut}; use core::convert::{TryFrom, TryInto}; +use core::iter::{FromIterator, FusedIterator}; use core::marker::PhantomData; -use core::mem::{self, size_of, size_of_val}; -use core::ptr; +use core::mem::{size_of, size_of_val, take}; +use core::{ptr, slice}; use super::{RecvFlags, SendFlags, SocketAddrAny, SocketAddrV4, SocketAddrV6}; @@ -130,9 +131,8 @@ impl<'buf, 'slice, 'fd> SendAncillaryBuffer<'buf, 'slice, 'fd> { pub fn push(&mut self, msg: SendAncillaryMessage<'slice, 'fd>) -> bool { match msg { SendAncillaryMessage::ScmRights(fds) => { - let fds_bytes = unsafe { - core::slice::from_raw_parts(fds.as_ptr().cast::(), size_of_val(fds)) - }; + let fds_bytes = + unsafe { slice::from_raw_parts(fds.as_ptr().cast::(), size_of_val(fds)) }; self.push_ancillary(fds_bytes, c::SOL_SOCKET as _, c::SCM_RIGHTS as _) } } @@ -294,7 +294,7 @@ impl<'buf> AncillaryDrain<'buf> { let payload_len = msg.cmsg_len as usize - c::CMSG_LEN(0) as usize; // Get a mutable slice of the payload. - let payload: &'buf mut [u8] = core::slice::from_raw_parts_mut(payload, payload_len); + let payload: &'buf mut [u8] = slice::from_raw_parts_mut(payload, payload_len); // Determine what type it is. let (level, msg_type) = (msg.cmsg_level, msg.cmsg_type); @@ -356,7 +356,7 @@ impl<'buf> Iterator for AncillaryDrain<'buf> { .last() } - fn collect>(mut self) -> B + fn collect>(mut self) -> B where Self: Sized, { @@ -368,7 +368,7 @@ impl<'buf> Iterator for AncillaryDrain<'buf> { } } -impl core::iter::FusedIterator for AncillaryDrain<'_> {} +impl FusedIterator for AncillaryDrain<'_> {} /// `sendmsg(msghdr)`—Sends a message on a socket. /// @@ -393,7 +393,7 @@ impl core::iter::FusedIterator for AncillaryDrain<'_> {} #[inline] pub fn sendmsg_noaddr( socket: impl AsFd, - iov: &[io::IoSlice<'_>], + iov: &[IoSlice<'_>], control: &mut SendAncillaryBuffer<'_, '_, '_>, flags: SendFlags, ) -> io::Result { @@ -424,7 +424,7 @@ pub fn sendmsg_noaddr( pub fn sendmsg_v4( socket: impl AsFd, addr: &SocketAddrV4, - iov: &[io::IoSlice<'_>], + iov: &[IoSlice<'_>], control: &mut SendAncillaryBuffer<'_, '_, '_>, flags: SendFlags, ) -> io::Result { @@ -455,7 +455,7 @@ pub fn sendmsg_v4( pub fn sendmsg_v6( socket: impl AsFd, addr: &SocketAddrV6, - iov: &[io::IoSlice<'_>], + iov: &[IoSlice<'_>], control: &mut SendAncillaryBuffer<'_, '_, '_>, flags: SendFlags, ) -> io::Result { @@ -488,7 +488,7 @@ pub fn sendmsg_v6( pub fn sendmsg_unix( socket: impl AsFd, addr: &super::SocketAddrUnix, - iov: &[io::IoSlice<'_>], + iov: &[IoSlice<'_>], control: &mut SendAncillaryBuffer<'_, '_, '_>, flags: SendFlags, ) -> io::Result { @@ -519,7 +519,7 @@ pub fn sendmsg_unix( pub fn sendmsg_any( socket: impl AsFd, addr: Option<&SocketAddrAny>, - iov: &[io::IoSlice<'_>], + iov: &[IoSlice<'_>], control: &mut SendAncillaryBuffer<'_, '_, '_>, flags: SendFlags, ) -> io::Result { @@ -561,7 +561,7 @@ pub fn sendmsg_any( #[inline] pub fn recvmsg( socket: impl AsFd, - iov: &mut [io::IoSliceMut<'_>], + iov: &mut [IoSliceMut<'_>], control: &mut RecvAncillaryBuffer<'_>, flags: RecvFlags, ) -> io::Result { @@ -621,10 +621,10 @@ impl Iterator for AncillaryIter<'_, T> { } // Get the next item. - let item = unsafe { ptr::read_unaligned(self.data.as_ptr().cast::()) }; + let item = unsafe { self.data.as_ptr().cast::().read_unaligned() }; // Move forward. - let data = mem::take(&mut self.data); + let data = take(&mut self.data); self.data = &mut data[size_of::()..]; Some(item) @@ -644,7 +644,7 @@ impl Iterator for AncillaryIter<'_, T> { } } -impl core::iter::FusedIterator for AncillaryIter<'_, T> {} +impl FusedIterator for AncillaryIter<'_, T> {} impl ExactSizeIterator for AncillaryIter<'_, T> { fn len(&self) -> usize { @@ -662,12 +662,12 @@ impl DoubleEndedIterator for AncillaryIter<'_, T> { // Get the next item. let item = unsafe { let ptr = self.data.as_ptr().add(self.data.len() - size_of::()); - ptr::read_unaligned(ptr.cast::()) + ptr.cast::().read_unaligned() }; // Move forward. let len = self.data.len(); - let data = mem::take(&mut self.data); + let data = take(&mut self.data); self.data = &mut data[..len - size_of::()]; Some(item) @@ -677,7 +677,9 @@ impl DoubleEndedIterator for AncillaryIter<'_, T> { mod messages { use crate::backend::c; use core::convert::TryInto; + use core::iter::FusedIterator; use core::marker::PhantomData; + use core::mem::zeroed; use core::ptr::NonNull; /// An iterator over the messages in an ancillary buffer. @@ -698,7 +700,7 @@ mod messages { /// Create a new iterator over messages from a byte buffer. pub(super) fn new(buf: &'buf mut [u8]) -> Self { let msghdr = { - let mut h: c::msghdr = unsafe { core::mem::zeroed() }; + let mut h: c::msghdr = unsafe { zeroed() }; h.msg_control = buf.as_mut_ptr().cast(); h.msg_controllen = buf.len().try_into().expect("buffer too large for msghdr"); h @@ -747,5 +749,5 @@ mod messages { } } - impl core::iter::FusedIterator for Messages<'_> {} + impl FusedIterator for Messages<'_> {} } diff --git a/src/path/arg.rs b/src/path/arg.rs index b6b2a8a73..38c02420b 100644 --- a/src/path/arg.rs +++ b/src/path/arg.rs @@ -19,17 +19,13 @@ use core::mem::MaybeUninit; use core::{ptr, slice, str}; #[cfg(feature = "std")] use std::ffi::{OsStr, OsString}; -#[cfg(feature = "std")] -#[cfg(target_os = "hermit")] +#[cfg(all(feature = "std", target_os = "hermit"))] use std::os::hermit::ext::ffi::{OsStrExt, OsStringExt}; -#[cfg(feature = "std")] -#[cfg(unix)] +#[cfg(all(feature = "std", unix))] use std::os::unix::ffi::{OsStrExt, OsStringExt}; -#[cfg(feature = "std")] -#[cfg(target_os = "vxworks")] +#[cfg(all(feature = "std", target_os = "vxworks"))] use std::os::vxworks::ext::ffi::{OsStrExt, OsStringExt}; -#[cfg(feature = "std")] -#[cfg(target_os = "wasi")] +#[cfg(all(feature = "std", target_os = "wasi"))] use std::os::wasi::ffi::{OsStrExt, OsStringExt}; #[cfg(feature = "std")] use std::path::{Component, Components, Iter, Path, PathBuf}; diff --git a/src/path/dec_int.rs b/src/path/dec_int.rs index 5ba8be4fc..05086af43 100644 --- a/src/path/dec_int.rs +++ b/src/path/dec_int.rs @@ -8,20 +8,14 @@ use crate::backend::fd::{AsFd, AsRawFd}; use crate::ffi::CStr; -#[cfg(feature = "std")] -use core::fmt; use core::fmt::Write; use itoa::{Buffer, Integer}; -#[cfg(feature = "std")] -use std::ffi::OsStr; -#[cfg(feature = "std")] -#[cfg(unix)] +#[cfg(all(feature = "std", unix))] use std::os::unix::ffi::OsStrExt; -#[cfg(feature = "std")] -#[cfg(target_os = "wasi")] +#[cfg(all(feature = "std", target_os = "wasi"))] use std::os::wasi::ffi::OsStrExt; #[cfg(feature = "std")] -use std::path::Path; +use {core::fmt, std::ffi::OsStr, std::path::Path}; /// Format an integer into a decimal `Path` component, without constructing a /// temporary `PathBuf` or `String`. diff --git a/src/process/prctl.rs b/src/process/prctl.rs index a4e1e546c..9b9bd5bd7 100644 --- a/src/process/prctl.rs +++ b/src/process/prctl.rs @@ -6,9 +6,8 @@ #![allow(unsafe_code)] use core::convert::{TryFrom, TryInto}; -use core::mem::MaybeUninit; -use core::ptr::NonNull; -use core::{mem, ptr}; +use core::mem::{size_of, MaybeUninit}; +use core::ptr::{null, null_mut, NonNull}; use bitflags::bitflags; @@ -26,13 +25,13 @@ use crate::process::{Pid, RawPid}; #[inline] pub(crate) unsafe fn prctl_1arg(option: c_int) -> io::Result { - const NULL: *mut c_void = ptr::null_mut(); + 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 = ptr::null_mut(); + const NULL: *mut c_void = null_mut(); syscalls::prctl(option, arg2, NULL, NULL, NULL) } @@ -42,7 +41,7 @@ pub(crate) unsafe fn prctl_3args( arg2: *mut c_void, arg3: *mut c_void, ) -> io::Result { - syscalls::prctl(option, arg2, arg3, ptr::null_mut(), ptr::null_mut()) + syscalls::prctl(option, arg2, arg3, null_mut(), null_mut()) } #[inline] @@ -578,7 +577,7 @@ pub fn set_machine_check_memory_corruption_kill_policy( let (sub_operation, policy) = if let Some(policy) = policy { (PR_MCE_KILL_SET, policy as usize as *mut _) } else { - (PR_MCE_KILL_CLEAR, ptr::null_mut()) + (PR_MCE_KILL_CLEAR, null_mut()) }; unsafe { prctl_3args(PR_MCE_KILL, sub_operation as *mut _, policy) }.map(|_r| ()) @@ -654,7 +653,7 @@ pub unsafe fn set_virtual_memory_map_address( option: VirtualMemoryMapAddress, address: Option>, ) -> io::Result<()> { - let address = address.map_or_else(ptr::null_mut, NonNull::as_ptr); + let address = address.map_or_else(null_mut, NonNull::as_ptr); prctl_3args(PR_SET_MM, option as usize as *mut _, address).map(|_r| ()) } @@ -689,7 +688,7 @@ pub unsafe fn set_auxiliary_vector(auxv: &[*const c_void]) -> io::Result<()> { PR_SET_MM_AUXV as *mut _, auxv.as_ptr() as *mut _, auxv.len() as *mut _, - ptr::null_mut(), + null_mut(), ) .map(|_r| ()) } @@ -763,8 +762,8 @@ pub unsafe fn configure_virtual_memory_map(config: &PrctlMmMap) -> io::Result<() PR_SET_MM, PR_SET_MM_MAP as *mut _, config as *const PrctlMmMap as *mut _, - mem::size_of::() as *mut _, - ptr::null_mut(), + size_of::() as *mut _, + null_mut(), ) .map(|_r| ()) } @@ -798,7 +797,7 @@ pub enum PTracer { #[inline] pub fn set_ptracer(tracer: PTracer) -> io::Result<()> { let pid = match tracer { - PTracer::None => ptr::null_mut(), + PTracer::None => null_mut(), PTracer::Any => PR_SET_PTRACER_ANY as *mut _, PTracer::ProcessID(pid) => pid.as_raw_nonzero().get() as usize as *mut _, }; @@ -1123,7 +1122,7 @@ pub fn set_virtual_memory_region_name(region: &[u8], name: Option<&CStr>) -> io: PR_SET_VMA_ANON_NAME as *mut _, region.as_ptr() as *mut _, region.len() as *mut _, - name.map_or_else(ptr::null, CStr::as_ptr) as *mut _, + name.map_or_else(null, CStr::as_ptr) as *mut _, ) .map(|_r| ()) } diff --git a/src/process/procctl.rs b/src/process/procctl.rs index 244e565dc..b86afbd8d 100644 --- a/src/process/procctl.rs +++ b/src/process/procctl.rs @@ -5,7 +5,7 @@ #![allow(unsafe_code)] -use alloc::vec::Vec; +use alloc::{vec, vec::Vec}; use core::mem::MaybeUninit; use core::ptr; @@ -330,7 +330,7 @@ pub fn get_reaper_pids(process: ProcSelector) -> io::Result> { // Sadly no better way to guarantee that we get all the results than to // allocate ~8MB of memory.. const PID_MAX: usize = 99999; - let mut pids: Vec = alloc::vec![Default::default(); PID_MAX]; + let mut pids: Vec = vec![Default::default(); PID_MAX]; let mut pinfo = procctl_reaper_pids { rp_count: PID_MAX as _, rp_pad0: [0; 15], diff --git a/src/utils.rs b/src/utils.rs index 1a47833e6..df2ac315b 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -1,5 +1,9 @@ #![allow(dead_code)] +use core::ffi::c_void; +use core::mem::{align_of, size_of}; +use core::ptr::{null, null_mut, NonNull}; + /// Convert a `&T` into a `*const T` without using an `as`. #[inline] pub(crate) const fn as_ptr(t: &T) -> *const T { @@ -17,7 +21,7 @@ pub(crate) fn as_mut_ptr(t: &mut T) -> *mut T { pub(crate) const fn optional_as_ptr(t: Option<&T>) -> *const T { match t { Some(t) => t, - None => core::ptr::null(), + None => null(), } } @@ -26,21 +30,19 @@ pub(crate) const fn optional_as_ptr(t: Option<&T>) -> *const T { pub(crate) fn optional_as_mut_ptr(t: Option<&mut T>) -> *mut T { match t { Some(t) => t, - None => core::ptr::null_mut(), + None => null_mut(), } } /// Convert a `*mut c_void` to a `*mut T`, checking that it is not null, /// misaligned, or pointing to a region of memory that wraps around the address /// space. -pub(crate) fn check_raw_pointer(value: *mut core::ffi::c_void) -> Option> { - if (value as usize) - .checked_add(core::mem::size_of::()) - .is_none() - || (value as usize) % core::mem::align_of::() != 0 +pub(crate) fn check_raw_pointer(value: *mut c_void) -> Option> { + if (value as usize).checked_add(size_of::()).is_none() + || (value as usize) % align_of::() != 0 { return None; } - core::ptr::NonNull::new(value.cast()) + NonNull::new(value.cast()) }