From b807419234314665a7020869c25e99a7320dc8ca Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sat, 23 Sep 2023 09:23:18 -0600 Subject: [PATCH 001/140] Add a maintenance-status badge to the README [skip ci] --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index e172de2750..452d65466e 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,7 @@ [![Cirrus Build Status](https://api.cirrus-ci.com/github/nix-rust/nix.svg)](https://cirrus-ci.com/github/nix-rust/nix) [![crates.io](https://img.shields.io/crates/v/nix.svg)](https://crates.io/crates/nix) +[![maintenance-status](https://img.shields.io/badge/maintenance-looking--for--maintainer-orange.svg)](https://github.com/nix-rust/nix/issues/2132) [Documentation (Releases)](https://docs.rs/nix/) From 154a8a4a00fea72ada265de69485b67634fb49b9 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sat, 23 Sep 2023 10:14:59 -0600 Subject: [PATCH 002/140] Clippy cleanup: endless_loop (#2135) --- test/sys/test_socket.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index ed1686e87d..d540cfc116 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1302,7 +1302,7 @@ pub fn test_sendmsg_empty_cmsgs() { ) .unwrap(); - for _ in msg.cmsgs() { + if msg.cmsgs().next().is_some() { panic!("unexpected cmsg"); } assert!(!msg From 90e3c3a1ef9a62a0294bb61de4fcd54731a898bf Mon Sep 17 00:00:00 2001 From: William Woodruff Date: Sat, 30 Sep 2023 00:00:37 -0400 Subject: [PATCH 003/140] unistd: make getpeereid take AsFd rather than a raw FD (#2137) * unistd: make getpeereid take AsFd rather than a raw FD `AsFd` returns a `BorrowedFd` that is correct by construction, meaning that this API rejects more error states at the type level (such as passing in `fd = -1`). * CHANGELOG: record changes * unistd: pass AsFd impl by value * unistd: more AsFd usage * CHANGELOG: update changes --- CHANGELOG.md | 19 +++++++++++++++++-- src/sys/socket/sockopt.rs | 12 ++++++++++-- src/unistd.rs | 20 ++++++++++---------- test/test_unistd.rs | 39 ++++++++------------------------------- 4 files changed, 45 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a171afd68..a1a99728c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,21 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/). +## [Unreleased] - ReleaseDate + +### Changed + +- The following APIs now take an implementation of `AsFd` rather than a + `RawFd`: + + - `unistd::tcgetpgrp` + - `unistd::tcsetpgrp` + - `unistd::fpathconf` + - `unistd::ttyname` + - `unistd::getpeereid` + + ([#2137](https://github.com/nix-rust/nix/pull/2137)) + ## [0.27.1] - 2023-08-28 ### Fixed @@ -99,7 +114,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [0.26.3] - 2023-08-27 ### Fixed -- Fix: send `ETH_P_ALL` in htons format +- Fix: send `ETH_P_ALL` in htons format ([#1925](https://github.com/nix-rust/nix/pull/1925)) - Fix: `recvmsg` now sets the length of the received `sockaddr_un` field correctly on Linux platforms. ([#2041](https://github.com/nix-rust/nix/pull/2041)) @@ -187,7 +202,7 @@ This project adheres to [Semantic Versioning](https://semver.org/). ([#1824](https://github.com/nix-rust/nix/pull/1824)) - Workaround XNU bug causing netmasks returned by `getifaddrs` to misbehave. ([#1788](https://github.com/nix-rust/nix/pull/1788)) - + ### Removed - Removed deprecated error constants and conversions. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 44f3ebbc1d..3192df1fa6 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -550,7 +550,11 @@ cfg_if! { TcpMaxSeg, GetOnly, libc::IPPROTO_TCP, libc::TCP_MAXSEG, u32); } } -#[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "redox")))] +#[cfg(not(any( + target_os = "openbsd", + target_os = "haiku", + target_os = "redox" +)))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -572,7 +576,11 @@ sockopt_impl!( libc::TCP_REPAIR, u32 ); -#[cfg(not(any(target_os = "openbsd", target_os = "haiku", target_os = "redox")))] +#[cfg(not(any( + target_os = "openbsd", + target_os = "haiku", + target_os = "redox" +)))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] diff --git a/src/unistd.rs b/src/unistd.rs index bb9f1c1f67..d950ad6ee1 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -366,8 +366,8 @@ feature! { /// Get the group process id (GPID) of the foreground process group on the /// terminal associated to file descriptor (FD). #[inline] -pub fn tcgetpgrp(fd: c_int) -> Result { - let res = unsafe { libc::tcgetpgrp(fd) }; +pub fn tcgetpgrp(fd: F) -> Result { + let res = unsafe { libc::tcgetpgrp(fd.as_fd().as_raw_fd()) }; Errno::result(res).map(Pid) } /// Set the terminal foreground process group (see @@ -376,8 +376,8 @@ pub fn tcgetpgrp(fd: c_int) -> Result { /// Get the group process id (PGID) to the foreground process group on the /// terminal associated to file descriptor (FD). #[inline] -pub fn tcsetpgrp(fd: c_int, pgrp: Pid) -> Result<()> { - let res = unsafe { libc::tcsetpgrp(fd, pgrp.into()) }; +pub fn tcsetpgrp(fd: F, pgrp: Pid) -> Result<()> { + let res = unsafe { libc::tcsetpgrp(fd.as_fd().as_raw_fd(), pgrp.into()) }; Errno::result(res).map(drop) } } @@ -2192,10 +2192,10 @@ pub enum PathconfVar { /// - `Ok(None)`: the variable has no limit (for limit variables) or is /// unsupported (for option variables) /// - `Err(x)`: an error occurred -pub fn fpathconf(fd: RawFd, var: PathconfVar) -> Result> { +pub fn fpathconf(fd: F, var: PathconfVar) -> Result> { let raw = unsafe { Errno::clear(); - libc::fpathconf(fd, var as c_int) + libc::fpathconf(fd.as_fd().as_raw_fd(), var as c_int) }; if raw == -1 { if errno::errno() == 0 { @@ -3913,12 +3913,12 @@ feature! { /// Get the name of the terminal device that is open on file descriptor fd /// (see [`ttyname(3)`](https://man7.org/linux/man-pages/man3/ttyname.3.html)). #[cfg(not(target_os = "fuchsia"))] -pub fn ttyname(fd: RawFd) -> Result { +pub fn ttyname(fd: F) -> Result { const PATH_MAX: usize = libc::PATH_MAX as usize; let mut buf = vec![0_u8; PATH_MAX]; let c_buf = buf.as_mut_ptr() as *mut libc::c_char; - let ret = unsafe { libc::ttyname_r(fd, c_buf, buf.len()) }; + let ret = unsafe { libc::ttyname_r(fd.as_fd().as_raw_fd(), c_buf, buf.len()) }; if ret != 0 { return Err(Errno::from_i32(ret)); } @@ -3943,11 +3943,11 @@ feature! { target_os = "netbsd", target_os = "dragonfly", ))] -pub fn getpeereid(fd: RawFd) -> Result<(Uid, Gid)> { +pub fn getpeereid(fd: F) -> Result<(Uid, Gid)> { let mut uid = 1; let mut gid = 1; - let ret = unsafe { libc::getpeereid(fd, &mut uid, &mut gid) }; + let ret = unsafe { libc::getpeereid(fd.as_fd().as_raw_fd(), &mut uid, &mut gid) }; Errno::result(ret).map(|_| (Uid(uid), Gid(gid))) } diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 10284e4127..80abdc436d 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -635,7 +635,7 @@ fn test_acct() { fn test_fpathconf_limited() { let f = tempfile().unwrap(); // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test - let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX); + let path_max = fpathconf(f, PathconfVar::PATH_MAX); assert!( path_max .expect("fpathconf failed") @@ -1230,9 +1230,11 @@ fn test_ttyname() { grantpt(&fd).expect("grantpt failed"); unlockpt(&fd).expect("unlockpt failed"); let sname = unsafe { ptsname(&fd) }.expect("ptsname failed"); - let fds = open(Path::new(&sname), OFlag::O_RDWR, stat::Mode::empty()) + let fds = fs::OpenOptions::new() + .read(true) + .write(true) + .open(Path::new(&sname)) .expect("open failed"); - assert!(fds > 0); let name = ttyname(fds).expect("ttyname failed"); assert!(name.starts_with("/dev")); @@ -1242,18 +1244,7 @@ fn test_ttyname() { #[cfg(not(any(target_os = "redox", target_os = "fuchsia")))] fn test_ttyname_not_pty() { let fd = File::open("/dev/zero").unwrap(); - assert!(fd.as_raw_fd() > 0); - assert_eq!(ttyname(fd.as_raw_fd()), Err(Errno::ENOTTY)); -} - -#[test] -#[cfg(not(any( - target_os = "redox", - target_os = "fuchsia", - target_os = "haiku" -)))] -fn test_ttyname_invalid_fd() { - assert_eq!(ttyname(-1), Err(Errno::EBADF)); + assert_eq!(ttyname(fd), Err(Errno::ENOTTY)); } #[test] @@ -1269,8 +1260,8 @@ fn test_getpeereid() { use std::os::unix::net::UnixStream; let (sock_a, sock_b) = UnixStream::pair().unwrap(); - let (uid_a, gid_a) = getpeereid(sock_a.as_raw_fd()).unwrap(); - let (uid_b, gid_b) = getpeereid(sock_b.as_raw_fd()).unwrap(); + let (uid_a, gid_a) = getpeereid(sock_a).unwrap(); + let (uid_b, gid_b) = getpeereid(sock_b).unwrap(); let uid = geteuid(); let gid = getegid(); @@ -1281,20 +1272,6 @@ fn test_getpeereid() { assert_eq!(gid_a, gid_b); } -#[test] -#[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly", -))] -fn test_getpeereid_invalid_fd() { - // getpeereid is not POSIX, so error codes are inconsistent between different Unices. - getpeereid(-1).expect_err("assertion failed"); -} - #[test] #[cfg(not(target_os = "redox"))] fn test_faccessat_none_not_existing() { From 2ab317255ed7591718cc4145e5fcdcac807896a1 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Sat, 30 Sep 2023 00:02:31 -0400 Subject: [PATCH 004/140] Add #[inline] to fspacectl to prevent linker errors with dylibs and --no-allow-shlib-undefined (#2122) --- src/fcntl.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/fcntl.rs b/src/fcntl.rs index 9bfecda5ac..00c83a18c7 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -849,6 +849,7 @@ impl SpacectlRange { /// assert_eq!(buf, b"012\0\0\0\0\0\09abcdef"); /// ``` #[cfg(target_os = "freebsd")] +#[inline] // Delays codegen, preventing linker errors with dylibs and --no-allow-shlib-undefined pub fn fspacectl(fd: RawFd, range: SpacectlRange) -> Result { let mut rqsr = libc::spacectl_range { r_offset: range.0, @@ -897,6 +898,7 @@ pub fn fspacectl(fd: RawFd, range: SpacectlRange) -> Result { /// assert_eq!(buf, b"012\0\0\0\0\0\09abcdef"); /// ``` #[cfg(target_os = "freebsd")] +#[inline] // Delays codegen, preventing linker errors with dylibs and --no-allow-shlib-undefined pub fn fspacectl_all( fd: RawFd, offset: libc::off_t, From 8ad064d7b9df86b66090539b2f509c179aa9c15a Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Sat, 30 Sep 2023 08:52:11 +0100 Subject: [PATCH 005/140] feat: I/O safety `pipe`, `pipe2` & `write` (#2100) --- src/pty.rs | 4 ++-- src/sys/epoll.rs | 4 ++-- src/sys/select.rs | 21 +++++--------------- src/sys/socket/mod.rs | 4 ++-- src/unistd.rs | 26 +++++++++++++++---------- test/sys/test_select.rs | 10 +++------- test/sys/test_socket.rs | 16 ++++++---------- test/sys/test_sockopt.rs | 6 +++--- test/sys/test_termios.rs | 2 +- test/sys/test_uio.rs | 24 +++++++---------------- test/test_fcntl.rs | 41 +++++++++++++++------------------------- test/test_poll.rs | 12 ++++-------- test/test_pty.rs | 14 +++++++------- test/test_sendfile.rs | 23 ++++------------------ test/test_unistd.rs | 16 ++++++++++------ 15 files changed, 87 insertions(+), 136 deletions(-) diff --git a/src/pty.rs b/src/pty.rs index 455828b703..28c1f4fc73 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -71,7 +71,7 @@ impl io::Read for PtyMaster { impl io::Write for PtyMaster { fn write(&mut self, buf: &[u8]) -> io::Result { - unistd::write(self.0.as_raw_fd(), buf).map_err(io::Error::from) + unistd::write(&self.0, buf).map_err(io::Error::from) } fn flush(&mut self) -> io::Result<()> { Ok(()) @@ -86,7 +86,7 @@ impl io::Read for &PtyMaster { impl io::Write for &PtyMaster { fn write(&mut self, buf: &[u8]) -> io::Result { - unistd::write(self.0.as_raw_fd(), buf).map_err(io::Error::from) + unistd::write(&self.0, buf).map_err(io::Error::from) } fn flush(&mut self) -> io::Result<()> { Ok(()) diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index 36f9c17d0e..acb08d0787 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -73,7 +73,7 @@ impl EpollEvent { /// ``` /// # use nix::sys::{epoll::{Epoll, EpollEvent, EpollFlags, EpollCreateFlags}, eventfd::{eventfd, EfdFlags}}; /// # use nix::unistd::write; -/// # use std::os::unix::io::{OwnedFd, FromRawFd, AsRawFd, AsFd}; +/// # use std::os::unix::io::{OwnedFd, FromRawFd, AsFd}; /// # use std::time::{Instant, Duration}; /// # fn main() -> nix::Result<()> { /// const DATA: u64 = 17; @@ -87,7 +87,7 @@ impl EpollEvent { /// epoll.add(&eventfd, EpollEvent::new(EpollFlags::EPOLLIN,DATA))?; /// /// // Arm eventfd & Time wait -/// write(eventfd.as_raw_fd(), &1u64.to_ne_bytes())?; +/// write(&eventfd, &1u64.to_ne_bytes())?; /// let now = Instant::now(); /// /// // Wait on event diff --git a/src/sys/select.rs b/src/sys/select.rs index 0e2193b130..4c5521be90 100644 --- a/src/sys/select.rs +++ b/src/sys/select.rs @@ -322,8 +322,8 @@ where mod tests { use super::*; use crate::sys::time::{TimeVal, TimeValLike}; - use crate::unistd::{close, pipe, write}; - use std::os::unix::io::{FromRawFd, OwnedFd, RawFd}; + use crate::unistd::{pipe, write}; + use std::os::unix::io::RawFd; #[test] fn fdset_insert() { @@ -466,12 +466,9 @@ mod tests { #[test] fn test_select() { let (r1, w1) = pipe().unwrap(); - let r1 = unsafe { OwnedFd::from_raw_fd(r1) }; - let w1 = unsafe { OwnedFd::from_raw_fd(w1) }; let (r2, _w2) = pipe().unwrap(); - let r2 = unsafe { OwnedFd::from_raw_fd(r2) }; - write(w1.as_raw_fd(), b"hi!").unwrap(); + write(&w1, b"hi!").unwrap(); let mut fd_set = FdSet::new(); fd_set.insert(&r1); fd_set.insert(&r2); @@ -483,18 +480,14 @@ mod tests { ); assert!(fd_set.contains(&r1)); assert!(!fd_set.contains(&r2)); - close(_w2).unwrap(); } #[test] fn test_select_nfds() { let (r1, w1) = pipe().unwrap(); let (r2, _w2) = pipe().unwrap(); - let r1 = unsafe { OwnedFd::from_raw_fd(r1) }; - let w1 = unsafe { OwnedFd::from_raw_fd(w1) }; - let r2 = unsafe { OwnedFd::from_raw_fd(r2) }; - write(w1.as_raw_fd(), b"hi!").unwrap(); + write(&w1, b"hi!").unwrap(); let mut fd_set = FdSet::new(); fd_set.insert(&r1); fd_set.insert(&r2); @@ -521,16 +514,13 @@ mod tests { } assert!(fd_set.contains(&r1)); assert!(!fd_set.contains(&r2)); - close(_w2).unwrap(); } #[test] fn test_select_nfds2() { let (r1, w1) = pipe().unwrap(); - write(w1, b"hi!").unwrap(); + write(&w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); - let r1 = unsafe { OwnedFd::from_raw_fd(r1) }; - let r2 = unsafe { OwnedFd::from_raw_fd(r2) }; let mut fd_set = FdSet::new(); fd_set.insert(&r1); fd_set.insert(&r2); @@ -549,6 +539,5 @@ mod tests { ); assert!(fd_set.contains(&r1)); assert!(!fd_set.contains(&r2)); - close(_w2).unwrap(); } } diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 78dd617c55..b56d694ab5 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1479,7 +1479,7 @@ impl<'a> ControlMessage<'a> { /// let (r, w) = pipe().unwrap(); /// /// let iov = [IoSlice::new(b"hello")]; -/// let fds = [r]; +/// let fds = [r.as_raw_fd()]; /// let cmsg = ControlMessage::ScmRights(&fds); /// sendmsg::<()>(fd1.as_raw_fd(), &iov, &[cmsg], MsgFlags::empty(), None).unwrap(); /// ``` @@ -1496,7 +1496,7 @@ impl<'a> ControlMessage<'a> { /// let (r, w) = pipe().unwrap(); /// /// let iov = [IoSlice::new(b"hello")]; -/// let fds = [r]; +/// let fds = [r.as_raw_fd()]; /// let cmsg = ControlMessage::ScmRights(&fds); /// sendmsg(fd.as_raw_fd(), &iov, &[cmsg], MsgFlags::empty(), Some(&localhost)).unwrap(); /// ``` diff --git a/src/unistd.rs b/src/unistd.rs index d950ad6ee1..066f50e5aa 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -35,7 +35,7 @@ use std::ffi::{CString, OsStr}; use std::os::unix::ffi::OsStrExt; use std::os::unix::ffi::OsStringExt; use std::os::unix::io::RawFd; -use std::os::unix::io::{AsFd, AsRawFd}; +use std::os::unix::io::{AsFd, AsRawFd, OwnedFd}; use std::path::PathBuf; use std::{fmt, mem, ptr}; @@ -260,7 +260,7 @@ impl ForkResult { /// } /// Ok(ForkResult::Child) => { /// // Unsafe to use `println!` (or `unwrap`) here. See Safety. -/// write(libc::STDOUT_FILENO, "I'm a new child process\n".as_bytes()).ok(); +/// write(std::io::stdout(), "I'm a new child process\n".as_bytes()).ok(); /// unsafe { libc::_exit(0) }; /// } /// Err(_) => println!("Fork failed"), @@ -1115,9 +1115,13 @@ pub fn read(fd: RawFd, buf: &mut [u8]) -> Result { /// Write to a raw file descriptor. /// /// See also [write(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html) -pub fn write(fd: RawFd, buf: &[u8]) -> Result { +pub fn write(fd: Fd, buf: &[u8]) -> Result { let res = unsafe { - libc::write(fd, buf.as_ptr() as *const c_void, buf.len() as size_t) + libc::write( + fd.as_fd().as_raw_fd(), + buf.as_ptr() as *const c_void, + buf.len() as size_t, + ) }; Errno::result(res).map(|r| r as usize) @@ -1189,14 +1193,15 @@ pub fn lseek64( /// Create an interprocess channel. /// /// See also [pipe(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pipe.html) -pub fn pipe() -> std::result::Result<(RawFd, RawFd), Error> { - let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit(); +pub fn pipe() -> std::result::Result<(OwnedFd, OwnedFd), Error> { + let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit(); let res = unsafe { libc::pipe(fds.as_mut_ptr() as *mut c_int) }; Error::result(res)?; - unsafe { Ok((fds.assume_init()[0], fds.assume_init()[1])) } + let [read, write] = unsafe { fds.assume_init() }; + Ok((read, write)) } feature! { @@ -1230,15 +1235,16 @@ feature! { target_os = "openbsd", target_os = "solaris" ))] -pub fn pipe2(flags: OFlag) -> Result<(RawFd, RawFd)> { - let mut fds = mem::MaybeUninit::<[c_int; 2]>::uninit(); +pub fn pipe2(flags: OFlag) -> Result<(OwnedFd, OwnedFd)> { + let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit(); let res = unsafe { libc::pipe2(fds.as_mut_ptr() as *mut c_int, flags.bits()) }; Errno::result(res)?; - unsafe { Ok((fds.assume_init()[0], fds.assume_init()[1])) } + let [read, write] = unsafe { fds.assume_init() }; + Ok((read, write)) } /// Truncate a file to a specified length diff --git a/test/sys/test_select.rs b/test/sys/test_select.rs index 79f75de3b4..6b4d1c54c1 100644 --- a/test/sys/test_select.rs +++ b/test/sys/test_select.rs @@ -2,17 +2,15 @@ use nix::sys::select::*; use nix::sys::signal::SigSet; use nix::sys::time::{TimeSpec, TimeValLike}; use nix::unistd::{pipe, write}; -use std::os::unix::io::{AsRawFd, BorrowedFd, FromRawFd, OwnedFd}; +use std::os::unix::io::{AsRawFd, BorrowedFd}; #[test] pub fn test_pselect() { let _mtx = crate::SIGNAL_MTX.lock(); let (r1, w1) = pipe().unwrap(); - write(w1, b"hi!").unwrap(); - let r1 = unsafe { OwnedFd::from_raw_fd(r1) }; + write(&w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); - let r2 = unsafe { OwnedFd::from_raw_fd(r2) }; let mut fd_set = FdSet::new(); fd_set.insert(&r1); @@ -31,10 +29,8 @@ pub fn test_pselect() { #[test] pub fn test_pselect_nfds2() { let (r1, w1) = pipe().unwrap(); - write(w1, b"hi!").unwrap(); - let r1 = unsafe { OwnedFd::from_raw_fd(r1) }; + write(&w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); - let r2 = unsafe { OwnedFd::from_raw_fd(r2) }; let mut fd_set = FdSet::new(); fd_set.insert(&r1); diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index d540cfc116..12615b422f 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -200,7 +200,7 @@ pub fn test_socketpair() { SockFlag::empty(), ) .unwrap(); - write(fd1.as_raw_fd(), b"hello").unwrap(); + write(&fd1, b"hello").unwrap(); let mut buf = [0; 5]; read(fd2.as_raw_fd(), &mut buf).unwrap(); @@ -757,7 +757,7 @@ pub fn test_scm_rights() { { let iov = [IoSlice::new(b"hello")]; - let fds = [r]; + let fds = [r.as_raw_fd()]; let cmsg = ControlMessage::ScmRights(&fds); assert_eq!( sendmsg::<()>( @@ -770,7 +770,6 @@ pub fn test_scm_rights() { .unwrap(), 5 ); - close(r).unwrap(); } { @@ -803,12 +802,11 @@ pub fn test_scm_rights() { let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works - write(w.as_raw_fd(), b"world").unwrap(); + write(&w, b"world").unwrap(); let mut buf = [0u8; 5]; read(received_r.as_raw_fd(), &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); - close(w).unwrap(); } // Disable the test on emulated platforms due to not enabled support of AF_ALG in QEMU from rust cross @@ -1451,7 +1449,7 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { gid: getgid().as_raw(), } .into(); - let fds = [r]; + let fds = [r.as_raw_fd()]; let cmsgs = [ ControlMessage::ScmCredentials(&cred), ControlMessage::ScmRights(&fds), @@ -1467,7 +1465,6 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { .unwrap(), 5 ); - close(r).unwrap(); } { @@ -1510,12 +1507,11 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works - write(w.as_raw_fd(), b"world").unwrap(); + write(&w, b"world").unwrap(); let mut buf = [0u8; 5]; read(received_r.as_raw_fd(), &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); - close(w).unwrap(); } // Test creating and using named unix domain sockets @@ -1548,7 +1544,7 @@ pub fn test_named_unixdomain() { ) .expect("socket failed"); connect(s2.as_raw_fd(), &sockaddr).expect("connect failed"); - write(s2.as_raw_fd(), b"hello").expect("write failed"); + write(&s2, b"hello").expect("write failed"); }); let s3 = accept(s1.as_raw_fd()).expect("accept failed"); diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 0e34917325..90432f9ab9 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -5,7 +5,7 @@ use nix::sys::socket::{ SockProtocol, SockType, }; use rand::{thread_rng, Rng}; -use std::os::unix::io::AsRawFd; +use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd}; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. #[cfg(any(target_os = "dragonfly", target_os = "freebsd",))] @@ -151,7 +151,8 @@ fn test_so_tcp_maxseg() { .unwrap(); connect(ssock.as_raw_fd(), &sock_addr).unwrap(); let rsess = accept(rsock.as_raw_fd()).unwrap(); - write(rsess, b"hello").unwrap(); + let rsess = unsafe { OwnedFd::from_raw_fd(rsess) }; + write(&rsess, b"hello").unwrap(); let actual = getsockopt(&ssock, sockopt::TcpMaxSeg).unwrap(); // Actual max segment size takes header lengths into account, max IPv4 options (60 bytes) + max // TCP options (40 bytes) are subtracted from the requested maximum as a lower boundary. @@ -185,7 +186,6 @@ fn test_so_type() { #[test] fn test_so_type_unknown() { use nix::errno::Errno; - use std::os::unix::io::{FromRawFd, OwnedFd}; require_capability!("test_so_type", CAP_NET_RAW); let raw_fd = unsafe { libc::socket(libc::AF_PACKET, libc::SOCK_PACKET, 0) }; diff --git a/test/sys/test_termios.rs b/test/sys/test_termios.rs index 83919378a7..21bb8c61ef 100644 --- a/test/sys/test_termios.rs +++ b/test/sys/test_termios.rs @@ -11,7 +11,7 @@ use nix::unistd::{read, write}; fn write_all(f: Fd, buf: &[u8]) { let mut len = 0; while len < buf.len() { - len += write(f.as_fd().as_raw_fd(), &buf[len..]).unwrap(); + len += write(f.as_fd(), &buf[len..]).unwrap(); } } diff --git a/test/sys/test_uio.rs b/test/sys/test_uio.rs index fc09465f19..fe0a3bde07 100644 --- a/test/sys/test_uio.rs +++ b/test/sys/test_uio.rs @@ -4,7 +4,7 @@ use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; use std::fs::OpenOptions; use std::io::IoSlice; -use std::os::unix::io::{FromRawFd, OwnedFd}; +use std::os::unix::io::AsRawFd; use std::{cmp, iter}; #[cfg(not(target_os = "redox"))] @@ -44,22 +44,17 @@ fn test_writev() { // FileDesc will close its filedesc (reader). let mut read_buf: Vec = iter::repeat(0u8).take(128 * 16).collect(); - // Temporary workaround to cope with the existing RawFd pipe(2), should be - // removed when pipe(2) becomes I/O-safe. - let writer = unsafe { OwnedFd::from_raw_fd(writer) }; - // Blocking io, should write all data. let write_res = writev(&writer, &iovecs); let written = write_res.expect("couldn't write"); // Check whether we written all data assert_eq!(to_write.len(), written); - let read_res = read(reader, &mut read_buf[..]); + let read_res = read(reader.as_raw_fd(), &mut read_buf[..]); let read = read_res.expect("couldn't read"); // Check we have read as much as we written assert_eq!(read, written); // Check equality of written and read data assert_eq!(&to_write, &read_buf); - close(reader).expect("closed reader"); } #[test] @@ -92,10 +87,6 @@ fn test_readv() { // Blocking io, should write all data. write(writer, &to_write).expect("write failed"); - // Temporary workaround to cope with the existing RawFd pipe(2), should be - // removed when pipe(2) becomes I/O-safe. - let reader = unsafe { OwnedFd::from_raw_fd(reader) }; - let read = readv(&reader, &mut iovecs[..]).expect("read failed"); // Check whether we've read all data assert_eq!(to_write.len(), read); @@ -108,7 +99,6 @@ fn test_readv() { assert_eq!(read_buf.len(), to_write.len()); // Check equality of written and read data assert_eq!(&read_buf, &to_write); - close(writer).expect("couldn't close writer"); } #[test] @@ -230,6 +220,7 @@ fn test_process_vm_readv() { use nix::sys::signal::*; use nix::sys::wait::*; use nix::unistd::ForkResult::*; + use std::os::unix::io::AsRawFd; require_capability!("test_process_vm_readv", CAP_SYS_PTRACE); let _m = crate::FORK_MTX.lock(); @@ -241,10 +232,10 @@ fn test_process_vm_readv() { let (r, w) = pipe().unwrap(); match unsafe { fork() }.expect("Error: Fork Failed") { Parent { child } => { - close(w).unwrap(); + drop(w); // wait for child - read(r, &mut [0u8]).unwrap(); - close(r).unwrap(); + read(r.as_raw_fd(), &mut [0u8]).unwrap(); + drop(r); let ptr = vector.as_ptr() as usize; let remote_iov = RemoteIoVec { base: ptr, len: 5 }; @@ -263,12 +254,11 @@ fn test_process_vm_readv() { assert_eq!(20u8, buf.iter().sum()); } Child => { - let _ = close(r); + drop(r); for i in &mut vector { *i += 1; } let _ = write(w, b"\0"); - let _ = close(w); loop { pause(); } diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 5fef04ba9b..f216458e8a 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -280,7 +280,7 @@ mod linux_android { use std::os::unix::prelude::*; use nix::fcntl::*; - use nix::unistd::{close, pipe, read, write}; + use nix::unistd::{pipe, read, write}; use tempfile::tempfile; #[cfg(target_os = "linux")] @@ -299,7 +299,7 @@ mod linux_android { let res = splice( tmp.as_raw_fd(), Some(&mut offset), - wr, + wr.as_raw_fd(), None, 2, SpliceFFlags::empty(), @@ -309,12 +309,9 @@ mod linux_android { assert_eq!(2, res); let mut buf = [0u8; 1024]; - assert_eq!(2, read(rd, &mut buf).unwrap()); + assert_eq!(2, read(rd.as_raw_fd(), &mut buf).unwrap()); assert_eq!(b"f1", &buf[0..2]); assert_eq!(7, offset); - - close(rd).unwrap(); - close(wr).unwrap(); } #[test] @@ -323,24 +320,21 @@ mod linux_android { let (rd2, wr2) = pipe().unwrap(); write(wr1, b"abc").unwrap(); - let res = tee(rd1, wr2, 2, SpliceFFlags::empty()).unwrap(); + let res = + tee(rd1.as_raw_fd(), wr2.as_raw_fd(), 2, SpliceFFlags::empty()) + .unwrap(); assert_eq!(2, res); let mut buf = [0u8; 1024]; // Check the tee'd bytes are at rd2. - assert_eq!(2, read(rd2, &mut buf).unwrap()); + assert_eq!(2, read(rd2.as_raw_fd(), &mut buf).unwrap()); assert_eq!(b"ab", &buf[0..2]); // Check all the bytes are still at rd1. - assert_eq!(3, read(rd1, &mut buf).unwrap()); + assert_eq!(3, read(rd1.as_raw_fd(), &mut buf).unwrap()); assert_eq!(b"abc", &buf[0..3]); - - close(rd1).unwrap(); - close(wr1).unwrap(); - close(rd2).unwrap(); - close(wr2).unwrap(); } #[test] @@ -351,17 +345,15 @@ mod linux_android { let buf2 = b"defghi"; let iovecs = [IoSlice::new(&buf1[0..3]), IoSlice::new(&buf2[0..3])]; - let res = vmsplice(wr, &iovecs[..], SpliceFFlags::empty()).unwrap(); + let res = vmsplice(wr.as_raw_fd(), &iovecs[..], SpliceFFlags::empty()) + .unwrap(); assert_eq!(6, res); // Check the bytes can be read at rd. let mut buf = [0u8; 32]; - assert_eq!(6, read(rd, &mut buf).unwrap()); + assert_eq!(6, read(rd.as_raw_fd(), &mut buf).unwrap()); assert_eq!(b"abcdef", &buf[0..6]); - - close(rd).unwrap(); - close(wr).unwrap(); } #[cfg(target_os = "linux")] @@ -494,7 +486,7 @@ mod test_posix_fadvise { use nix::errno::Errno; use nix::fcntl::*; use nix::unistd::pipe; - use std::os::unix::io::{AsRawFd, RawFd}; + use std::os::unix::io::AsRawFd; use tempfile::NamedTempFile; #[test] @@ -509,7 +501,7 @@ mod test_posix_fadvise { fn test_errno() { let (rd, _wr) = pipe().unwrap(); let res = posix_fadvise( - rd as RawFd, + rd.as_raw_fd(), 0, 100, PosixFadviseAdvice::POSIX_FADV_WILLNEED, @@ -532,10 +524,7 @@ mod test_posix_fallocate { use nix::errno::Errno; use nix::fcntl::*; use nix::unistd::pipe; - use std::{ - io::Read, - os::unix::io::{AsRawFd, RawFd}, - }; + use std::{io::Read, os::unix::io::AsRawFd}; use tempfile::NamedTempFile; #[test] @@ -565,7 +554,7 @@ mod test_posix_fallocate { #[test] fn errno() { let (rd, _wr) = pipe().unwrap(); - let err = posix_fallocate(rd as RawFd, 0, 100).unwrap_err(); + let err = posix_fallocate(rd.as_raw_fd(), 0, 100).unwrap_err(); match err { Errno::EINVAL | Errno::ENODEV | Errno::ESPIPE | Errno::EBADF => (), errno => panic!("unexpected errno {errno}",), diff --git a/test/test_poll.rs b/test/test_poll.rs index 045ccd3df1..30207c95ea 100644 --- a/test/test_poll.rs +++ b/test/test_poll.rs @@ -1,9 +1,9 @@ use nix::{ errno::Errno, poll::{poll, PollFd, PollFlags}, - unistd::{close, pipe, write}, + unistd::{pipe, write}, }; -use std::os::unix::io::{BorrowedFd, FromRawFd, OwnedFd}; +use std::os::unix::io::BorrowedFd; macro_rules! loop_while_eintr { ($poll_expr: expr) => { @@ -20,7 +20,6 @@ macro_rules! loop_while_eintr { #[test] fn test_poll() { let (r, w) = pipe().unwrap(); - let r = unsafe { OwnedFd::from_raw_fd(r) }; let mut fds = [PollFd::new(&r, PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout @@ -28,13 +27,12 @@ fn test_poll() { assert_eq!(nfds, 0); assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN)); - write(w, b".").unwrap(); + write(&w, b".").unwrap(); // Poll a readable pipe. Should return an event. let nfds = poll(&mut fds, 100).unwrap(); assert_eq!(nfds, 1); assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN)); - close(w).unwrap(); } // ppoll(2) is the same as poll except for how it handles timeouts and signals. @@ -54,7 +52,6 @@ fn test_ppoll() { let timeout = TimeSpec::milliseconds(1); let (r, w) = pipe().unwrap(); - let r = unsafe { OwnedFd::from_raw_fd(r) }; let mut fds = [PollFd::new(&r, PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout @@ -63,13 +60,12 @@ fn test_ppoll() { assert_eq!(nfds, 0); assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN)); - write(w, b".").unwrap(); + write(&w, b".").unwrap(); // Poll a readable pipe. Should return an event. let nfds = ppoll(&mut fds, Some(timeout), None).unwrap(); assert_eq!(nfds, 1); assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN)); - close(w).unwrap(); } #[test] diff --git a/test/test_pty.rs b/test/test_pty.rs index 4cc6620c3c..9b5c500e45 100644 --- a/test/test_pty.rs +++ b/test/test_pty.rs @@ -1,9 +1,9 @@ use std::fs::File; -use std::io::{Read, Write}; +use std::io::{stdout, Read, Write}; use std::os::unix::prelude::*; use std::path::Path; -use libc::{_exit, STDOUT_FILENO}; +use libc::_exit; use nix::fcntl::{open, OFlag}; use nix::pty::*; use nix::sys::stat; @@ -185,7 +185,7 @@ fn test_openpty() { // Writing to one should be readable on the other one let string = "foofoofoo\n"; let mut buf = [0u8; 10]; - write(pty.master.as_raw_fd(), string.as_bytes()).unwrap(); + write(&pty.master, string.as_bytes()).unwrap(); crate::read_exact(&pty.slave, &mut buf); assert_eq!(&buf, string.as_bytes()); @@ -199,7 +199,7 @@ fn test_openpty() { let string2 = "barbarbarbar\n"; let echoed_string2 = "barbarbarbar\r\n"; let mut buf = [0u8; 14]; - write(pty.slave.as_raw_fd(), string2.as_bytes()).unwrap(); + write(&pty.slave, string2.as_bytes()).unwrap(); crate::read_exact(&pty.master, &mut buf); assert_eq!(&buf, echoed_string2.as_bytes()); @@ -224,7 +224,7 @@ fn test_openpty_with_termios() { // Writing to one should be readable on the other one let string = "foofoofoo\n"; let mut buf = [0u8; 10]; - write(pty.master.as_raw_fd(), string.as_bytes()).unwrap(); + write(&pty.master, string.as_bytes()).unwrap(); crate::read_exact(&pty.slave, &mut buf); assert_eq!(&buf, string.as_bytes()); @@ -237,7 +237,7 @@ fn test_openpty_with_termios() { let string2 = "barbarbarbar\n"; let echoed_string2 = "barbarbarbar\n"; let mut buf = [0u8; 13]; - write(pty.slave.as_raw_fd(), string2.as_bytes()).unwrap(); + write(&pty.slave, string2.as_bytes()).unwrap(); crate::read_exact(&pty.master, &mut buf); assert_eq!(&buf, echoed_string2.as_bytes()); @@ -258,7 +258,7 @@ fn test_forkpty() { let pty = unsafe { forkpty(None, None).unwrap() }; match pty.fork_result { Child => { - write(STDOUT_FILENO, string.as_bytes()).unwrap(); + write(stdout(), string.as_bytes()).unwrap(); pause(); // we need the child to stay alive until the parent calls read unsafe { _exit(0); diff --git a/test/test_sendfile.rs b/test/test_sendfile.rs index b85e030fd3..a594f18e39 100644 --- a/test/test_sendfile.rs +++ b/test/test_sendfile.rs @@ -1,6 +1,4 @@ use std::io::prelude::*; -#[cfg(any(target_os = "android", target_os = "linux"))] -use std::os::unix::io::{FromRawFd, OwnedFd}; use libc::off_t; use nix::sys::sendfile::*; @@ -8,7 +6,8 @@ use tempfile::tempfile; cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { - use nix::unistd::{close, pipe, read}; + use nix::unistd::{pipe, read}; + use std::os::unix::io::AsRawFd; } else if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] { use std::net::Shutdown; use std::os::unix::net::UnixStream; @@ -24,21 +23,14 @@ fn test_sendfile_linux() { let (rd, wr) = pipe().unwrap(); let mut offset: off_t = 5; - // The construct of this `OwnedFd` is a temporary workaround, when `pipe(2)` - // becomes I/O-safe: - // pub fn pipe() -> std::result::Result<(OwnedFd, OwnedFd), Error> - // then it is no longer needed. - let wr = unsafe { OwnedFd::from_raw_fd(wr) }; let res = sendfile(&wr, &tmp, Some(&mut offset), 2).unwrap(); assert_eq!(2, res); let mut buf = [0u8; 1024]; - assert_eq!(2, read(rd, &mut buf).unwrap()); + assert_eq!(2, read(rd.as_raw_fd(), &mut buf).unwrap()); assert_eq!(b"f1", &buf[0..2]); assert_eq!(7, offset); - - close(rd).unwrap(); } #[cfg(target_os = "linux")] @@ -50,21 +42,14 @@ fn test_sendfile64_linux() { let (rd, wr) = pipe().unwrap(); let mut offset: libc::off64_t = 5; - // The construct of this `OwnedFd` is a temporary workaround, when `pipe(2)` - // becomes I/O-safe: - // pub fn pipe() -> std::result::Result<(OwnedFd, OwnedFd), Error> - // then it is no longer needed. - let wr = unsafe { OwnedFd::from_raw_fd(wr) }; let res = sendfile64(&wr, &tmp, Some(&mut offset), 2).unwrap(); assert_eq!(2, res); let mut buf = [0u8; 1024]; - assert_eq!(2, read(rd, &mut buf).unwrap()); + assert_eq!(2, read(rd.as_raw_fd(), &mut buf).unwrap()); assert_eq!(b"f1", &buf[0..2]); assert_eq!(7, offset); - - close(rd).unwrap(); } #[cfg(target_os = "freebsd")] diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 80abdc436d..bdfa09beb8 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -356,7 +356,7 @@ macro_rules! execve_test_factory ( match unsafe{fork()}.unwrap() { Child => { // Make `writer` be the stdout of the new process. - dup2(writer, 1).unwrap(); + dup2(writer.as_raw_fd(), 1).unwrap(); let r = syscall(); let _ = std::io::stderr() .write_all(format!("{:?}", r).as_bytes()); @@ -370,7 +370,7 @@ macro_rules! execve_test_factory ( assert_eq!(ws, Ok(WaitStatus::Exited(child, 0))); // Read 1024 bytes. let mut buf = [0u8; 1024]; - read(reader, &mut buf).unwrap(); + read(reader.as_raw_fd(), &mut buf).unwrap(); // It should contain the things we printed using `/bin/sh`. let string = String::from_utf8_lossy(&buf); assert!(string.contains("nix!!!")); @@ -714,12 +714,12 @@ fn test_getresgid() { fn test_pipe() { let (fd0, fd1) = pipe().unwrap(); let m0 = stat::SFlag::from_bits_truncate( - stat::fstat(fd0).unwrap().st_mode as mode_t, + stat::fstat(fd0.as_raw_fd()).unwrap().st_mode as mode_t, ); // S_IFIFO means it's a pipe assert_eq!(m0, SFlag::S_IFIFO); let m1 = stat::SFlag::from_bits_truncate( - stat::fstat(fd1).unwrap().st_mode as mode_t, + stat::fstat(fd1.as_raw_fd()).unwrap().st_mode as mode_t, ); assert_eq!(m1, SFlag::S_IFIFO); } @@ -743,9 +743,13 @@ fn test_pipe2() { use nix::fcntl::{fcntl, FcntlArg, FdFlag}; let (fd0, fd1) = pipe2(OFlag::O_CLOEXEC).unwrap(); - let f0 = FdFlag::from_bits_truncate(fcntl(fd0, FcntlArg::F_GETFD).unwrap()); + let f0 = FdFlag::from_bits_truncate( + fcntl(fd0.as_raw_fd(), FcntlArg::F_GETFD).unwrap(), + ); assert!(f0.contains(FdFlag::FD_CLOEXEC)); - let f1 = FdFlag::from_bits_truncate(fcntl(fd1, FcntlArg::F_GETFD).unwrap()); + let f1 = FdFlag::from_bits_truncate( + fcntl(fd1.as_raw_fd(), FcntlArg::F_GETFD).unwrap(), + ); assert!(f1.contains(FdFlag::FD_CLOEXEC)); } From 57663c094848a80123794a7bd3ca88115fac055e Mon Sep 17 00:00:00 2001 From: germag Date: Sat, 30 Sep 2023 12:38:26 +0200 Subject: [PATCH 006/140] SigSet: Fix incorrect implementation of Eq, PartialEq and Hash (#1946) `signal::SigSet` derives `Eq`, `PartialEq` and `Hash`, but on linux, sigfillset(3) only initializes the first 64 bits, leaving the rest uninitialized. So two `signal::SigSets` can be different even though both have the same set of signals. Signed-off-by: German Maglione --- CHANGELOG.md | 4 +++ src/sys/signal.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a1a99728c3..60604580a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] - ReleaseDate +### Fixed +- Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` + ([#1946](https://github.com/nix-rust/nix/pull/1946)) + ### Changed - The following APIs now take an implementation of `AsFd` rather than a diff --git a/src/sys/signal.rs b/src/sys/signal.rs index c946e4a0b1..de16aed5da 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -7,6 +7,7 @@ use crate::errno::Errno; use crate::{Error, Result}; use cfg_if::cfg_if; use std::fmt; +use std::hash::{Hash, Hasher}; use std::mem; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] use std::os::unix::io::RawFd; @@ -486,7 +487,7 @@ use std::iter::IntoIterator; // We are using `transparent` here to be super sure that `SigSet` // is represented exactly like the `sigset_t` struct from C. #[repr(transparent)] -#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +#[derive(Clone, Copy, Debug, Eq)] pub struct SigSet { sigset: libc::sigset_t } @@ -628,6 +629,27 @@ impl FromIterator for SigSet { } } +impl PartialEq for SigSet { + fn eq(&self, other: &Self) -> bool { + for signal in Signal::iterator() { + if self.contains(signal) != other.contains(signal) { + return false; + } + } + true + } +} + +impl Hash for SigSet { + fn hash(&self, state: &mut H) { + for signal in Signal::iterator() { + if self.contains(signal) { + signal.hash(state); + } + } + } +} + /// Iterator for a [`SigSet`]. /// /// Call [`SigSet::iter`] to create an iterator. @@ -1554,4 +1576,48 @@ mod tests { assert!(set.contains(signal)); } } + + #[test] + fn test_eq_empty() { + let set0 = SigSet::empty(); + let set1 = SigSet::empty(); + assert_eq!(set0, set1); + } + + #[test] + fn test_eq_all() { + let set0 = SigSet::all(); + let set1 = SigSet::all(); + assert_eq!(set0, set1); + } + + #[test] + fn test_hash_empty() { + use std::collections::hash_map::DefaultHasher; + + let set0 = SigSet::empty(); + let mut h0 = DefaultHasher::new(); + set0.hash(&mut h0); + + let set1 = SigSet::empty(); + let mut h1 = DefaultHasher::new(); + set1.hash(&mut h1); + + assert_eq!(h0.finish(), h1.finish()); + } + + #[test] + fn test_hash_all() { + use std::collections::hash_map::DefaultHasher; + + let set0 = SigSet::all(); + let mut h0 = DefaultHasher::new(); + set0.hash(&mut h0); + + let set1 = SigSet::all(); + let mut h1 = DefaultHasher::new(); + set1.hash(&mut h1); + + assert_eq!(h0.finish(), h1.finish()); + } } From e5b2df67bce76e4bb4ed717017b771273774fb97 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sat, 30 Sep 2023 18:29:52 -0600 Subject: [PATCH 007/140] Cast pointers more carefully (#2140) * Cast pointers more carefully Prefer ptr::{cast, cast_const, cast_mut} over `as`. The latter makes it too easy to accidentally change both the type and mutability when changing only one was intended. This exercise caught an unintended mutability cast in one function, the BSD version of sendfile. In this case there's no UB because it isn't possible for anything else to get a reference to the data that was incorrectly cast. There was also a type cast that wasn't guaranteed to be correct (but probably was) due to memory layout guarantees in if_nametoindex. * Remove unnecessary cast in UnixCredentials::groups --- src/fcntl.rs | 8 ++++---- src/ifaddrs.rs | 2 +- src/lib.rs | 2 +- src/mount/bsd.rs | 4 ++-- src/mqueue.rs | 13 ++++--------- src/net/if_.rs | 3 ++- src/poll.rs | 8 ++------ src/sys/aio.rs | 10 +++++----- src/sys/epoll.rs | 4 ++-- src/sys/event.rs | 4 ++-- src/sys/inotify.rs | 2 +- src/sys/ptrace/linux.rs | 4 ++-- src/sys/quota.rs | 6 +++--- src/sys/sendfile.rs | 14 ++++++++------ src/sys/signalfd.rs | 2 +- src/sys/socket/addr.rs | 24 ++++++++++++------------ src/sys/socket/mod.rs | 26 +++++++++++++------------- src/sys/socket/sockopt.rs | 14 +++++++------- src/sys/uio.rs | 22 +++++++++++----------- src/unistd.rs | 37 ++++++++++++++++++------------------- test/sys/test_mman.rs | 12 ++++++------ test/sys/test_socket.rs | 5 ++--- 22 files changed, 109 insertions(+), 117 deletions(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index 00c83a18c7..e9c67fe4dd 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -1,5 +1,5 @@ use crate::errno::Errno; -use libc::{self, c_char, c_int, c_uint, size_t, ssize_t}; +use libc::{self, c_int, c_uint, size_t, ssize_t}; use std::ffi::OsString; #[cfg(not(target_os = "redox"))] use std::os::raw; @@ -306,12 +306,12 @@ fn readlink_maybe_at( Some(dirfd) => libc::readlinkat( dirfd, cstr.as_ptr(), - v.as_mut_ptr() as *mut c_char, + v.as_mut_ptr().cast(), v.capacity() as size_t, ), None => libc::readlink( cstr.as_ptr(), - v.as_mut_ptr() as *mut c_char, + v.as_mut_ptr().cast(), v.capacity() as size_t, ), } @@ -724,7 +724,7 @@ pub fn vmsplice( let ret = unsafe { libc::vmsplice( fd, - iov.as_ptr() as *const libc::iovec, + iov.as_ptr().cast(), iov.len(), flags.bits(), ) diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index 70b50b01eb..e7bf9d0c5a 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -65,7 +65,7 @@ unsafe fn workaround_xnu_bug(info: &libc::ifaddrs) -> Option { // memcpy only sa_len bytes, assume the rest is zero std::ptr::copy_nonoverlapping( src_sock as *const u8, - dst_sock.as_mut_ptr() as *mut u8, + dst_sock.as_mut_ptr().cast(), (*src_sock).sa_len.into(), ); diff --git a/src/lib.rs b/src/lib.rs index af0c67b0f3..959e76e768 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -311,7 +311,7 @@ impl NixPath for [u8] { } let mut buf = MaybeUninit::<[u8; MAX_STACK_ALLOCATION]>::uninit(); - let buf_ptr = buf.as_mut_ptr() as *mut u8; + let buf_ptr = buf.as_mut_ptr().cast(); unsafe { ptr::copy_nonoverlapping(self.as_ptr(), buf_ptr, self.len()); diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index 6ed2dc7fbf..3076304cab 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -215,7 +215,7 @@ impl<'a> Nmount<'a> { /// Helper function to push a slice onto the `iov` array. fn push_slice(&mut self, val: &'a [u8], is_owned: bool) { self.iov.push(libc::iovec { - iov_base: val.as_ptr() as *mut _, + iov_base: val.as_ptr().cast_mut().cast(), iov_len: val.len(), }); self.is_owned.push(is_owned); @@ -386,7 +386,7 @@ impl<'a> Nmount<'a> { // SAFETY: we are pushing a mutable iovec here, so we can't use // the above method self.iov.push(libc::iovec { - iov_base: errmsg.as_mut_ptr() as *mut c_void, + iov_base: errmsg.as_mut_ptr().cast(), iov_len: errmsg.len(), }); diff --git a/src/mqueue.rs b/src/mqueue.rs index fb07d2accb..c6b60a09b1 100644 --- a/src/mqueue.rs +++ b/src/mqueue.rs @@ -35,7 +35,7 @@ use crate::NixPath; use crate::Result; use crate::sys::stat::Mode; -use libc::{self, c_char, mqd_t, size_t}; +use libc::{self, mqd_t, size_t}; use std::mem; #[cfg(any( target_os = "linux", @@ -205,7 +205,7 @@ pub fn mq_receive( let res = unsafe { libc::mq_receive( mqdes.0, - message.as_mut_ptr() as *mut c_char, + message.as_mut_ptr().cast(), len, msg_prio as *mut u32, ) @@ -229,7 +229,7 @@ feature! { let res = unsafe { libc::mq_timedreceive( mqdes.0, - message.as_mut_ptr() as *mut c_char, + message.as_mut_ptr().cast(), len, msg_prio as *mut u32, abstime.as_ref(), @@ -244,12 +244,7 @@ feature! { /// See also [`mq_send(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_send.html) pub fn mq_send(mqdes: &MqdT, message: &[u8], msq_prio: u32) -> Result<()> { let res = unsafe { - libc::mq_send( - mqdes.0, - message.as_ptr() as *const c_char, - message.len(), - msq_prio, - ) + libc::mq_send(mqdes.0, message.as_ptr().cast(), message.len(), msq_prio) }; Errno::result(res).map(drop) } diff --git a/src/net/if_.rs b/src/net/if_.rs index ec46260714..2f13a96d94 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -373,6 +373,7 @@ mod if_nameindex { } /// A list of the network interfaces available on this system. Obtained from [`if_nameindex()`]. + #[repr(transparent)] pub struct Interfaces { ptr: NonNull, } @@ -388,7 +389,7 @@ mod if_nameindex { /// null-terminated, so calling this calculates the length. If random access isn't needed, /// [`Interfaces::iter()`] should be used instead. pub fn to_slice(&self) -> &[Interface] { - let ifs = self.ptr.as_ptr() as *const Interface; + let ifs = self.ptr.as_ptr().cast(); let len = self.iter().count(); unsafe { std::slice::from_raw_parts(ifs, len) } } diff --git a/src/poll.rs b/src/poll.rs index 9181bf7f30..7fc3dc85de 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -190,11 +190,7 @@ libc_bitflags! { /// ready. pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result { let res = unsafe { - libc::poll( - fds.as_mut_ptr() as *mut libc::pollfd, - fds.len() as libc::nfds_t, - timeout, - ) + libc::poll(fds.as_mut_ptr().cast(), fds.len() as libc::nfds_t, timeout) }; Errno::result(res) @@ -223,7 +219,7 @@ pub fn ppoll( let timeout = timeout.as_ref().map_or(core::ptr::null(), |r| r.as_ref()); let sigmask = sigmask.as_ref().map_or(core::ptr::null(), |r| r.as_ref()); let res = unsafe { - libc::ppoll(fds.as_mut_ptr() as *mut libc::pollfd, + libc::ppoll(fds.as_mut_ptr().cast(), fds.len() as libc::nfds_t, timeout, sigmask) diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 5471177e3e..3716f4190d 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -35,7 +35,7 @@ use std::{ ptr, thread, }; -use libc::{c_void, off_t}; +use libc::off_t; use pin_utils::unsafe_pinned; use crate::{ @@ -581,7 +581,7 @@ impl<'a> AioRead<'a> { ) -> Self { let mut aiocb = AioCb::common_init(fd, prio, sigev_notify); aiocb.aiocb.0.aio_nbytes = buf.len(); - aiocb.aiocb.0.aio_buf = buf.as_mut_ptr() as *mut c_void; + aiocb.aiocb.0.aio_buf = buf.as_mut_ptr().cast(); aiocb.aiocb.0.aio_lio_opcode = libc::LIO_READ; aiocb.aiocb.0.aio_offset = offs; AioRead { @@ -702,7 +702,7 @@ impl<'a> AioReadv<'a> { // In vectored mode, aio_nbytes stores the length of the iovec array, // not the byte count. aiocb.aiocb.0.aio_nbytes = bufs.len(); - aiocb.aiocb.0.aio_buf = bufs.as_mut_ptr() as *mut c_void; + aiocb.aiocb.0.aio_buf = bufs.as_mut_ptr().cast(); aiocb.aiocb.0.aio_lio_opcode = libc::LIO_READV; aiocb.aiocb.0.aio_offset = offs; AioReadv { @@ -817,7 +817,7 @@ impl<'a> AioWrite<'a> { // but technically its only unsafe to dereference it, not to create // it. Type Safety guarantees that we'll never pass aiocb to // aio_read or aio_readv. - aiocb.aiocb.0.aio_buf = buf.as_ptr() as *mut c_void; + aiocb.aiocb.0.aio_buf = buf.as_ptr().cast_mut().cast(); aiocb.aiocb.0.aio_lio_opcode = libc::LIO_WRITE; aiocb.aiocb.0.aio_offset = offs; AioWrite { @@ -935,7 +935,7 @@ impl<'a> AioWritev<'a> { // but technically its only unsafe to dereference it, not to create // it. Type Safety guarantees that we'll never pass aiocb to // aio_read or aio_readv. - aiocb.aiocb.0.aio_buf = bufs.as_ptr() as *mut c_void; + aiocb.aiocb.0.aio_buf = bufs.as_ptr().cast_mut().cast(); aiocb.aiocb.0.aio_lio_opcode = libc::LIO_WRITEV; aiocb.aiocb.0.aio_offset = offs; AioWritev { diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index acb08d0787..679f9c47d1 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -148,7 +148,7 @@ impl Epoll { let res = unsafe { libc::epoll_wait( self.0.as_raw_fd(), - events.as_mut_ptr() as *mut libc::epoll_event, + events.as_mut_ptr().cast(), events.len() as c_int, timeout as c_int, ) @@ -240,7 +240,7 @@ pub fn epoll_wait( let res = unsafe { libc::epoll_wait( epfd, - events.as_mut_ptr() as *mut libc::epoll_event, + events.as_mut_ptr().cast(), events.len() as c_int, timeout_ms as c_int, ) diff --git a/src/sys/event.rs b/src/sys/event.rs index ec7f7e277a..47ea2d027b 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -63,9 +63,9 @@ impl Kqueue { let res = unsafe { libc::kevent( self.0.as_raw_fd(), - changelist.as_ptr() as *const libc::kevent, + changelist.as_ptr().cast(), changelist.len() as type_of_nchanges, - eventlist.as_mut_ptr() as *mut libc::kevent, + eventlist.as_mut_ptr().cast(), eventlist.len() as type_of_nchanges, if let Some(ref timeout) = timeout_opt { timeout as *const timespec diff --git a/src/sys/inotify.rs b/src/sys/inotify.rs index e5fe930f49..c1b15f9bf6 100644 --- a/src/sys/inotify.rs +++ b/src/sys/inotify.rs @@ -202,7 +202,7 @@ impl Inotify { let mut event = MaybeUninit::::uninit(); ptr::copy_nonoverlapping( buffer.as_ptr().add(offset), - event.as_mut_ptr() as *mut u8, + event.as_mut_ptr().cast(), (BUFSIZ - offset).min(header_size), ); event.assume_init() diff --git a/src/sys/ptrace/linux.rs b/src/sys/ptrace/linux.rs index 8c134cf7ee..8c87e795f1 100644 --- a/src/sys/ptrace/linux.rs +++ b/src/sys/ptrace/linux.rs @@ -241,13 +241,13 @@ pub fn setregs(pid: Pid, regs: user_regs_struct) -> Result<()> { /// and therefore use the data field to return values. This function handles these /// requests. fn ptrace_get_data(request: Request, pid: Pid) -> Result { - let mut data = mem::MaybeUninit::uninit(); + let mut data = mem::MaybeUninit::::uninit(); let res = unsafe { libc::ptrace( request as RequestType, libc::pid_t::from(pid), ptr::null_mut::(), - data.as_mut_ptr() as *const _ as *const c_void, + data.as_mut_ptr(), ) }; Errno::result(res)?; diff --git a/src/sys/quota.rs b/src/sys/quota.rs index a32d07aa1e..2d12b858bf 100644 --- a/src/sys/quota.rs +++ b/src/sys/quota.rs @@ -264,7 +264,7 @@ pub fn quotactl_on( ) -> Result<()> { quota_file.with_nix_path(|path| { let mut path_copy = path.to_bytes_with_nul().to_owned(); - let p: *mut c_char = path_copy.as_mut_ptr() as *mut c_char; + let p: *mut c_char = path_copy.as_mut_ptr().cast(); quotactl( QuotaCmd(QuotaSubCmd::Q_QUOTAON, which), Some(special), @@ -308,12 +308,12 @@ pub fn quotactl_get( special: &P, id: c_int, ) -> Result { - let mut dqblk = mem::MaybeUninit::uninit(); + let mut dqblk = mem::MaybeUninit::::uninit(); quotactl( QuotaCmd(QuotaSubCmd::Q_GETQUOTA, which), Some(special), id, - dqblk.as_mut_ptr() as *mut c_char, + dqblk.as_mut_ptr().cast(), )?; Ok(unsafe { Dqblk(dqblk.assume_init()) }) } diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 9f3c333f97..da979d337b 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -96,22 +96,24 @@ cfg_if! { headers: Option<&'a [&'a [u8]]>, trailers: Option<&'a [&'a [u8]]> ) -> SendfileHeaderTrailer<'a> { - let header_iovecs: Option>> = + let mut header_iovecs: Option>> = headers.map(|s| s.iter().map(|b| IoSlice::new(b)).collect()); - let trailer_iovecs: Option>> = + let mut trailer_iovecs: Option>> = trailers.map(|s| s.iter().map(|b| IoSlice::new(b)).collect()); SendfileHeaderTrailer( libc::sf_hdtr { headers: { header_iovecs - .as_ref() - .map_or(ptr::null(), |v| v.as_ptr()) as *mut libc::iovec + .as_mut() + .map_or(ptr::null_mut(), |v| v.as_mut_ptr()) + .cast() }, hdr_cnt: header_iovecs.as_ref().map(|v| v.len()).unwrap_or(0) as i32, trailers: { trailer_iovecs - .as_ref() - .map_or(ptr::null(), |v| v.as_ptr()) as *mut libc::iovec + .as_mut() + .map_or(ptr::null_mut(), |v| v.as_mut_ptr()) + .cast() }, trl_cnt: trailer_iovecs.as_ref().map(|v| v.len()).unwrap_or(0) as i32 }, diff --git a/src/sys/signalfd.rs b/src/sys/signalfd.rs index 2b80ea643f..697bcf073d 100644 --- a/src/sys/signalfd.rs +++ b/src/sys/signalfd.rs @@ -109,7 +109,7 @@ impl SignalFd { let size = mem::size_of_val(&buffer); let res = Errno::result(unsafe { - libc::read(self.0.as_raw_fd(), buffer.as_mut_ptr() as *mut libc::c_void, size) + libc::read(self.0.as_raw_fd(), buffer.as_mut_ptr().cast(), size) }) .map(|r| r as usize); match res { diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 1783531d49..c42f86e34f 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -499,13 +499,13 @@ impl<'a> UnixAddrKind<'a> { #[cfg(any(target_os = "android", target_os = "linux"))] if sun.sun_path[0] == 0 { let name = slice::from_raw_parts( - sun.sun_path.as_ptr().add(1) as *const u8, + sun.sun_path.as_ptr().add(1).cast(), path_len - 1, ); return Self::Abstract(name); } let pathname = - slice::from_raw_parts(sun.sun_path.as_ptr() as *const u8, path_len); + slice::from_raw_parts(sun.sun_path.as_ptr().cast(), path_len); if pathname.last() == Some(&0) { // A trailing NUL is not considered part of the path, and it does // not need to be included in the addrlen passed to functions like @@ -557,7 +557,7 @@ impl UnixAddr { } ptr::copy_nonoverlapping( bytes.as_ptr(), - ret.sun_path.as_mut_ptr() as *mut u8, + ret.sun_path.as_mut_ptr().cast(), bytes.len(), ); @@ -593,7 +593,7 @@ impl UnixAddr { // b'\0', so copy starting one byte in. ptr::copy_nonoverlapping( path.as_ptr(), - ret.sun_path.as_mut_ptr().offset(1) as *mut u8, + ret.sun_path.as_mut_ptr().offset(1).cast(), path.len(), ); @@ -1829,7 +1829,7 @@ pub mod netlink { #[cfg_attr(docsrs, doc(cfg(all())))] pub mod alg { use super::*; - use libc::{c_char, sockaddr_alg, AF_ALG}; + use libc::{sockaddr_alg, AF_ALG}; use std::ffi::CStr; use std::hash::{Hash, Hasher}; use std::{fmt, mem, str}; @@ -1919,14 +1919,14 @@ pub mod alg { /// Return the socket's cipher type, for example `hash` or `aead`. pub fn alg_type(&self) -> &CStr { unsafe { - CStr::from_ptr(self.0.salg_type.as_ptr() as *const c_char) + CStr::from_ptr(self.0.salg_type.as_ptr().cast()) } } /// Return the socket's cipher name, for example `sha1`. pub fn alg_name(&self) -> &CStr { unsafe { - CStr::from_ptr(self.0.salg_name.as_ptr() as *const c_char) + CStr::from_ptr(self.0.salg_name.as_ptr().cast()) } } } @@ -2474,7 +2474,7 @@ mod tests { let bytes = Raw([ 17u8, 0, 0, 0, 1, 0, 0, 0, 4, 3, 0, 6, 1, 2, 3, 4, 5, 6, 0, 0, ]); - let sa = bytes.0.as_ptr() as *const libc::sockaddr; + let sa = bytes.0.as_ptr().cast(); let len = None; let sock_addr = unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); @@ -2490,7 +2490,7 @@ mod tests { fn macos_loopback() { let bytes = [20i8, 18, 1, 0, 24, 3, 0, 0, 108, 111, 48, 0, 0, 0, 0, 0]; - let sa = bytes.as_ptr() as *const libc::sockaddr; + let sa = bytes.as_ptr().cast(); let len = Some(bytes.len() as socklen_t); let sock_addr = unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); @@ -2628,7 +2628,7 @@ mod tests { #[test] fn from_sockaddr_un_named() { let ua = UnixAddr::new("/var/run/mysock").unwrap(); - let ptr = ua.as_ptr() as *const libc::sockaddr; + let ptr = ua.as_ptr().cast(); let ss = unsafe { SockaddrStorage::from_raw(ptr, Some(ua.len())) } .unwrap(); assert_eq!(ss.len(), ua.len()); @@ -2639,7 +2639,7 @@ mod tests { fn from_sockaddr_un_abstract_named() { let name = String::from("nix\0abstract\0test"); let ua = UnixAddr::new_abstract(name.as_bytes()).unwrap(); - let ptr = ua.as_ptr() as *const libc::sockaddr; + let ptr = ua.as_ptr().cast(); let ss = unsafe { SockaddrStorage::from_raw(ptr, Some(ua.len())) } .unwrap(); assert_eq!(ss.len(), ua.len()); @@ -2649,7 +2649,7 @@ mod tests { #[test] fn from_sockaddr_un_abstract_unnamed() { let ua = UnixAddr::new_unnamed(); - let ptr = ua.as_ptr() as *const libc::sockaddr; + let ptr = ua.as_ptr().cast(); let ss = unsafe { SockaddrStorage::from_raw(ptr, Some(ua.len())) } .unwrap(); assert_eq!(ss.len(), ua.len()); diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index b56d694ab5..e03b1d690d 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -9,10 +9,10 @@ use crate::sys::time::TimeSpec; use crate::sys::time::TimeVal; use crate::{errno::Errno, Result}; use cfg_if::cfg_if; -use libc::{self, c_int, c_void, size_t, socklen_t}; +use libc::{self, c_int, size_t, socklen_t}; #[cfg(all(feature = "uio", not(target_os = "redox")))] use libc::{ - iovec, CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_NXTHDR, CMSG_SPACE, + c_void, iovec, CMSG_DATA, CMSG_FIRSTHDR, CMSG_LEN, CMSG_NXTHDR, CMSG_SPACE, }; #[cfg(not(target_os = "redox"))] use std::io::{IoSlice, IoSliceMut}; @@ -487,7 +487,7 @@ cfg_if! { pub fn groups(&self) -> &[libc::gid_t] { unsafe { std::slice::from_raw_parts( - self.0.cmcred_groups.as_ptr() as *const libc::gid_t, + self.0.cmcred_groups.as_ptr(), self.0.cmcred_ngroups as _ ) } @@ -2025,7 +2025,7 @@ fn pack_mhdr_to_send<'a, I, C, S>( // The message header must be initialized before the individual cmsgs. let cmsg_ptr = if capacity > 0 { - cmsg_buffer.as_mut_ptr() as *mut c_void + cmsg_buffer.as_mut_ptr().cast() } else { ptr::null_mut() }; @@ -2035,11 +2035,11 @@ fn pack_mhdr_to_send<'a, I, C, S>( // initialize it. let mut mhdr = mem::MaybeUninit::::zeroed(); let p = mhdr.as_mut_ptr(); - (*p).msg_name = addr.map(S::as_ptr).unwrap_or(ptr::null()) as *mut _; + (*p).msg_name = addr.map(S::as_ptr).unwrap_or(ptr::null()).cast_mut().cast(); (*p).msg_namelen = addr.map(S::len).unwrap_or(0); // transmute iov into a mutable pointer. sendmsg doesn't really mutate // the buffer, but the standard says that it takes a mutable pointer - (*p).msg_iov = iov.as_ref().as_ptr() as *mut _; + (*p).msg_iov = iov.as_ref().as_ptr().cast_mut().cast(); (*p).msg_iovlen = iov.as_ref().len() as _; (*p).msg_control = cmsg_ptr; (*p).msg_controllen = capacity as _; @@ -2245,7 +2245,7 @@ pub fn recv(sockfd: RawFd, buf: &mut [u8], flags: MsgFlags) -> Result { unsafe { let ret = libc::recv( sockfd, - buf.as_mut_ptr() as *mut c_void, + buf.as_mut_ptr().cast(), buf.len() as size_t, flags.bits(), ); @@ -2269,10 +2269,10 @@ pub fn recvfrom( let ret = Errno::result(libc::recvfrom( sockfd, - buf.as_mut_ptr() as *mut c_void, + buf.as_mut_ptr().cast(), buf.len() as size_t, 0, - addr.as_mut_ptr() as *mut sockaddr, + addr.as_mut_ptr().cast(), &mut len as *mut socklen_t, ))? as usize; @@ -2298,7 +2298,7 @@ pub fn sendto( let ret = unsafe { libc::sendto( fd, - buf.as_ptr() as *const c_void, + buf.as_ptr().cast(), buf.len() as size_t, flags.bits(), addr.as_ptr(), @@ -2316,7 +2316,7 @@ pub fn send(fd: RawFd, buf: &[u8], flags: MsgFlags) -> Result { let ret = unsafe { libc::send( fd, - buf.as_ptr() as *const c_void, + buf.as_ptr().cast(), buf.len() as size_t, flags.bits(), ) @@ -2387,7 +2387,7 @@ pub fn getpeername(fd: RawFd) -> Result { let mut len = T::size(); let ret = - libc::getpeername(fd, addr.as_mut_ptr() as *mut sockaddr, &mut len); + libc::getpeername(fd, addr.as_mut_ptr().cast(), &mut len); Errno::result(ret)?; @@ -2404,7 +2404,7 @@ pub fn getsockname(fd: RawFd) -> Result { let mut len = T::size(); let ret = - libc::getsockname(fd, addr.as_mut_ptr() as *mut sockaddr, &mut len); + libc::getsockname(fd, addr.as_mut_ptr().cast(), &mut len); Errno::result(ret)?; diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 3192df1fa6..b46f208216 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -1111,7 +1111,7 @@ where fd.as_fd().as_raw_fd(), libc::SOL_ALG, libc::ALG_SET_KEY, - val.as_ref().as_ptr() as *const _, + val.as_ref().as_ptr().cast(), val.as_ref().len() as libc::socklen_t, ); Errno::result(res).map(drop) @@ -1166,7 +1166,7 @@ impl Get for GetStruct { } fn ffi_ptr(&mut self) -> *mut c_void { - self.val.as_mut_ptr() as *mut c_void + self.val.as_mut_ptr().cast() } fn ffi_len(&mut self) -> *mut socklen_t { @@ -1217,7 +1217,7 @@ impl Get for GetBool { } fn ffi_ptr(&mut self) -> *mut c_void { - self.val.as_mut_ptr() as *mut c_void + self.val.as_mut_ptr().cast() } fn ffi_len(&mut self) -> *mut socklen_t { @@ -1270,7 +1270,7 @@ impl Get for GetU8 { } fn ffi_ptr(&mut self) -> *mut c_void { - self.val.as_mut_ptr() as *mut c_void + self.val.as_mut_ptr().cast() } fn ffi_len(&mut self) -> *mut socklen_t { @@ -1321,7 +1321,7 @@ impl Get for GetUsize { } fn ffi_ptr(&mut self) -> *mut c_void { - self.val.as_mut_ptr() as *mut c_void + self.val.as_mut_ptr().cast() } fn ffi_len(&mut self) -> *mut socklen_t { @@ -1372,7 +1372,7 @@ impl> Get for GetOsString { } fn ffi_ptr(&mut self) -> *mut c_void { - self.val.as_mut_ptr() as *mut c_void + self.val.as_mut_ptr().cast() } fn ffi_len(&mut self) -> *mut socklen_t { @@ -1399,7 +1399,7 @@ impl<'a> Set<'a, OsString> for SetOsString<'a> { } fn ffi_ptr(&self) -> *const c_void { - self.val.as_bytes().as_ptr() as *const c_void + self.val.as_bytes().as_ptr().cast() } fn ffi_len(&self) -> socklen_t { diff --git a/src/sys/uio.rs b/src/sys/uio.rs index eaf61edfd4..4b55d4200f 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -2,7 +2,7 @@ use crate::errno::Errno; use crate::Result; -use libc::{self, c_int, c_void, off_t, size_t}; +use libc::{self, c_int, off_t, size_t}; use std::io::{IoSlice, IoSliceMut}; use std::os::unix::io::{AsFd, AsRawFd}; @@ -18,7 +18,7 @@ pub fn writev(fd: Fd, iov: &[IoSlice<'_>]) -> Result { // // Because it is ABI compatible, a pointer cast here is valid let res = unsafe { - libc::writev(fd.as_fd().as_raw_fd(), iov.as_ptr() as *const libc::iovec, iov.len() as c_int) + libc::writev(fd.as_fd().as_raw_fd(), iov.as_ptr().cast(), iov.len() as c_int) }; Errno::result(res).map(|r| r as usize) @@ -33,7 +33,7 @@ pub fn writev(fd: Fd, iov: &[IoSlice<'_>]) -> Result { pub fn readv(fd: Fd, iov: &mut [IoSliceMut<'_>]) -> Result { // SAFETY: same as in writev(), IoSliceMut is ABI-compatible with iovec let res = unsafe { - libc::readv(fd.as_fd().as_raw_fd(), iov.as_ptr() as *const libc::iovec, iov.len() as c_int) + libc::readv(fd.as_fd().as_raw_fd(), iov.as_ptr().cast(), iov.len() as c_int) }; Errno::result(res).map(|r| r as usize) @@ -55,7 +55,7 @@ pub fn pwritev(fd: Fd, iov: &[IoSlice<'_>], offset: off_t) -> Result( let res = unsafe { libc::preadv( fd.as_fd().as_raw_fd(), - iov.as_ptr() as *const libc::iovec, + iov.as_ptr().cast(), iov.len() as c_int, offset, ) @@ -105,7 +105,7 @@ pub fn pwrite(fd: Fd, buf: &[u8], offset: off_t) -> Result { let res = unsafe { libc::pwrite( fd.as_fd().as_raw_fd(), - buf.as_ptr() as *const c_void, + buf.as_ptr().cast(), buf.len() as size_t, offset, ) @@ -122,7 +122,7 @@ pub fn pread(fd: Fd, buf: &mut [u8], offset: off_t) -> Result { let res = unsafe { libc::pread( fd.as_fd().as_raw_fd(), - buf.as_mut_ptr() as *mut c_void, + buf.as_mut_ptr().cast(), buf.len() as size_t, offset, ) @@ -181,8 +181,8 @@ pub fn process_vm_writev( { let res = unsafe { libc::process_vm_writev(pid.into(), - local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, - remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) + local_iov.as_ptr().cast(), local_iov.len() as libc::c_ulong, + remote_iov.as_ptr().cast(), remote_iov.len() as libc::c_ulong, 0) }; Errno::result(res).map(|r| r as usize) @@ -216,8 +216,8 @@ pub fn process_vm_readv( { let res = unsafe { libc::process_vm_readv(pid.into(), - local_iov.as_ptr() as *const libc::iovec, local_iov.len() as libc::c_ulong, - remote_iov.as_ptr() as *const libc::iovec, remote_iov.len() as libc::c_ulong, 0) + local_iov.as_ptr().cast(), local_iov.len() as libc::c_ulong, + remote_iov.as_ptr().cast(), remote_iov.len() as libc::c_ulong, 0) }; Errno::result(res).map(|r| r as usize) diff --git a/src/unistd.rs b/src/unistd.rs index 066f50e5aa..2eb23fa95c 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -24,8 +24,8 @@ use crate::{Error, NixPath, Result}; #[cfg(not(target_os = "redox"))] use cfg_if::cfg_if; use libc::{ - self, c_char, c_int, c_long, c_uint, c_void, gid_t, mode_t, off_t, pid_t, - size_t, uid_t, PATH_MAX, + self, c_char, c_int, c_long, c_uint, gid_t, mode_t, off_t, pid_t, size_t, + uid_t, PATH_MAX, }; use std::convert::Infallible; use std::ffi::{CStr, OsString}; @@ -664,17 +664,17 @@ feature! { /// ``` #[inline] pub fn getcwd() -> Result { - let mut buf = Vec::with_capacity(512); + let mut buf = Vec::::with_capacity(512); loop { unsafe { - let ptr = buf.as_mut_ptr() as *mut c_char; + let ptr = buf.as_mut_ptr().cast(); // The buffer must be large enough to store the absolute pathname plus // a terminating null byte, or else null is returned. // To safely handle this we start with a reasonable size (512 bytes) // and double the buffer size upon every error if !libc::getcwd(ptr, buf.capacity()).is_null() { - let len = CStr::from_ptr(buf.as_ptr() as *const c_char) + let len = CStr::from_ptr(buf.as_ptr().cast()) .to_bytes() .len(); buf.set_len(len); @@ -1032,7 +1032,7 @@ pub fn sethostname>(name: S) -> Result<()> { type sethostname_len_t = size_t; } } - let ptr = name.as_ref().as_bytes().as_ptr() as *const c_char; + let ptr = name.as_ref().as_bytes().as_ptr().cast(); let len = name.as_ref().len() as sethostname_len_t; let res = unsafe { libc::sethostname(ptr, len) }; @@ -1056,14 +1056,14 @@ pub fn sethostname>(name: S) -> Result<()> { pub fn gethostname() -> Result { // The capacity is the max length of a hostname plus the NUL terminator. let mut buffer: Vec = Vec::with_capacity(256); - let ptr = buffer.as_mut_ptr() as *mut c_char; + let ptr = buffer.as_mut_ptr().cast(); let len = buffer.capacity() as size_t; let res = unsafe { libc::gethostname(ptr, len) }; Errno::result(res).map(|_| { unsafe { buffer.as_mut_ptr().wrapping_add(len - 1).write(0); // ensure always null-terminated - let len = CStr::from_ptr(buffer.as_ptr() as *const c_char).len(); + let len = CStr::from_ptr(buffer.as_ptr().cast()).len(); buffer.set_len(len); } OsString::from_vec(buffer) @@ -1105,9 +1105,8 @@ pub fn close(fd: RawFd) -> Result<()> { /// /// See also [read(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html) pub fn read(fd: RawFd, buf: &mut [u8]) -> Result { - let res = unsafe { - libc::read(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t) - }; + let res = + unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len() as size_t) }; Errno::result(res).map(|r| r as usize) } @@ -1119,7 +1118,7 @@ pub fn write(fd: Fd, buf: &[u8]) -> Result { let res = unsafe { libc::write( fd.as_fd().as_raw_fd(), - buf.as_ptr() as *const c_void, + buf.as_ptr().cast(), buf.len() as size_t, ) }; @@ -1196,7 +1195,7 @@ pub fn lseek64( pub fn pipe() -> std::result::Result<(OwnedFd, OwnedFd), Error> { let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit(); - let res = unsafe { libc::pipe(fds.as_mut_ptr() as *mut c_int) }; + let res = unsafe { libc::pipe(fds.as_mut_ptr().cast()) }; Error::result(res)?; @@ -1239,7 +1238,7 @@ pub fn pipe2(flags: OFlag) -> Result<(OwnedFd, OwnedFd)> { let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit(); let res = - unsafe { libc::pipe2(fds.as_mut_ptr() as *mut c_int, flags.bits()) }; + unsafe { libc::pipe2(fds.as_mut_ptr().cast(), flags.bits()) }; Errno::result(res)?; @@ -1594,7 +1593,7 @@ pub fn getgroups() -> Result> { let ngroups = unsafe { libc::getgroups( groups.capacity() as c_int, - groups.as_mut_ptr() as *mut gid_t, + groups.as_mut_ptr().cast(), ) }; @@ -1673,7 +1672,7 @@ pub fn setgroups(groups: &[Gid]) -> Result<()> { let res = unsafe { libc::setgroups( groups.len() as setgroups_ngroups_t, - groups.as_ptr() as *const gid_t, + groups.as_ptr().cast(), ) }; @@ -1728,7 +1727,7 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { libc::getgrouplist( user.as_ptr(), gid as getgrouplist_group_t, - groups.as_mut_ptr() as *mut getgrouplist_group_t, + groups.as_mut_ptr().cast(), &mut ngroups, ) }; @@ -1976,7 +1975,7 @@ feature! { pub fn mkstemp(template: &P) -> Result<(RawFd, PathBuf)> { let mut path = template.with_nix_path(|path| path.to_bytes_with_nul().to_owned())?; - let p = path.as_mut_ptr() as *mut _; + let p = path.as_mut_ptr().cast(); let fd = unsafe { libc::mkstemp(p) }; let last = path.pop(); // drop the trailing nul debug_assert!(last == Some(b'\0')); @@ -3922,7 +3921,7 @@ feature! { pub fn ttyname(fd: F) -> Result { const PATH_MAX: usize = libc::PATH_MAX as usize; let mut buf = vec![0_u8; PATH_MAX]; - let c_buf = buf.as_mut_ptr() as *mut libc::c_char; + let c_buf = buf.as_mut_ptr().cast(); let ret = unsafe { libc::ttyname_r(fd.as_fd().as_raw_fd(), c_buf, buf.len()) }; if ret != 0 { diff --git a/test/sys/test_mman.rs b/test/sys/test_mman.rs index b4674e53fa..704e14f9c5 100644 --- a/test/sys/test_mman.rs +++ b/test/sys/test_mman.rs @@ -22,7 +22,7 @@ fn test_mmap_anonymous() { #[test] #[cfg(any(target_os = "linux", target_os = "netbsd"))] fn test_mremap_grow() { - use nix::libc::{c_void, size_t}; + use nix::libc::size_t; use nix::sys::mman::{mremap, MRemapFlags}; const ONE_K: size_t = 1024; @@ -47,7 +47,7 @@ fn test_mremap_grow() { let slice: &mut [u8] = unsafe { #[cfg(target_os = "linux")] let mem = mremap( - slice.as_mut_ptr() as *mut c_void, + slice.as_mut_ptr().cast(), ONE_K, 10 * ONE_K, MRemapFlags::MREMAP_MAYMOVE, @@ -56,7 +56,7 @@ fn test_mremap_grow() { .unwrap(); #[cfg(target_os = "netbsd")] let mem = mremap( - slice.as_mut_ptr() as *mut c_void, + slice.as_mut_ptr().cast(), ONE_K, 10 * ONE_K, MRemapFlags::MAP_REMAPDUP, @@ -80,7 +80,7 @@ fn test_mremap_grow() { // Segfaults for unknown reasons under QEMU for 32-bit targets #[cfg_attr(all(target_pointer_width = "32", qemu), ignore)] fn test_mremap_shrink() { - use nix::libc::{c_void, size_t}; + use nix::libc::size_t; use nix::sys::mman::{mremap, MRemapFlags}; use std::num::NonZeroUsize; @@ -104,7 +104,7 @@ fn test_mremap_shrink() { let slice: &mut [u8] = unsafe { let mem = mremap( - slice.as_mut_ptr() as *mut c_void, + slice.as_mut_ptr().cast(), ten_one_k.into(), ONE_K, MRemapFlags::empty(), @@ -113,7 +113,7 @@ fn test_mremap_shrink() { .unwrap(); // Since we didn't supply MREMAP_MAYMOVE, the address should be the // same. - assert_eq!(mem, slice.as_mut_ptr() as *mut c_void); + assert_eq!(mem, slice.as_mut_ptr().cast()); std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) }; diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 12615b422f..df83189981 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -78,9 +78,8 @@ pub fn test_path_to_sock_addr() { let actual = Path::new(path); let addr = UnixAddr::new(actual).unwrap(); - let expect: &[c_char] = unsafe { - slice::from_raw_parts(path.as_ptr() as *const c_char, path.len()) - }; + let expect: &[c_char] = + unsafe { slice::from_raw_parts(path.as_ptr().cast(), path.len()) }; assert_eq!(unsafe { &(*addr.as_ptr()).sun_path[..8] }, expect); assert_eq!(addr.path(), Some(actual)); From c4ba87782088854dcf055fbc64849229e9b863c6 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 1 Oct 2023 04:51:07 -0600 Subject: [PATCH 008/140] Relax lifetime requirements for FdSet::{insert, remove, contains} (#2136) * Relax lifetime requirements for FdSet::{insert, remove, contains} Fixes #2130 * Take BorrowedFd as the argument for FdSet::{insert, remove, contains} &AsFd doesn't work because there are 'static types, like std::fs::File, which implement AsFd. * fix changelog & remove unused entries * fix wrong PR number --------- Co-authored-by: Steve Lau --- CHANGELOG.md | 4 ++ src/sys/select.rs | 100 ++++++++++++++++++++-------------------- test/sys/test_select.rs | 20 ++++---- 3 files changed, 64 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60604580a0..51cf8a2f46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). ([#2137](https://github.com/nix-rust/nix/pull/2137)) +- `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have + relaxed lifetime requirements relative to 0.27.1. + ([#2136](https://github.com/nix-rust/nix/pull/2136)) + ## [0.27.1] - 2023-08-28 ### Fixed diff --git a/src/sys/select.rs b/src/sys/select.rs index 4c5521be90..ea0c41d4be 100644 --- a/src/sys/select.rs +++ b/src/sys/select.rs @@ -7,7 +7,7 @@ use std::convert::TryFrom; use std::iter::FusedIterator; use std::mem; use std::ops::Range; -use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; +use std::os::unix::io::{AsRawFd, BorrowedFd, RawFd}; use std::ptr::{null, null_mut}; pub use libc::FD_SETSIZE; @@ -41,21 +41,21 @@ impl<'fd> FdSet<'fd> { } /// Add a file descriptor to an `FdSet` - pub fn insert(&mut self, fd: &'fd Fd) { - assert_fd_valid(fd.as_fd().as_raw_fd()); - unsafe { libc::FD_SET(fd.as_fd().as_raw_fd(), &mut self.set) }; + pub fn insert(&mut self, fd: BorrowedFd<'fd>) { + assert_fd_valid(fd.as_raw_fd()); + unsafe { libc::FD_SET(fd.as_raw_fd(), &mut self.set) }; } /// Remove a file descriptor from an `FdSet` - pub fn remove(&mut self, fd: &'fd Fd) { - assert_fd_valid(fd.as_fd().as_raw_fd()); - unsafe { libc::FD_CLR(fd.as_fd().as_raw_fd(), &mut self.set) }; + pub fn remove(&mut self, fd: BorrowedFd<'fd>) { + assert_fd_valid(fd.as_raw_fd()); + unsafe { libc::FD_CLR(fd.as_raw_fd(), &mut self.set) }; } /// Test an `FdSet` for the presence of a certain file descriptor. - pub fn contains(&self, fd: &'fd Fd) -> bool { - assert_fd_valid(fd.as_fd().as_raw_fd()); - unsafe { libc::FD_ISSET(fd.as_fd().as_raw_fd(), &self.set) } + pub fn contains(&self, fd: BorrowedFd<'fd>) -> bool { + assert_fd_valid(fd.as_raw_fd()); + unsafe { libc::FD_ISSET(fd.as_raw_fd(), &self.set) } } /// Remove all file descriptors from this `FdSet`. @@ -77,8 +77,8 @@ impl<'fd> FdSet<'fd> { /// let fd_four = unsafe {BorrowedFd::borrow_raw(4)}; /// let fd_nine = unsafe {BorrowedFd::borrow_raw(9)}; /// let mut set = FdSet::new(); - /// set.insert(&fd_four); - /// set.insert(&fd_nine); + /// set.insert(fd_four); + /// set.insert(fd_nine); /// assert_eq!(set.highest().map(|borrowed_fd|borrowed_fd.as_raw_fd()), Some(9)); /// ``` /// @@ -101,8 +101,8 @@ impl<'fd> FdSet<'fd> { /// let mut set = FdSet::new(); /// let fd_four = unsafe {BorrowedFd::borrow_raw(4)}; /// let fd_nine = unsafe {BorrowedFd::borrow_raw(9)}; - /// set.insert(&fd_four); - /// set.insert(&fd_nine); + /// set.insert(fd_four); + /// set.insert(fd_nine); /// let fds: Vec = set.fds(None).map(|borrowed_fd|borrowed_fd.as_raw_fd()).collect(); /// assert_eq!(fds, vec![4, 9]); /// ``` @@ -134,7 +134,7 @@ impl<'a, 'fd> Iterator for Fds<'a, 'fd> { fn next(&mut self) -> Option { for i in &mut self.range { let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - if self.set.contains(&borrowed_i) { + if self.set.contains(borrowed_i) { return Some(borrowed_i); } } @@ -153,7 +153,7 @@ impl<'a, 'fd> DoubleEndedIterator for Fds<'a, 'fd> { fn next_back(&mut self) -> Option> { while let Some(i) = self.range.next_back() { let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - if self.set.contains(&borrowed_i) { + if self.set.contains(borrowed_i) { return Some(borrowed_i); } } @@ -323,7 +323,7 @@ mod tests { use super::*; use crate::sys::time::{TimeVal, TimeValLike}; use crate::unistd::{pipe, write}; - use std::os::unix::io::RawFd; + use std::os::unix::io::{AsFd, RawFd}; #[test] fn fdset_insert() { @@ -331,13 +331,13 @@ mod tests { for i in 0..FD_SETSIZE { let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(&borrowed_i)); + assert!(!fd_set.contains(borrowed_i)); } let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; - fd_set.insert(&fd_seven); + fd_set.insert(fd_seven); - assert!(fd_set.contains(&fd_seven)); + assert!(fd_set.contains(fd_seven)); } #[test] @@ -346,16 +346,16 @@ mod tests { for i in 0..FD_SETSIZE { let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(&borrowed_i)); + assert!(!fd_set.contains(borrowed_i)); } let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; - fd_set.insert(&fd_seven); - fd_set.remove(&fd_seven); + fd_set.insert(fd_seven); + fd_set.remove(fd_seven); for i in 0..FD_SETSIZE { let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(&borrowed_i)); + assert!(!fd_set.contains(borrowed_i)); } } @@ -364,19 +364,19 @@ mod tests { fn fdset_clear() { let mut fd_set = FdSet::new(); let fd_one = unsafe { BorrowedFd::borrow_raw(1) }; - let fd_FD_SETSIZE_devided_by_two = + let fd_FD_SETSIZE_divided_by_two = unsafe { BorrowedFd::borrow_raw((FD_SETSIZE / 2) as RawFd) }; let fd_FD_SETSIZE_minus_one = unsafe { BorrowedFd::borrow_raw((FD_SETSIZE - 1) as RawFd) }; - fd_set.insert(&fd_one); - fd_set.insert(&fd_FD_SETSIZE_devided_by_two); - fd_set.insert(&fd_FD_SETSIZE_minus_one); + fd_set.insert(fd_one); + fd_set.insert(fd_FD_SETSIZE_divided_by_two); + fd_set.insert(fd_FD_SETSIZE_minus_one); fd_set.clear(); for i in 0..FD_SETSIZE { let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(&borrowed_i)); + assert!(!fd_set.contains(borrowed_i)); } } @@ -389,22 +389,22 @@ mod tests { ); let fd_zero = unsafe { BorrowedFd::borrow_raw(0) }; let fd_ninety = unsafe { BorrowedFd::borrow_raw(90) }; - set.insert(&fd_zero); + set.insert(fd_zero); assert_eq!( set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), Some(0) ); - set.insert(&fd_ninety); + set.insert(fd_ninety); assert_eq!( set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), Some(90) ); - set.remove(&fd_zero); + set.remove(fd_zero); assert_eq!( set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), Some(90) ); - set.remove(&fd_ninety); + set.remove(fd_ninety); assert_eq!( set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), None @@ -413,9 +413,9 @@ mod tests { let fd_four = unsafe { BorrowedFd::borrow_raw(4) }; let fd_five = unsafe { BorrowedFd::borrow_raw(5) }; let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; - set.insert(&fd_four); - set.insert(&fd_five); - set.insert(&fd_seven); + set.insert(fd_four); + set.insert(fd_five); + set.insert(fd_seven); assert_eq!( set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), Some(7) @@ -433,14 +433,14 @@ mod tests { .collect::>(), vec![] ); - set.insert(&fd_zero); + set.insert(fd_zero); assert_eq!( set.fds(None) .map(|borrowed_fd| borrowed_fd.as_raw_fd()) .collect::>(), vec![0] ); - set.insert(&fd_ninety); + set.insert(fd_ninety); assert_eq!( set.fds(None) .map(|borrowed_fd| borrowed_fd.as_raw_fd()) @@ -470,16 +470,16 @@ mod tests { write(&w1, b"hi!").unwrap(); let mut fd_set = FdSet::new(); - fd_set.insert(&r1); - fd_set.insert(&r2); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); let mut timeout = TimeVal::seconds(10); assert_eq!( 1, select(None, &mut fd_set, None, None, &mut timeout).unwrap() ); - assert!(fd_set.contains(&r1)); - assert!(!fd_set.contains(&r2)); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); } #[test] @@ -489,8 +489,8 @@ mod tests { write(&w1, b"hi!").unwrap(); let mut fd_set = FdSet::new(); - fd_set.insert(&r1); - fd_set.insert(&r2); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); let mut timeout = TimeVal::seconds(10); { @@ -512,8 +512,8 @@ mod tests { .unwrap() ); } - assert!(fd_set.contains(&r1)); - assert!(!fd_set.contains(&r2)); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); } #[test] @@ -522,8 +522,8 @@ mod tests { write(&w1, b"hi!").unwrap(); let (r2, _w2) = pipe().unwrap(); let mut fd_set = FdSet::new(); - fd_set.insert(&r1); - fd_set.insert(&r2); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); let mut timeout = TimeVal::seconds(10); assert_eq!( @@ -537,7 +537,7 @@ mod tests { ) .unwrap() ); - assert!(fd_set.contains(&r1)); - assert!(!fd_set.contains(&r2)); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); } } diff --git a/test/sys/test_select.rs b/test/sys/test_select.rs index 6b4d1c54c1..111e444d49 100644 --- a/test/sys/test_select.rs +++ b/test/sys/test_select.rs @@ -2,7 +2,7 @@ use nix::sys::select::*; use nix::sys::signal::SigSet; use nix::sys::time::{TimeSpec, TimeValLike}; use nix::unistd::{pipe, write}; -use std::os::unix::io::{AsRawFd, BorrowedFd}; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd}; #[test] pub fn test_pselect() { @@ -13,8 +13,8 @@ pub fn test_pselect() { let (r2, _w2) = pipe().unwrap(); let mut fd_set = FdSet::new(); - fd_set.insert(&r1); - fd_set.insert(&r2); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); let timeout = TimeSpec::seconds(10); let sigmask = SigSet::empty(); @@ -22,8 +22,8 @@ pub fn test_pselect() { 1, pselect(None, &mut fd_set, None, None, &timeout, &sigmask).unwrap() ); - assert!(fd_set.contains(&r1)); - assert!(!fd_set.contains(&r2)); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); } #[test] @@ -33,8 +33,8 @@ pub fn test_pselect_nfds2() { let (r2, _w2) = pipe().unwrap(); let mut fd_set = FdSet::new(); - fd_set.insert(&r1); - fd_set.insert(&r2); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); let timeout = TimeSpec::seconds(10); assert_eq!( @@ -49,8 +49,8 @@ pub fn test_pselect_nfds2() { ) .unwrap() ); - assert!(fd_set.contains(&r1)); - assert!(!fd_set.contains(&r2)); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); } macro_rules! generate_fdset_bad_fd_tests { @@ -60,7 +60,7 @@ macro_rules! generate_fdset_bad_fd_tests { #[should_panic] fn $method() { let bad_fd = unsafe{BorrowedFd::borrow_raw($fd)}; - FdSet::new().$method(&bad_fd); + FdSet::new().$method(bad_fd); } )* } From 489621e86af7c985ed136483dad09422cce6ea72 Mon Sep 17 00:00:00 2001 From: Carlos B Date: Sun, 1 Oct 2023 13:20:45 +0200 Subject: [PATCH 009/140] Changed signature for openat function (#2139) * Changed signature for openat function Signed-off-by: carlosb1 * Fixed tests for openat to apply Options Signed-off-by: carlosb1 * Updated changelog Signed-off-by: carlosb1 * Fixed num PR Signed-off-by: carlosb1 --------- Signed-off-by: carlosb1 --- CHANGELOG.md | 3 +++ src/dir.rs | 2 +- src/fcntl.rs | 4 ++-- test/test_fcntl.rs | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51cf8a2f46..2fe3e8a70f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ This project adheres to [Semantic Versioning](https://semver.org/). - `unistd::getpeereid` ([#2137](https://github.com/nix-rust/nix/pull/2137)) + +- Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s + ([#2139](https://github.com/nix-rust/nix/pull/2139)) - `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have relaxed lifetime requirements relative to 0.27.1. diff --git a/src/dir.rs b/src/dir.rs index 96a5843bc6..bdec58bd1b 100644 --- a/src/dir.rs +++ b/src/dir.rs @@ -44,7 +44,7 @@ impl Dir { /// Opens the given path as with `fcntl::openat`. pub fn openat( - dirfd: RawFd, + dirfd: Option, path: &P, oflag: OFlag, mode: sys::stat::Mode, diff --git a/src/fcntl.rs b/src/fcntl.rs index e9c67fe4dd..1ee8c96352 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -220,13 +220,13 @@ pub fn open( #[allow(clippy::useless_conversion)] #[cfg(not(target_os = "redox"))] pub fn openat( - dirfd: RawFd, + dirfd: Option, path: &P, oflag: OFlag, mode: Mode, ) -> Result { let fd = path.with_nix_path(|cstr| unsafe { - libc::openat(dirfd, cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) + libc::openat(at_rawfd(dirfd), cstr.as_ptr(), oflag.bits(), mode.bits() as c_uint) })?; Errno::result(fd) } diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index f216458e8a..45698490b6 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -42,7 +42,7 @@ fn test_openat() { open(tmp.path().parent().unwrap(), OFlag::empty(), Mode::empty()) .unwrap(); let fd = openat( - dirfd, + Some(dirfd), tmp.path().file_name().unwrap(), OFlag::O_RDONLY, Mode::empty(), From ea888247b731c32afaebe81fc9620060867b641e Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 1 Oct 2023 05:30:52 -0600 Subject: [PATCH 010/140] Relax lifetime requirements for PollFd::new (#2134) * Relax lifetime requirements for PollFd::new Fixes #2118 * Take BorrowedFd as the argument for PollFd::new &AsFd didn't work because there are 'static types, like std::fs::File, which implement AsFd. The created BorrowedFd type within the PollFd::new method would have a very brief lifetime, but the PhantomData would capture the lifetime of the std::fs::File. Taking BorrowFd<'fd> argument makes the lifetime explicit. * fix legacy comment --------- Co-authored-by: Steve Lau --- CHANGELOG.md | 4 ++++ src/poll.rs | 35 +++++++++++++++++++++++------------ test/test_poll.rs | 8 ++++---- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fe3e8a70f..69f628d8a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s ([#2139](https://github.com/nix-rust/nix/pull/2139)) +- `PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime + requirements relative to the previous version. + ([#2134](https://github.com/nix-rust/nix/pull/2134)) + - `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have relaxed lifetime requirements relative to 0.27.1. ([#2136](https://github.com/nix-rust/nix/pull/2136)) diff --git a/src/poll.rs b/src/poll.rs index 7fc3dc85de..2a8b62d2ad 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -22,24 +22,35 @@ pub struct PollFd<'fd> { impl<'fd> PollFd<'fd> { /// Creates a new `PollFd` specifying the events of interest /// for a given file descriptor. - // - // Different from other I/O-safe interfaces, here, we have to take `AsFd` - // by reference to prevent the case where the `fd` is closed but it is - // still in use. For example: + /// + /// # Examples + /// ```no_run + /// # use std::os::unix::io::{AsFd, AsRawFd, FromRawFd}; + /// # use nix::{ + /// # poll::{PollFd, PollFlags, poll}, + /// # unistd::{pipe, read} + /// # }; + /// let (r, w) = pipe().unwrap(); + /// let pfd = PollFd::new(r.as_fd(), PollFlags::POLLIN); + /// let mut fds = [pfd]; + /// poll(&mut fds, -1).unwrap(); + /// let mut buf = [0u8; 80]; + /// read(r.as_raw_fd(), &mut buf[..]); + /// ``` + // Unlike I/O functions, constructors like this must take `BorrowedFd` + // instead of AsFd or &AsFd. Otherwise, an `OwnedFd` argument would be + // dropped at the end of the method, leaving the structure referencing a + // closed file descriptor. For example: // // ```rust - // let (reader, _) = pipe().unwrap(); - // - // // If `PollFd::new()` takes `AsFd` by value, then `reader` will be consumed, - // // but the file descriptor of `reader` will still be in use. - // let pollfd = PollFd::new(reader, flag); - // + // let (r, _) = pipe().unwrap(); + // let pollfd = PollFd::new(r, flag); // Drops the OwnedFd // // Do something with `pollfd`, which uses the CLOSED fd. // ``` - pub fn new(fd: &'fd Fd, events: PollFlags) -> PollFd<'fd> { + pub fn new(fd: BorrowedFd<'fd>, events: PollFlags) -> PollFd<'fd> { PollFd { pollfd: libc::pollfd { - fd: fd.as_fd().as_raw_fd(), + fd: fd.as_raw_fd(), events: events.bits(), revents: PollFlags::empty().bits(), }, diff --git a/test/test_poll.rs b/test/test_poll.rs index 30207c95ea..fb4291721d 100644 --- a/test/test_poll.rs +++ b/test/test_poll.rs @@ -3,7 +3,7 @@ use nix::{ poll::{poll, PollFd, PollFlags}, unistd::{pipe, write}, }; -use std::os::unix::io::BorrowedFd; +use std::os::unix::io::{AsFd, BorrowedFd}; macro_rules! loop_while_eintr { ($poll_expr: expr) => { @@ -20,7 +20,7 @@ macro_rules! loop_while_eintr { #[test] fn test_poll() { let (r, w) = pipe().unwrap(); - let mut fds = [PollFd::new(&r, PollFlags::POLLIN)]; + let mut fds = [PollFd::new(r.as_fd(), PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout let nfds = loop_while_eintr!(poll(&mut fds, 100)); @@ -52,7 +52,7 @@ fn test_ppoll() { let timeout = TimeSpec::milliseconds(1); let (r, w) = pipe().unwrap(); - let mut fds = [PollFd::new(&r, PollFlags::POLLIN)]; + let mut fds = [PollFd::new(r.as_fd(), PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout let sigset = SigSet::empty(); @@ -71,7 +71,7 @@ fn test_ppoll() { #[test] fn test_pollfd_events() { let fd_zero = unsafe { BorrowedFd::borrow_raw(0) }; - let mut pfd = PollFd::new(&fd_zero, PollFlags::POLLIN); + let mut pfd = PollFd::new(fd_zero.as_fd(), PollFlags::POLLIN); assert_eq!(pfd.events(), PollFlags::POLLIN); pfd.set_events(PollFlags::POLLOUT); assert_eq!(pfd.events(), PollFlags::POLLOUT); From ca62a55a79e4fe32c05eebaeb688fc210cccef3d Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 2 Oct 2023 02:59:23 +0800 Subject: [PATCH 011/140] chore: add PR template (#2143) --- .github/PULL_REQUEST_TEMPLATE.md | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..ba373546b8 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,7 @@ +## What does this PR do + +## Checklist: + +- [ ] I have read `CONTRIBUTING.md` +- [ ] I have written necessary tests and rustdoc comments +- [ ] A change log has been added if this PR modifies nix's API From 9f4e87764fecb4e6a97f5cc2d9a40cd3a9a54aa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ad=C3=A4?= <35699107+Jan561@users.noreply.github.com> Date: Sun, 1 Oct 2023 20:59:36 +0200 Subject: [PATCH 012/140] fixes UB for recvmmsg, simplifies function signature of recvmmsg and sendmmsg (#2120) --- CHANGELOG.md | 5 +++++ src/sys/socket/mod.rs | 44 ++++++++++++++++++++++++++--------------- test/sys/test_socket.rs | 19 +++++++++++------- 3 files changed, 45 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69f628d8a0..d876b76017 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` ([#1946](https://github.com/nix-rust/nix/pull/1946)) +- Fixed the function signature of `recvmmsg`, potentially causing UB + ([#2119](https://github.com/nix-rust/nix/issues/2119)) + ### Changed - The following APIs now take an implementation of `AsFd` rather than a @@ -33,6 +36,8 @@ This project adheres to [Semantic Versioning](https://semver.org/). relaxed lifetime requirements relative to 0.27.1. ([#2136](https://github.com/nix-rust/nix/pull/2136)) +- Simplified the function signatures of `recvmmsg` and `sendmmsg` + ## [0.27.1] - 2023-08-28 ### Fixed diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index e03b1d690d..69933bd1a9 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1552,11 +1552,11 @@ pub fn sendmmsg<'a, XS, AS, C, I, S>( flags: MsgFlags ) -> crate::Result> where - XS: IntoIterator, + XS: IntoIterator, AS: AsRef<[Option]>, - I: AsRef<[IoSlice<'a>]> + 'a, - C: AsRef<[ControlMessage<'a>]> + 'a, - S: SockaddrLike + 'a + I: AsRef<[IoSlice<'a>]>, + C: AsRef<[ControlMessage<'a>]>, + S: SockaddrLike, { let mut count = 0; @@ -1564,11 +1564,11 @@ pub fn sendmmsg<'a, XS, AS, C, I, S>( for (i, ((slice, addr), mmsghdr)) in slices.into_iter().zip(addrs.as_ref()).zip(data.items.iter_mut() ).enumerate() { let p = &mut mmsghdr.msg_hdr; - p.msg_iov = slice.as_ref().as_ptr() as *mut libc::iovec; + p.msg_iov = slice.as_ref().as_ptr().cast_mut().cast(); p.msg_iovlen = slice.as_ref().len() as _; p.msg_namelen = addr.as_ref().map_or(0, S::len); - p.msg_name = addr.as_ref().map_or(ptr::null(), S::as_ptr) as _; + p.msg_name = addr.as_ref().map_or(ptr::null(), S::as_ptr).cast_mut().cast(); // Encode each cmsg. This must happen after initializing the header because // CMSG_NEXT_HDR and friends read the msg_control and msg_controllen fields. @@ -1583,9 +1583,16 @@ pub fn sendmmsg<'a, XS, AS, C, I, S>( pmhdr = unsafe { CMSG_NXTHDR(p, pmhdr) }; } - count = i+1; + // Doing an unchecked addition is alright here, as the only way to obtain an instance of `MultiHeaders` + // is through the `preallocate` function, which takes an `usize` as an argument to define its size, + // which also provides an upper bound for the size of this zipped iterator. Thus, `i < usize::MAX` or in + // other words: `count` doesn't overflow + count = i + 1; } + // SAFETY: all pointers are guaranteed to be valid for the scope of this function. `count` does represent the + // maximum number of messages that can be sent safely (i.e. `count` is the minimum of the sizes of `slices`, + // `data.items` and `addrs`) let sent = Errno::result(unsafe { libc::sendmmsg( fd, @@ -1711,14 +1718,19 @@ pub fn recvmmsg<'a, XS, S, I>( mut timeout: Option, ) -> crate::Result> where - XS: IntoIterator, - I: AsRef<[IoSliceMut<'a>]> + 'a, + XS: IntoIterator, + I: AsMut<[IoSliceMut<'a>]>, { let mut count = 0; - for (i, (slice, mmsghdr)) in slices.into_iter().zip(data.items.iter_mut()).enumerate() { + for (i, (mut slice, mmsghdr)) in slices.into_iter().zip(data.items.iter_mut()).enumerate() { let p = &mut mmsghdr.msg_hdr; - p.msg_iov = slice.as_ref().as_ptr() as *mut libc::iovec; - p.msg_iovlen = slice.as_ref().len() as _; + p.msg_iov = slice.as_mut().as_mut_ptr().cast(); + p.msg_iovlen = slice.as_mut().len() as _; + + // Doing an unchecked addition is alright here, as the only way to obtain an instance of `MultiHeaders` + // is through the `preallocate` function, which takes an `usize` as an argument to define its size, + // which also provides an upper bound for the size of this zipped iterator. Thus, `i < usize::MAX` or in + // other words: `count` doesn't overflow count = i + 1; } @@ -1726,6 +1738,8 @@ where .as_mut() .map_or_else(std::ptr::null_mut, |t| t as *mut _ as *mut libc::timespec); + // SAFETY: all pointers are guaranteed to be valid for the scope of this function. `count` does represent the + // maximum number of messages that can be received safely (i.e. `count` is the minimum of the sizes of `slices` and `data.items`) let received = Errno::result(unsafe { libc::recvmmsg( fd, @@ -1743,6 +1757,7 @@ where }) } +/// Iterator over results of [`recvmmsg`]/[`sendmmsg`] #[cfg(any( target_os = "linux", target_os = "android", @@ -1750,9 +1765,6 @@ where target_os = "netbsd", ))] #[derive(Debug)] -/// Iterator over results of [`recvmmsg`]/[`sendmmsg`] -/// -/// pub struct MultiResults<'a, S> { // preallocated structures rmm: &'a MultiHeaders, @@ -1903,7 +1915,7 @@ mod test { let t = sys::time::TimeSpec::from_duration(std::time::Duration::from_secs(10)); - let recv = super::recvmmsg(rsock.as_raw_fd(), &mut data, recv_iovs.iter(), flags, Some(t))?; + let recv = super::recvmmsg(rsock.as_raw_fd(), &mut data, recv_iovs.iter_mut(), flags, Some(t))?; for rmsg in recv { #[cfg(not(any(qemu, target_arch = "aarch64")))] diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index df83189981..4b55a71243 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -564,7 +564,7 @@ mod recvfrom { let res: Vec> = recvmmsg( rsock.as_raw_fd(), &mut data, - msgs.iter(), + msgs.iter_mut(), MsgFlags::empty(), None, ) @@ -652,7 +652,7 @@ mod recvfrom { let res: Vec> = recvmmsg( rsock.as_raw_fd(), &mut data, - msgs.iter(), + msgs.iter_mut(), MsgFlags::MSG_DONTWAIT, None, ) @@ -2324,12 +2324,17 @@ fn test_recvmmsg_timestampns() { // Receive the message let mut buffer = vec![0u8; message.len()]; let cmsgspace = nix::cmsg_space!(TimeSpec); - let iov = vec![[IoSliceMut::new(&mut buffer)]]; + let mut iov = vec![[IoSliceMut::new(&mut buffer)]]; let mut data = MultiHeaders::preallocate(1, Some(cmsgspace)); - let r: Vec> = - recvmmsg(in_socket.as_raw_fd(), &mut data, iov.iter(), flags, None) - .unwrap() - .collect(); + let r: Vec> = recvmmsg( + in_socket.as_raw_fd(), + &mut data, + iov.iter_mut(), + flags, + None, + ) + .unwrap() + .collect(); let rtime = match r[0].cmsgs().next() { Some(ControlMessageOwned::ScmTimestampns(rtime)) => rtime, Some(_) => panic!("Unexpected control message"), From 173bde107ae4566eaba09ac8ec85935fe2053fc2 Mon Sep 17 00:00:00 2001 From: Gilad Naaman <70581924+gnaaman-dn@users.noreply.github.com> Date: Sun, 1 Oct 2023 21:59:54 +0300 Subject: [PATCH 013/140] Add SockProtocol variants for ICMP{,v6} (#2103) --- CHANGELOG.md | 4 ++++ src/sys/socket/mod.rs | 24 ++++++++++++++++-------- test/sys/test_socket.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d876b76017..5a4c441805 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Simplified the function signatures of `recvmmsg` and `sendmmsg` +### Added +- Added `Icmp` and `IcmpV6` to `SockProtocol`. + (#[2103](https://github.com/nix-rust/nix/pull/2103)) + ## [0.27.1] - 2023-08-28 ### Fixed diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 69933bd1a9..81e4824129 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -132,11 +132,6 @@ pub enum SockProtocol { Udp = libc::IPPROTO_UDP, /// Raw sockets ([raw(7)](https://man7.org/linux/man-pages/man7/raw.7.html)) Raw = libc::IPPROTO_RAW, - /// Allows applications and other KEXTs to be notified when certain kernel events occur - /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) - #[cfg(any(target_os = "ios", target_os = "macos"))] - #[cfg_attr(docsrs, doc(cfg(all())))] - KextEvent = libc::SYSPROTO_EVENT, /// Allows applications to configure and control a KEXT /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) #[cfg(any(target_os = "ios", target_os = "macos"))] @@ -231,20 +226,33 @@ pub enum SockProtocol { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] EthAll = (libc::ETH_P_ALL as u16).to_be() as i32, + /// ICMP protocol ([icmp(7)](https://man7.org/linux/man-pages/man7/icmp.7.html)) + Icmp = libc::IPPROTO_ICMP, + /// ICMPv6 protocol (ICMP over IPv6) + IcmpV6 = libc::IPPROTO_ICMPV6, +} + +impl SockProtocol { /// The Controller Area Network raw socket protocol /// ([ref](https://docs.kernel.org/networking/can.html#how-to-use-socketcan)) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] - CanRaw = libc::CAN_RAW, -} + #[allow(non_upper_case_globals)] + pub const CanRaw: SockProtocol = SockProtocol::Icmp; // Matches libc::CAN_RAW -impl SockProtocol { /// The Controller Area Network broadcast manager protocol /// ([ref](https://docs.kernel.org/networking/can.html#how-to-use-socketcan)) #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(non_upper_case_globals)] pub const CanBcm: SockProtocol = SockProtocol::NetlinkUserSock; // Matches libc::CAN_BCM + + /// Allows applications and other KEXTs to be notified when certain kernel events occur + /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) + #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg_attr(docsrs, doc(cfg(all())))] + #[allow(non_upper_case_globals)] + pub const KextEvent: SockProtocol = SockProtocol::Icmp; // Matches libc::SYSPROTO_EVENT } #[cfg(any(target_os = "android", target_os = "linux"))] libc_bitflags! { diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 4b55a71243..49e46889b1 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -2685,3 +2685,36 @@ pub fn test_txtime() { recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, None, MsgFlags::empty()) .unwrap(); } + +// cfg needed for capability check. +#[cfg(any(target_os = "android", target_os = "linux"))] +#[test] +fn test_icmp_protocol() { + use nix::sys::socket::{ + sendto, socket, AddressFamily, MsgFlags, SockFlag, SockProtocol, + SockType, SockaddrIn, + }; + + require_capability!("test_icmp_protocol", CAP_NET_RAW); + + let owned_fd = socket( + AddressFamily::Inet, + SockType::Raw, + SockFlag::empty(), + SockProtocol::Icmp, + ) + .unwrap(); + + // Send a minimal ICMP packet with no payload. + let packet = [ + 0x08, // Type + 0x00, // Code + 0x84, 0x85, // Checksum + 0x73, 0x8a, // ID + 0x00, 0x00, // Sequence Number + ]; + + let dest_addr = SockaddrIn::new(127, 0, 0, 1, 0); + sendto(owned_fd.as_raw_fd(), &packet, &dest_addr, MsgFlags::empty()) + .unwrap(); +} From 591e2ed4f50f62acdc1a8ee2cb60773cf5dd020d Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 1 Oct 2023 20:28:34 -0600 Subject: [PATCH 014/140] Fix SignalFd::set_mask (#2141) In 0.27.0 it inadvertently closed the file descriptor, leaving the SignalFd object accessing a stale file descriptor. Fixes #2116 --- CHANGELOG.md | 4 ++++ src/sys/signalfd.rs | 13 ++++++++++++- test/sys/test_signalfd.rs | 29 +++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a4c441805..0d21cad4b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Fixed the function signature of `recvmmsg`, potentially causing UB ([#2119](https://github.com/nix-rust/nix/issues/2119)) +- Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file + descriptor. + ([#2141](https://github.com/nix-rust/nix/pull/2141)) + ### Changed - The following APIs now take an implementation of `AsFd` rather than a diff --git a/src/sys/signalfd.rs b/src/sys/signalfd.rs index 697bcf073d..36516074a6 100644 --- a/src/sys/signalfd.rs +++ b/src/sys/signalfd.rs @@ -101,7 +101,7 @@ impl SignalFd { } pub fn set_mask(&mut self, mask: &SigSet) -> Result<()> { - _signalfd(Some(self.0.as_fd()), mask, SfdFlags::empty()).map(drop) + self.update(mask, SfdFlags::empty()) } pub fn read_signal(&mut self) -> Result> { @@ -119,6 +119,17 @@ impl SignalFd { Err(error) => Err(error), } } + + fn update(&self, mask: &SigSet, flags: SfdFlags) -> Result<()> { + let raw_fd = self.0.as_raw_fd(); + unsafe { + Errno::result(libc::signalfd( + raw_fd, + mask.as_ref(), + flags.bits(), + )).map(drop) + } + } } impl AsFd for SignalFd { diff --git a/test/sys/test_signalfd.rs b/test/sys/test_signalfd.rs index 87153c9572..6a279d1832 100644 --- a/test/sys/test_signalfd.rs +++ b/test/sys/test_signalfd.rs @@ -25,3 +25,32 @@ fn test_signalfd() { let signo = Signal::try_from(res.ssi_signo as i32).unwrap(); assert_eq!(signo, signal::SIGUSR1); } + +/// Update the signal mask of an already existing signalfd. +#[test] +fn test_signalfd_setmask() { + use nix::sys::signal::{self, raise, SigSet, Signal}; + use nix::sys::signalfd::SignalFd; + + // Grab the mutex for altering signals so we don't interfere with other tests. + let _m = crate::SIGNAL_MTX.lock(); + + // Block the SIGUSR1 signal from automatic processing for this thread + let mut mask = SigSet::empty(); + + let mut fd = SignalFd::new(&mask).unwrap(); + + mask.add(signal::SIGUSR1); + mask.thread_block().unwrap(); + fd.set_mask(&mask).unwrap(); + + // Send a SIGUSR1 signal to the current process. Note that this uses `raise` instead of `kill` + // because `kill` with `getpid` isn't correct during multi-threaded execution like during a + // cargo test session. Instead use `raise` which does the correct thing by default. + raise(signal::SIGUSR1).expect("Error: raise(SIGUSR1) failed"); + + // And now catch that same signal. + let res = fd.read_signal().unwrap().unwrap(); + let signo = Signal::try_from(res.ssi_signo as i32).unwrap(); + assert_eq!(signo, signal::SIGUSR1); +} From 2f4861f876e8194fe06934afb6e91957b25fdab9 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 1 Oct 2023 22:02:56 -0600 Subject: [PATCH 015/140] Raise MSRV to 1.69.0 (#2144) * Raise MSRV to 1.69.0 This allows us to use the very useful CStr::from_bytes_until_nul * Respond to review comments * Switch the name of the Fuchsia CI target x86_64-fuchsia -> x86_64-unknown-fuchsia --- .cirrus.yml | 12 ++++++------ CHANGELOG.md | 3 +++ README.md | 2 +- src/mount/bsd.rs | 11 ++++------- src/sys/prctl.rs | 9 +++++---- src/unistd.rs | 17 +++++++---------- 6 files changed, 26 insertions(+), 28 deletions(-) diff --git a/.cirrus.yml b/.cirrus.yml index 522bdafcdb..fc564e65aa 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -9,7 +9,7 @@ env: RUSTFLAGS: -D warnings RUSTDOCFLAGS: -D warnings TOOL: cargo - MSRV: 1.65.0 + MSRV: 1.69.0 ZFLAGS: # Tests that don't require executing the build binaries @@ -146,7 +146,7 @@ task: matrix: - name: Linux aarch64 arm_container: - image: rust:1.65.0 + image: rust:1.69.0 cpu: 1 depends_on: - FreeBSD 14 amd64 & i686 @@ -160,13 +160,13 @@ task: TARGET: aarch64-unknown-linux-gnu - name: Linux x86_64 container: - image: rust:1.65.0 + image: rust:1.69.0 cpu: 1 env: TARGET: x86_64-unknown-linux-gnu - name: Linux x86_64 musl container: - image: rust:1.65.0 + image: rust:1.69.0 cpu: 1 depends_on: - FreeBSD 14 amd64 & i686 @@ -199,7 +199,7 @@ task: # Tasks for cross-compiling, but no testing task: container: - image: rust:1.65.0 + image: rust:1.69.0 cpu: 1 depends_on: - FreeBSD 14 amd64 & i686 @@ -235,7 +235,7 @@ task: TARGET: arm-unknown-linux-musleabi - name: Fuchsia x86_64 env: - TARGET: x86_64-fuchsia + TARGET: x86_64-unknown-fuchsia - name: Illumos env: TARGET: x86_64-unknown-illumos diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d21cad4b8..2406958e0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,9 @@ This project adheres to [Semantic Versioning](https://semver.org/). ### Changed +- The MSRV is now 1.69 + ([#2144](https://github.com/nix-rust/nix/pull/2144)) + - The following APIs now take an implementation of `AsFd` rather than a `RawFd`: diff --git a/README.md b/README.md index 452d65466e..157b8da120 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ The following targets are supported by `nix`: ## Minimum Supported Rust Version (MSRV) -nix is supported on Rust 1.65 and higher. Its MSRV will not be +nix is supported on Rust 1.69 and higher. Its MSRV will not be changed in the future without bumping the major or minor version. ## Contributing diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index 3076304cab..bc28b49b71 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -396,13 +396,10 @@ impl<'a> Nmount<'a> { match Errno::result(res) { Ok(_) => Ok(()), Err(error) => { - let errmsg = match errmsg.iter().position(|&x| x == 0) { - None => None, - Some(0) => None, - Some(n) => { - let sl = &errmsg[0..n + 1]; - Some(CStr::from_bytes_with_nul(sl).unwrap()) - } + let errmsg = if errmsg[0] == 0 { + None + } else { + CStr::from_bytes_until_nul(&errmsg[..]).ok() }; Err(NmountError::new(error, errmsg)) } diff --git a/src/sys/prctl.rs b/src/sys/prctl.rs index 995382cb0c..a48065a66b 100644 --- a/src/sys/prctl.rs +++ b/src/sys/prctl.rs @@ -151,10 +151,11 @@ pub fn get_name() -> Result { let res = unsafe { libc::prctl(libc::PR_GET_NAME, &buf, 0, 0, 0) }; - let len = buf.iter().position(|&c| c == 0).unwrap_or(buf.len()); - let name = CStr::from_bytes_with_nul(&buf[..=len]).map_err(|_| Errno::EINVAL)?; - - Errno::result(res).map(|_| name.to_owned()) + Errno::result(res).and_then(|_| { + CStr::from_bytes_until_nul(&buf) + .map(CStr::to_owned) + .map_err(|_| Errno::EINVAL) + }) } /// Sets the timer slack value for the calling thread. Timer slack is used by the kernel to group diff --git a/src/unistd.rs b/src/unistd.rs index 2eb23fa95c..700a4af3ba 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -28,14 +28,11 @@ use libc::{ uid_t, PATH_MAX, }; use std::convert::Infallible; -use std::ffi::{CStr, OsString}; #[cfg(not(target_os = "redox"))] -use std::ffi::{CString, OsStr}; -#[cfg(not(target_os = "redox"))] -use std::os::unix::ffi::OsStrExt; -use std::os::unix::ffi::OsStringExt; -use std::os::unix::io::RawFd; -use std::os::unix::io::{AsFd, AsRawFd, OwnedFd}; +use std::ffi::CString; +use std::ffi::{CStr, OsStr, OsString}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; +use std::os::unix::io::{AsFd, AsRawFd, OwnedFd, RawFd}; use std::path::PathBuf; use std::{fmt, mem, ptr}; @@ -3928,9 +3925,9 @@ pub fn ttyname(fd: F) -> Result { return Err(Errno::from_i32(ret)); } - let nul = buf.iter().position(|c| *c == b'\0').unwrap(); - buf.truncate(nul); - Ok(OsString::from_vec(buf).into()) + CStr::from_bytes_until_nul(&buf[..]) + .map(|s| OsStr::from_bytes(s.to_bytes()).into()) + .map_err(|_| Errno::EINVAL) } } From 14a2969431d5a518ac5f9f0e7ba80530afdde24a Mon Sep 17 00:00:00 2001 From: sgasse <47532708+sgasse@users.noreply.github.com> Date: Tue, 3 Oct 2023 09:43:56 +0200 Subject: [PATCH 016/140] 2075: Add ControlMessage::Ipv6HopLimit (#2074) When sending IPv6 packets with `sendmsg`, Linux does not use the hop limit set on the socket. Instead, the hop limit has to be specified for each individual message with ancillary data in a cmsg. This commit adds the enum variant `ControlMessage::Ipv6HopLimit` to specify the limit. The variant is available on the `net` feature flag for Linux, MacOs, FreeBSD, DragonflyBSD, Android, iOS and Haiku. Co-authored-by: Simon B. Gasse --- CHANGELOG.md | 4 +++ src/sys/socket/mod.rs | 66 ++++++++++++++++++++++++++++++++++--------- 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2406958e0f..f73e2a0e78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,10 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Added `Icmp` and `IcmpV6` to `SockProtocol`. (#[2103](https://github.com/nix-rust/nix/pull/2103)) +- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, + MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. + ([#2074](https://github.com/nix-rust/nix/pull/2074)) + ## [0.27.1] - 2023-08-28 ### Fixed diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 81e4824129..b34c4c3fdb 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -18,7 +18,7 @@ use libc::{ use std::io::{IoSlice, IoSliceMut}; #[cfg(feature = "net")] use std::net; -use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, RawFd, OwnedFd}; +use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::{mem, ptr}; #[deny(missing_docs)] @@ -62,7 +62,11 @@ pub use crate::sys::socket::addr::netlink::NetlinkAddr; #[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg(feature = "ioctl")] pub use crate::sys::socket::addr::sys_control::SysControlAddr; -#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] +#[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" +))] pub use crate::sys::socket::addr::vsock::VsockAddr; #[cfg(all(feature = "uio", not(target_os = "redox")))] @@ -1147,7 +1151,7 @@ pub enum ControlMessage<'a> { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] UdpGsoSegments(&'a u16), - /// Configure the sending addressing and interface for v4 + /// Configure the sending addressing and interface for v4. /// /// For further information, please refer to the /// [`ip(7)`](https://man7.org/linux/man-pages/man7/ip.7.html) man page. @@ -1160,7 +1164,7 @@ pub enum ControlMessage<'a> { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4PacketInfo(&'a libc::in_pktinfo), - /// Configure the sending addressing and interface for v6 + /// Configure the sending addressing and interface for v6. /// /// For further information, please refer to the /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. @@ -1185,6 +1189,22 @@ pub enum ControlMessage<'a> { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4SendSrcAddr(&'a libc::in_addr), + /// Configure the hop limit for v6 multicast traffic. + /// + /// Set the IPv6 hop limit for this message. The argument is an integer + /// between 0 and 255. A value of -1 will set the hop limit to the route + /// default if possible on the interface. Without this cmsg, packets sent + /// with sendmsg have a hop limit of 1 and will not leave the local network. + /// For further information, please refer to the + /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. + #[cfg(any(target_os = "linux", target_os = "macos", + target_os = "freebsd", target_os = "dragonfly", + target_os = "android", target_os = "ios", + target_os = "haiku"))] + #[cfg(feature = "net")] + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + Ipv6HopLimit(&'a libc::c_int), + /// SO_RXQ_OVFL indicates that an unsigned 32 bit value /// ancilliary msg (cmsg) should be attached to recieved /// skbs indicating the number of packets dropped by the @@ -1298,6 +1318,12 @@ impl<'a> ControlMessage<'a> { target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => addr as *const _ as *const u8, + #[cfg(any(target_os = "linux", target_os = "macos", + target_os = "freebsd", target_os = "dragonfly", + target_os = "android", target_os = "ios", + target_os = "haiku"))] + #[cfg(feature = "net")] + ControlMessage::Ipv6HopLimit(limit) => limit as *const _ as *const u8, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(drop_count) => { drop_count as *const _ as *const u8 @@ -1361,6 +1387,14 @@ impl<'a> ControlMessage<'a> { target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => mem::size_of_val(addr), + #[cfg(any(target_os = "linux", target_os = "macos", + target_os = "freebsd", target_os = "dragonfly", + target_os = "android", target_os = "ios", + target_os = "haiku"))] + #[cfg(feature = "net")] + ControlMessage::Ipv6HopLimit(limit) => { + mem::size_of_val(limit) + }, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(drop_count) => { mem::size_of_val(drop_count) @@ -1400,6 +1434,12 @@ impl<'a> ControlMessage<'a> { target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IPPROTO_IP, + #[cfg(any(target_os = "linux", target_os = "macos", + target_os = "freebsd", target_os = "dragonfly", + target_os = "android", target_os = "ios", + target_os = "haiku"))] + #[cfg(feature = "net")] + ControlMessage::Ipv6HopLimit(_) => libc::IPPROTO_IPV6, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(_) => libc::SOL_SOCKET, #[cfg(target_os = "linux")] @@ -1446,6 +1486,12 @@ impl<'a> ControlMessage<'a> { target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IP_SENDSRCADDR, + #[cfg(any(target_os = "linux", target_os = "macos", + target_os = "freebsd", target_os = "dragonfly", + target_os = "android", target_os = "ios", + target_os = "haiku"))] + #[cfg(feature = "net")] + ControlMessage::Ipv6HopLimit(_) => libc::IPV6_HOPLIMIT, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] ControlMessage::RxqOvfl(_) => { libc::SO_RXQ_OVFL @@ -2186,9 +2232,7 @@ pub fn socketpair>>( Errno::result(res)?; // Safe because socketpair returned success. - unsafe { - Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) - } + unsafe { Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) } } /// Listen for connections on a socket @@ -2296,13 +2340,7 @@ pub fn recvfrom( &mut len as *mut socklen_t, ))? as usize; - Ok(( - ret, - T::from_raw( - addr.assume_init().as_ptr(), - Some(len), - ), - )) + Ok((ret, T::from_raw(addr.assume_init().as_ptr(), Some(len)))) } } From 68c230b37e82c6e714cbd7b5b1b9c3785fda2438 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Tue, 3 Oct 2023 10:16:32 +0100 Subject: [PATCH 017/140] fcntl add F_GETPATH support for apple/netbsd/dragonfly (#2142) * fcntl add F_GETPATH support for apple/netbsd * changes from review * CHANGELOG entry --------- Co-authored-by: SteveLauC --- CHANGELOG.md | 3 +++ src/fcntl.rs | 25 +++++++++++++++++++++++++ test/test_fcntl.rs | 23 +++++++++++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f73e2a0e78..aaab7b2d75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,9 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Added `Icmp` and `IcmpV6` to `SockProtocol`. (#[2103](https://github.com/nix-rust/nix/pull/2103)) +- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. + ([#2142](https://github.com/nix-rust/nix/pull/2142)) + - Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. ([#2074](https://github.com/nix-rust/nix/pull/2074)) diff --git a/src/fcntl.rs b/src/fcntl.rs index 1ee8c96352..a711a41170 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -1,11 +1,25 @@ use crate::errno::Errno; use libc::{self, c_int, c_uint, size_t, ssize_t}; +#[cfg(any( + target_os = "netbsd", + target_os = "macos", + target_os = "ios", + target_os = "dragonfly", +))] +use std::ffi::CStr; use std::ffi::OsString; #[cfg(not(target_os = "redox"))] use std::os::raw; use std::os::unix::ffi::OsStringExt; use std::os::unix::io::RawFd; // For splice and copy_file_range +#[cfg(any( + target_os = "netbsd", + target_os = "macos", + target_os = "ios", + target_os = "dragonfly", +))] +use std::path::PathBuf; #[cfg(any( target_os = "android", target_os = "freebsd", @@ -489,6 +503,8 @@ pub enum FcntlArg<'a> { F_GETPIPE_SZ, #[cfg(any(target_os = "linux", target_os = "android"))] F_SETPIPE_SZ(c_int), + #[cfg(any(target_os = "netbsd", target_os = "dragonfly", target_os = "macos", target_os = "ios"))] + F_GETPATH(&'a mut PathBuf), // TODO: Rest of flags } @@ -549,6 +565,15 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { F_GETPIPE_SZ => libc::fcntl(fd, libc::F_GETPIPE_SZ), #[cfg(any(target_os = "linux", target_os = "android"))] F_SETPIPE_SZ(size) => libc::fcntl(fd, libc::F_SETPIPE_SZ, size), + #[cfg(any(target_os = "dragonfly", target_os = "netbsd", target_os = "macos", target_os = "ios"))] + F_GETPATH(path) => { + let mut buffer = vec![0; libc::PATH_MAX as usize]; + let res = libc::fcntl(fd, libc::F_GETPATH, buffer.as_mut_ptr()); + let ok_res = Errno::result(res)?; + let optr = CStr::from_bytes_until_nul(&buffer).unwrap(); + *path = PathBuf::from(OsString::from(optr.to_str().unwrap())); + return Ok(ok_res) + }, } }; diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 45698490b6..0faf39d237 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -561,3 +561,26 @@ mod test_posix_fallocate { } } } + +#[cfg(any( + target_os = "dragonfly", + target_os = "netbsd", + target_os = "macos", + target_os = "ios" +))] +#[test] +fn test_f_get_path() { + use nix::fcntl::*; + use std::{os::unix::io::AsRawFd, path::PathBuf}; + + let tmp = NamedTempFile::new().unwrap(); + let fd = tmp.as_raw_fd(); + let mut path = PathBuf::new(); + let res = + fcntl(fd, FcntlArg::F_GETPATH(&mut path)).expect("get path failed"); + assert_ne!(res, -1); + assert_eq!( + path.as_path().canonicalize().unwrap(), + tmp.path().canonicalize().unwrap() + ); +} From ae9b09284357eb33536eba7cdca34e8a3ea1bf93 Mon Sep 17 00:00:00 2001 From: Carlos B Date: Wed, 4 Oct 2023 12:00:18 +0200 Subject: [PATCH 018/140] Updated CONTRIBUTING.md with correct test command (#2150) * Updated CONTRIBUTING.md with correct test command Signed-off-by: carlosb1 * Changed test command --------- Signed-off-by: carlosb1 --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8898a7c1fa..70e7cd7f95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -70,7 +70,7 @@ follow the conventions of [Keep A CHANGELOG][kacl]. ## Testing -nix has a test suite that you can run with `cargo test`. Ideally, we'd like pull +nix has a test suite that you can run with `cargo test --all-features`. Ideally, we'd like pull requests to include tests where they make sense. For example, when fixing a bug, add a test that would have failed without the fix. From 6906a61a9d25def9b21d14fa84d9e4e12a618317 Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Thu, 5 Oct 2023 10:26:13 +0100 Subject: [PATCH 019/140] Sigset conveniance (#1959) * feat: `impl From for SigSet` * feat: `impl std::ops::BitOr for SigSet` * feat: `impl std::ops::BitOr for Signal` * feat: `impl std::ops::BitOr for SigSet` --- CHANGELOG.md | 10 ++++++++++ src/sys/signal.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index aaab7b2d75..45a7710774 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Fixed the function signature of `recvmmsg`, potentially causing UB ([#2119](https://github.com/nix-rust/nix/issues/2119)) +### Added + +- Added `impl From for SigSet`. + ([#1959](https://github.com/nix-rust/nix/pull/1959)) +- Added `impl std::ops::BitOr for SigSet`. + ([#1959](https://github.com/nix-rust/nix/pull/1959)) +- Added `impl std::ops::BitOr for Signal`. + ([#1959](https://github.com/nix-rust/nix/pull/1959)) +- Added `impl std::ops::BitOr for SigSet` + ([#1959](https://github.com/nix-rust/nix/pull/1959)) - Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file descriptor. diff --git a/src/sys/signal.rs b/src/sys/signal.rs index de16aed5da..e3274f27e9 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -9,6 +9,7 @@ use cfg_if::cfg_if; use std::fmt; use std::hash::{Hash, Hasher}; use std::mem; +use std::ops::BitOr; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] use std::os::unix::io::RawFd; use std::ptr; @@ -604,6 +605,42 @@ impl SigSet { } } +impl From for SigSet { + fn from(signal: Signal) -> SigSet { + let mut sigset = SigSet::empty(); + sigset.add(signal); + sigset + } +} + +impl BitOr for Signal { + type Output = SigSet; + + fn bitor(self, rhs: Self) -> Self::Output { + let mut sigset = SigSet::empty(); + sigset.add(self); + sigset.add(rhs); + sigset + } +} + +impl BitOr for SigSet { + type Output = SigSet; + + fn bitor(mut self, rhs: Signal) -> Self::Output { + self.add(rhs); + self + } +} + +impl BitOr for SigSet { + type Output = Self; + + fn bitor(self, rhs: Self) -> Self::Output { + self.iter().chain(rhs.iter()).collect() + } +} + impl AsRef for SigSet { fn as_ref(&self) -> &libc::sigset_t { &self.sigset From ed3ed6ba4fde75ac9140df9705a21f60d3f1c931 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Fri, 6 Oct 2023 01:47:14 +0100 Subject: [PATCH 020/140] fcntl update following up with F_GETPATH but with FreeBSD's F_KINFO flag support instead (#2152) --- CHANGELOG.md | 3 +++ src/fcntl.rs | 18 ++++++++++++++++++ test/test_fcntl.rs | 19 +++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45a7710774..fa7d597174 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -66,6 +66,9 @@ This project adheres to [Semantic Versioning](https://semver.org/). MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. ([#2074](https://github.com/nix-rust/nix/pull/2074)) +- Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. + ([#2152](https://github.com/nix-rust/nix/pull/2152)) + ## [0.27.1] - 2023-08-28 ### Fixed diff --git a/src/fcntl.rs b/src/fcntl.rs index a711a41170..5dd05751cf 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -1,10 +1,13 @@ use crate::errno::Errno; +#[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] +use core::slice; use libc::{self, c_int, c_uint, size_t, ssize_t}; #[cfg(any( target_os = "netbsd", target_os = "macos", target_os = "ios", target_os = "dragonfly", + all(target_os = "freebsd", target_arch = "x86_64"), ))] use std::ffi::CStr; use std::ffi::OsString; @@ -18,6 +21,7 @@ use std::os::unix::io::RawFd; target_os = "macos", target_os = "ios", target_os = "dragonfly", + all(target_os = "freebsd", target_arch = "x86_64"), ))] use std::path::PathBuf; #[cfg(any( @@ -505,6 +509,8 @@ pub enum FcntlArg<'a> { F_SETPIPE_SZ(c_int), #[cfg(any(target_os = "netbsd", target_os = "dragonfly", target_os = "macos", target_os = "ios"))] F_GETPATH(&'a mut PathBuf), + #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] + F_KINFO(&'a mut PathBuf), // TODO: Rest of flags } @@ -574,6 +580,18 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { *path = PathBuf::from(OsString::from(optr.to_str().unwrap())); return Ok(ok_res) }, + #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] + F_KINFO(path) => { + let mut info: libc::kinfo_file = std::mem::zeroed(); + info.kf_structsize = std::mem::size_of::() as i32; + let res = libc::fcntl(fd, libc::F_KINFO, &mut info); + let ok_res = Errno::result(res)?; + let p = info.kf_path; + let u8_slice = slice::from_raw_parts(p.as_ptr().cast(), p.len()); + let optr = CStr::from_bytes_until_nul(u8_slice).unwrap(); + *path = PathBuf::from(OsString::from(optr.to_str().unwrap())); + return Ok(ok_res) + }, } }; diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 0faf39d237..13b6485eb3 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -584,3 +584,22 @@ fn test_f_get_path() { tmp.path().canonicalize().unwrap() ); } + +#[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] +#[test] +fn test_f_kinfo() { + use nix::fcntl::*; + use std::{os::unix::io::AsRawFd, path::PathBuf}; + + let tmp = NamedTempFile::new().unwrap(); + // With TMPDIR set with UFS, the vnode name is not entered + // into the name cache thus path is always empty. + // Therefore, we reopen the tempfile a second time for the test + // to pass. + let tmp2 = File::open(tmp.path()).unwrap(); + let fd = tmp2.as_raw_fd(); + let mut path = PathBuf::new(); + let res = fcntl(fd, FcntlArg::F_KINFO(&mut path)).expect("get path failed"); + assert_ne!(res, -1); + assert_eq!(path, tmp.path()); +} From e7c877abf73f7f74e358f260683b70ce46db13b0 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 6 Oct 2023 09:09:59 +0800 Subject: [PATCH 021/140] chose: fix CHANGELOG.md remvoe duplicate Added sections (#2158) --- CHANGELOG.md | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa7d597174..f085067a07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,13 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Added `impl From for SigSet`. ([#1959](https://github.com/nix-rust/nix/pull/1959)) + - Added `impl std::ops::BitOr for SigSet`. ([#1959](https://github.com/nix-rust/nix/pull/1959)) + - Added `impl std::ops::BitOr for Signal`. ([#1959](https://github.com/nix-rust/nix/pull/1959)) + - Added `impl std::ops::BitOr for SigSet` ([#1959](https://github.com/nix-rust/nix/pull/1959)) @@ -26,6 +29,19 @@ This project adheres to [Semantic Versioning](https://semver.org/). descriptor. ([#2141](https://github.com/nix-rust/nix/pull/2141)) +- Added `Icmp` and `IcmpV6` to `SockProtocol`. + (#[2103](https://github.com/nix-rust/nix/pull/2103)) + +- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. + ([#2142](https://github.com/nix-rust/nix/pull/2142)) + +- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, + MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. + ([#2074](https://github.com/nix-rust/nix/pull/2074)) + +- Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. + ([#2152](https://github.com/nix-rust/nix/pull/2152)) + ### Changed - The MSRV is now 1.69 @@ -55,20 +71,6 @@ This project adheres to [Semantic Versioning](https://semver.org/). - Simplified the function signatures of `recvmmsg` and `sendmmsg` -### Added -- Added `Icmp` and `IcmpV6` to `SockProtocol`. - (#[2103](https://github.com/nix-rust/nix/pull/2103)) - -- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. - ([#2142](https://github.com/nix-rust/nix/pull/2142)) - -- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, - MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. - ([#2074](https://github.com/nix-rust/nix/pull/2074)) - -- Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. - ([#2152](https://github.com/nix-rust/nix/pull/2152)) - ## [0.27.1] - 2023-08-28 ### Fixed From b28132b7fb7c71e0cc4acc801b5e91e5e769ad47 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sat, 7 Oct 2023 09:38:09 +0800 Subject: [PATCH 022/140] chore: use towncrier for CHANGELOG (#2149) --- CHANGELOG.md | 70 +-------------------------------------- CONTRIBUTING.md | 27 ++++++++++++--- RELEASE_PROCEDURE.md | 3 ++ changelog/.keep | 5 +++ changelog/1946.fixed.md | 1 + changelog/1959.added.md | 4 +++ changelog/2074.added.md | 2 ++ changelog/2103.added.md | 1 + changelog/2119.changed.md | 1 + changelog/2119.fixed.md | 1 + changelog/2134.changed.md | 2 ++ changelog/2136.changed.md | 2 ++ changelog/2137.changed.md | 8 +++++ changelog/2139.changed.md | 1 + changelog/2141.fixed.md | 1 + changelog/2142.added.md | 1 + changelog/2144.changed.md | 1 + changelog/2152.added.md | 1 + release.toml | 4 --- towncrier.toml | 27 +++++++++++++++ 20 files changed, 86 insertions(+), 77 deletions(-) create mode 100644 changelog/.keep create mode 100644 changelog/1946.fixed.md create mode 100644 changelog/1959.added.md create mode 100644 changelog/2074.added.md create mode 100644 changelog/2103.added.md create mode 100644 changelog/2119.changed.md create mode 100644 changelog/2119.fixed.md create mode 100644 changelog/2134.changed.md create mode 100644 changelog/2136.changed.md create mode 100644 changelog/2137.changed.md create mode 100644 changelog/2139.changed.md create mode 100644 changelog/2141.fixed.md create mode 100644 changelog/2142.added.md create mode 100644 changelog/2144.changed.md create mode 100644 changelog/2152.added.md delete mode 100644 release.toml create mode 100644 towncrier.toml diff --git a/CHANGELOG.md b/CHANGELOG.md index f085067a07..934d611e84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,75 +1,7 @@ -# Change Log - All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/). -## [Unreleased] - ReleaseDate - -### Fixed -- Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` - ([#1946](https://github.com/nix-rust/nix/pull/1946)) - -- Fixed the function signature of `recvmmsg`, potentially causing UB - ([#2119](https://github.com/nix-rust/nix/issues/2119)) -### Added - -- Added `impl From for SigSet`. - ([#1959](https://github.com/nix-rust/nix/pull/1959)) - -- Added `impl std::ops::BitOr for SigSet`. - ([#1959](https://github.com/nix-rust/nix/pull/1959)) - -- Added `impl std::ops::BitOr for Signal`. - ([#1959](https://github.com/nix-rust/nix/pull/1959)) - -- Added `impl std::ops::BitOr for SigSet` - ([#1959](https://github.com/nix-rust/nix/pull/1959)) - -- Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file - descriptor. - ([#2141](https://github.com/nix-rust/nix/pull/2141)) - -- Added `Icmp` and `IcmpV6` to `SockProtocol`. - (#[2103](https://github.com/nix-rust/nix/pull/2103)) - -- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. - ([#2142](https://github.com/nix-rust/nix/pull/2142)) - -- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, - MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. - ([#2074](https://github.com/nix-rust/nix/pull/2074)) - -- Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. - ([#2152](https://github.com/nix-rust/nix/pull/2152)) - -### Changed - -- The MSRV is now 1.69 - ([#2144](https://github.com/nix-rust/nix/pull/2144)) - -- The following APIs now take an implementation of `AsFd` rather than a - `RawFd`: - - - `unistd::tcgetpgrp` - - `unistd::tcsetpgrp` - - `unistd::fpathconf` - - `unistd::ttyname` - - `unistd::getpeereid` - - ([#2137](https://github.com/nix-rust/nix/pull/2137)) - -- Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s - ([#2139](https://github.com/nix-rust/nix/pull/2139)) - -- `PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime - requirements relative to the previous version. - ([#2134](https://github.com/nix-rust/nix/pull/2134)) - -- `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have - relaxed lifetime requirements relative to 0.27.1. - ([#2136](https://github.com/nix-rust/nix/pull/2136)) - -- Simplified the function signatures of `recvmmsg` and `sendmmsg` +# Change Log ## [0.27.1] - 2023-08-28 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 70e7cd7f95..a45fc9905c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -61,11 +61,30 @@ pull' model described there. Please make pull requests against the `master` branch. If you change the API by way of adding, removing or changing something or if -you fix a bug, please add an appropriate note to the [change log][cl]. We -follow the conventions of [Keep A CHANGELOG][kacl]. +you fix a bug, please add an appropriate note, every note should be a new markdown +file under the [changelog directory][cl] stating the change made by your pull request, +the filename should be in the following foramt: -[cl]: https://github.com/nix-rust/nix/blob/master/CHANGELOG.md -[kacl]: https://github.com/olivierlacan/keep-a-changelog/tree/18adb5f5be7a898d046f6a4acb93e39dcf40c4ad +``` +..md +``` + +These are 4 `TYPE`s available: + +1. `added` +2. `changed` +3. `fixed` +4. `removed` + +Let's say you have added a new API to nix, then a change log like this should +be added (assume it is PR #0) + +```md +# file: 0.added.md +Added a new API xxx +``` + +[cl]: https://github.com/nix-rust/nix/tree/master/changelog [pr-docs]: https://help.github.com/articles/using-pull-requests/ ## Testing diff --git a/RELEASE_PROCEDURE.md b/RELEASE_PROCEDURE.md index 9c68f78b18..1ffd21aa84 100644 --- a/RELEASE_PROCEDURE.md +++ b/RELEASE_PROCEDURE.md @@ -13,6 +13,9 @@ The release is prepared as follows: - Ask for a new libc version if, necessary. It usually is. Then update the dependency in Cargo.toml accordingly. +- Update the version number in `Cargo.toml` +- Generate `CHANGELOG.md` for this release by + `towncrier build --version= --yes` - Confirm that everything's ready for a release by running `cargo release ` - Create the release with `cargo release -x ` diff --git a/changelog/.keep b/changelog/.keep new file mode 100644 index 0000000000..f36597d920 --- /dev/null +++ b/changelog/.keep @@ -0,0 +1,5 @@ +Do not remove this file. This is used to keep the `changelog` dir around after +generating new changelog file. + +Without this, `towncrier` would remove the changelog files as well as the +directory if it is empty. diff --git a/changelog/1946.fixed.md b/changelog/1946.fixed.md new file mode 100644 index 0000000000..7c96cde003 --- /dev/null +++ b/changelog/1946.fixed.md @@ -0,0 +1 @@ +Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` diff --git a/changelog/1959.added.md b/changelog/1959.added.md new file mode 100644 index 0000000000..c7dfb49465 --- /dev/null +++ b/changelog/1959.added.md @@ -0,0 +1,4 @@ +- Added `impl From for SigSet`. +- Added `impl std::ops::BitOr for SigSet`. +- Added `impl std::ops::BitOr for Signal`. +- Added `impl std::ops::BitOr for SigSet` \ No newline at end of file diff --git a/changelog/2074.added.md b/changelog/2074.added.md new file mode 100644 index 0000000000..e11a09c47e --- /dev/null +++ b/changelog/2074.added.md @@ -0,0 +1,2 @@ +Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, +MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. diff --git a/changelog/2103.added.md b/changelog/2103.added.md new file mode 100644 index 0000000000..dc39d75258 --- /dev/null +++ b/changelog/2103.added.md @@ -0,0 +1 @@ +Added `Icmp` and `IcmpV6` to `SockProtocol` diff --git a/changelog/2119.changed.md b/changelog/2119.changed.md new file mode 100644 index 0000000000..88b88fa595 --- /dev/null +++ b/changelog/2119.changed.md @@ -0,0 +1 @@ +Simplified the function signatures of `recvmmsg` and `sendmmsg` diff --git a/changelog/2119.fixed.md b/changelog/2119.fixed.md new file mode 100644 index 0000000000..d0d665fc5c --- /dev/null +++ b/changelog/2119.fixed.md @@ -0,0 +1 @@ +Fixed the function signature of `recvmmsg`, potentially causing UB diff --git a/changelog/2134.changed.md b/changelog/2134.changed.md new file mode 100644 index 0000000000..d884c596c6 --- /dev/null +++ b/changelog/2134.changed.md @@ -0,0 +1,2 @@ +`PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime + requirements relative to the previous version. diff --git a/changelog/2136.changed.md b/changelog/2136.changed.md new file mode 100644 index 0000000000..991a6c5d03 --- /dev/null +++ b/changelog/2136.changed.md @@ -0,0 +1,2 @@ +`FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have +relaxed lifetime requirements relative to 0.27.1. diff --git a/changelog/2137.changed.md b/changelog/2137.changed.md new file mode 100644 index 0000000000..d5df4836c9 --- /dev/null +++ b/changelog/2137.changed.md @@ -0,0 +1,8 @@ +The following APIs now take an implementation of `AsFd` rather than a + `RawFd`: + + - `unistd::tcgetpgrp` + - `unistd::tcsetpgrp` + - `unistd::fpathconf` + - `unistd::ttyname` + - `unistd::getpeereid` diff --git a/changelog/2139.changed.md b/changelog/2139.changed.md new file mode 100644 index 0000000000..e6df6a0000 --- /dev/null +++ b/changelog/2139.changed.md @@ -0,0 +1 @@ +Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s diff --git a/changelog/2141.fixed.md b/changelog/2141.fixed.md new file mode 100644 index 0000000000..d14401b93c --- /dev/null +++ b/changelog/2141.fixed.md @@ -0,0 +1 @@ +Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file descriptor. diff --git a/changelog/2142.added.md b/changelog/2142.added.md new file mode 100644 index 0000000000..077a800927 --- /dev/null +++ b/changelog/2142.added.md @@ -0,0 +1 @@ +Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. diff --git a/changelog/2144.changed.md b/changelog/2144.changed.md new file mode 100644 index 0000000000..250c9fde9d --- /dev/null +++ b/changelog/2144.changed.md @@ -0,0 +1 @@ +The MSRV is now 1.69 diff --git a/changelog/2152.added.md b/changelog/2152.added.md new file mode 100644 index 0000000000..3b39063a2b --- /dev/null +++ b/changelog/2152.added.md @@ -0,0 +1 @@ +Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. diff --git a/release.toml b/release.toml deleted file mode 100644 index 23488fbfa5..0000000000 --- a/release.toml +++ /dev/null @@ -1,4 +0,0 @@ -pre-release-replacements = [ - { file="CHANGELOG.md", search="Unreleased", replace="{{version}}" }, - { file="CHANGELOG.md", search="ReleaseDate", replace="{{date}}" } -] diff --git a/towncrier.toml b/towncrier.toml new file mode 100644 index 0000000000..d324433ed5 --- /dev/null +++ b/towncrier.toml @@ -0,0 +1,27 @@ +# towncrier configuration document: +# https://towncrier.readthedocs.io/en/stable/configuration.html + +[tool.towncrier] +# Read news fragments from this directory +directory = "changelog" +# Concatenate fragments, and prepend to this file +filename = "CHANGELOG.md" +title_format = "## [{version}] - {project_date}" +# Used to disable towncrier's "=====" title header +underlines = ["", "", ""] +# Wrap news fragments to a line length of 79 +wrap = true +# Every news fragement under the `changelog` directory is named "..md", +# this `id` field, is called issue/ticket number in towncrier's term +# `issue_format` controls how this will be rendered in the final CHANGELOG +# We use this for Pull Request even though it is called "issue" +issue_format = "[#{issue}](https://github.com/nix-rust/nix/pull/{issue})" +# Ask towncrier to add new notes after this +start_string = "# Change Log\n" + +# nix's change log typs (in alphabetical order) +# These types will be capitalized by default. +[tool.towncrier.fragment.added] +[tool.towncrier.fragment.changed] +[tool.towncrier.fragment.fixed] +[tool.towncrier.fragment.removed] From ed0f7ff67998f9d466a131150fac50627965d69c Mon Sep 17 00:00:00 2001 From: Carlos B Date: Sun, 5 Nov 2023 05:06:23 +0100 Subject: [PATCH 023/140] Modified return type for ipaddr (#2151) * Modifie return type for ipaddr Signed-off-by: carlosb1 * Updated changelog with correct pull id Signed-off-by: carlosb1 * Fix error for getting ipv4 address Signed-off-by: carlosb1 * Added test for ip function Signed-off-by: carlosb1 * Changed as const functions SockaddrIn::ip SockaddrIn6::ip Signed-off-by: carlosb1 * Refactor ip function for ipv6 Signed-off-by: carlosb1 * Update changelog for ipv6 const function Signed-off-by: carlosb1 --------- Signed-off-by: carlosb1 --- CHANGELOG.md | 56 ++++++++++++++++++++++++++++++++++++++++++ src/sys/socket/addr.rs | 36 ++++++++++++++++++++++++--- 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 934d611e84..515bce6d55 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,62 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/). +## [Unreleased] - ReleaseDate + +### Fixed +- Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` + ([#1946](https://github.com/nix-rust/nix/pull/1946)) + +- Fixed the function signature of `recvmmsg`, potentially causing UB + ([#2119](https://github.com/nix-rust/nix/issues/2119)) + +- Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file + descriptor. + ([#2141](https://github.com/nix-rust/nix/pull/2141)) + +### Changed + +- Changed function `SockaddrIn::ip()` to return `net::Ipv4Addr` and + refactored `SocketAddrV6::ip()` to use `const` + ([#2151](https://github.com/nix-rust/nix/pull/2151)) + +- The MSRV is now 1.69 + ([#2144](https://github.com/nix-rust/nix/pull/2144)) + +- The following APIs now take an implementation of `AsFd` rather than a + `RawFd`: + + - `unistd::tcgetpgrp` + - `unistd::tcsetpgrp` + - `unistd::fpathconf` + - `unistd::ttyname` + - `unistd::getpeereid` + + ([#2137](https://github.com/nix-rust/nix/pull/2137)) + +- Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s + ([#2139](https://github.com/nix-rust/nix/pull/2139)) + +- `PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime + requirements relative to the previous version. + ([#2134](https://github.com/nix-rust/nix/pull/2134)) + +- `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have + relaxed lifetime requirements relative to 0.27.1. + ([#2136](https://github.com/nix-rust/nix/pull/2136)) + +- Simplified the function signatures of `recvmmsg` and `sendmmsg` + +### Added +- Added `Icmp` and `IcmpV6` to `SockProtocol`. + (#[2103](https://github.com/nix-rust/nix/pull/2103)) + +- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. + ([#2142](https://github.com/nix-rust/nix/pull/2142)) + +- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, + MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. + ([#2074](https://github.com/nix-rust/nix/pull/2074)) # Change Log ## [0.27.1] - 2023-08-28 diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index c42f86e34f..097a9d786a 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -36,6 +36,7 @@ use std::hash::{Hash, Hasher}; use std::os::unix::ffi::OsStrExt; use std::path::Path; use std::{fmt, mem, net, ptr, slice}; +use std::net::{Ipv4Addr,Ipv6Addr}; /// Convert a std::net::Ipv4Addr into the libc form. #[cfg(feature = "net")] @@ -1006,8 +1007,10 @@ pub struct SockaddrIn(libc::sockaddr_in); impl SockaddrIn { /// Returns the IP address associated with this socket address, in native /// endian. - pub const fn ip(&self) -> libc::in_addr_t { - u32::from_be(self.0.sin_addr.s_addr) + pub const fn ip(&self) -> net::Ipv4Addr { + let bytes = self.0.sin_addr.s_addr.to_ne_bytes(); + let (a, b, c, d) = (bytes[0], bytes[1], bytes[2], bytes[3]); + Ipv4Addr::new(a, b, c, d) } /// Creates a new socket address from IPv4 octets and a port number. @@ -1143,8 +1146,18 @@ impl SockaddrIn6 { } /// Returns the IP address associated with this socket address. - pub fn ip(&self) -> net::Ipv6Addr { - net::Ipv6Addr::from(self.0.sin6_addr.s6_addr) + pub const fn ip(&self) -> net::Ipv6Addr { + let bytes = self.0.sin6_addr.s6_addr; + let (a, b, c, d, e, f, g, h) = (((bytes[0] as u16) << 8) | bytes[1] as u16, + ((bytes[2] as u16) << 8) | bytes[3] as u16, + ((bytes[4] as u16) << 8) | bytes[5] as u16, + ((bytes[6] as u16) << 8) | bytes[7] as u16, + ((bytes[8] as u16) << 8) | bytes[9] as u16, + ((bytes[10] as u16) << 8) | bytes[11] as u16, + ((bytes[12] as u16) << 8) | bytes[13] as u16, + ((bytes[14] as u16) << 8) | bytes[15] as u16 + ); + Ipv6Addr::new(a, b, c, d, e, f, g, h) } /// Returns the port number associated with this socket address, in native @@ -2588,6 +2601,13 @@ mod tests { SockaddrIn::size() as usize ); } + + #[test] + fn ip() { + let s = "127.0.0.1:8080"; + let ip = SockaddrIn::from_str(s).unwrap().ip(); + assert_eq!("127.0.0.1", format!("{ip}")); + } } mod sockaddr_in6 { @@ -2609,6 +2629,14 @@ mod tests { ); } + #[test] + fn ip() { + let s = "[1234:5678:90ab:cdef::1111:2222]:8080"; + let ip = SockaddrIn6::from_str(s).unwrap().ip(); + assert_eq!("1234:5678:90ab:cdef::1111:2222", format!("{ip}")); + + } + #[test] // Ensure that we can convert to-and-from std::net variants without change. fn to_and_from() { From 4b6104c84656df28f67d191ddc56457f414f3fce Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 5 Nov 2023 13:24:05 +0800 Subject: [PATCH 024/140] chore: fix the changelog of #2151 (#2178) --- CHANGELOG.md | 56 --------------------------------------- changelog/2151.changed.md | 2 ++ 2 files changed, 2 insertions(+), 56 deletions(-) create mode 100644 changelog/2151.changed.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 515bce6d55..934d611e84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,62 +1,6 @@ All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](https://semver.org/). -## [Unreleased] - ReleaseDate - -### Fixed -- Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` - ([#1946](https://github.com/nix-rust/nix/pull/1946)) - -- Fixed the function signature of `recvmmsg`, potentially causing UB - ([#2119](https://github.com/nix-rust/nix/issues/2119)) - -- Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file - descriptor. - ([#2141](https://github.com/nix-rust/nix/pull/2141)) - -### Changed - -- Changed function `SockaddrIn::ip()` to return `net::Ipv4Addr` and - refactored `SocketAddrV6::ip()` to use `const` - ([#2151](https://github.com/nix-rust/nix/pull/2151)) - -- The MSRV is now 1.69 - ([#2144](https://github.com/nix-rust/nix/pull/2144)) - -- The following APIs now take an implementation of `AsFd` rather than a - `RawFd`: - - - `unistd::tcgetpgrp` - - `unistd::tcsetpgrp` - - `unistd::fpathconf` - - `unistd::ttyname` - - `unistd::getpeereid` - - ([#2137](https://github.com/nix-rust/nix/pull/2137)) - -- Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s - ([#2139](https://github.com/nix-rust/nix/pull/2139)) - -- `PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime - requirements relative to the previous version. - ([#2134](https://github.com/nix-rust/nix/pull/2134)) - -- `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have - relaxed lifetime requirements relative to 0.27.1. - ([#2136](https://github.com/nix-rust/nix/pull/2136)) - -- Simplified the function signatures of `recvmmsg` and `sendmmsg` - -### Added -- Added `Icmp` and `IcmpV6` to `SockProtocol`. - (#[2103](https://github.com/nix-rust/nix/pull/2103)) - -- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. - ([#2142](https://github.com/nix-rust/nix/pull/2142)) - -- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, - MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. - ([#2074](https://github.com/nix-rust/nix/pull/2074)) # Change Log ## [0.27.1] - 2023-08-28 diff --git a/changelog/2151.changed.md b/changelog/2151.changed.md new file mode 100644 index 0000000000..922acc820b --- /dev/null +++ b/changelog/2151.changed.md @@ -0,0 +1,2 @@ +Changed function `SockaddrIn::ip()` to return `net::Ipv4Addr` and refactored +`SocketAddrV6::ip()` to be `const` From e5cc5cea4640acc5ee55f53bb328aba8e58620b8 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 5 Nov 2023 14:02:40 +0800 Subject: [PATCH 025/140] refactor: change `dirfd` arg of `xxxat()` to `Option` (#2157) * refactor: change dirfd arg of xxxat() to Option * changelog * gate at_rawfd() with features fs or process * fix import * fix test on Android * simplify at_rawfd() * update changelog --- changelog/2157.changed.md | 7 +++++++ src/fcntl.rs | 25 +++++++++++++------------ src/sys/stat.rs | 9 ++++++--- src/unistd.rs | 12 ++++++++++-- test/test_fcntl.rs | 2 +- test/test_stat.rs | 12 ++++++------ test/test_unistd.rs | 17 +++++++++-------- 7 files changed, 52 insertions(+), 32 deletions(-) create mode 100644 changelog/2157.changed.md diff --git a/changelog/2157.changed.md b/changelog/2157.changed.md new file mode 100644 index 0000000000..6af97f8942 --- /dev/null +++ b/changelog/2157.changed.md @@ -0,0 +1,7 @@ +The following APIs now take optional `dirfd`s: + +- `readlinkat()` +- `fstatat()` +- `mknodat()` +- `mkdirat()` +- `execveat()` diff --git a/src/fcntl.rs b/src/fcntl.rs index 5dd05751cf..0485f0db5d 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -217,6 +217,15 @@ libc_bitflags!( } ); +/// Computes the raw fd consumed by a function of the form `*at`. +#[cfg(any( + all(feature = "fs", not(target_os = "redox")), + all(feature = "process", any(target_os = "android", target_os = "linux")) +))] +pub(crate) fn at_rawfd(fd: Option) -> raw::c_int { + fd.unwrap_or(libc::AT_FDCWD) +} + feature! { #![feature = "fs"] @@ -366,7 +375,7 @@ fn inner_readlink( AtFlags::empty() }; super::sys::stat::fstatat( - dirfd, + Some(dirfd), path, flags | AtFlags::AT_SYMLINK_NOFOLLOW, ) @@ -377,7 +386,7 @@ fn inner_readlink( target_os = "redox" )))] Some(dirfd) => super::sys::stat::fstatat( - dirfd, + Some(dirfd), path, AtFlags::AT_SYMLINK_NOFOLLOW, ), @@ -424,20 +433,12 @@ pub fn readlink(path: &P) -> Result { #[cfg(not(target_os = "redox"))] pub fn readlinkat( - dirfd: RawFd, + dirfd: Option, path: &P, ) -> Result { + let dirfd = at_rawfd(dirfd); inner_readlink(Some(dirfd), path) } - -/// Computes the raw fd consumed by a function of the form `*at`. -#[cfg(not(target_os = "redox"))] -pub(crate) fn at_rawfd(fd: Option) -> raw::c_int { - match fd { - None => libc::AT_FDCWD, - Some(fd) => fd, - } -} } #[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 7e51c03a3f..162e97042a 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -192,12 +192,13 @@ pub fn mknod( )))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn mknodat( - dirfd: RawFd, + dirfd: Option, path: &P, kind: SFlag, perm: Mode, dev: dev_t, ) -> Result<()> { + let dirfd = at_rawfd(dirfd); let res = path.with_nix_path(|cstr| unsafe { libc::mknodat( dirfd, @@ -270,10 +271,11 @@ pub fn fstat(fd: RawFd) -> Result { #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn fstatat( - dirfd: RawFd, + dirfd: Option, pathname: &P, f: AtFlags, ) -> Result { + let dirfd = at_rawfd(dirfd); let mut dst = mem::MaybeUninit::uninit(); let res = pathname.with_nix_path(|cstr| unsafe { libc::fstatat( @@ -468,10 +470,11 @@ pub fn utimensat( #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn mkdirat( - fd: RawFd, + fd: Option, path: &P, mode: Mode, ) -> Result<()> { + let fd = at_rawfd(fd); let res = path.with_nix_path(|cstr| unsafe { libc::mkdirat(fd, cstr.as_ptr(), mode.bits() as mode_t) })?; diff --git a/src/unistd.rs b/src/unistd.rs index 700a4af3ba..69dd83d6f9 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1,9 +1,16 @@ //! Safe wrappers around functions found in libc "unistd.h" header use crate::errno::{self, Errno}; + +#[cfg(any( + all(feature = "fs", not(target_os = "redox")), + all(feature = "process", any(target_os = "android", target_os = "linux")) +))] +use crate::fcntl::at_rawfd; #[cfg(not(target_os = "redox"))] #[cfg(feature = "fs")] -use crate::fcntl::{at_rawfd, AtFlags}; +use crate::fcntl::AtFlags; + #[cfg(feature = "fs")] use crate::fcntl::{fcntl, FcntlArg::F_SETFD, FdFlag, OFlag}; #[cfg(all( @@ -939,12 +946,13 @@ pub fn fexecve, SE: AsRef>( #[cfg(any(target_os = "android", target_os = "linux"))] #[inline] pub fn execveat, SE: AsRef>( - dirfd: RawFd, + dirfd: Option, pathname: &CStr, args: &[SA], env: &[SE], flags: super::fcntl::AtFlags, ) -> Result { + let dirfd = at_rawfd(dirfd); let args_p = to_exec_array(args); let env_p = to_exec_array(env); diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 13b6485eb3..cb18b2e7d9 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -222,7 +222,7 @@ fn test_readlink() { assert_eq!(readlink(&dst).unwrap().to_str().unwrap(), expected_dir); assert_eq!( - readlinkat(dirfd, "b").unwrap().to_str().unwrap(), + readlinkat(Some(dirfd), "b").unwrap().to_str().unwrap(), expected_dir ); } diff --git a/test/test_stat.rs b/test/test_stat.rs index 55f15c0771..a61d4068b3 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -117,7 +117,7 @@ fn test_fstatat() { fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()); let result = - stat::fstatat(dirfd.unwrap(), &filename, fcntl::AtFlags::empty()); + stat::fstatat(Some(dirfd.unwrap()), &filename, fcntl::AtFlags::empty()); assert_stat_results(result); } @@ -323,7 +323,7 @@ fn test_mkdirat_success_path() { let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) .unwrap(); - mkdirat(dirfd, filename, Mode::S_IRWXU).expect("mkdirat failed"); + mkdirat(Some(dirfd), filename, Mode::S_IRWXU).expect("mkdirat failed"); assert!(Path::exists(&tempdir.path().join(filename))); } @@ -337,7 +337,7 @@ fn test_mkdirat_success_mode() { let dirfd = fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) .unwrap(); - mkdirat(dirfd, filename, Mode::S_IRWXU).expect("mkdirat failed"); + mkdirat(Some(dirfd), filename, Mode::S_IRWXU).expect("mkdirat failed"); let permissions = fs::metadata(tempdir.path().join(filename)) .unwrap() .permissions(); @@ -357,7 +357,7 @@ fn test_mkdirat_fail() { stat::Mode::empty(), ) .unwrap(); - let result = mkdirat(dirfd, filename, Mode::S_IRWXU).unwrap_err(); + let result = mkdirat(Some(dirfd), filename, Mode::S_IRWXU).unwrap_err(); assert_eq!(result, Errno::ENOTDIR); } @@ -402,7 +402,7 @@ fn test_mknodat() { let target_dir = Dir::open(tempdir.path(), OFlag::O_DIRECTORY, Mode::S_IRWXU).unwrap(); mknodat( - target_dir.as_raw_fd(), + Some(target_dir.as_raw_fd()), file_name, SFlag::S_IFREG, Mode::S_IRWXU, @@ -410,7 +410,7 @@ fn test_mknodat() { ) .unwrap(); let mode = fstatat( - target_dir.as_raw_fd(), + Some(target_dir.as_raw_fd()), file_name, AtFlags::AT_SYMLINK_NOFOLLOW, ) diff --git a/test/test_unistd.rs b/test/test_unistd.rs index bdfa09beb8..1378a15ced 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -163,7 +163,8 @@ fn test_mkfifoat() { mkfifoat(Some(dirfd), mkfifoat_name, Mode::S_IRUSR).unwrap(); let stats = - stat::fstatat(dirfd, mkfifoat_name, fcntl::AtFlags::empty()).unwrap(); + stat::fstatat(Some(dirfd), mkfifoat_name, fcntl::AtFlags::empty()) + .unwrap(); let typ = stat::SFlag::from_bits_truncate(stats.st_mode); assert_eq!(typ, SFlag::S_IFIFO); } @@ -197,7 +198,7 @@ fn test_mkfifoat_directory() { let tempdir = tempdir().unwrap(); let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); let mkfifoat_dir = "mkfifoat_dir"; - stat::mkdirat(dirfd, mkfifoat_dir, Mode::S_IRUSR).unwrap(); + stat::mkdirat(Some(dirfd), mkfifoat_dir, Mode::S_IRUSR).unwrap(); mkfifoat(Some(dirfd), mkfifoat_dir, Mode::S_IRUSR) .expect_err("assertion failed"); @@ -429,21 +430,21 @@ cfg_if! { if #[cfg(target_os = "android")] { use nix::fcntl::AtFlags; execve_test_factory!(test_execveat_empty, execveat, - File::open("/system/bin/sh").unwrap().into_raw_fd(), + Some(File::open("/system/bin/sh").unwrap().into_raw_fd()), "", AtFlags::AT_EMPTY_PATH); execve_test_factory!(test_execveat_relative, execveat, - File::open("/system/bin/").unwrap().into_raw_fd(), + Some(File::open("/system/bin/").unwrap().into_raw_fd()), "./sh", AtFlags::empty()); execve_test_factory!(test_execveat_absolute, execveat, - File::open("/").unwrap().into_raw_fd(), + Some(File::open("/").unwrap().into_raw_fd()), "/system/bin/sh", AtFlags::empty()); } else if #[cfg(all(target_os = "linux", any(target_arch ="x86_64", target_arch ="x86")))] { use nix::fcntl::AtFlags; - execve_test_factory!(test_execveat_empty, execveat, File::open("/bin/sh").unwrap().into_raw_fd(), + execve_test_factory!(test_execveat_empty, execveat, Some(File::open("/bin/sh").unwrap().into_raw_fd()), "", AtFlags::AT_EMPTY_PATH); - execve_test_factory!(test_execveat_relative, execveat, File::open("/bin/").unwrap().into_raw_fd(), + execve_test_factory!(test_execveat_relative, execveat, Some(File::open("/bin/").unwrap().into_raw_fd()), "./sh", AtFlags::empty()); - execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(), + execve_test_factory!(test_execveat_absolute, execveat, Some(File::open("/").unwrap().into_raw_fd()), "/bin/sh", AtFlags::empty()); } } From a3881188702592466e4380fc3d7219e28628734c Mon Sep 17 00:00:00 2001 From: Artyom Pavlov Date: Sun, 5 Nov 2023 16:34:57 +0300 Subject: [PATCH 026/140] Add `mmap_anonymous` function (#2127) * Add `mmap_anonymous` function * Add changelog note * Add changelog note for mmap change --- changelog/2127.added.md | 1 + changelog/2127.changed.md | 1 + src/sys/mman.rs | 45 ++++++++++++++++++++++++++++++++------- test/sys/test_mman.rs | 22 +++++++------------ 4 files changed, 47 insertions(+), 22 deletions(-) create mode 100644 changelog/2127.added.md create mode 100644 changelog/2127.changed.md diff --git a/changelog/2127.added.md b/changelog/2127.added.md new file mode 100644 index 0000000000..c3302bb592 --- /dev/null +++ b/changelog/2127.added.md @@ -0,0 +1 @@ +Added `mmap_anonymous` function \ No newline at end of file diff --git a/changelog/2127.changed.md b/changelog/2127.changed.md new file mode 100644 index 0000000000..10cfdea7ad --- /dev/null +++ b/changelog/2127.changed.md @@ -0,0 +1 @@ +`mmap` function now accepts `F` instead of `Option` \ No newline at end of file diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 8cfd6d6d54..af986f5ab5 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -411,7 +411,9 @@ pub fn munlockall() -> Result<()> { unsafe { Errno::result(libc::munlockall()) }.map(drop) } -/// allocate memory, or map files or devices into memory +/// Allocate memory, or map files or devices into memory +/// +/// For anonymous mappings (`MAP_ANON`/`MAP_ANONYMOUS`), see [mmap_anonymous]. /// /// # Safety /// @@ -423,13 +425,12 @@ pub unsafe fn mmap( length: NonZeroUsize, prot: ProtFlags, flags: MapFlags, - f: Option, + f: F, offset: off_t, ) -> Result<*mut c_void> { - let ptr = - addr.map_or(std::ptr::null_mut(), |a| usize::from(a) as *mut c_void); + let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void); - let fd = f.map(|f| f.as_fd().as_raw_fd()).unwrap_or(-1); + let fd = f.as_fd().as_raw_fd(); let ret = libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), fd, offset); @@ -440,6 +441,34 @@ pub unsafe fn mmap( } } +/// Create an anonymous memory mapping. +/// +/// This function is a wrapper around [`mmap`]: +/// `mmap(ptr, len, prot, MAP_ANONYMOUS | flags, -1, 0)`. +/// +/// # Safety +/// +/// See the [`mmap(2)`] man page for detailed requirements. +/// +/// [`mmap(2)`]: https://man7.org/linux/man-pages/man2/mmap.2.html +pub unsafe fn mmap_anonymous( + addr: Option, + length: NonZeroUsize, + prot: ProtFlags, + flags: MapFlags, +) -> Result<*mut c_void> { + let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void); + + let flags = MapFlags::MAP_ANONYMOUS | flags; + let ret = libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), -1, 0); + + if ret == libc::MAP_FAILED { + Err(Errno::last()) + } else { + Ok(ret) + } +} + /// Expands (or shrinks) an existing memory mapping, potentially moving it at /// the same time. /// @@ -519,14 +548,14 @@ pub unsafe fn madvise( /// /// ``` /// # use nix::libc::size_t; -/// # use nix::sys::mman::{mmap, mprotect, MapFlags, ProtFlags}; +/// # use nix::sys::mman::{mmap_anonymous, mprotect, MapFlags, ProtFlags}; /// # use std::ptr; /// # use std::os::unix::io::BorrowedFd; /// const ONE_K: size_t = 1024; /// let one_k_non_zero = std::num::NonZeroUsize::new(ONE_K).unwrap(); /// let mut slice: &mut [u8] = unsafe { -/// let mem = mmap::(None, one_k_non_zero, ProtFlags::PROT_NONE, -/// MapFlags::MAP_ANON | MapFlags::MAP_PRIVATE, None, 0).unwrap(); +/// let mem = mmap_anonymous(None, one_k_non_zero, ProtFlags::PROT_NONE, MapFlags::MAP_PRIVATE) +/// .unwrap(); /// mprotect(mem, ONE_K, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE).unwrap(); /// std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) /// }; diff --git a/test/sys/test_mman.rs b/test/sys/test_mman.rs index 704e14f9c5..585b6d6363 100644 --- a/test/sys/test_mman.rs +++ b/test/sys/test_mman.rs @@ -1,16 +1,14 @@ -use nix::sys::mman::{mmap, MapFlags, ProtFlags}; -use std::{num::NonZeroUsize, os::unix::io::BorrowedFd}; +use nix::sys::mman::{mmap_anonymous, MapFlags, ProtFlags}; +use std::num::NonZeroUsize; #[test] fn test_mmap_anonymous() { unsafe { - let ptr = mmap::( + let ptr = mmap_anonymous( None, NonZeroUsize::new(1).unwrap(), ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_PRIVATE | MapFlags::MAP_ANONYMOUS, - None, - 0, + MapFlags::MAP_PRIVATE, ) .unwrap() as *mut u8; assert_eq!(*ptr, 0x00u8); @@ -29,13 +27,11 @@ fn test_mremap_grow() { let one_k_non_zero = NonZeroUsize::new(ONE_K).unwrap(); let slice: &mut [u8] = unsafe { - let mem = mmap::( + let mem = mmap_anonymous( None, one_k_non_zero, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, - None, - 0, + MapFlags::MAP_PRIVATE, ) .unwrap(); std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) @@ -87,13 +83,11 @@ fn test_mremap_shrink() { const ONE_K: size_t = 1024; let ten_one_k = NonZeroUsize::new(10 * ONE_K).unwrap(); let slice: &mut [u8] = unsafe { - let mem = mmap::( + let mem = mmap_anonymous( None, ten_one_k, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, - MapFlags::MAP_ANONYMOUS | MapFlags::MAP_PRIVATE, - None, - 0, + MapFlags::MAP_PRIVATE, ) .unwrap(); std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) From ad6078415fd98a02a89aaf29969b520895c8d350 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 6 Nov 2023 07:40:02 +0800 Subject: [PATCH 027/140] fix: copy_file_range fd_in arg on Linux/Android (#2173) * fix: copy_file_range fd_in arg on Linux/Android * trigger CI * trigger CI --- src/fcntl.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index 0485f0db5d..0a0acd026a 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -713,7 +713,7 @@ pub fn copy_file_range( let ret = unsafe { libc::syscall( libc::SYS_copy_file_range, - fd_in, + fd_in.as_fd().as_raw_fd(), off_in, fd_out.as_fd().as_raw_fd(), off_out, From b5e1a76e225b45371174be554d70742a5611dba3 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Mon, 6 Nov 2023 06:15:35 +0000 Subject: [PATCH 028/140] fcntl adding few apple extensions (#2155) --- changelog/2155.added.md | 2 ++ src/fcntl.rs | 15 +++++++++++++++ test/test_fcntl.rs | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 49 insertions(+) create mode 100644 changelog/2155.added.md diff --git a/changelog/2155.added.md b/changelog/2155.added.md new file mode 100644 index 0000000000..5a550c925c --- /dev/null +++ b/changelog/2155.added.md @@ -0,0 +1,2 @@ +Added `F_GETPATH_NOFIRMLINK` and `F_BARRIERFSYNC` FcntlFlags entry +on Apple for `::nix::fcntl`. diff --git a/src/fcntl.rs b/src/fcntl.rs index 0a0acd026a..2ecd0735c6 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -504,6 +504,8 @@ pub enum FcntlArg<'a> { F_GET_SEALS, #[cfg(any(target_os = "macos", target_os = "ios"))] F_FULLFSYNC, + #[cfg(any(target_os = "macos", target_os = "ios"))] + F_BARRIERFSYNC, #[cfg(any(target_os = "linux", target_os = "android"))] F_GETPIPE_SZ, #[cfg(any(target_os = "linux", target_os = "android"))] @@ -512,6 +514,8 @@ pub enum FcntlArg<'a> { F_GETPATH(&'a mut PathBuf), #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] F_KINFO(&'a mut PathBuf), + #[cfg(any(target_os = "macos", target_os = "ios"))] + F_GETPATH_NOFIRMLINK(&'a mut PathBuf), // TODO: Rest of flags } @@ -568,6 +572,8 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { F_GET_SEALS => libc::fcntl(fd, libc::F_GET_SEALS), #[cfg(any(target_os = "macos", target_os = "ios"))] F_FULLFSYNC => libc::fcntl(fd, libc::F_FULLFSYNC), + #[cfg(any(target_os = "macos", target_os = "ios"))] + F_BARRIERFSYNC => libc::fcntl(fd, libc::F_BARRIERFSYNC), #[cfg(any(target_os = "linux", target_os = "android"))] F_GETPIPE_SZ => libc::fcntl(fd, libc::F_GETPIPE_SZ), #[cfg(any(target_os = "linux", target_os = "android"))] @@ -593,6 +599,15 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { *path = PathBuf::from(OsString::from(optr.to_str().unwrap())); return Ok(ok_res) }, + #[cfg(any(target_os = "macos", target_os = "ios"))] + F_GETPATH_NOFIRMLINK(path) => { + let mut buffer = vec![0; libc::PATH_MAX as usize]; + let res = libc::fcntl(fd, libc::F_GETPATH_NOFIRMLINK, buffer.as_mut_ptr()); + let ok_res = Errno::result(res)?; + let optr = CStr::from_bytes_until_nul(&buffer).unwrap(); + *path = PathBuf::from(OsString::from(optr.to_str().unwrap())); + return Ok(ok_res) + }, } }; diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index cb18b2e7d9..1c5cb4f9b3 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -585,6 +585,38 @@ fn test_f_get_path() { ); } +#[cfg(any(target_os = "macos", target_os = "ios"))] +#[test] +fn test_f_get_path_nofirmlink() { + use nix::fcntl::*; + use std::{os::unix::io::AsRawFd, path::PathBuf}; + + let tmp = NamedTempFile::new().unwrap(); + let fd = tmp.as_raw_fd(); + let mut path = PathBuf::new(); + let res = fcntl(fd, FcntlArg::F_GETPATH_NOFIRMLINK(&mut path)) + .expect("get path failed"); + let mut tmpstr = String::from("/System/Volumes/Data"); + tmpstr.push_str( + &tmp.path() + .canonicalize() + .unwrap() + .into_os_string() + .into_string() + .unwrap(), + ); + assert_ne!(res, -1); + assert_eq!( + path.as_path() + .canonicalize() + .unwrap() + .into_os_string() + .into_string() + .unwrap(), + tmpstr + ); +} + #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] #[test] fn test_f_kinfo() { From 582e77334fe9cde1ec9a36fd14cbb53be5bfa4bb Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Tue, 7 Nov 2023 07:28:34 +0800 Subject: [PATCH 029/140] docs: document that having multi logs for 1 PR is allowed (#2179) --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a45fc9905c..30b3a17ff8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,6 +84,8 @@ be added (assume it is PR #0) Added a new API xxx ``` +And having multiple change logs for one PR is allowed. + [cl]: https://github.com/nix-rust/nix/tree/master/changelog [pr-docs]: https://help.github.com/articles/using-pull-requests/ From 68684896ff94e5d071864085f2ee989f66f8e9ad Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Wed, 8 Nov 2023 08:53:46 +0800 Subject: [PATCH 030/140] chore: try GitHub Action (#2166) * chore: try GitHub Action * fix branch name * migrate 33 tasks * add RUSTFLAGS and RUSTDOCFLAGS to env * respond to review --- .github/actions/build/action.yml | 72 +++++++ .github/actions/test/action.yml | 27 +++ .github/workflows/ci.yml | 334 +++++++++++++++++++++++++++++++ 3 files changed, 433 insertions(+) create mode 100644 .github/actions/build/action.yml create mode 100644 .github/actions/test/action.yml create mode 100644 .github/workflows/ci.yml diff --git a/.github/actions/build/action.yml b/.github/actions/build/action.yml new file mode 100644 index 0000000000..9cf2fbff5d --- /dev/null +++ b/.github/actions/build/action.yml @@ -0,0 +1,72 @@ +name: 'Build' +description: 'Build nix' +inputs: + # This is required + TARGET: + required: true + + BUILD: + required: false + default: build + + CLIPPYFLAGS: + required: false + default: -D warnings -A unknown-lints + + RUSTFLAGS: + required: false + default: -D warnings -A unknown-lints + + RUSTDOCFLAGS: + required: false + default: -D warnings + + TOOL: + description: 'Tool used to involve the BUILD command, can be cargo or cross' + required: false + default: cargo + + ZFLAGS: + required: false + default: + + NOHACK: + description: "whether to run cargo hack" + required: false + default: false + +runs: + using: "composite" + steps: + - name: set up Rust env + shell: bash + run: | + echo "RUSTFLAGS=${{ inputs.RUSTFLAGS }}" >> $GITHUB_ENV + echo "RUSTDOCFLAGS=${{ inputs.RUSTDOCFLAGS }}" >> $GITHUB_ENV + + - name: debug info + shell: bash + run: | + ${{ inputs.TOOL }} -Vv + rustc -Vv + + - name: build + shell: bash + run: ${{ inputs.TOOL }} ${{ inputs.BUILD }} ${{ inputs.ZFLAGS }} --target ${{ inputs.TARGET }} --all-targets --all-features + + - name: doc + shell: bash + run: ${{ inputs.TOOL }} doc ${{ inputs.ZFLAGS }} --no-deps --target ${{ inputs.TARGET }} --all-features + + - name: clippy + shell: bash + run: ${{ inputs.TOOL}} clippy ${{ inputs.ZFLAGS }} --target ${{ inputs.TARGET }} --all-targets --all-features -- ${{ inputs.CLIPPYFLAGS }} + + - name: Set up cargo-hack + if: inputs.NOHACK == 'false' + uses: taiki-e/install-action@cargo-hack + + - name: run cargo hack + shell: bash + if: inputs.NOHACK == 'false' + run: ${{ inputs.TOOL }} hack ${{ inputs.ZFLAGS }} check --target ${{ inputs.TARGET }} --each-feature diff --git a/.github/actions/test/action.yml b/.github/actions/test/action.yml new file mode 100644 index 0000000000..ce011a2da2 --- /dev/null +++ b/.github/actions/test/action.yml @@ -0,0 +1,27 @@ +name: 'Test' +description: 'Test nix' +inputs: + # This is required + TARGET: + required: true + + TOOL: + description: 'Tool used to involve the test command, can be cargo or cross' + required: false + default: cargo + + RUSTFLAGS: + required: false + default: -D warnings -A unknown-lints + +runs: + using: "composite" + steps: + - name: set up Rust env + shell: bash + run: | + echo "RUSTFLAGS=${{ inputs.RUSTFLAGS }}" >> $GITHUB_ENV + + - name: test + shell: bash + run: ${{ inputs.TOOL }} test --target ${{ inputs.TARGET }} --all-features diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000000..0ff0afe5af --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,334 @@ +name: CI + +on: + pull_request: + types: [opened, synchronize, reopened] + push: + branches: + - master + +permissions: + contents: read + +env: + MSRV: 1.69.0 + +jobs: + + macos: + runs-on: macos-13 + env: + TARGET: x86_64-apple-darwin + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: '${{ env.MSRV }}' + components: clippy + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ env.TARGET }}' + + - name: test + uses: ./.github/actions/test + with: + TARGET: '${{ env.TARGET }}' + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + + # Use cross for QEMU-based testing + # cross needs to execute Docker, GitHub Action already has it installed + cross: + runs-on: ubuntu-20.04 + needs: [rustfmt, minver, macos, linux_native_builds, rust_stable] + strategy: + fail-fast: false + matrix: + target: [ + arm-unknown-linux-gnueabi, + armv7-unknown-linux-gnueabihf, + i686-unknown-linux-gnu, + i686-unknown-linux-musl, + mips-unknown-linux-gnu, + mips64-unknown-linux-gnuabi64, + mips64el-unknown-linux-gnuabi64, + mipsel-unknown-linux-gnu, + powerpc64le-unknown-linux-gnu, + ] + + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: '${{ env.MSRV }}' + components: clippy + + # cross relies on docker or podman, GitHub Acton already has it installed. + - name: Set up cross + uses: taiki-e/install-action@v2 + with: + tool: cross@0.2.5 + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ matrix.target }}' + TOOL: cross + RUSTFLAGS: --cfg qemu -D warnings + + - name: test + uses: ./.github/actions/test + with: + TARGET: '${{ matrix.target }}' + TOOL: cross + RUSTFLAGS: --cfg qemu -D warnings + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + + + # Tasks for Linux native builds + # Only test x86_64 targets on GitHub Action, leave aarch64 one in Cirrus CI. + linux_native_builds: + runs-on: ubuntu-20.04 + strategy: + fail-fast: false + matrix: + target: [ + x86_64-unknown-linux-gnu, + x86_64-unknown-linux-musl, + ] + + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: '${{ env.MSRV }}' + components: clippy + + - name: install targets + run: rustup target add ${{ matrix.target }} + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ matrix.TARGET }}' + + - name: test + uses: ./.github/actions/test + with: + TARGET: '${{ matrix.TARGET }}' + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + rust_stable: + runs-on: ubuntu-20.04 + env: + TARGET: x86_64-unknown-linux-gnu + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@stable + with: + components: clippy + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ env.TARGET }}' + + - name: test + uses: ./.github/actions/test + with: + TARGET: '${{ env.TARGET }}' + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + + + # Tasks for cross-compiling, but no testing + cross_compiling: + runs-on: ubuntu-20.04 + needs: [rustfmt, minver, macos, linux_native_builds, rust_stable] + env: + BUILD: check + strategy: + fail-fast: false + matrix: + include: + # Cross claims to support Android, but when it tries to run Nix's tests it + # reports undefined symbol references. + - target: aarch64-linux-android + - target: arm-linux-androideabi + - target: armv7-linux-androideabi + - target: i686-linux-android + - target: x86_64-linux-android + - target: arm-unknown-linux-musleabi + - target: x86_64-unknown-fuchsia + - target: x86_64-unknown-illumos + # Cross claims to support running tests on iOS, but it actually doesn't. + # https://github.com/rust-embedded/cross/issues/535 + - target: aarch64-apple-ios + # cargo hack tries to invoke the iphonesimulator SDK for iOS + NOHACK: true + # Cross claims to support Linux powerpc64, but it really doesn't. + # https://github.com/rust-embedded/cross/issues/441 + - target: powerpc64-unknown-linux-gnu + - target: s390x-unknown-linux-gnu + - target: x86_64-unknown-linux-gnux32 + - target: x86_64-unknown-netbsd + + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: '${{ env.MSRV }}' + components: clippy + + - name: install targets + run: rustup target add ${{ matrix.target }} + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ matrix.target }}' + BUILD: '${{ env.BUILD }}' + NOHACK: '${{ matrix.NOHACK }}' + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + + redox: + runs-on: ubuntu-20.04 + needs: [rustfmt, minver, macos, linux_native_builds, rust_stable] + env: + TARGET: x86_64-unknown-redox + CLIPPYFLAGS: -D warnings + BUILD: check + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + # Redox's MSRV policy is unclear. Until they define it, use nightly. + uses: dtolnay/rust-toolchain@nightly + with: + components: clippy + + - name: install targets + run: rustup target add ${{ env.TARGET }} + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ env.TARGET }}' + BUILD: '${{ env.BUILD }}' + CLIPPYFLAGS: '${{ env.CLIPPYFLAGS }}' + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + + + # Rust Tier 3 targets can't use Rustup + tier3: + runs-on: ubuntu-20.04 + env: + BUILD: check + ZFLAGS: -Zbuild-std + CLIPPYFLAGS: -D warnings + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-unknown-dragonfly + - target: x86_64-unknown-openbsd + - target: armv7-unknown-linux-uclibceabihf + - target: x86_64-unknown-haiku + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@nightly + with: + components: clippy + + - name: install src + run: rustup component add rust-src + + - name: build + uses: ./.github/actions/build + with: + TARGET: '${{ matrix.target }}' + BUILD: '${{ env.BUILD }}' + ZFLAGS: '${{ env.ZFLAGS }}' + CLIPPYFLAGS: '${{ env.CLIPPYFLAGS }}' + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + + # Test that we can build with the lowest version of all dependencies. + # "cargo test" doesn't work because some of our dev-dependencies, like + # rand, can't build with their own minimal dependencies. + minver: + runs-on: ubuntu-20.04 + env: + TARGET: x86_64-unknown-linux-gnu + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@nightly + + - name: setup + run: cargo update -Zminimal-versions + + - name: check + run: cargo check + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + + # Tasks that checks if the code is formatted right using `cargo fmt` tool + rustfmt: + runs-on: ubuntu-20.04 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Rust + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt + + - name: Check format + run: cargo fmt --all -- --check **/*.rs + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index + From 0ff46212a58381dd0954735fa53d4349c2d27f8d Mon Sep 17 00:00:00 2001 From: Matthew Maurer Date: Tue, 7 Nov 2023 18:37:03 -0800 Subject: [PATCH 031/140] Pass pointers, not slices, to libc::ioctl (#2181) Slices are not FFI-safe. &[u8] and &mut [u8] are *wide pointers*, which means that at the moment, we're getting lucky because they're passed via the "ScalarPair" ABI, and this means that passing a `&[u8]` results in passing two arguments, `*const u8` and `usize` for pointer and length. This passes an extra argument to ioctl, which happens to work because the extra vararg is skipped. We're getting lucky right now, and we should explicitly pass the pointer we meant to pass instead. This is normally checked on `extern "C"` functions, but `ioctl` in particular uses varargs which prevents the compiler check from reporting. --- src/sys/ioctl/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index 0b3fe3e769..af846f21bb 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -181,7 +181,7 @@ //! pub unsafe fn spi_message(fd: c_int, data: &mut [spi_ioc_transfer]) -> Result { //! let res = libc::ioctl(fd, //! request_code_write!(SPI_IOC_MAGIC, SPI_IOC_TYPE_MESSAGE, data.len() * mem::size_of::()), -//! data); +//! data.as_ptr()); //! Errno::result(res) //! } //! # fn main() {} @@ -712,7 +712,7 @@ macro_rules! ioctl_read_buf { pub unsafe fn $name(fd: $crate::libc::c_int, data: &mut [$ty]) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_read!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data)) + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_read!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_mut_ptr())) } ) } @@ -751,7 +751,7 @@ macro_rules! ioctl_write_buf { pub unsafe fn $name(fd: $crate::libc::c_int, data: &[$ty]) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data)) + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_ptr())) } ) } @@ -780,7 +780,7 @@ macro_rules! ioctl_readwrite_buf { pub unsafe fn $name(fd: $crate::libc::c_int, data: &mut [$ty]) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_readwrite!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data)) + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_readwrite!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_mut_ptr())) } ) } From 49283c9031c1f75588733d5f910d03ce7a7396a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Cruz?= Date: Thu, 9 Nov 2023 01:00:20 +0000 Subject: [PATCH 032/140] Add apple tvos support (#2169) --- Cargo.toml | 3 + build.rs | 11 ++ src/dir.rs | 3 +- src/errno.rs | 116 ++++++----------- src/fcntl.rs | 42 ++++--- src/features.rs | 3 +- src/ifaddrs.rs | 8 +- src/lib.rs | 3 +- src/mount/linux.rs | 2 +- src/net/if_.rs | 35 ++---- src/sys/aio.rs | 11 +- src/sys/event.rs | 78 ++++++------ src/sys/inotify.rs | 14 ++- src/sys/ioctl/mod.rs | 6 +- src/sys/mman.rs | 25 ++-- src/sys/mod.rs | 15 +-- src/sys/prctl.rs | 14 ++- src/sys/resource.rs | 6 +- src/sys/sendfile.rs | 5 +- src/sys/signalfd.rs | 30 ++--- src/sys/socket/addr.rs | 253 ++++++++++++++++++++------------------ src/sys/socket/mod.rs | 135 ++++++++------------ src/sys/socket/sockopt.rs | 35 ++---- src/sys/stat.rs | 24 ++-- src/sys/statfs.rs | 22 ++-- src/sys/termios.rs | 118 ++++++------------ src/sys/uio.rs | 18 ++- src/sys/utsname.rs | 2 +- src/sys/wait.rs | 13 +- src/time.rs | 20 +-- src/unistd.rs | 189 ++++++++++------------------ test/sys/mod.rs | 3 +- test/sys/test_aio_drop.rs | 3 +- test/sys/test_ioctl.rs | 3 +- test/sys/test_socket.rs | 14 +-- test/sys/test_sockopt.rs | 18 +-- test/test.rs | 3 +- test/test_fcntl.rs | 9 +- test/test_sendfile.rs | 8 +- test/test_stat.rs | 12 +- test/test_unistd.rs | 31 ++--- 41 files changed, 575 insertions(+), 788 deletions(-) create mode 100644 build.rs diff --git a/Cargo.toml b/Cargo.toml index 5a7806075a..8cd6e3a09e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,9 @@ caps = "0.5.3" [target.'cfg(target_os = "freebsd")'.dev-dependencies] sysctl = "0.4" +[build-dependencies] +cfg_aliases = "0.1.1" + [[test]] name = "test" path = "test/test.rs" diff --git a/build.rs b/build.rs new file mode 100644 index 0000000000..15847184f2 --- /dev/null +++ b/build.rs @@ -0,0 +1,11 @@ +use cfg_aliases::cfg_aliases; + +fn main() { + cfg_aliases! { + ios: { target_os = "ios" }, + macos: { target_os = "macos" }, + watchos: { target_os = "watchos" }, + tvos: { target_os = "tvos" }, + apple_targets: { any(ios, macos, watchos, tvos) }, + } +} diff --git a/src/dir.rs b/src/dir.rs index bdec58bd1b..6dec1525d5 100644 --- a/src/dir.rs +++ b/src/dir.rs @@ -230,10 +230,9 @@ impl Entry { target_os = "fuchsia", target_os = "haiku", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "l4re", target_os = "linux", - target_os = "macos", target_os = "solaris"))] { self.0.d_ino as u64 } else { diff --git a/src/errno.rs b/src/errno.rs index 50b35248f8..6b69ccac00 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -8,8 +8,7 @@ pub use self::consts::*; cfg_if! { if #[cfg(any(target_os = "freebsd", - target_os = "ios", - target_os = "macos"))] { + apple_targets,))] { unsafe fn errno_location() -> *mut c_int { libc::__error() } @@ -796,20 +795,18 @@ fn desc(errno: Errno) -> &'static str { ECAPMODE => "Not permitted in capability mode", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] ENEEDAUTH => "Need authenticator", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "redox", @@ -819,10 +816,9 @@ fn desc(errno: Errno) -> &'static str { EOVERFLOW => "Value too large to be stored in data type", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "netbsd", target_os = "redox", target_os = "haiku" @@ -830,10 +826,9 @@ fn desc(errno: Errno) -> &'static str { EILSEQ => "Illegal byte sequence", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "haiku" @@ -841,10 +836,9 @@ fn desc(errno: Errno) -> &'static str { ENOATTR => "Attribute not found", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "redox", @@ -853,10 +847,9 @@ fn desc(errno: Errno) -> &'static str { EBADMSG => "Bad message", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "redox", @@ -865,28 +858,25 @@ fn desc(errno: Errno) -> &'static str { EPROTO => "Protocol error", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd" ))] ENOTRECOVERABLE => "State not recoverable", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd" ))] EOWNERDEAD => "Previous owner died", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "aix", @@ -897,10 +887,9 @@ fn desc(errno: Errno) -> &'static str { ENOTSUP => "Operation not supported", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "openbsd", target_os = "netbsd" @@ -908,10 +897,9 @@ fn desc(errno: Errno) -> &'static str { EPROCLIM => "Too many processes", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "openbsd", target_os = "netbsd", @@ -920,10 +908,9 @@ fn desc(errno: Errno) -> &'static str { EUSERS => "Too many users", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "redox", @@ -935,10 +922,9 @@ fn desc(errno: Errno) -> &'static str { EDQUOT => "Disc quota exceeded", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd", target_os = "redox", @@ -950,10 +936,9 @@ fn desc(errno: Errno) -> &'static str { ESTALE => "Stale NFS file handle", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "openbsd", target_os = "netbsd", @@ -962,80 +947,72 @@ fn desc(errno: Errno) -> &'static str { EREMOTE => "Too many levels of remote in path", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] EBADRPC => "RPC struct is bad", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] ERPCMISMATCH => "RPC version wrong", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] EPROGUNAVAIL => "RPC prog. not avail", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] EPROGMISMATCH => "Program version wrong", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] EPROCUNAVAIL => "Bad procedure for program", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] EFTYPE => "Inappropriate file type or format", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "openbsd", target_os = "netbsd" ))] EAUTH => "Authentication error", #[cfg(any( - target_os = "macos", target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "openbsd", target_os = "netbsd", @@ -1043,52 +1020,40 @@ fn desc(errno: Errno) -> &'static str { ))] ECANCELED => "Operation canceled", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] EPWROFF => "Device power is off", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] EDEVERR => "Device error, e.g. paper out", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] EBADEXEC => "Bad executable", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] EBADARCH => "Bad CPU type in executable", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] ESHLIBVERS => "Shared library version mismatch", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] EBADMACHO => "Malformed Macho file", - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "netbsd", - target_os = "haiku" - ))] + #[cfg(any(apple_targets, target_os = "netbsd", target_os = "haiku"))] EMULTIHOP => "Reserved", #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "netbsd", target_os = "redox" ))] ENODATA => "No message available on STREAM", - #[cfg(any( - target_os = "macos", - target_os = "ios", - target_os = "netbsd", - target_os = "haiku" - ))] + #[cfg(any(apple_targets, target_os = "netbsd", target_os = "haiku"))] ENOLINK => "Reserved", #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "netbsd", target_os = "redox" @@ -1096,8 +1061,7 @@ fn desc(errno: Errno) -> &'static str { ENOSR => "No STREAM resources", #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "netbsd", target_os = "redox" @@ -1105,8 +1069,7 @@ fn desc(errno: Errno) -> &'static str { ENOSTR => "Not a STREAM", #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "netbsd", target_os = "redox" @@ -1114,18 +1077,17 @@ fn desc(errno: Errno) -> &'static str { ETIME => "STREAM ioctl timeout", #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "aix", target_os = "illumos", target_os = "solaris" ))] EOPNOTSUPP => "Operation not supported on socket", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] ENOPOLICY => "No such policy registered", - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] EQFULL => "Interface output queue is full", #[cfg(target_os = "openbsd")] @@ -1438,7 +1400,7 @@ mod consts { } } -#[cfg(any(target_os = "macos", target_os = "ios"))] +#[cfg(apple_targets)] mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] diff --git a/src/fcntl.rs b/src/fcntl.rs index 2ecd0735c6..aacd1e1675 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -4,8 +4,7 @@ use core::slice; use libc::{self, c_int, c_uint, size_t, ssize_t}; #[cfg(any( target_os = "netbsd", - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "dragonfly", all(target_os = "freebsd", target_arch = "x86_64"), ))] @@ -18,8 +17,7 @@ use std::os::unix::io::RawFd; // For splice and copy_file_range #[cfg(any( target_os = "netbsd", - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "dragonfly", all(target_os = "freebsd", target_arch = "x86_64"), ))] @@ -106,9 +104,8 @@ libc_bitflags!( O_DIRECTORY; /// Implicitly follow each `write()` with an `fdatasync()`. #[cfg(any(target_os = "android", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -122,8 +119,7 @@ libc_bitflags!( /// Open with an exclusive file lock. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", target_os = "redox"))] @@ -132,9 +128,8 @@ libc_bitflags!( /// Same as `O_SYNC`. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, all(target_os = "linux", not(target_env = "musl")), - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "redox"))] @@ -189,8 +184,7 @@ libc_bitflags!( /// Open with a shared file lock. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", target_os = "redox"))] @@ -502,19 +496,23 @@ pub enum FcntlArg<'a> { target_os = "freebsd" ))] F_GET_SEALS, - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] F_FULLFSYNC, - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] F_BARRIERFSYNC, #[cfg(any(target_os = "linux", target_os = "android"))] F_GETPIPE_SZ, #[cfg(any(target_os = "linux", target_os = "android"))] F_SETPIPE_SZ(c_int), - #[cfg(any(target_os = "netbsd", target_os = "dragonfly", target_os = "macos", target_os = "ios"))] + #[cfg(any( + target_os = "netbsd", + target_os = "dragonfly", + apple_targets, + ))] F_GETPATH(&'a mut PathBuf), #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] F_KINFO(&'a mut PathBuf), - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] F_GETPATH_NOFIRMLINK(&'a mut PathBuf), // TODO: Rest of flags } @@ -570,15 +568,19 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { target_os = "freebsd" ))] F_GET_SEALS => libc::fcntl(fd, libc::F_GET_SEALS), - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] F_FULLFSYNC => libc::fcntl(fd, libc::F_FULLFSYNC), - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] F_BARRIERFSYNC => libc::fcntl(fd, libc::F_BARRIERFSYNC), #[cfg(any(target_os = "linux", target_os = "android"))] F_GETPIPE_SZ => libc::fcntl(fd, libc::F_GETPIPE_SZ), #[cfg(any(target_os = "linux", target_os = "android"))] F_SETPIPE_SZ(size) => libc::fcntl(fd, libc::F_SETPIPE_SZ, size), - #[cfg(any(target_os = "dragonfly", target_os = "netbsd", target_os = "macos", target_os = "ios"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "netbsd", + apple_targets, + ))] F_GETPATH(path) => { let mut buffer = vec![0; libc::PATH_MAX as usize]; let res = libc::fcntl(fd, libc::F_GETPATH, buffer.as_mut_ptr()); @@ -599,7 +601,7 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { *path = PathBuf::from(OsString::from(optr.to_str().unwrap())); return Ok(ok_res) }, - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] F_GETPATH_NOFIRMLINK(path) => { let mut buffer = vec![0; libc::PATH_MAX as usize]; let res = libc::fcntl(fd, libc::F_GETPATH_NOFIRMLINK, buffer.as_mut_ptr()); diff --git a/src/features.rs b/src/features.rs index 9e292cbf5d..8aac9ede1e 100644 --- a/src/features.rs +++ b/src/features.rs @@ -114,8 +114,7 @@ mod os { #[cfg(any( target_os = "aix", - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "fuchsia", target_os = "haiku", target_os = "solaris" diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index e7bf9d0c5a..75795dfe9e 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -4,7 +4,7 @@ //! of interfaces and their associated addresses. use cfg_if::cfg_if; -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] use std::convert::TryFrom; use std::ffi; use std::iter::Iterator; @@ -53,7 +53,7 @@ cfg_if! { /// ss_len field to sizeof(sockaddr_storage). This is supposedly valid as all /// members of the sockaddr_storage are "ok" with being zeroed out (there are /// no pointers). -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] unsafe fn workaround_xnu_bug(info: &libc::ifaddrs) -> Option { let src_sock = info.ifa_netmask; if src_sock.is_null() { @@ -85,9 +85,9 @@ impl InterfaceAddress { fn from_libc_ifaddrs(info: &libc::ifaddrs) -> InterfaceAddress { let ifname = unsafe { ffi::CStr::from_ptr(info.ifa_name) }; let address = unsafe { SockaddrStorage::from_raw(info.ifa_addr, None) }; - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] let netmask = unsafe { workaround_xnu_bug(info) }; - #[cfg(not(any(target_os = "ios", target_os = "macos")))] + #[cfg(not(apple_targets))] let netmask = unsafe { SockaddrStorage::from_raw(info.ifa_netmask, None) }; let mut addr = InterfaceAddress { diff --git a/src/lib.rs b/src/lib.rs index 959e76e768..fd750a3426 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -124,9 +124,8 @@ feature! { #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "illumos", target_os = "openbsd"))] diff --git a/src/mount/linux.rs b/src/mount/linux.rs index e987603786..aa166bc9d3 100644 --- a/src/mount/linux.rs +++ b/src/mount/linux.rs @@ -85,7 +85,7 @@ libc_bitflags!( MNT_DETACH; /// Mark the mount point as expired. MNT_EXPIRE; - /// Don't dereference `target` if it is a symlink. + /// Don't dereference `target` if it is a symlink. UMOUNT_NOFOLLOW; } ); diff --git a/src/net/if_.rs b/src/net/if_.rs index 2f13a96d94..6fbe137075 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -41,9 +41,8 @@ libc_bitflags!( /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "illumos", target_os = "solaris"))] @@ -60,9 +59,8 @@ libc_bitflags!( target_os = "freebsd", target_os = "fuchsia", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] @@ -84,10 +82,9 @@ libc_bitflags!( IFF_MASTER; /// transmission in progress, tx hardware queue is full #[cfg(any(target_os = "freebsd", - target_os = "macos", + apple_targets, target_os = "netbsd", - target_os = "openbsd", - target_os = "ios"))] + target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] IFF_OACTIVE; /// Protocol code on board. @@ -113,10 +110,9 @@ libc_bitflags!( /// Per link layer defined bit. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "macos", + apple_targets, target_os = "netbsd", - target_os = "openbsd", - target_os = "ios"))] + target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LINK0; /// Multicast using broadcast. @@ -131,10 +127,9 @@ libc_bitflags!( /// Per link layer defined bit. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "macos", + apple_targets, target_os = "netbsd", - target_os = "openbsd", - target_os = "ios"))] + target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LINK1; /// Non-unique address. @@ -149,17 +144,15 @@ libc_bitflags!( /// Per link layer defined bit. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "macos", + apple_targets, target_os = "netbsd", - target_os = "openbsd", - target_os = "ios"))] + target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LINK2; /// Use alternate physical connection. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "macos", - target_os = "ios"))] + apple_targets,))] #[cfg_attr(docsrs, doc(cfg(all())))] IFF_ALTPHYS; /// DHCP controls interface. @@ -329,9 +322,8 @@ libc_bitflags!( target_os = "dragonfly", target_os = "freebsd", target_os = "fuchsia", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "illumos", @@ -462,9 +454,8 @@ mod if_nameindex { target_os = "dragonfly", target_os = "freebsd", target_os = "fuchsia", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "illumos", diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 3716f4190d..132889e36d 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -53,9 +53,8 @@ libc_enum! { /// do it like `fsync` O_SYNC, /// on supported operating systems only, do it like `fdatasync` - #[cfg(any(target_os = "ios", + #[cfg(any(apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -1055,7 +1054,8 @@ pub fn aio_suspend( // generic, and accepting arguments like &[AioWrite]. But that would // prevent using aio_suspend to wait on a heterogeneous list of mixed // operations. - let v = list.iter() + let v = list + .iter() .map(|x| x.as_ref() as *const libc::aiocb) .collect::>(); let p = v.as_ptr(); @@ -1175,7 +1175,10 @@ pub fn aio_suspend( /// // notification, we know that all operations are complete. /// assert_eq!(aiow.as_mut().aio_return().unwrap(), WBUF.len()); /// ``` -#[deprecated(since = "0.27.0", note = "https://github.com/nix-rust/nix/issues/2017")] +#[deprecated( + since = "0.27.0", + note = "https://github.com/nix-rust/nix/issues/2017" +)] pub fn lio_listio( mode: LioMode, list: &mut [Pin<&mut dyn AsMut>], diff --git a/src/sys/event.rs b/src/sys/event.rs index 47ea2d027b..4372508499 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -81,8 +81,7 @@ impl Kqueue { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "openbsd" ))] type type_of_udata = *mut libc::c_void; @@ -111,8 +110,7 @@ libc_enum! { EVFILT_EXCEPT, #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos"))] + apple_targets))] /// Establishes a file system monitor. EVFILT_FS, #[cfg(target_os = "freebsd")] @@ -120,7 +118,7 @@ libc_enum! { /// # See Also /// [lio_listio(2)](https://www.freebsd.org/cgi/man.cgi?query=lio_listio) EVFILT_LIO, - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] /// Mach portsets EVFILT_MACHPORT, /// Notifies when a process performs one or more of the requested @@ -146,11 +144,10 @@ libc_enum! { EVFILT_TIMER, #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos"))] + apple_targets))] /// Notifies only when explicitly requested by the user. EVFILT_USER, - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] /// Virtual memory events EVFILT_VM, /// Notifies when a requested event happens on a specified file. @@ -165,8 +162,7 @@ libc_enum! { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "openbsd" ))] #[doc(hidden)] @@ -188,7 +184,7 @@ libc_bitflags! { #[allow(missing_docs)] EV_DISABLE; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[allow(missing_docs)] EV_DISPATCH; @@ -201,7 +197,7 @@ libc_bitflags! { EV_EOF; #[allow(missing_docs)] EV_ERROR; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] EV_FLAG0; #[allow(missing_docs)] @@ -211,14 +207,14 @@ libc_bitflags! { EV_NODATA; #[allow(missing_docs)] EV_ONESHOT; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(any(target_os = "macos", target_os = "tvos"))] #[allow(missing_docs)] EV_OOBAND; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] EV_POLL; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[allow(missing_docs)] EV_RECEIPT; @@ -231,7 +227,7 @@ libc_bitflags!( // that wouldn't simply be repeating the man page. #[allow(missing_docs)] pub struct FilterFlag: u32 { - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_ABSOLUTE; #[allow(missing_docs)] @@ -247,43 +243,37 @@ libc_bitflags!( NOTE_EXEC; #[allow(missing_docs)] NOTE_EXIT; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_EXITSTATUS; #[allow(missing_docs)] NOTE_EXTEND; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] NOTE_FFAND; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] NOTE_FFCOPY; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] NOTE_FFCTRLMASK; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] NOTE_FFLAGSMASK; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] NOTE_FFNOP; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] @@ -297,10 +287,12 @@ libc_bitflags!( #[cfg(target_os = "freebsd")] #[allow(missing_docs)] NOTE_MSECONDS; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_NONE; - #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] + #[cfg(any( + apple_targets, + target_os = "freebsd"))] #[allow(missing_docs)] NOTE_NSECONDS; #[cfg(target_os = "dragonfly")] @@ -314,18 +306,19 @@ libc_bitflags!( NOTE_RENAME; #[allow(missing_docs)] NOTE_REVOKE; - #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] + #[cfg(any( + apple_targets, + target_os = "freebsd"))] #[allow(missing_docs)] NOTE_SECONDS; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_SIGNAL; #[allow(missing_docs)] NOTE_TRACK; #[allow(missing_docs)] NOTE_TRACKERR; - #[cfg(any(target_os = "macos", - target_os = "ios", + #[cfg(any(apple_targets, target_os = "freebsd", target_os = "dragonfly"))] #[allow(missing_docs)] @@ -333,19 +326,21 @@ libc_bitflags!( #[cfg(target_os = "openbsd")] #[allow(missing_docs)] NOTE_TRUNCATE; - #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))] + #[cfg(any( + apple_targets, + target_os = "freebsd"))] #[allow(missing_docs)] NOTE_USECONDS; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_VM_ERROR; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_VM_PRESSURE; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_VM_PRESSURE_SUDDEN_TERMINATE; - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[allow(missing_docs)] NOTE_VM_PRESSURE_TERMINATE; #[allow(missing_docs)] @@ -444,8 +439,7 @@ pub fn kevent( } #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd" diff --git a/src/sys/inotify.rs b/src/sys/inotify.rs index c1b15f9bf6..a3a037689f 100644 --- a/src/sys/inotify.rs +++ b/src/sys/inotify.rs @@ -143,7 +143,9 @@ impl Inotify { pub fn init(flags: InitFlags) -> Result { let res = Errno::result(unsafe { libc::inotify_init1(flags.bits()) }); - res.map(|fd| Inotify { fd: unsafe { OwnedFd::from_raw_fd(fd) } }) + res.map(|fd| Inotify { + fd: unsafe { OwnedFd::from_raw_fd(fd) }, + }) } /// Adds a new watch on the target file or directory. @@ -157,7 +159,11 @@ impl Inotify { mask: AddWatchFlags, ) -> Result { let res = path.with_nix_path(|cstr| unsafe { - libc::inotify_add_watch(self.fd.as_raw_fd(), cstr.as_ptr(), mask.bits()) + libc::inotify_add_watch( + self.fd.as_raw_fd(), + cstr.as_ptr(), + mask.bits(), + ) })?; Errno::result(res).map(|wd| WatchDescriptor { wd }) @@ -237,7 +243,9 @@ impl Inotify { impl FromRawFd for Inotify { unsafe fn from_raw_fd(fd: RawFd) -> Self { - Inotify { fd: OwnedFd::from_raw_fd(fd) } + Inotify { + fd: OwnedFd::from_raw_fd(fd), + } } } diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index af846f21bb..1eda874966 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -238,8 +238,7 @@ pub use self::linux::*; target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "haiku", target_os = "openbsd" @@ -251,8 +250,7 @@ mod bsd; target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "haiku", target_os = "openbsd" diff --git a/src/sys/mman.rs b/src/sys/mman.rs index af986f5ab5..c2299e9648 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -8,7 +8,10 @@ use crate::Result; #[cfg(feature = "fs")] use crate::{fcntl::OFlag, sys::stat::Mode}; use libc::{self, c_int, c_void, off_t, size_t}; -use std::{num::NonZeroUsize, os::unix::io::{AsRawFd, AsFd}}; +use std::{ + num::NonZeroUsize, + os::unix::io::{AsFd, AsRawFd}, +}; libc_bitflags! { /// Desired memory protection of a memory mapping. @@ -169,11 +172,11 @@ libc_bitflags! { #[cfg_attr(docsrs, doc(cfg(all())))] MAP_STACK; /// Pages in this mapping are not retained in the kernel's memory cache. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NOCACHE; /// Allows the W/X bit on the page, it's necessary on aarch64 architecture. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MAP_JIT; /// Allows to use large pages, underlying alignment based on size. @@ -314,19 +317,19 @@ libc_enum! { #[cfg_attr(docsrs, doc(cfg(all())))] MADV_SETMAP, /// Indicates that the application will not need the data in the given range. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_ZERO_WIRED_PAGES, /// Pages can be reused (by anyone). - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE_REUSABLE, /// Caller wants to reuse those pages. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE_REUSE, // Darwin doesn't document this flag's behavior. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(missing_docs)] MADV_CAN_REUSE, @@ -341,11 +344,11 @@ libc_bitflags! { /// Invalidate all cached data. MS_INVALIDATE; /// Invalidate pages, but leave them mapped. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MS_KILLPAGES; /// Deactivate pages, but leave them mapped. - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] MS_DEACTIVATE; /// Perform an update and wait for it to complete. @@ -605,11 +608,11 @@ pub fn shm_open

( use std::os::unix::io::{FromRawFd, OwnedFd}; let ret = name.with_nix_path(|cstr| { - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] unsafe { libc::shm_open(cstr.as_ptr(), flag.bits(), mode.bits() as libc::c_uint) } - #[cfg(not(any(target_os = "macos", target_os = "ios")))] + #[cfg(not(apple_targets))] unsafe { libc::shm_open(cstr.as_ptr(), flag.bits(), mode.bits() as libc::mode_t) } diff --git a/src/sys/mod.rs b/src/sys/mod.rs index bf047b3dda..f43d8787eb 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -2,9 +2,8 @@ #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", all(target_os = "linux", not(target_env = "uclibc")), - target_os = "macos", + apple_targets, target_os = "netbsd" ))] feature! { @@ -21,8 +20,7 @@ feature! { #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] pub mod event; @@ -36,10 +34,9 @@ feature! { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", target_os = "redox", - target_os = "macos", target_os = "netbsd", target_os = "illumos", target_os = "openbsd" @@ -125,9 +122,8 @@ feature! { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos" ))] feature! { #![feature = "zerocopy"] @@ -159,9 +155,8 @@ feature! { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] feature! { diff --git a/src/sys/prctl.rs b/src/sys/prctl.rs index a48065a66b..42324beab2 100644 --- a/src/sys/prctl.rs +++ b/src/sys/prctl.rs @@ -50,7 +50,9 @@ pub fn get_child_subreaper() -> Result { // prctl writes into this var let mut subreaper: c_int = 0; - let res = unsafe { libc::prctl(libc::PR_GET_CHILD_SUBREAPER, &mut subreaper, 0, 0, 0) }; + let res = unsafe { + libc::prctl(libc::PR_GET_CHILD_SUBREAPER, &mut subreaper, 0, 0, 0) + }; Errno::result(res).map(|_| subreaper != 0) } @@ -78,7 +80,9 @@ pub fn get_keepcaps() -> Result { /// Clear the thread memory corruption kill policy and use the system-wide default pub fn clear_mce_kill() -> Result<()> { - let res = unsafe { libc::prctl(libc::PR_MCE_KILL, libc::PR_MCE_KILL_CLEAR, 0, 0, 0) }; + let res = unsafe { + libc::prctl(libc::PR_MCE_KILL, libc::PR_MCE_KILL_CLEAR, 0, 0, 0) + }; Errno::result(res).map(drop) } @@ -175,14 +179,16 @@ pub fn get_timerslack() -> Result { /// Disable all performance counters attached to the calling process. pub fn task_perf_events_disable() -> Result<()> { - let res = unsafe { libc::prctl(libc::PR_TASK_PERF_EVENTS_DISABLE, 0, 0, 0, 0) }; + let res = + unsafe { libc::prctl(libc::PR_TASK_PERF_EVENTS_DISABLE, 0, 0, 0, 0) }; Errno::result(res).map(drop) } /// Enable all performance counters attached to the calling process. pub fn task_perf_events_enable() -> Result<()> { - let res = unsafe { libc::prctl(libc::PR_TASK_PERF_EVENTS_ENABLE, 0, 0, 0, 0) }; + let res = + unsafe { libc::prctl(libc::PR_TASK_PERF_EVENTS_ENABLE, 0, 0, 0, 0) }; Errno::result(res).map(drop) } diff --git a/src/sys/resource.rs b/src/sys/resource.rs index f42d32e3ca..a040774c58 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -16,8 +16,7 @@ cfg_if! { target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "android", target_os = "dragonfly", target_os = "aix", @@ -48,8 +47,7 @@ libc_enum! { target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "android", target_os = "dragonfly", target_os = "aix", diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index da979d337b..7e4ee74210 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -80,8 +80,7 @@ pub fn sendfile64( cfg_if! { if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos"))] { + apple_targets,))] { use std::io::IoSlice; #[derive(Clone, Debug)] @@ -244,7 +243,7 @@ cfg_if! { }; (Errno::result(return_code).and(Ok(())), bytes_sent) } - } else if #[cfg(any(target_os = "ios", target_os = "macos"))] { + } else if #[cfg(apple_targets)] { /// Read bytes from `in_fd` starting at `offset` and write up to `count` bytes to /// `out_sock`. /// diff --git a/src/sys/signalfd.rs b/src/sys/signalfd.rs index 36516074a6..aefc89bc73 100644 --- a/src/sys/signalfd.rs +++ b/src/sys/signalfd.rs @@ -21,7 +21,7 @@ use crate::Result; pub use libc::signalfd_siginfo as siginfo; use std::mem; -use std::os::unix::io::{AsRawFd, RawFd, FromRawFd, OwnedFd, AsFd, BorrowedFd}; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd}; libc_bitflags! { pub struct SfdFlags: libc::c_int { @@ -45,18 +45,23 @@ pub const SIGNALFD_SIGINFO_SIZE: usize = mem::size_of::(); /// /// See [the signalfd man page for more information](https://man7.org/linux/man-pages/man2/signalfd.2.html) #[deprecated(since = "0.27.0", note = "Use SignalFd instead")] -pub fn signalfd(fd: Option, mask: &SigSet, flags: SfdFlags) -> Result { +pub fn signalfd( + fd: Option, + mask: &SigSet, + flags: SfdFlags, +) -> Result { _signalfd(fd, mask, flags) } -fn _signalfd(fd: Option, mask: &SigSet, flags: SfdFlags) -> Result { - let raw_fd = fd.map_or(-1, |x|x.as_fd().as_raw_fd()); +fn _signalfd( + fd: Option, + mask: &SigSet, + flags: SfdFlags, +) -> Result { + let raw_fd = fd.map_or(-1, |x| x.as_fd().as_raw_fd()); unsafe { - Errno::result(libc::signalfd( - raw_fd, - mask.as_ref(), - flags.bits(), - )).map(|raw_fd|FromRawFd::from_raw_fd(raw_fd)) + Errno::result(libc::signalfd(raw_fd, mask.as_ref(), flags.bits())) + .map(|raw_fd| FromRawFd::from_raw_fd(raw_fd)) } } @@ -123,11 +128,8 @@ impl SignalFd { fn update(&self, mask: &SigSet, flags: SfdFlags) -> Result<()> { let raw_fd = self.0.as_raw_fd(); unsafe { - Errno::result(libc::signalfd( - raw_fd, - mask.as_ref(), - flags.bits(), - )).map(drop) + Errno::result(libc::signalfd(raw_fd, mask.as_ref(), flags.bits())) + .map(drop) } } } diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 097a9d786a..f973bfaedb 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -2,9 +2,8 @@ target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "illumos", target_os = "netbsd", target_os = "openbsd", @@ -14,7 +13,11 @@ ))] #[cfg(feature = "net")] pub use self::datalink::LinkAddr; -#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] +#[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" +))] pub use self::vsock::VsockAddr; use super::sa_family_t; use crate::errno::Errno; @@ -22,10 +25,7 @@ use crate::errno::Errno; use crate::sys::socket::addr::alg::AlgAddr; #[cfg(any(target_os = "android", target_os = "linux"))] use crate::sys::socket::addr::netlink::NetlinkAddr; -#[cfg(all( - feature = "ioctl", - any(target_os = "ios", target_os = "macos") -))] +#[cfg(all(feature = "ioctl", apple_targets))] use crate::sys::socket::addr::sys_control::SysControlAddr; use crate::{NixPath, Result}; use cfg_if::cfg_if; @@ -33,16 +33,16 @@ use memoffset::offset_of; use std::convert::TryInto; use std::ffi::OsStr; use std::hash::{Hash, Hasher}; +use std::net::{Ipv4Addr, Ipv6Addr}; use std::os::unix::ffi::OsStrExt; use std::path::Path; use std::{fmt, mem, net, ptr, slice}; -use std::net::{Ipv4Addr,Ipv6Addr}; /// Convert a std::net::Ipv4Addr into the libc form. #[cfg(feature = "net")] pub(crate) const fn ipv4addr_to_libc(addr: net::Ipv4Addr) -> libc::in_addr { libc::in_addr { - s_addr: u32::from_ne_bytes(addr.octets()) + s_addr: u32::from_ne_bytes(addr.octets()), } } @@ -50,7 +50,7 @@ pub(crate) const fn ipv4addr_to_libc(addr: net::Ipv4Addr) -> libc::in_addr { #[cfg(feature = "net")] pub(crate) const fn ipv6addr_to_libc(addr: &net::Ipv6Addr) -> libc::in6_addr { libc::in6_addr { - s6_addr: addr.octets() + s6_addr: addr.octets(), } } @@ -93,7 +93,7 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] Packet = libc::AF_PACKET, /// KEXT Controls and Notifications - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] System = libc::AF_SYSTEM, /// Amateur radio AX.25 protocol @@ -205,8 +205,7 @@ pub enum AddressFamily { #[cfg(not(any( target_os = "aix", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "solaris", target_os = "redox", )))] @@ -253,15 +252,18 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] Nfc = libc::AF_NFC, /// VMWare VSockets protocol for hypervisor-guest interaction. - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Vsock = libc::AF_VSOCK, /// ARPANet IMP addresses #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -271,8 +273,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -282,28 +283,21 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] Chaos = libc::AF_CHAOS, /// Novell and Xerox protocol - #[cfg(any( - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] Ns = libc::AF_NS, #[allow(missing_docs)] // Not documented anywhere that I can find #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -313,8 +307,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -324,8 +317,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -335,8 +327,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -346,8 +337,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -357,8 +347,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -368,8 +357,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "openbsd" @@ -380,8 +368,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -391,8 +378,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -402,8 +388,7 @@ pub enum AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -441,14 +426,17 @@ impl AddressFamily { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "illumos", target_os = "openbsd" ))] libc::AF_LINK => Some(AddressFamily::Link), - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] libc::AF_VSOCK => Some(AddressFamily::Vsock), _ => None, } @@ -489,7 +477,7 @@ enum UnixAddrKind<'a> { } impl<'a> UnixAddrKind<'a> { /// Safety: sun & sun_len must be valid - #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms + #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms unsafe fn get(sun: &'a libc::sockaddr_un, sun_len: u8) -> Self { assert!(sun_len as usize >= offset_of!(libc::sockaddr_un, sun_path)); let path_len = @@ -526,7 +514,7 @@ impl<'a> UnixAddrKind<'a> { impl UnixAddr { /// Create a new sockaddr_un representing a filesystem path. - #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms + #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms pub fn new(path: &P) -> Result { path.with_nix_path(|cstr| unsafe { let mut ret = libc::sockaddr_un { @@ -548,8 +536,7 @@ impl UnixAddr { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -574,7 +561,7 @@ impl UnixAddr { /// processes to communicate with processes having a different filesystem view. #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] - #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms + #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms pub fn new_abstract(path: &[u8]) -> Result { unsafe { let mut ret = libc::sockaddr_un { @@ -771,7 +758,10 @@ impl SockaddrLike for UnixAddr { mem::size_of::() as libc::socklen_t } - unsafe fn set_length(&mut self, new_length: usize) -> std::result::Result<(), SocketAddressLengthNotDynamic> { + unsafe fn set_length( + &mut self, + new_length: usize, + ) -> std::result::Result<(), SocketAddressLengthNotDynamic> { // `new_length` is only used on some platforms, so it must be provided even when not used #![allow(unused_variables)] cfg_if! { @@ -897,8 +887,7 @@ pub trait SockaddrLike: private::SockaddrLikePriv { cfg_if! { if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] { /// Return the length of valid data in the sockaddr structure. @@ -947,7 +936,10 @@ pub trait SockaddrLike: private::SockaddrLikePriv { /// `new_length` must be a valid length for this type of address. Specifically, reads of that /// length from `self` must be valid. #[doc(hidden)] - unsafe fn set_length(&mut self, _new_length: usize) -> std::result::Result<(), SocketAddressLengthNotDynamic> { + unsafe fn set_length( + &mut self, + _new_length: usize, + ) -> std::result::Result<(), SocketAddressLengthNotDynamic> { Err(SocketAddressLengthNotDynamic) } } @@ -1019,8 +1011,7 @@ impl SockaddrIn { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "aix", target_os = "haiku", @@ -1099,8 +1090,7 @@ impl From for SockaddrIn { target_os = "freebsd", target_os = "haiku", target_os = "hermit", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -1148,14 +1138,15 @@ impl SockaddrIn6 { /// Returns the IP address associated with this socket address. pub const fn ip(&self) -> net::Ipv6Addr { let bytes = self.0.sin6_addr.s6_addr; - let (a, b, c, d, e, f, g, h) = (((bytes[0] as u16) << 8) | bytes[1] as u16, + let (a, b, c, d, e, f, g, h) = ( + ((bytes[0] as u16) << 8) | bytes[1] as u16, ((bytes[2] as u16) << 8) | bytes[3] as u16, ((bytes[4] as u16) << 8) | bytes[5] as u16, ((bytes[6] as u16) << 8) | bytes[7] as u16, ((bytes[8] as u16) << 8) | bytes[9] as u16, ((bytes[10] as u16) << 8) | bytes[11] as u16, ((bytes[12] as u16) << 8) | bytes[13] as u16, - ((bytes[14] as u16) << 8) | bytes[15] as u16 + ((bytes[14] as u16) << 8) | bytes[15] as u16, ); Ipv6Addr::new(a, b, c, d, e, f, g, h) } @@ -1227,8 +1218,7 @@ impl From for SockaddrIn6 { target_os = "freebsd", target_os = "haiku", target_os = "hermit", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -1294,10 +1284,7 @@ pub union SockaddrStorage { dl: LinkAddr, #[cfg(any(target_os = "android", target_os = "linux"))] nl: NetlinkAddr, - #[cfg(all( - feature = "ioctl", - any(target_os = "ios", target_os = "macos") - ))] + #[cfg(all(feature = "ioctl", apple_targets))] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] sctl: SysControlAddr, #[cfg(feature = "net")] @@ -1306,7 +1293,11 @@ pub union SockaddrStorage { sin6: SockaddrIn6, ss: libc::sockaddr_storage, su: UnixAddr, - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos" ))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] vsock: VsockAddr, } @@ -1367,8 +1358,7 @@ impl SockaddrLike for SockaddrStorage { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "haiku", @@ -1391,14 +1381,15 @@ impl SockaddrLike for SockaddrStorage { libc::AF_PACKET => { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) } - #[cfg(all( - feature = "ioctl", - any(target_os = "ios", target_os = "macos") - ))] + #[cfg(all(feature = "ioctl", apple_targets))] libc::AF_SYSTEM => { SysControlAddr::from_raw(addr, l).map(|sctl| Self { sctl }) } - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos" ))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] libc::AF_VSOCK => { VsockAddr::from_raw(addr, l).map(|vsock| Self { vsock }) } @@ -1422,11 +1413,12 @@ impl SockaddrLike for SockaddrStorage { } } - unsafe fn set_length(&mut self, new_length: usize) -> std::result::Result<(), SocketAddressLengthNotDynamic> { + unsafe fn set_length( + &mut self, + new_length: usize, + ) -> std::result::Result<(), SocketAddressLengthNotDynamic> { match self.as_unix_addr_mut() { - Some(addr) => { - addr.set_length(new_length) - }, + Some(addr) => addr.set_length(new_length), None => Err(SocketAddressLengthNotDynamic), } } @@ -1544,8 +1536,7 @@ impl SockaddrStorage { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "openbsd" @@ -1569,12 +1560,16 @@ impl SockaddrStorage { accessors! {as_netlink_addr, as_netlink_addr_mut, NetlinkAddr, AddressFamily::Netlink, libc::sockaddr_nl, nl} - #[cfg(all(feature = "ioctl", any(target_os = "ios", target_os = "macos")))] + #[cfg(all(feature = "ioctl", apple_targets))] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] accessors! {as_sys_control_addr, as_sys_control_addr_mut, SysControlAddr, AddressFamily::System, libc::sockaddr_ctl, sctl} - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] accessors! {as_vsock_addr, as_vsock_addr_mut, VsockAddr, AddressFamily::Vsock, libc::sockaddr_vm, vsock} @@ -1603,8 +1598,7 @@ impl fmt::Display for SockaddrStorage { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "openbsd" @@ -1620,11 +1614,15 @@ impl fmt::Display for SockaddrStorage { ))] #[cfg(feature = "net")] libc::AF_PACKET => self.dl.fmt(f), - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg(feature = "ioctl")] libc::AF_SYSTEM => self.sctl.fmt(f), libc::AF_UNIX => self.su.fmt(f), - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] libc::AF_VSOCK => self.vsock.fmt(f), _ => "

".fmt(f), } @@ -1677,8 +1675,7 @@ impl Hash for SockaddrStorage { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "openbsd" @@ -1694,11 +1691,15 @@ impl Hash for SockaddrStorage { ))] #[cfg(feature = "net")] libc::AF_PACKET => self.dl.hash(s), - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg(feature = "ioctl")] libc::AF_SYSTEM => self.sctl.hash(s), libc::AF_UNIX => self.su.hash(s), - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] libc::AF_VSOCK => self.vsock.hash(s), _ => self.ss.hash(s), } @@ -1719,8 +1720,7 @@ impl PartialEq for SockaddrStorage { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "openbsd" @@ -1736,11 +1736,15 @@ impl PartialEq for SockaddrStorage { ))] #[cfg(feature = "net")] (libc::AF_PACKET, libc::AF_PACKET) => self.dl == other.dl, - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg(feature = "ioctl")] (libc::AF_SYSTEM, libc::AF_SYSTEM) => self.sctl == other.sctl, (libc::AF_UNIX, libc::AF_UNIX) => self.su == other.su, - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos" + ))] (libc::AF_VSOCK, libc::AF_VSOCK) => self.vsock == other.vsock, _ => false, } @@ -1931,16 +1935,12 @@ pub mod alg { /// Return the socket's cipher type, for example `hash` or `aead`. pub fn alg_type(&self) -> &CStr { - unsafe { - CStr::from_ptr(self.0.salg_type.as_ptr().cast()) - } + unsafe { CStr::from_ptr(self.0.salg_type.as_ptr().cast()) } } /// Return the socket's cipher name, for example `sha1`. pub fn alg_name(&self) -> &CStr { - unsafe { - CStr::from_ptr(self.0.salg_name.as_ptr().cast()) - } + unsafe { CStr::from_ptr(self.0.salg_name.as_ptr().cast()) } } } @@ -1964,7 +1964,7 @@ pub mod alg { feature! { #![feature = "ioctl"] -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] pub mod sys_control { use crate::sys::socket::addr::AddressFamily; use libc::{self, c_uchar}; @@ -2168,8 +2168,7 @@ mod datalink { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "illumos", target_os = "netbsd", target_os = "haiku", @@ -2344,8 +2343,17 @@ pub mod vsock { #[cfg(target_os = "macos")] fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); - (inner.svm_family, inner.svm_cid, inner.svm_port, inner.svm_len) - == (other.svm_family, other.svm_cid, other.svm_port, inner.svm_len) + ( + inner.svm_family, + inner.svm_cid, + inner.svm_port, + inner.svm_len, + ) == ( + other.svm_family, + other.svm_cid, + other.svm_port, + inner.svm_len, + ) } } @@ -2360,7 +2368,13 @@ pub mod vsock { #[cfg(target_os = "macos")] fn hash(&self, s: &mut H) { let inner = self.0; - (inner.svm_family, inner.svm_cid, inner.svm_port, inner.svm_len).hash(s); + ( + inner.svm_family, + inner.svm_cid, + inner.svm_port, + inner.svm_len, + ) + .hash(s); } } @@ -2378,7 +2392,7 @@ pub mod vsock { #[cfg(target_os = "macos")] { - addr.svm_len = std::mem::size_of::() as u8; + addr.svm_len = std::mem::size_of::() as u8; } VsockAddr(addr) } @@ -2436,11 +2450,7 @@ mod tests { mod link { #![allow(clippy::cast_ptr_alignment)] - #[cfg(any( - target_os = "ios", - target_os = "macos", - target_os = "illumos" - ))] + #[cfg(any(apple_targets, target_os = "illumos"))] use super::super::super::socklen_t; use super::*; @@ -2448,8 +2458,7 @@ mod tests { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -2498,7 +2507,7 @@ mod tests { } } - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[test] fn macos_loopback() { let bytes = @@ -2516,7 +2525,7 @@ mod tests { } } - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[test] fn macos_tap() { let bytes = [ @@ -2565,8 +2574,7 @@ mod tests { target_os = "aix", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "illumos", target_os = "openbsd", @@ -2634,7 +2642,6 @@ mod tests { let s = "[1234:5678:90ab:cdef::1111:2222]:8080"; let ip = SockaddrIn6::from_str(s).unwrap().ip(); assert_eq!("1234:5678:90ab:cdef::1111:2222", format!("{ip}")); - } #[test] diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index b34c4c3fdb..6f8c6f3eb2 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -59,7 +59,7 @@ pub use self::addr::{SockaddrIn, SockaddrIn6}; pub use crate::sys::socket::addr::alg::AlgAddr; #[cfg(any(target_os = "android", target_os = "linux"))] pub use crate::sys::socket::addr::netlink::NetlinkAddr; -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] #[cfg(feature = "ioctl")] pub use crate::sys::socket::addr::sys_control::SysControlAddr; #[cfg(any( @@ -138,7 +138,7 @@ pub enum SockProtocol { Raw = libc::IPPROTO_RAW, /// Allows applications to configure and control a KEXT /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] KextControl = libc::SYSPROTO_CONTROL, /// Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link @@ -253,10 +253,10 @@ impl SockProtocol { /// Allows applications and other KEXTs to be notified when certain kernel events occur /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(non_upper_case_globals)] - pub const KextEvent: SockProtocol = SockProtocol::Icmp; // Matches libc::SYSPROTO_EVENT + pub const KextEvent: SockProtocol = SockProtocol::Icmp; // Matches libc::SYSPROTO_EVENT } #[cfg(any(target_os = "android", target_os = "linux"))] libc_bitflags! { @@ -518,8 +518,7 @@ cfg_if! { if #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "macos", - target_os = "ios" + apple_targets ))] { /// Return type of [`LocalPeerCred`](crate::sys::socket::sockopt::LocalPeerCred) #[repr(transparent)] @@ -782,9 +781,8 @@ pub enum ControlMessageOwned { ScmTimestampns(TimeSpec), #[cfg(any( target_os = "android", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", ))] #[cfg(feature = "net")] @@ -794,9 +792,8 @@ pub enum ControlMessageOwned { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd", target_os = "netbsd", ))] @@ -805,8 +802,7 @@ pub enum ControlMessageOwned { Ipv6PacketInfo(libc::in6_pktinfo), #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -815,8 +811,7 @@ pub enum ControlMessageOwned { Ipv4RecvIf(libc::sockaddr_dl), #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -947,9 +942,8 @@ impl ControlMessageOwned { #[cfg(any( target_os = "android", target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos" + apple_targets, + target_os = "linux" ))] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_PKTINFO) => { @@ -958,9 +952,8 @@ impl ControlMessageOwned { } #[cfg(any( target_os = "android", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", ))] #[cfg(feature = "net")] @@ -970,8 +963,7 @@ impl ControlMessageOwned { } #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -982,8 +974,7 @@ impl ControlMessageOwned { }, #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -1156,10 +1147,9 @@ pub enum ControlMessage<'a> { /// For further information, please refer to the /// [`ip(7)`](https://man7.org/linux/man-pages/man7/ip.7.html) man page. #[cfg(any(target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "android", - target_os = "ios",))] + apple_targets))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4PacketInfo(&'a libc::in_pktinfo), @@ -1169,11 +1159,10 @@ pub enum ControlMessage<'a> { /// For further information, please refer to the /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. #[cfg(any(target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "freebsd", target_os = "android", - target_os = "ios",))] + apple_targets))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6PacketInfo(&'a libc::in6_pktinfo), @@ -1197,10 +1186,9 @@ pub enum ControlMessage<'a> { /// with sendmsg have a hop limit of 1 and will not leave the local network. /// For further information, please refer to the /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "freebsd", target_os = "dragonfly", - target_os = "android", target_os = "ios", - target_os = "haiku"))] + #[cfg(any(target_os = "linux", target_os = "freebsd", + target_os = "dragonfly", target_os = "android", + apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6HopLimit(&'a libc::c_int), @@ -1304,24 +1292,22 @@ impl<'a> ControlMessage<'a> { ControlMessage::UdpGsoSegments(gso_size) => { gso_size as *const _ as *const u8 }, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "android", - target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "android", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(info) => info as *const _ as *const u8, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "freebsd", - target_os = "android", target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "freebsd", target_os = "android", + apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => info as *const _ as *const u8, #[cfg(any(target_os = "netbsd", target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => addr as *const _ as *const u8, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "freebsd", target_os = "dragonfly", - target_os = "android", target_os = "ios", - target_os = "haiku"))] + #[cfg(any(target_os = "linux", target_os = "freebsd", + target_os = "dragonfly", target_os = "android", + apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(limit) => limit as *const _ as *const u8, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] @@ -1373,24 +1359,22 @@ impl<'a> ControlMessage<'a> { ControlMessage::UdpGsoSegments(gso_size) => { mem::size_of_val(gso_size) }, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "android", - target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "android", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(info) => mem::size_of_val(info), - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "freebsd", - target_os = "android", target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "freebsd", target_os = "android", + apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => mem::size_of_val(info), #[cfg(any(target_os = "netbsd", target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => mem::size_of_val(addr), - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "freebsd", target_os = "dragonfly", - target_os = "android", target_os = "ios", - target_os = "haiku"))] + #[cfg(any(target_os = "linux", target_os = "freebsd", + target_os = "dragonfly", target_os = "android", + apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(limit) => { mem::size_of_val(limit) @@ -1420,24 +1404,22 @@ impl<'a> ControlMessage<'a> { #[cfg(target_os = "linux")] #[cfg(feature = "net")] ControlMessage::UdpGsoSegments(_) => libc::SOL_UDP, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "android", - target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "android", apple_targets,))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(_) => libc::IPPROTO_IP, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "freebsd", - target_os = "android", target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "freebsd", target_os = "android", + apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPPROTO_IPV6, #[cfg(any(target_os = "netbsd", target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IPPROTO_IP, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "freebsd", target_os = "dragonfly", - target_os = "android", target_os = "ios", - target_os = "haiku"))] + #[cfg(any(target_os = "linux", target_os = "freebsd", + target_os = "dragonfly", target_os = "android", + apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(_) => libc::IPPROTO_IPV6, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] @@ -1472,24 +1454,22 @@ impl<'a> ControlMessage<'a> { ControlMessage::UdpGsoSegments(_) => { libc::UDP_SEGMENT }, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "android", - target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "android", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(_) => libc::IP_PKTINFO, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "netbsd", target_os = "freebsd", - target_os = "android", target_os = "ios",))] + #[cfg(any(target_os = "linux", target_os = "netbsd", + target_os = "freebsd", target_os = "android", + apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPV6_PKTINFO, #[cfg(any(target_os = "netbsd", target_os = "freebsd", target_os = "openbsd", target_os = "dragonfly"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IP_SENDSRCADDR, - #[cfg(any(target_os = "linux", target_os = "macos", - target_os = "freebsd", target_os = "dragonfly", - target_os = "android", target_os = "ios", - target_os = "haiku"))] + #[cfg(any(target_os = "linux", target_os = "freebsd", + target_os = "dragonfly", target_os = "android", + apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(_) => libc::IPV6_HOPLIMIT, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] @@ -2372,12 +2352,7 @@ pub fn sendto( /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/send.html) pub fn send(fd: RawFd, buf: &[u8], flags: MsgFlags) -> Result { let ret = unsafe { - libc::send( - fd, - buf.as_ptr().cast(), - buf.len() as size_t, - flags.bits(), - ) + libc::send(fd, buf.as_ptr().cast(), buf.len() as size_t, flags.bits()) }; Errno::result(ret).map(|r| r as usize) @@ -2444,8 +2419,7 @@ pub fn getpeername(fd: RawFd) -> Result { let mut addr = mem::MaybeUninit::::uninit(); let mut len = T::size(); - let ret = - libc::getpeername(fd, addr.as_mut_ptr().cast(), &mut len); + let ret = libc::getpeername(fd, addr.as_mut_ptr().cast(), &mut len); Errno::result(ret)?; @@ -2461,8 +2435,7 @@ pub fn getsockname(fd: RawFd) -> Result { let mut addr = mem::MaybeUninit::::uninit(); let mut len = T::size(); - let ret = - libc::getsockname(fd, addr.as_mut_ptr().cast(), &mut len); + let ret = libc::getsockname(fd, addr.as_mut_ptr().cast(), &mut len); Errno::result(ret)?; diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index b46f208216..07a0ac4ed5 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -332,8 +332,7 @@ cfg_if! { } else if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] { @@ -477,12 +476,7 @@ sockopt_impl!( libc::SO_KEEPALIVE, bool ); -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "ios" -))] +#[cfg(any(target_os = "dragonfly", target_os = "freebsd", apple_targets))] sockopt_impl!( /// Get the credentials of the peer process of a connected unix domain /// socket. @@ -492,7 +486,7 @@ sockopt_impl!( libc::LOCAL_PEERCRED, super::XuCred ); -#[cfg(any(target_os = "macos", target_os = "ios"))] +#[cfg(apple_targets)] sockopt_impl!( /// Get the PID of the peer process of a connected unix domain socket. LocalPeerPid, @@ -510,7 +504,7 @@ sockopt_impl!( libc::SO_PEERCRED, super::UnixCredentials ); -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -838,9 +832,8 @@ sockopt_impl!( ); #[cfg(any( target_os = "android", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", ))] #[cfg(feature = "net")] @@ -857,9 +850,8 @@ sockopt_impl!( #[cfg(any( target_os = "android", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] @@ -876,8 +868,7 @@ sockopt_impl!( ); #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -894,8 +885,7 @@ sockopt_impl!( ); #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -1035,7 +1025,7 @@ sockopt_impl!( libc::IPV6_ORIGDSTADDR, bool ); -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] sockopt_impl!( /// Set "don't fragment packet" flag on the IP packet. IpDontFrag, @@ -1044,12 +1034,7 @@ sockopt_impl!( libc::IP_DONTFRAG, bool ); -#[cfg(any( - target_os = "android", - target_os = "ios", - target_os = "linux", - target_os = "macos", -))] +#[cfg(any(target_os = "android", apple_targets, target_os = "linux",))] sockopt_impl!( /// Set "don't fragment packet" flag on the IPv6 packet. Ipv6DontFrag, diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 162e97042a..cc15495baf 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -1,4 +1,4 @@ -#[cfg(any(target_os = "macos", target_os = "ios", target_os = "openbsd"))] +#[cfg(any(apple_targets, target_os = "openbsd"))] pub use libc::c_uint; #[cfg(any( target_os = "netbsd", @@ -65,7 +65,7 @@ libc_bitflags! { } } -#[cfg(any(target_os = "macos", target_os = "ios", target_os = "openbsd"))] +#[cfg(any(apple_targets, target_os = "openbsd"))] pub type type_of_file_flag = c_uint; #[cfg(any( target_os = "netbsd", @@ -79,8 +79,7 @@ pub type type_of_file_flag = c_ulong; target_os = "netbsd", target_os = "freebsd", target_os = "dragonfly", - target_os = "macos", - target_os = "ios" + apple_targets ))] libc_bitflags! { /// File flags. @@ -121,14 +120,13 @@ libc_bitflags! { #[cfg(any(target_os = "dragonfly"))] UF_CACHE; /// File is compressed at the file system level. - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] UF_COMPRESSED; /// The file may be hidden from directory listings at the application's /// discretion. #[cfg(any( target_os = "freebsd", - target_os = "macos", - target_os = "ios", + apple_targets, ))] UF_HIDDEN; /// The file may not be changed. @@ -162,7 +160,7 @@ libc_bitflags! { #[cfg(any(target_os = "freebsd"))] UF_SYSTEM; /// File renames and deletes are tracked. - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] UF_TRACKED; #[cfg(any(target_os = "dragonfly"))] UF_XLINK; @@ -184,12 +182,7 @@ pub fn mknod( } /// Create a special or ordinary file, relative to a given directory. -#[cfg(not(any( - target_os = "ios", - target_os = "macos", - target_os = "redox", - target_os = "haiku" -)))] +#[cfg(not(any(apple_targets, target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn mknodat( dirfd: Option, @@ -385,8 +378,7 @@ pub fn utimes( #[cfg(any( target_os = "linux", target_os = "haiku", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "freebsd", target_os = "netbsd" ))] diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index 5111df2e6e..52e2a6b43b 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -302,8 +302,7 @@ impl Statfs { #[cfg(not(any( target_os = "openbsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos" + apple_targets, )))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn filesystem_type(&self) -> FsType { @@ -319,7 +318,7 @@ impl Statfs { } /// Optimal transfer block size - #[cfg(any(target_os = "ios", target_os = "macos"))] + #[cfg(apple_targets)] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> i32 { self.0.f_iosize @@ -385,7 +384,7 @@ impl Statfs { } /// Size of a block - #[cfg(any(target_os = "ios", target_os = "macos", target_os = "openbsd"))] + #[cfg(any(apple_targets, target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> u32 { self.0.f_bsize @@ -528,8 +527,7 @@ impl Statfs { /// Total data blocks in filesystem #[cfg(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "android", target_os = "freebsd", target_os = "fuchsia", @@ -557,8 +555,7 @@ impl Statfs { /// Free blocks in filesystem #[cfg(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "android", target_os = "freebsd", target_os = "fuchsia", @@ -586,8 +583,7 @@ impl Statfs { /// Free blocks available to unprivileged user #[cfg(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "android", target_os = "fuchsia", target_os = "linux", @@ -620,8 +616,7 @@ impl Statfs { /// Total file nodes in filesystem #[cfg(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "android", target_os = "freebsd", target_os = "fuchsia", @@ -649,8 +644,7 @@ impl Statfs { /// Free file nodes in filesystem #[cfg(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "android", target_os = "fuchsia", target_os = "openbsd", diff --git a/src/sys/termios.rs b/src/sys/termios.rs index ecaa3eaf8f..85d27bcd52 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -89,8 +89,7 @@ any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ), @@ -100,8 +99,7 @@ not(any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" )), @@ -122,8 +120,7 @@ any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ), @@ -133,8 +130,7 @@ not(any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" )), @@ -155,8 +151,7 @@ any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ), @@ -166,8 +161,7 @@ not(any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" )), @@ -189,8 +183,7 @@ any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ), @@ -200,8 +193,7 @@ not(any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" )), @@ -356,8 +348,8 @@ libc_enum! { /// /// B0 is special and will disable the port. #[cfg_attr(target_os = "haiku", repr(u8))] - #[cfg_attr(all(any(target_os = "ios", target_os = "macos"), target_pointer_width = "64"), repr(u64))] - #[cfg_attr(all(not(all(any(target_os = "ios", target_os = "macos"), target_pointer_width = "64")), not(target_os = "haiku")), repr(u32))] + #[cfg_attr(all(apple_targets, target_pointer_width = "64"), repr(u64))] + #[cfg_attr(all(not(all(apple_targets, target_pointer_width = "64")), not(target_os = "haiku")), repr(u32))] #[non_exhaustive] pub enum BaudRate { B0, @@ -472,8 +464,7 @@ libc_enum! { #[cfg(any( target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] @@ -678,88 +669,76 @@ libc_bitflags! { ONLRET as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] OFILL as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] OFDEL as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] NL0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] NL1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] CR0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] CR1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] CR2 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] CR3 as tcflag_t; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] TAB0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] TAB1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] TAB2 as tcflag_t; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] TAB3 as tcflag_t; #[cfg(any(target_os = "android", target_os = "linux"))] @@ -767,50 +746,43 @@ libc_bitflags! { XTABS; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] BS0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] BS1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] VT0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] VT1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] FF0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] FF1 as tcflag_t; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -829,45 +801,39 @@ libc_bitflags! { #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] NLDLY as tcflag_t; // FIXME: Datatype needs to be corrected in libc for mac #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] CRDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] TABDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] BSDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] VTDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", - target_os = "ios", target_os = "linux", - target_os = "macos"))] + apple_targets))] #[cfg_attr(docsrs, doc(cfg(all())))] FFDLY as tcflag_t; } @@ -878,8 +844,7 @@ libc_bitflags! { pub struct ControlFlags: tcflag_t { #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -973,8 +938,7 @@ libc_bitflags! { ICANON; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -989,8 +953,7 @@ libc_bitflags! { FLUSHO; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -1005,8 +968,7 @@ libc_bitflags! { cfg_if! { if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd"))] { /// Get input baud rate (see diff --git a/src/sys/uio.rs b/src/sys/uio.rs index 4b55d4200f..3744902489 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -18,7 +18,11 @@ pub fn writev(fd: Fd, iov: &[IoSlice<'_>]) -> Result { // // Because it is ABI compatible, a pointer cast here is valid let res = unsafe { - libc::writev(fd.as_fd().as_raw_fd(), iov.as_ptr().cast(), iov.len() as c_int) + libc::writev( + fd.as_fd().as_raw_fd(), + iov.as_ptr().cast(), + iov.len() as c_int, + ) }; Errno::result(res).map(|r| r as usize) @@ -33,7 +37,11 @@ pub fn writev(fd: Fd, iov: &[IoSlice<'_>]) -> Result { pub fn readv(fd: Fd, iov: &mut [IoSliceMut<'_>]) -> Result { // SAFETY: same as in writev(), IoSliceMut is ABI-compatible with iovec let res = unsafe { - libc::readv(fd.as_fd().as_raw_fd(), iov.as_ptr().cast(), iov.len() as c_int) + libc::readv( + fd.as_fd().as_raw_fd(), + iov.as_ptr().cast(), + iov.len() as c_int, + ) }; Errno::result(res).map(|r| r as usize) @@ -47,7 +55,11 @@ pub fn readv(fd: Fd, iov: &mut [IoSliceMut<'_>]) -> Result { /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) #[cfg(not(any(target_os = "redox", target_os = "haiku")))] #[cfg_attr(docsrs, doc(cfg(all())))] -pub fn pwritev(fd: Fd, iov: &[IoSlice<'_>], offset: off_t) -> Result { +pub fn pwritev( + fd: Fd, + iov: &[IoSlice<'_>], + offset: off_t, +) -> Result { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t diff --git a/src/sys/utsname.rs b/src/sys/utsname.rs index b48ed9f45e..a6d128bcd7 100644 --- a/src/sys/utsname.rs +++ b/src/sys/utsname.rs @@ -71,7 +71,7 @@ mod test { assert_eq!(super::uname().unwrap().sysname(), "Linux"); } - #[cfg(any(target_os = "macos", target_os = "ios"))] + #[cfg(apple_targets)] #[test] pub fn test_uname_darwin() { assert_eq!(super::uname().unwrap().sysname(), "Darwin"); diff --git a/src/sys/wait.rs b/src/sys/wait.rs index f7a63ffcd2..62928bf042 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -27,10 +27,9 @@ libc_bitflags!( #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", - target_os = "ios", + apple_targets, target_os = "linux", target_os = "redox", - target_os = "macos", target_os = "netbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] WEXITED; @@ -42,10 +41,9 @@ libc_bitflags!( #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", - target_os = "ios", + apple_targets, target_os = "linux", target_os = "redox", - target_os = "macos", target_os = "netbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] WSTOPPED; @@ -53,10 +51,9 @@ libc_bitflags!( #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", - target_os = "ios", + apple_targets, target_os = "linux", target_os = "redox", - target_os = "macos", target_os = "netbsd"))] #[cfg_attr(docsrs, doc(cfg(all())))] WNOWAIT; @@ -378,7 +375,9 @@ pub fn waitid(id: Id, flags: WaitPidFlag) -> Result { Id::PGid(pid) => (libc::P_PGID, pid.as_raw() as libc::id_t), #[cfg(any(target_os = "android", target_os = "linux"))] Id::PIDFd(fd) => (libc::P_PIDFD, fd.as_raw_fd() as libc::id_t), - Id::_Unreachable(_) => unreachable!("This variant could never be constructed"), + Id::_Unreachable(_) => { + unreachable!("This variant could never be constructed") + } }; let siginfo = unsafe { diff --git a/src/time.rs b/src/time.rs index 2e03c46cf4..e35e29d9ce 100644 --- a/src/time.rs +++ b/src/time.rs @@ -54,12 +54,7 @@ impl ClockId { } /// Sets time to `timespec` on the clock id - #[cfg(not(any( - target_os = "macos", - target_os = "ios", - target_os = "redox", - target_os = "hermit", - )))] + #[cfg(not(any(apple_targets, target_os = "redox", target_os = "hermit",)))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn set_time(self, timespec: TimeSpec) -> Result<()> { clock_settime(self, timespec) @@ -117,8 +112,7 @@ impl ClockId { target_os = "android", target_os = "emscripten", target_os = "fuchsia", - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "freebsd", target_os = "dragonfly", target_os = "redox", @@ -178,8 +172,7 @@ impl ClockId { target_os = "android", target_os = "emscripten", target_os = "fuchsia", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "freebsd", target_os = "dragonfly", target_os = "linux" @@ -246,12 +239,7 @@ pub fn clock_gettime(clock_id: ClockId) -> Result { /// Set the time of the specified clock, (see /// [clock_settime(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_settime.html)). -#[cfg(not(any( - target_os = "macos", - target_os = "ios", - target_os = "redox", - target_os = "hermit", -)))] +#[cfg(not(any(apple_targets, target_os = "redox", target_os = "hermit",)))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn clock_settime(clock_id: ClockId, timespec: TimeSpec) -> Result<()> { let ret = diff --git a/src/unistd.rs b/src/unistd.rs index 69dd83d6f9..9397d41ba9 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -20,8 +20,7 @@ use crate::fcntl::{fcntl, FcntlArg::F_SETFD, FdFlag, OFlag}; target_os = "netbsd", target_os = "freebsd", target_os = "dragonfly", - target_os = "macos", - target_os = "ios" + apple_targets, ) ))] use crate::sys::stat::FileFlag; @@ -587,8 +586,7 @@ pub fn mkfifo(path: &P, mode: Mode) -> Result<()> { // mkfifoat is not implemented in OSX or android #[inline] #[cfg(not(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "haiku", target_os = "android", target_os = "redox" @@ -1028,8 +1026,7 @@ pub fn sethostname>(name: S) -> Result<()> { if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "aix", target_os = "solaris", ))] { type sethostname_len_t = c_int; @@ -1565,7 +1562,7 @@ feature! { /// **Note:** This function is not available for Apple platforms. On those /// platforms, checking group membership should be achieved via communication /// with the `opendirectoryd` service. -#[cfg(not(any(target_os = "ios", target_os = "macos")))] +#[cfg(not(apple_targets))] pub fn getgroups() -> Result> { // First get the maximum number of groups. The value returned // shall always be greater than or equal to one and less than or @@ -1650,8 +1647,7 @@ pub fn getgroups() -> Result> { /// # try_main().unwrap(); /// ``` #[cfg(not(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "redox", target_os = "haiku" )))] @@ -1661,8 +1657,7 @@ pub fn setgroups(groups: &[Gid]) -> Result<()> { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] { @@ -1707,8 +1702,7 @@ pub fn setgroups(groups: &[Gid]) -> Result<()> { #[cfg(not(any( target_os = "aix", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "redox" )))] pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { @@ -1719,7 +1713,7 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { use std::cmp::min; let mut groups = Vec::::with_capacity(min(ngroups_max, 8) as usize); cfg_if! { - if #[cfg(any(target_os = "ios", target_os = "macos"))] { + if #[cfg(apple_targets)] { type getgrouplist_group_t = c_int; } else { type getgrouplist_group_t = gid_t; @@ -1791,14 +1785,13 @@ pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { /// # try_main().unwrap(); /// ``` #[cfg(not(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "redox", target_os = "haiku" )))] pub fn initgroups(user: &CStr, group: Gid) -> Result<()> { cfg_if! { - if #[cfg(any(target_os = "ios", target_os = "macos"))] { + if #[cfg(apple_targets)] { type initgroups_group_t = c_int; } else { type initgroups_group_t = gid_t; @@ -2296,9 +2289,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2349,9 +2341,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris" @@ -2399,9 +2390,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2411,9 +2401,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris" @@ -2429,9 +2418,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris" @@ -2443,9 +2431,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris" @@ -2461,9 +2448,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd", target_os = "solaris" ))] @@ -2503,9 +2489,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd", target_os = "solaris" ))] @@ -2520,9 +2505,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd", target_os = "solaris" ))] @@ -2533,9 +2517,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris" @@ -2547,9 +2530,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2559,9 +2541,8 @@ pub enum SysconfVar { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", target_os = "solaris" @@ -2584,9 +2565,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2596,9 +2576,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2608,9 +2587,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2620,18 +2598,16 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Process Sporadic Server option. _POSIX_SPORADIC_SERVER = libc::_SC_SPORADIC_SERVER, #[cfg(any( - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2649,9 +2625,8 @@ pub enum SysconfVar { #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_ATTR_STACKSIZE = libc::_SC_THREAD_ATTR_STACKSIZE, #[cfg(any( - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2674,9 +2649,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2707,9 +2681,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2722,9 +2695,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2737,9 +2709,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2748,18 +2719,16 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Trace Event Filter option. _POSIX_TRACE_EVENT_FILTER = libc::_SC_TRACE_EVENT_FILTER, #[cfg(any( - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2767,9 +2736,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2778,34 +2746,30 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Trace Log option. _POSIX_TRACE_LOG = libc::_SC_TRACE_LOG, #[cfg(any( - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TRACE_NAME_MAX = libc::_SC_TRACE_NAME_MAX, #[cfg(any( - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TRACE_SYS_MAX = libc::_SC_TRACE_SYS_MAX, #[cfg(any( - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2813,9 +2777,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -2828,9 +2791,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2841,9 +2803,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2855,9 +2816,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2868,9 +2828,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2907,9 +2866,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2920,9 +2878,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2932,9 +2889,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2944,9 +2900,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2956,9 +2911,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -2968,9 +2922,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -3013,9 +2966,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3027,9 +2979,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3038,9 +2989,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3049,9 +2999,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd" ))] @@ -3066,9 +3015,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3078,9 +3026,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3091,9 +3038,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3102,9 +3048,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3114,9 +3059,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3130,9 +3074,8 @@ pub enum SysconfVar { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3142,9 +3085,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3154,9 +3096,8 @@ pub enum SysconfVar { target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "openbsd" ))] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -3946,8 +3887,7 @@ feature! { /// /// See also [getpeereid(3)](https://www.freebsd.org/cgi/man.cgi?query=getpeereid) #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", @@ -3974,8 +3914,7 @@ feature! { target_os = "netbsd", target_os = "freebsd", target_os = "dragonfly", - target_os = "macos", - target_os = "ios" + apple_targets ))] pub fn chflags(path: &P, flags: FileFlag) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { diff --git a/test/sys/mod.rs b/test/sys/mod.rs index 20312120a6..ae4ff953fe 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -7,9 +7,8 @@ mod test_signal; // cases on DragonFly. #[cfg(any( target_os = "freebsd", - target_os = "ios", + apple_targets, all(target_os = "linux", not(target_env = "uclibc")), - target_os = "macos", target_os = "netbsd" ))] mod test_aio; diff --git a/test/sys/test_aio_drop.rs b/test/sys/test_aio_drop.rs index bbe6623fd7..54106dd168 100644 --- a/test/sys/test_aio_drop.rs +++ b/test/sys/test_aio_drop.rs @@ -8,8 +8,7 @@ not(target_env = "uclibc"), any( target_os = "linux", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "freebsd", target_os = "netbsd" ) diff --git a/test/sys/test_ioctl.rs b/test/sys/test_ioctl.rs index 40f60cfdbc..b9d9f9f0c3 100644 --- a/test/sys/test_ioctl.rs +++ b/test/sys/test_ioctl.rs @@ -137,8 +137,7 @@ mod linux { #[cfg(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 49e46889b1..ddd4f7c730 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1604,7 +1604,7 @@ pub fn test_unnamed_unixdomain_autobind() { } // Test creating and using named system control sockets -#[cfg(any(target_os = "macos", target_os = "ios"))] +#[cfg(apple_targets)] #[test] pub fn test_syscontrol() { use nix::errno::Errno; @@ -1633,9 +1633,8 @@ pub fn test_syscontrol() { #[cfg(any( target_os = "android", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] @@ -1667,9 +1666,8 @@ fn loopback_address( #[cfg(any( target_os = "android", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", ))] // qemu doesn't seem to be emulating this correctly in these architectures @@ -1762,8 +1760,7 @@ pub fn test_recv_ipv4pktinfo() { #[cfg(any( target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", ))] @@ -2053,9 +2050,8 @@ pub fn test_recvif_ipv6() { #[cfg(any( target_os = "android", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos", target_os = "netbsd", target_os = "openbsd", ))] diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 90432f9ab9..a3100c99a8 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -29,12 +29,7 @@ pub fn test_local_peercred_seqpacket() { assert_eq!(Gid::from_raw(xucred.groups()[0]), Gid::current()); } -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "ios" -))] +#[cfg(any(target_os = "dragonfly", target_os = "freebsd", apple_targets))] #[test] pub fn test_local_peercred_stream() { use nix::{ @@ -55,7 +50,7 @@ pub fn test_local_peercred_stream() { assert_eq!(Gid::from_raw(xucred.groups()[0]), Gid::current()); } -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] #[test] pub fn test_local_peer_pid() { use nix::sys::socket::socketpair; @@ -331,7 +326,7 @@ fn test_ttl_opts() { } #[test] -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] fn test_dontfrag_opts() { let fd4 = socket( AddressFamily::Inet, @@ -361,12 +356,7 @@ fn test_dontfrag_opts() { } #[test] -#[cfg(any( - target_os = "android", - target_os = "ios", - target_os = "linux", - target_os = "macos", -))] +#[cfg(any(target_os = "android", apple_targets, target_os = "linux",))] // Disable the test under emulation because it fails in Cirrus-CI. Lack // of QEMU support is suspected. #[cfg_attr(qemu, ignore)] diff --git a/test/test.rs b/test/test.rs index 7e73bb3056..c8c9bf1aa7 100644 --- a/test/test.rs +++ b/test/test.rs @@ -42,9 +42,8 @@ mod test_sched; target_os = "android", target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", + apple_targets, target_os = "linux", - target_os = "macos" ))] mod test_sendfile; mod test_stat; diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 1c5cb4f9b3..112d03a38a 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -562,12 +562,7 @@ mod test_posix_fallocate { } } -#[cfg(any( - target_os = "dragonfly", - target_os = "netbsd", - target_os = "macos", - target_os = "ios" -))] +#[cfg(any(target_os = "dragonfly", target_os = "netbsd", apple_targets))] #[test] fn test_f_get_path() { use nix::fcntl::*; @@ -585,7 +580,7 @@ fn test_f_get_path() { ); } -#[cfg(any(target_os = "macos", target_os = "ios"))] +#[cfg(apple_targets)] #[test] fn test_f_get_path_nofirmlink() { use nix::fcntl::*; diff --git a/test/test_sendfile.rs b/test/test_sendfile.rs index a594f18e39..99493f0a60 100644 --- a/test/test_sendfile.rs +++ b/test/test_sendfile.rs @@ -8,7 +8,11 @@ cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { use nix::unistd::{pipe, read}; use std::os::unix::io::AsRawFd; - } else if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos"))] { + } else if #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + apple_targets, + ))] { use std::net::Shutdown; use std::os::unix::net::UnixStream; } @@ -152,7 +156,7 @@ fn test_sendfile_dragonfly() { assert_eq!(expected_string, read_string); } -#[cfg(any(target_os = "ios", target_os = "macos"))] +#[cfg(apple_targets)] #[test] fn test_sendfile_darwin() { // Declare the content diff --git a/test/test_stat.rs b/test/test_stat.rs index a61d4068b3..6bae35e188 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -21,8 +21,7 @@ use nix::errno::Errno; use nix::fcntl; #[cfg(any( target_os = "linux", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "freebsd", target_os = "netbsd" ))] @@ -235,8 +234,7 @@ fn test_utimes() { #[test] #[cfg(any( target_os = "linux", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "freebsd", target_os = "netbsd" ))] @@ -365,8 +363,7 @@ fn test_mkdirat_fail() { #[cfg(not(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "haiku", target_os = "redox" )))] @@ -387,8 +384,7 @@ fn test_mknod() { target_os = "dragonfly", target_os = "freebsd", target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "haiku", target_os = "redox" )))] diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 1378a15ced..44cf460253 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -126,8 +126,7 @@ fn test_mkfifo_directory() { #[test] #[cfg(not(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "android", target_os = "redox", target_os = "haiku" @@ -147,8 +146,7 @@ fn test_mkfifoat_none() { #[test] #[cfg(not(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "android", target_os = "redox", target_os = "haiku" @@ -171,8 +169,7 @@ fn test_mkfifoat() { #[test] #[cfg(not(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "android", target_os = "redox", target_os = "haiku" @@ -187,8 +184,7 @@ fn test_mkfifoat_directory_none() { #[test] #[cfg(not(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "android", target_os = "redox", target_os = "haiku" @@ -235,8 +231,7 @@ mod linux_android { #[test] // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms #[cfg(not(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "redox", target_os = "fuchsia", target_os = "haiku" @@ -264,8 +259,7 @@ fn test_setgroups() { #[test] // `getgroups()` and `setgroups()` do not behave as expected on Apple platforms #[cfg(not(any( - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "redox", target_os = "fuchsia", target_os = "haiku", @@ -413,8 +407,7 @@ cfg_if! { execve_test_factory!(test_execve, execve, CString::new("/bin/sh").unwrap().as_c_str()); execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd()); } else if #[cfg(any(target_os = "illumos", - target_os = "ios", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] { @@ -988,12 +981,7 @@ fn test_linkat_newdirfd_none() { } #[test] -#[cfg(not(any( - target_os = "ios", - target_os = "macos", - target_os = "redox", - target_os = "haiku" -)))] +#[cfg(not(any(apple_targets, target_os = "redox", target_os = "haiku")))] fn test_linkat_no_follow_symlink() { let _m = crate::CWD_LOCK.read(); @@ -1254,8 +1242,7 @@ fn test_ttyname_not_pty() { #[test] #[cfg(any( - target_os = "macos", - target_os = "ios", + apple_targets, target_os = "freebsd", target_os = "openbsd", target_os = "netbsd", From b9ff39e24d40ab396975816818f0c484b6e918a5 Mon Sep 17 00:00:00 2001 From: Amos Wenger Date: Fri, 10 Nov 2023 04:33:15 +0100 Subject: [PATCH 033/140] Parse SOL_TLS control message, closes #2064 (#2065) * Parse SOL_TLS control message, closes #2064 * Only Linux gets SOL_TLS I guess (this is wrong, BSDs have it too) * Use libc constants * Also parse SOL_TLS on Android * Decode TLS record types * Only have TlsGetRecordType enum variant on supported platforms * Remove android from target platforms ...since the corresponding libc constant isn't gated for Android. * Add changelog entry --- Cargo.toml | 2 +- changelog/2065.added.md | 1 + src/sys/socket/mod.rs | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 changelog/2065.added.md diff --git a/Cargo.toml b/Cargo.toml index 8cd6e3a09e..0ed900400f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { version = "0.2.147", features = ["extra_traits"] } +libc = { version = "0.2.148", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } diff --git a/changelog/2065.added.md b/changelog/2065.added.md new file mode 100644 index 0000000000..a3dcd5a833 --- /dev/null +++ b/changelog/2065.added.md @@ -0,0 +1 @@ +Added `TlsGetRecordType` control message type and corresponding enum for linux \ No newline at end of file diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 6f8c6f3eb2..2d94b47aea 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -863,6 +863,10 @@ pub enum ControlMessageOwned { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6RecvErr(libc::sock_extended_err, Option), + /// `SOL_TLS` messages of type `TLS_GET_RECORD_TYPE` + #[cfg(any(target_os = "linux"))] + TlsGetRecordType(TlsGetRecordType), + /// Catch-all variant for unimplemented cmsg types. #[doc(hidden)] Unknown(UnknownCmsg), @@ -880,6 +884,33 @@ pub struct Timestamps { pub hw_raw: TimeSpec, } +/// These constants correspond to TLS 1.2 message types, as defined in +/// RFC 5246, Appendix A.1 +#[cfg(any(target_os = "linux"))] +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[repr(u8)] +#[non_exhaustive] +pub enum TlsGetRecordType { + ChangeCipherSpec , + Alert, + Handshake, + ApplicationData, + Unknown(u8), +} + +#[cfg(any(target_os = "linux"))] +impl From for TlsGetRecordType { + fn from(x: u8) -> Self { + match x { + 20 => TlsGetRecordType::ChangeCipherSpec, + 21 => TlsGetRecordType::Alert, + 22 => TlsGetRecordType::Handshake, + 23 => TlsGetRecordType::ApplicationData, + _ => TlsGetRecordType::Unknown(x), + } + } +} + impl ControlMessageOwned { /// Decodes a `ControlMessageOwned` from raw bytes. /// @@ -1018,6 +1049,11 @@ impl ControlMessageOwned { let dl = ptr::read_unaligned(p as *const libc::sockaddr_in6); ControlMessageOwned::Ipv6OrigDstAddr(dl) }, + #[cfg(any(target_os = "linux"))] + (libc::SOL_TLS, libc::TLS_GET_RECORD_TYPE) => { + let content_type = ptr::read_unaligned(p as *const u8); + ControlMessageOwned::TlsGetRecordType(content_type.into()) + }, (_, _) => { let sl = std::slice::from_raw_parts(p, len); let ucmsg = UnknownCmsg(*header, Vec::::from(sl)); From 105709217b36b7b8471f9222489765d6233c8976 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 12 Nov 2023 23:53:47 +0800 Subject: [PATCH 034/140] chore: remove migrated CI tasks from Cirrus (#2182) * chore: remove migrated CI tasks from Cirrus * chore: remove migrated CI tasks from Cirrus --- .cirrus.yml | 289 +----------------------------------------------- CONTRIBUTING.md | 6 +- 2 files changed, 4 insertions(+), 291 deletions(-) diff --git a/.cirrus.yml b/.cirrus.yml index fc564e65aa..d2df3ba4f5 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -65,83 +65,7 @@ task: - if [ -z "$NOHACK" ]; then cargo hack check --each-feature --target i686-unknown-freebsd; fi before_cache_script: rm -rf $CARGO_HOME/registry/index -# Test macOS aarch64 in a full VM -task: - name: macOS aarch64 - env: - TARGET: aarch64-apple-darwin - macos_instance: - image: ghcr.io/cirruslabs/macos-ventura-base:latest - setup_script: - - curl --proto '=https' --tlsv1.2 -sSf -o rustup.sh https://sh.rustup.rs - - sh rustup.sh -y --profile=minimal --default-toolchain $MSRV - - . $HOME/.cargo/env - - rustup component add clippy - << : *TEST - before_cache_script: rm -rf $CARGO_HOME/registry/index - -# Use cross for QEMU-based testing -# cross needs to execute Docker, so we must use Cirrus's Docker Builder task. -task: - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - RUST_TEST_THREADS: 1 # QEMU works best with 1 thread - HOME: /tmp/home - HOST: x86_64-unknown-linux-gnu - PATH: $HOME/.cargo/bin:$PATH - RUSTFLAGS: --cfg qemu -D warnings - TOOL: cross - matrix: - - name: Linux arm gnueabi - env: - TARGET: arm-unknown-linux-gnueabi - - name: Linux armv7 gnueabihf - env: - TARGET: armv7-unknown-linux-gnueabihf - - name: Linux i686 - env: - TARGET: i686-unknown-linux-gnu - - name: Linux i686 musl - env: - TARGET: i686-unknown-linux-musl - - name: Linux MIPS - env: - TARGET: mips-unknown-linux-gnu - - name: Linux MIPS64 - env: - TARGET: mips64-unknown-linux-gnuabi64 - - name: Linux MIPS64 el - env: - TARGET: mips64el-unknown-linux-gnuabi64 - - name: Linux mipsel - env: - TARGET: mipsel-unknown-linux-gnu - - name: Linux powerpc64le - env: - TARGET: powerpc64le-unknown-linux-gnu - compute_engine_instance: - image_project: cirrus-images - image: family/docker-builder - platform: linux - cpu: 1 # Since QEMU will only use 1 thread - memory: 4G - setup_script: - - mkdir /tmp/home - - curl --proto '=https' --tlsv1.2 -sSf -o rustup.sh https://sh.rustup.rs - - sh rustup.sh -y --profile=minimal --default-toolchain $MSRV - - . $HOME/.cargo/env - - cargo install cross --version 0.2.5 - << : *TEST - before_cache_script: rm -rf $CARGO_HOME/registry/index - -# Tasks for Linux native builds +# Tasks for Linux aarch64 native builds task: matrix: - name: Linux aarch64 @@ -150,221 +74,10 @@ task: cpu: 1 depends_on: - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable env: TARGET: aarch64-unknown-linux-gnu - - name: Linux x86_64 - container: - image: rust:1.69.0 - cpu: 1 - env: - TARGET: x86_64-unknown-linux-gnu - - name: Linux x86_64 musl - container: - image: rust:1.69.0 - cpu: 1 - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - TARGET: x86_64-unknown-linux-musl setup_script: - rustup target add $TARGET - rustup component add clippy << : *TEST before_cache_script: rm -rf $CARGO_HOME/registry/index - -task: - name: Rust Stable - container: - image: rust:latest - cpu: 1 - env: - TARGET: x86_64-unknown-linux-gnu - setup_script: - - rustup component add clippy - << : *TEST - before_cache_script: rm -rf $CARGO_HOME/registry/index - -# Tasks for cross-compiling, but no testing -task: - container: - image: rust:1.69.0 - cpu: 1 - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - BUILD: check - HOST: x86_64-unknown-linux-gnu - matrix: - # Cross claims to support Android, but when it tries to run Nix's tests it - # reports undefined symbol references. - - name: Android aarch64 - env: - TARGET: aarch64-linux-android - - name: Android arm - env: - TARGET: arm-linux-androideabi - - name: Android armv7 - env: - TARGET: armv7-linux-androideabi - - name: Android i686 - env: - TARGET: i686-linux-android - - name: Android x86_64 - env: - TARGET: x86_64-linux-android - - name: Linux arm-musleabi - env: - TARGET: arm-unknown-linux-musleabi - - name: Fuchsia x86_64 - env: - TARGET: x86_64-unknown-fuchsia - - name: Illumos - env: - TARGET: x86_64-unknown-illumos - # Cross claims to support running tests on iOS, but it actually doesn't. - # https://github.com/rust-embedded/cross/issues/535 - - name: iOS aarch64 - env: - # cargo hack tries to invoke the iphonesimulator SDK for iOS - NOHACK: 1 - TARGET: aarch64-apple-ios - # Cross claims to support Linux powerpc64, but it really doesn't. - # https://github.com/rust-embedded/cross/issues/441 - - name: Linux powerpc64 - env: - TARGET: powerpc64-unknown-linux-gnu - - name: Linux s390x - env: - TARGET: s390x-unknown-linux-gnu - - name: Linux x32 - env: - TARGET: x86_64-unknown-linux-gnux32 - - name: NetBSD x86_64 - env: - TARGET: x86_64-unknown-netbsd - setup_script: - - rustup target add $TARGET - - rustup component add clippy - << : *BUILD - before_cache_script: rm -rf $CARGO_HOME/registry/index - -task: - container: - # Redox's MSRV policy is unclear. Until they define it, use nightly. - image: rustlang/rust:nightly - cpu: 1 - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - BUILD: check - name: Redox x86_64 - env: - HOST: x86_64-unknown-linux-gnu - TARGET: x86_64-unknown-redox - CLIPPYFLAGS: -D warnings - setup_script: - - rustup target add $TARGET - - rustup component add clippy - << : *BUILD - before_cache_script: rm -rf $CARGO_HOME/registry/index - -## Rust Tier 3 targets can't use Rustup -task: - container: - image: rustlang/rust:nightly - cpu: 1 - env: - BUILD: check - HOST: x86_64-unknown-linux-gnu - ZFLAGS: -Zbuild-std - CLIPPYFLAGS: -D warnings - matrix: - - name: DragonFly BSD x86_64 - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - TARGET: x86_64-unknown-dragonfly - - name: OpenBSD x86_64 - env: - TARGET: x86_64-unknown-openbsd - - name: Linux armv7 uclibceabihf - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - TARGET: armv7-unknown-linux-uclibceabihf - - name: Haiku x86_64 - depends_on: - - FreeBSD 14 amd64 & i686 - - Linux x86_64 - - macOS aarch64 - - Rust Formatter - - OpenBSD x86_64 - - Minver - - Rust Stable - env: - TARGET: x86_64-unknown-haiku - setup_script: - - rustup component add rust-src - << : *BUILD - before_cache_script: rm -rf $CARGO_HOME/registry/index - -# Test that we can build with the lowest version of all dependencies. -# "cargo test" doesn't work because some of our dev-dependencies, like -# rand, can't build with their own minimal dependencies. -task: - name: Minver - env: - HOST: x86_64-unknown-linux-gnu - container: - image: rustlang/rust:nightly - cpu: 1 - setup_script: - - cargo update -Zminimal-versions - check_script: - - cargo check - before_cache_script: rm -rf $CARGO_HOME/registry/index - -# Tasks that checks if the code is formatted right using `cargo fmt` tool -task: - name: Rust Formatter - container: - image: rust:latest - cpu: 1 - setup_script: rustup component add rustfmt - test_script: cargo fmt --all -- --check **/*.rs diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 30b3a17ff8..ef31b36dcc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -96,9 +96,9 @@ requests to include tests where they make sense. For example, when fixing a bug, add a test that would have failed without the fix. After you've made your change, make sure the tests pass in your development -environment. We also have [continuous integration set up on -Cirrus-CI][cirrus-ci], which might find some issues on other platforms. The CI -will run once you open a pull request. +environment. We also have continuous integration set up on [Cirrus-CI][cirrus-ci] +and GitHub Action, which might find some issues on other platforms. The CI will +run once you open a pull request. [cirrus-ci]: https://cirrus-ci.com/github/nix-rust/nix From f5130accd019b41023442ac653c301308bacdcb3 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 13 Nov 2023 13:11:20 +0800 Subject: [PATCH 035/140] CI: fix merge queue (#2189) --- .github/workflows/ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ff0afe5af..e07d2572ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,6 +6,8 @@ on: push: branches: - master + merge_group: + types: [checks_requested] permissions: contents: read From 7c1045e5c78b87d1c7271ef26c1ca04386db6ae6 Mon Sep 17 00:00:00 2001 From: Henry Chen Date: Sun, 12 Nov 2023 23:29:51 -0600 Subject: [PATCH 036/140] sys: add MIPS R6 support (#2138) Currently R6 targets are almost identical to their R2/R5 counterparts. --- changelog/2138.added.md | 1 + src/sys/ioctl/linux.rs | 2 ++ src/sys/ptrace/linux.rs | 28 ++++++++++++++++++++++++---- src/sys/signal.rs | 19 +++++++++++++++++-- test/sys/test_aio.rs | 4 +++- test/sys/test_ioctl.rs | 18 ++++++++++++++++-- test/sys/test_socket.rs | 6 ++++++ test/sys/test_wait.rs | 14 ++++++++++++-- test/test_mq.rs | 20 ++++++++++++++++++-- 9 files changed, 99 insertions(+), 13 deletions(-) create mode 100644 changelog/2138.added.md diff --git a/changelog/2138.added.md b/changelog/2138.added.md new file mode 100644 index 0000000000..888e364984 --- /dev/null +++ b/changelog/2138.added.md @@ -0,0 +1 @@ +Added `mips32r6` and `mips64r6` support for signal, ioctl and ptrace diff --git a/src/sys/ioctl/linux.rs b/src/sys/ioctl/linux.rs index 610b8ddac0..52312f4f04 100644 --- a/src/sys/ioctl/linux.rs +++ b/src/sys/ioctl/linux.rs @@ -19,7 +19,9 @@ pub const TYPEBITS: ioctl_num_type = 8; cfg_if! { if #[cfg(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc", target_arch = "powerpc64", target_arch = "sparc64" diff --git a/src/sys/ptrace/linux.rs b/src/sys/ptrace/linux.rs index 8c87e795f1..17da41af06 100644 --- a/src/sys/ptrace/linux.rs +++ b/src/sys/ptrace/linux.rs @@ -53,28 +53,36 @@ libc_enum! { #[cfg(any(all(target_os = "android", target_pointer_width = "32"), all(target_os = "linux", any(target_env = "musl", target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "x86_64", target_pointer_width = "32"))))] PTRACE_GETREGS, #[cfg(any(all(target_os = "android", target_pointer_width = "32"), all(target_os = "linux", any(target_env = "musl", target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "x86_64", target_pointer_width = "32"))))] PTRACE_SETREGS, #[cfg(any(all(target_os = "android", target_pointer_width = "32"), all(target_os = "linux", any(target_env = "musl", target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "x86_64", target_pointer_width = "32"))))] PTRACE_GETFPREGS, #[cfg(any(all(target_os = "android", target_pointer_width = "32"), all(target_os = "linux", any(target_env = "musl", target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "x86_64", target_pointer_width = "32"))))] PTRACE_SETFPREGS, @@ -82,13 +90,17 @@ libc_enum! { PTRACE_DETACH, #[cfg(all(target_os = "linux", any(target_env = "musl", target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "x86", target_arch = "x86_64")))] PTRACE_GETFPXREGS, #[cfg(all(target_os = "linux", any(target_env = "musl", target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "x86", target_arch = "x86_64")))] PTRACE_SETFPXREGS, @@ -98,10 +110,14 @@ libc_enum! { PTRACE_GETSIGINFO, PTRACE_SETSIGINFO, #[cfg(all(target_os = "linux", not(any(target_arch = "mips", - target_arch = "mips64"))))] + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6"))))] PTRACE_GETREGSET, #[cfg(all(target_os = "linux", not(any(target_arch = "mips", - target_arch = "mips64"))))] + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6"))))] PTRACE_SETREGSET, #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] @@ -110,10 +126,14 @@ libc_enum! { #[cfg_attr(docsrs, doc(cfg(all())))] PTRACE_INTERRUPT, #[cfg(all(target_os = "linux", not(any(target_arch = "mips", - target_arch = "mips64"))))] + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6"))))] PTRACE_LISTEN, #[cfg(all(target_os = "linux", not(any(target_arch = "mips", - target_arch = "mips64"))))] + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6"))))] PTRACE_PEEKSIGINFO, #[cfg(all(target_os = "linux", target_env = "gnu", any(target_arch = "x86", target_arch = "x86_64")))] diff --git a/src/sys/signal.rs b/src/sys/signal.rs index e3274f27e9..408471143f 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -67,7 +67,10 @@ libc_enum! { /// Stack fault (obsolete) #[cfg(all(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux"), - not(any(target_arch = "mips", target_arch = "mips64", + not(any(target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", target_arch = "sparc64"))))] SIGSTKFLT, /// To parent on child stop or exit @@ -152,7 +155,9 @@ impl FromStr for Signal { ), not(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "sparc64" )) ))] @@ -236,7 +241,9 @@ impl Signal { ), not(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "sparc64" )) ))] @@ -329,7 +336,9 @@ const SIGNALS: [Signal; 28] = [ ), not(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "sparc64" )) ))] @@ -347,7 +356,13 @@ const SIGNALS: [Signal; 31] = [ target_os = "emscripten", target_os = "fuchsia" ), - any(target_arch = "mips", target_arch = "mips64", target_arch = "sparc64") + any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "sparc64" + ) ))] #[cfg(feature = "signal")] const SIGNALS: [Signal; 30] = [ diff --git a/test/sys/test_aio.rs b/test/sys/test_aio.rs index 5035b5a08f..1939ac767b 100644 --- a/test/sys/test_aio.rs +++ b/test/sys/test_aio.rs @@ -498,7 +498,9 @@ mod aio_writev { any( all(target_env = "musl", target_arch = "x86_64"), target_arch = "mips", - target_arch = "mips64" + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" ), ignore )] diff --git a/test/sys/test_ioctl.rs b/test/sys/test_ioctl.rs index b9d9f9f0c3..2062b25fb3 100644 --- a/test/sys/test_ioctl.rs +++ b/test/sys/test_ioctl.rs @@ -36,7 +36,9 @@ mod linux { fn test_op_none() { if cfg!(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc", target_arch = "powerpc64" )) { @@ -54,7 +56,9 @@ mod linux { fn test_op_write() { if cfg!(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc", target_arch = "powerpc64" )) { @@ -69,7 +73,11 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_write_64() { - if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { + if cfg!(any( + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc64" + )) { assert_eq!( request_code_write!(b'z', 10, 1u64 << 32) as u32, 0x8000_7A0A @@ -88,7 +96,9 @@ mod linux { fn test_op_read() { if cfg!(any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc", target_arch = "powerpc64" )) { @@ -103,7 +113,11 @@ mod linux { #[cfg(target_pointer_width = "64")] #[test] fn test_op_read_64() { - if cfg!(any(target_arch = "mips64", target_arch = "powerpc64")) { + if cfg!(any( + target_arch = "mips64", + target_arch = "mips64r6", + target_arch = "powerpc64" + )) { assert_eq!( request_code_read!(b'z', 10, 1u64 << 32) as u32, 0x4000_7A0A diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index ddd4f7c730..19b17fec46 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1676,7 +1676,9 @@ fn loopback_address( qemu, any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc64", ) ), @@ -1770,7 +1772,9 @@ pub fn test_recv_ipv4pktinfo() { qemu, any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc64", ) ), @@ -2061,7 +2065,9 @@ pub fn test_recvif_ipv6() { qemu, any( target_arch = "mips", + target_arch = "mips32r6", target_arch = "mips64", + target_arch = "mips64r6", target_arch = "powerpc64", ) ), diff --git a/test/sys/test_wait.rs b/test/sys/test_wait.rs index d472f1ec19..43fa05dbbf 100644 --- a/test/sys/test_wait.rs +++ b/test/sys/test_wait.rs @@ -33,7 +33,12 @@ fn test_wait_signal() { //target_os = "haiku", all(target_os = "linux", not(target_env = "uclibc")), ))] -#[cfg(not(any(target_arch = "mips", target_arch = "mips64")))] +#[cfg(not(any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" +)))] fn test_waitid_signal() { let _m = crate::FORK_MTX.lock(); @@ -76,7 +81,12 @@ fn test_wait_exit() { target_os = "haiku", all(target_os = "linux", not(target_env = "uclibc")), ))] -#[cfg(not(any(target_arch = "mips", target_arch = "mips64")))] +#[cfg(not(any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" +)))] fn test_waitid_exit() { let _m = crate::FORK_MTX.lock(); diff --git a/test/test_mq.rs b/test/test_mq.rs index 1fd8929c17..874a72b44d 100644 --- a/test/test_mq.rs +++ b/test/test_mq.rs @@ -112,7 +112,15 @@ fn test_mq_getattr() { // FIXME: Fix failures for mips in QEMU #[test] #[cfg_attr( - all(qemu, any(target_arch = "mips", target_arch = "mips64")), + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" + ) + ), ignore )] fn test_mq_setattr() { @@ -162,7 +170,15 @@ fn test_mq_setattr() { // FIXME: Fix failures for mips in QEMU #[test] #[cfg_attr( - all(qemu, any(target_arch = "mips", target_arch = "mips64")), + all( + qemu, + any( + target_arch = "mips", + target_arch = "mips32r6", + target_arch = "mips64", + target_arch = "mips64r6" + ) + ), ignore )] fn test_mq_set_nonblocking() { From 1ea59c7d7be37a841dc1d856f9579adcaf10719c Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Mon, 13 Nov 2023 20:40:59 +0000 Subject: [PATCH 037/140] feat: mman `NonNull` (#2000) * feat: mmap `NonNull` * feat: munmap `NonNull` * feat: mremap `NonNull` * feat: madvise `NonNull` * feat: msync `NonNull` * feat: mprotect `NonNull` * feat: munlock `NonNull` * feat mlock `NonNull` --- changelog/2000.changed.md | 1 + src/sys/mman.rs | 65 +++++++++++++++++++++------------------ test/sys/test_mman.rs | 31 +++++++++++-------- 3 files changed, 54 insertions(+), 43 deletions(-) create mode 100644 changelog/2000.changed.md diff --git a/changelog/2000.changed.md b/changelog/2000.changed.md new file mode 100644 index 0000000000..613e9dfef7 --- /dev/null +++ b/changelog/2000.changed.md @@ -0,0 +1 @@ +`mmap`, `mmap_anonymous`, `munmap`, `mremap`, `madvise`, `msync`, `mprotect`, `munlock` and `mlock` updated to use `NonNull`. \ No newline at end of file diff --git a/src/sys/mman.rs b/src/sys/mman.rs index c2299e9648..1e4536ae8c 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -8,10 +8,8 @@ use crate::Result; #[cfg(feature = "fs")] use crate::{fcntl::OFlag, sys::stat::Mode}; use libc::{self, c_int, c_void, off_t, size_t}; -use std::{ - num::NonZeroUsize, - os::unix::io::{AsFd, AsRawFd}, -}; +use std::{num::NonZeroUsize, os::unix::io::{AsRawFd, AsFd}}; +use std::ptr::NonNull; libc_bitflags! { /// Desired memory protection of a memory mapping. @@ -377,8 +375,8 @@ libc_bitflags! { /// `addr` must meet all the requirements described in the [`mlock(2)`] man page. /// /// [`mlock(2)`]: https://man7.org/linux/man-pages/man2/mlock.2.html -pub unsafe fn mlock(addr: *const c_void, length: size_t) -> Result<()> { - Errno::result(libc::mlock(addr, length)).map(drop) +pub unsafe fn mlock(addr: NonNull, length: size_t) -> Result<()> { + Errno::result(libc::mlock(addr.as_ptr(), length)).map(drop) } /// Unlocks all memory pages that contain part of the address range with @@ -390,8 +388,8 @@ pub unsafe fn mlock(addr: *const c_void, length: size_t) -> Result<()> { /// page. /// /// [`munlock(2)`]: https://man7.org/linux/man-pages/man2/munlock.2.html -pub unsafe fn munlock(addr: *const c_void, length: size_t) -> Result<()> { - Errno::result(libc::munlock(addr, length)).map(drop) +pub unsafe fn munlock(addr: NonNull, length: size_t) -> Result<()> { + Errno::result(libc::munlock(addr.as_ptr(), length)).map(drop) } /// Locks all memory pages mapped into this process' address space. @@ -430,7 +428,7 @@ pub unsafe fn mmap( flags: MapFlags, f: F, offset: off_t, -) -> Result<*mut c_void> { +) -> Result> { let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void); let fd = f.as_fd().as_raw_fd(); @@ -439,9 +437,12 @@ pub unsafe fn mmap( if ret == libc::MAP_FAILED { Err(Errno::last()) - } else { - Ok(ret) } + else { + // SAFETY: `libc::mmap` returns a valid non-null pointer or `libc::MAP_FAILED`, thus `ret` + // will be non-null here. + Ok(unsafe { NonNull::new_unchecked(ret) }) + } } /// Create an anonymous memory mapping. @@ -459,7 +460,7 @@ pub unsafe fn mmap_anonymous( length: NonZeroUsize, prot: ProtFlags, flags: MapFlags, -) -> Result<*mut c_void> { +) -> Result> { let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void); let flags = MapFlags::MAP_ANONYMOUS | flags; @@ -468,7 +469,9 @@ pub unsafe fn mmap_anonymous( if ret == libc::MAP_FAILED { Err(Errno::last()) } else { - Ok(ret) + // SAFETY: `libc::mmap` returns a valid non-null pointer or `libc::MAP_FAILED`, thus `ret` + // will be non-null here. + Ok(unsafe { NonNull::new_unchecked(ret) }) } } @@ -481,25 +484,25 @@ pub unsafe fn mmap_anonymous( /// detailed requirements. #[cfg(any(target_os = "linux", target_os = "netbsd"))] pub unsafe fn mremap( - addr: *mut c_void, + addr: NonNull, old_size: size_t, new_size: size_t, flags: MRemapFlags, - new_address: Option<*mut c_void>, -) -> Result<*mut c_void> { + new_address: Option>, +) -> Result> { #[cfg(target_os = "linux")] let ret = libc::mremap( - addr, + addr.as_ptr(), old_size, new_size, flags.bits(), - new_address.unwrap_or(std::ptr::null_mut()), + new_address.map(NonNull::as_ptr).unwrap_or(std::ptr::null_mut()), ); #[cfg(target_os = "netbsd")] let ret = libc::mremap( - addr, + addr.as_ptr(), old_size, - new_address.unwrap_or(std::ptr::null_mut()), + new_address.map(NonNull::as_ptr).unwrap_or(std::ptr::null_mut()), new_size, flags.bits(), ); @@ -507,7 +510,9 @@ pub unsafe fn mremap( if ret == libc::MAP_FAILED { Err(Errno::last()) } else { - Ok(ret) + // SAFETY: `libc::mremap` returns a valid non-null pointer or `libc::MAP_FAILED`, thus `ret` + // will be non-null here. + Ok(unsafe { NonNull::new_unchecked(ret) }) } } @@ -519,8 +524,8 @@ pub unsafe fn mremap( /// page. /// /// [`munmap(2)`]: https://man7.org/linux/man-pages/man2/munmap.2.html -pub unsafe fn munmap(addr: *mut c_void, len: size_t) -> Result<()> { - Errno::result(libc::munmap(addr, len)).map(drop) +pub unsafe fn munmap(addr: NonNull, len: size_t) -> Result<()> { + Errno::result(libc::munmap(addr.as_ptr(), len)).map(drop) } /// give advice about use of memory @@ -532,11 +537,11 @@ pub unsafe fn munmap(addr: *mut c_void, len: size_t) -> Result<()> { /// /// [`madvise(2)`]: https://man7.org/linux/man-pages/man2/madvise.2.html pub unsafe fn madvise( - addr: *mut c_void, + addr: NonNull, length: size_t, advise: MmapAdvise, ) -> Result<()> { - Errno::result(libc::madvise(addr, length, advise as i32)).map(drop) + Errno::result(libc::madvise(addr.as_ptr(), length, advise as i32)).map(drop) } /// Set protection of memory mapping. @@ -560,18 +565,18 @@ pub unsafe fn madvise( /// let mem = mmap_anonymous(None, one_k_non_zero, ProtFlags::PROT_NONE, MapFlags::MAP_PRIVATE) /// .unwrap(); /// mprotect(mem, ONE_K, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE).unwrap(); -/// std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) +/// std::slice::from_raw_parts_mut(mem.as_ptr().cast(), ONE_K) /// }; /// assert_eq!(slice[0], 0x00); /// slice[0] = 0xFF; /// assert_eq!(slice[0], 0xFF); /// ``` pub unsafe fn mprotect( - addr: *mut c_void, + addr: NonNull, length: size_t, prot: ProtFlags, ) -> Result<()> { - Errno::result(libc::mprotect(addr, length, prot.bits())).map(drop) + Errno::result(libc::mprotect(addr.as_ptr(), length, prot.bits())).map(drop) } /// synchronize a mapped region @@ -583,11 +588,11 @@ pub unsafe fn mprotect( /// /// [`msync(2)`]: https://man7.org/linux/man-pages/man2/msync.2.html pub unsafe fn msync( - addr: *mut c_void, + addr: NonNull, length: size_t, flags: MsFlags, ) -> Result<()> { - Errno::result(libc::msync(addr, length, flags.bits())).map(drop) + Errno::result(libc::msync(addr.as_ptr(), length, flags.bits())).map(drop) } #[cfg(not(target_os = "android"))] diff --git a/test/sys/test_mman.rs b/test/sys/test_mman.rs index 585b6d6363..3689f642be 100644 --- a/test/sys/test_mman.rs +++ b/test/sys/test_mman.rs @@ -1,19 +1,22 @@ +#![allow(clippy::redundant_slicing)] + use nix::sys::mman::{mmap_anonymous, MapFlags, ProtFlags}; use std::num::NonZeroUsize; #[test] fn test_mmap_anonymous() { unsafe { - let ptr = mmap_anonymous( + let mut ptr = mmap_anonymous( None, NonZeroUsize::new(1).unwrap(), ProtFlags::PROT_READ | ProtFlags::PROT_WRITE, MapFlags::MAP_PRIVATE, ) - .unwrap() as *mut u8; - assert_eq!(*ptr, 0x00u8); - *ptr = 0xffu8; - assert_eq!(*ptr, 0xffu8); + .unwrap() + .cast::(); + assert_eq!(*ptr.as_ref(), 0x00u8); + *ptr.as_mut() = 0xffu8; + assert_eq!(*ptr.as_ref(), 0xffu8); } } @@ -22,6 +25,7 @@ fn test_mmap_anonymous() { fn test_mremap_grow() { use nix::libc::size_t; use nix::sys::mman::{mremap, MRemapFlags}; + use std::ptr::NonNull; const ONE_K: size_t = 1024; let one_k_non_zero = NonZeroUsize::new(ONE_K).unwrap(); @@ -34,7 +38,7 @@ fn test_mremap_grow() { MapFlags::MAP_PRIVATE, ) .unwrap(); - std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) + std::slice::from_raw_parts_mut(mem.as_ptr().cast(), ONE_K) }; assert_eq!(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; @@ -43,7 +47,7 @@ fn test_mremap_grow() { let slice: &mut [u8] = unsafe { #[cfg(target_os = "linux")] let mem = mremap( - slice.as_mut_ptr().cast(), + NonNull::from(&mut slice[..]).cast(), ONE_K, 10 * ONE_K, MRemapFlags::MREMAP_MAYMOVE, @@ -52,14 +56,14 @@ fn test_mremap_grow() { .unwrap(); #[cfg(target_os = "netbsd")] let mem = mremap( - slice.as_mut_ptr().cast(), + NonNull::from(&mut slice[..]).cast(), ONE_K, 10 * ONE_K, MRemapFlags::MAP_REMAPDUP, None, ) .unwrap(); - std::slice::from_raw_parts_mut(mem as *mut u8, 10 * ONE_K) + std::slice::from_raw_parts_mut(mem.cast().as_ptr(), 10 * ONE_K) }; // The first KB should still have the old data in it. @@ -79,6 +83,7 @@ fn test_mremap_shrink() { use nix::libc::size_t; use nix::sys::mman::{mremap, MRemapFlags}; use std::num::NonZeroUsize; + use std::ptr::NonNull; const ONE_K: size_t = 1024; let ten_one_k = NonZeroUsize::new(10 * ONE_K).unwrap(); @@ -90,7 +95,7 @@ fn test_mremap_shrink() { MapFlags::MAP_PRIVATE, ) .unwrap(); - std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) + std::slice::from_raw_parts_mut(mem.as_ptr().cast(), ONE_K) }; assert_eq!(slice[ONE_K - 1], 0x00); slice[ONE_K - 1] = 0xFF; @@ -98,7 +103,7 @@ fn test_mremap_shrink() { let slice: &mut [u8] = unsafe { let mem = mremap( - slice.as_mut_ptr().cast(), + NonNull::from(&mut slice[..]).cast(), ten_one_k.into(), ONE_K, MRemapFlags::empty(), @@ -107,8 +112,8 @@ fn test_mremap_shrink() { .unwrap(); // Since we didn't supply MREMAP_MAYMOVE, the address should be the // same. - assert_eq!(mem, slice.as_mut_ptr().cast()); - std::slice::from_raw_parts_mut(mem as *mut u8, ONE_K) + assert_eq!(mem.as_ptr(), NonNull::from(&mut slice[..]).cast().as_ptr()); + std::slice::from_raw_parts_mut(mem.as_ptr().cast(), ONE_K) }; // The first KB should still be accessible and have the old data in it. From 3b16f0c8f71dee9010f71cb2a596caaf3723d3a0 Mon Sep 17 00:00:00 2001 From: Artyom Pavlov Date: Tue, 14 Nov 2023 05:20:53 +0300 Subject: [PATCH 038/140] Add `MapFlags::map_hugetlb_with_size_log2` (#2125) * Add `MapFlags::map_hugetlb_with_size_log2` * Add changelog * Add TODO note --- changelog/2125.added.md | 1 + src/sys/mman.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 changelog/2125.added.md diff --git a/changelog/2125.added.md b/changelog/2125.added.md new file mode 100644 index 0000000000..1a7600be9f --- /dev/null +++ b/changelog/2125.added.md @@ -0,0 +1 @@ +Added `MapFlags::map_hugetlb_with_size_log2` method for Linux targets \ No newline at end of file diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 1e4536ae8c..a86916c075 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -188,6 +188,33 @@ libc_bitflags! { } } +impl MapFlags { + /// Create `MAP_HUGETLB` with provided size of huge page. + /// + /// Under the hood it computes `MAP_HUGETLB | (huge_page_size_log2 << libc::MAP_HUGE_SHIFT`). + /// `huge_page_size_log2` denotes logarithm of huge page size to use and should be + /// between 16 and 63 (inclusively). + /// + /// ``` + /// # use nix::sys::mman::MapFlags; + /// let f = MapFlags::map_hugetlb_with_size_log2(30).unwrap(); + /// assert_eq!(f, MapFlags::MAP_HUGETLB | MapFlags::MAP_HUGE_1GB); + /// ``` + // TODO: support Andorid and Fuchsia when https://github.com/rust-lang/libc/pull/3444 + // will be released + #[cfg(target_os = "linux")] + #[cfg_attr(docsrs, doc(cfg(all())))] + pub fn map_hugetlb_with_size_log2(huge_page_size_log2: u32) -> Option { + if (16..=63).contains(&huge_page_size_log2) { + let flag = libc::MAP_HUGETLB + | (huge_page_size_log2 << libc::MAP_HUGE_SHIFT) as i32; + Some(Self(flag.into())) + } else { + None + } + } +} + #[cfg(any(target_os = "linux", target_os = "netbsd"))] libc_bitflags! { /// Options for [`mremap`]. From 62bf9f1184abdae17d6997e937f21bf30134ef21 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Wed, 15 Nov 2023 07:05:58 +0800 Subject: [PATCH 039/140] chore: update the rust-version key in Cargo.toml (#2193) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 0ed900400f..dbcb99e277 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "nix" description = "Rust friendly bindings to *nix APIs" edition = "2021" version = "0.27.1" -rust-version = "1.65" +rust-version = "1.69" authors = ["The nix-rust Project Developers"] repository = "https://github.com/nix-rust/nix" license = "MIT" From 6bacfe04af212df1bb51b18e5ca45377d17b304a Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Wed, 15 Nov 2023 07:06:25 +0800 Subject: [PATCH 040/140] refactor: remove legacy `#[doc(cfg(all()))]` attributes (#2192) * refactor: remove legacy #[doc(cfg(all()))] attributes * fix macOS * revert unintended change --- src/fcntl.rs | 20 ------- src/lib.rs | 1 - src/mount/bsd.rs | 15 ----- src/mount/mod.rs | 2 - src/mqueue.rs | 2 - src/net/if_.rs | 57 ------------------- src/poll.rs | 4 -- src/pty.rs | 1 - src/sched.rs | 1 - src/sys/aio.rs | 1 - src/sys/mman.rs | 62 -------------------- src/sys/mod.rs | 1 - src/sys/personality.rs | 2 - src/sys/ptrace/bsd.rs | 5 -- src/sys/ptrace/linux.rs | 4 -- src/sys/resource.rs | 16 ------ src/sys/sendfile.rs | 2 - src/sys/signal.rs | 10 ---- src/sys/socket/addr.rs | 62 -------------------- src/sys/socket/mod.rs | 40 ------------- src/sys/stat.rs | 10 ---- src/sys/statfs.rs | 45 --------------- src/sys/statvfs.rs | 11 ---- src/sys/termios.rs | 89 ----------------------------- src/sys/uio.rs | 3 - src/sys/wait.rs | 8 --- src/time.rs | 25 -------- src/unistd.rs | 123 ---------------------------------------- 28 files changed, 622 deletions(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index aacd1e1675..7910cc9b7d 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -73,7 +73,6 @@ libc_bitflags!( O_ACCMODE; /// Use alternate I/O semantics. #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] O_ALT_IO; /// Open the file in append-only mode. O_APPEND; @@ -82,7 +81,6 @@ libc_bitflags!( target_os = "illumos", target_os = "solaris", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_ASYNC; /// Closes the file descriptor once an `execve` call is made. /// @@ -96,11 +94,9 @@ libc_bitflags!( target_os = "freebsd", target_os = "linux", target_os = "netbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_DIRECT; /// If the specified path isn't a directory, fail. #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_DIRECTORY; /// Implicitly follow each `write()` with an `fdatasync()`. #[cfg(any(target_os = "android", @@ -108,13 +104,11 @@ libc_bitflags!( target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_DSYNC; /// Error out if a file was not created. O_EXCL; /// Open for execute only. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] O_EXEC; /// Open with an exclusive file lock. #[cfg(any(target_os = "dragonfly", @@ -123,7 +117,6 @@ libc_bitflags!( target_os = "netbsd", target_os = "openbsd", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_EXLOCK; /// Same as `O_SYNC`. #[cfg(any(target_os = "dragonfly", @@ -133,23 +126,18 @@ libc_bitflags!( target_os = "netbsd", target_os = "openbsd", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_FSYNC; /// Allow files whose sizes can't be represented in an `off_t` to be opened. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_LARGEFILE; /// Do not update the file last access time during `read(2)`s. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_NOATIME; /// Don't attach the device as the process' controlling terminal. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_NOCTTY; /// Same as `O_NONBLOCK`. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_NDELAY; /// `open()` will fail if the given path is a symbolic link. O_NOFOLLOW; @@ -157,13 +145,11 @@ libc_bitflags!( O_NONBLOCK; /// Don't deliver `SIGPIPE`. #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] O_NOSIGPIPE; /// Obtain a file descriptor for low-level access. /// /// The file itself is not opened and other file operations will fail. #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_PATH; /// Only allow reading. /// @@ -175,11 +161,9 @@ libc_bitflags!( O_RDWR; /// Similar to `O_DSYNC` but applies to `read`s instead. #[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_RSYNC; /// Skip search permission checks. #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] O_SEARCH; /// Open with a shared file lock. #[cfg(any(target_os = "dragonfly", @@ -188,21 +172,17 @@ libc_bitflags!( target_os = "netbsd", target_os = "openbsd", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_SHLOCK; /// Implicitly follow each `write()` with an `fsync()`. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_SYNC; /// Create an unnamed temporary file. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_TMPFILE; /// Truncate an existing regular file to 0 length if it allows writing. O_TRUNC; /// Restore default TTY attributes. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] O_TTY_INIT; /// Only allow writing. /// diff --git a/src/lib.rs b/src/lib.rs index fd750a3426..7bf5ce983c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,6 @@ //! * `zerocopy` - APIs like `sendfile` and `copy_file_range` #![crate_name = "nix"] #![cfg(unix)] -#![cfg_attr(docsrs, doc(cfg(all())))] #![allow(non_camel_case_types)] #![cfg_attr(test, deny(warnings))] #![recursion_limit = "500"] diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index bc28b49b71..daaf594871 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -17,36 +17,29 @@ libc_bitflags!( pub struct MntFlags: c_int { /// ACL support enabled. #[cfg(any(target_os = "netbsd", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_ACLS; /// All I/O to the file system should be done asynchronously. MNT_ASYNC; /// dir should instead be a file system ID encoded as “FSID:val0:val1”. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_BYFSID; /// Force a read-write mount even if the file system appears to be /// unclean. MNT_FORCE; /// GEOM journal support enabled. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_GJOURNAL; /// MAC support for objects. #[cfg(any(target_os = "macos", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_MULTILABEL; /// Disable read clustering. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_NOCLUSTERR; /// Disable write clustering. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_NOCLUSTERW; /// Enable NFS version 4 ACLs. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_NFS4ACLS; /// Do not update access times. MNT_NOATIME; @@ -56,7 +49,6 @@ libc_bitflags!( MNT_NOSUID; /// Do not follow symlinks. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_NOSYMFOLLOW; /// Mount read-only. MNT_RDONLY; @@ -67,7 +59,6 @@ libc_bitflags!( /// /// See [mksnap_ffs(8)](https://www.freebsd.org/cgi/man.cgi?query=mksnap_ffs) #[cfg(any(target_os = "macos", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_SNAPSHOT; /// Using soft updates. #[cfg(any( @@ -76,12 +67,10 @@ libc_bitflags!( target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_SOFTDEP; /// Directories with the SUID bit set chown new files to their own /// owner. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_SUIDDIR; /// All I/O to the file system should be done synchronously. MNT_SYNCHRONOUS; @@ -91,14 +80,12 @@ libc_bitflags!( target_os = "freebsd", target_os = "netbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_UNION; /// Indicates that the mount command is being applied to an already /// mounted file system. MNT_UPDATE; /// Check vnode use counts. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MNT_NONBUSY; } ); @@ -198,7 +185,6 @@ pub type NmountResult = std::result::Result<(), NmountError>; /// * [`nmount(2)`](https://www.freebsd.org/cgi/man.cgi?query=nmount) /// * [`nullfs(5)`](https://www.freebsd.org/cgi/man.cgi?query=nullfs) #[cfg(target_os = "freebsd")] -#[cfg_attr(docsrs, doc(cfg(all())))] #[derive(Debug, Default)] pub struct Nmount<'a> { // n.b. notgull: In reality, this is a list that contains @@ -210,7 +196,6 @@ pub struct Nmount<'a> { } #[cfg(target_os = "freebsd")] -#[cfg_attr(docsrs, doc(cfg(all())))] impl<'a> Nmount<'a> { /// Helper function to push a slice onto the `iov` array. fn push_slice(&mut self, val: &'a [u8], is_owned: bool) { diff --git a/src/mount/mod.rs b/src/mount/mod.rs index e98b49c343..6f00876fc2 100644 --- a/src/mount/mod.rs +++ b/src/mount/mod.rs @@ -1,6 +1,5 @@ //! Mount file systems #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod linux; #[cfg(any(target_os = "android", target_os = "linux"))] @@ -13,7 +12,6 @@ pub use self::linux::*; target_os = "netbsd", target_os = "openbsd" ))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod bsd; #[cfg(any( diff --git a/src/mqueue.rs b/src/mqueue.rs index c6b60a09b1..7f9d687521 100644 --- a/src/mqueue.rs +++ b/src/mqueue.rs @@ -88,11 +88,9 @@ pub struct MqdT(mqd_t); // See https://sourceware.org/bugzilla/show_bug.cgi?id=21279 /// Size of a message queue attribute member #[cfg(all(target_arch = "x86_64", target_pointer_width = "32"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub type mq_attr_member_t = i64; /// Size of a message queue attribute member #[cfg(not(all(target_arch = "x86_64", target_pointer_width = "32")))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub type mq_attr_member_t = libc::c_long; impl MqAttr { diff --git a/src/net/if_.rs b/src/net/if_.rs index 6fbe137075..1497e9d3c8 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -46,11 +46,9 @@ libc_bitflags!( target_os = "netbsd", target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NOTRAILERS; /// Interface manages own routes. #[cfg(any(target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_SMART; /// Resources allocated. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) @@ -64,7 +62,6 @@ libc_bitflags!( target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_RUNNING; /// No arp protocol, L2 destination address not set. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) @@ -78,23 +75,19 @@ libc_bitflags!( /// Master of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_MASTER; /// transmission in progress, tx hardware queue is full #[cfg(any(target_os = "freebsd", apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_OACTIVE; /// Protocol code on board. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_INTELLIGENT; /// Slave of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_SLAVE; /// Can't hear own transmissions. #[cfg(any(target_os = "dragonfly", @@ -102,7 +95,6 @@ libc_bitflags!( target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_SIMPLEX; /// Supports multicast. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) @@ -113,16 +105,13 @@ libc_bitflags!( apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LINK0; /// Multicast using broadcast. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_MULTI_BCAST; /// Is able to select media type via ifmap. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_PORTSEL; /// Per link layer defined bit. #[cfg(any(target_os = "dragonfly", @@ -130,16 +119,13 @@ libc_bitflags!( apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LINK1; /// Non-unique address. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_UNNUMBERED; /// Auto media selection active. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_AUTOMEDIA; /// Per link layer defined bit. #[cfg(any(target_os = "dragonfly", @@ -147,173 +133,131 @@ libc_bitflags!( apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LINK2; /// Use alternate physical connection. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", apple_targets,))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_ALTPHYS; /// DHCP controls interface. #[cfg(any(target_os = "solaris", target_os = "illumos"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_DHCPRUNNING; /// The addresses are lost when the interface goes down. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_DYNAMIC; /// Do not advertise. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_PRIVATE; /// Driver signals L1 up. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_LOWER_UP; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_POLLING_COMPAT; /// Unconfigurable using ioctl(2). #[cfg(any(target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_CANTCONFIG; /// Do not transmit packets. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NOXMIT; /// Driver signals dormant. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_DORMANT; /// User-requested promisc mode. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_PPROMISC; /// Just on-link subnet. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NOLOCAL; /// Echo sent packets. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_ECHO; /// User-requested monitor mode. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_MONITOR; /// Address is deprecated. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_DEPRECATED; /// Static ARP. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_STATICARP; /// Address from stateless addrconf. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_ADDRCONF; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NPOLLING; /// Router on interface. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_ROUTER; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_IDIRECT; /// Interface is winding down #[cfg(any(target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_DYING; /// No NUD on interface. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NONUD; /// Interface is being renamed #[cfg(any(target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_RENAMING; /// Anycast address. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_ANYCAST; /// Don't exchange routing info. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NORTEXCH; /// Do not provide packet information #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NO_PI as libc::c_int; /// TUN device (no Ethernet headers) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_TUN as libc::c_int; /// TAP device #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_TAP as libc::c_int; /// IPv4 interface. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_IPV4; /// IPv6 interface. #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_IPV6; /// in.mpathd test address #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_NOFAILOVER; /// Interface has failed #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_FAILED; /// Interface is a hot-spare #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_STANDBY; /// Functioning but not used #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_INACTIVE; /// Interface is offline #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_OFFLINE; #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_COS_ENABLED; /// Prefer as source addr. #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_PREFERRED; /// RFC3041 #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_TEMPORARY; /// MTU set with SIOCSLIFMTU #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_FIXEDMTU; /// Cannot send / receive packets #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_VIRTUAL; /// Local address in use #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_DUPLICATE; /// IPMP IP interface #[cfg(target_os = "solaris")] - #[cfg_attr(docsrs, doc(cfg(all())))] IFF_IPMP; } ); @@ -328,7 +272,6 @@ libc_bitflags!( target_os = "openbsd", target_os = "illumos", ))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod if_nameindex { use super::*; diff --git a/src/poll.rs b/src/poll.rs index 2a8b62d2ad..9462691aa0 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -144,19 +144,15 @@ libc_bitflags! { POLLOUT; /// Equivalent to [`POLLIN`](constant.POLLIN.html) #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] POLLRDNORM; #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Equivalent to [`POLLOUT`](constant.POLLOUT.html) POLLWRNORM; /// Priority band data can be read (generally unused on Linux). #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] POLLRDBAND; /// Priority data may be written. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] POLLWRBAND; /// Error condition (only returned in /// [`PollFd::revents`](struct.PollFd.html#method.revents); diff --git a/src/pty.rs b/src/pty.rs index 28c1f4fc73..3cbb118ac5 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -188,7 +188,6 @@ pub unsafe fn ptsname(fd: &PtyMaster) -> Result { /// This value is useful for opening the slave ptty once the master has already been opened with /// `posix_openpt()`. #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] #[inline] pub fn ptsname_r(fd: &PtyMaster) -> Result { let mut name_buf = Vec::::with_capacity(64); diff --git a/src/sched.rs b/src/sched.rs index c9d5d6d8a1..175fc466e5 100644 --- a/src/sched.rs +++ b/src/sched.rs @@ -8,7 +8,6 @@ use crate::{Errno, Result}; pub use self::sched_linux_like::*; #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod sched_linux_like { use crate::errno::Errno; use crate::unistd::Pid; diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 132889e36d..636611cf8b 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -57,7 +57,6 @@ libc_enum! { target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] O_DSYNC } impl TryFrom diff --git a/src/sys/mman.rs b/src/sys/mman.rs index a86916c075..4230014e8e 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -24,11 +24,9 @@ libc_bitflags! { PROT_EXEC; /// Apply protection up to the end of a mapping that grows upwards. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] PROT_GROWSDOWN; /// Apply protection down to the beginning of a mapping that grows downwards. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] PROT_GROWSUP; } } @@ -46,12 +44,10 @@ libc_bitflags! { MAP_FIXED; /// Place the mapping at exactly the address specified in `addr`, but never clobber an existing range. #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_FIXED_NOREPLACE; /// To be used with `MAP_FIXED`, to forbid the system /// to select a different address than the one specified. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_EXCL; /// Synonym for `MAP_ANONYMOUS`. MAP_ANON; @@ -62,128 +58,98 @@ libc_bitflags! { any(target_arch = "x86", target_arch = "x86_64")), all(target_os = "linux", target_env = "musl", any(target_arch = "x86", target_arch = "x86_64")), all(target_os = "freebsd", target_pointer_width = "64")))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_32BIT; /// Used for stacks; indicates to the kernel that the mapping should extend downward in memory. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_GROWSDOWN; /// Compatibility flag. Ignored. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_DENYWRITE; /// Compatibility flag. Ignored. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_EXECUTABLE; /// Mark the mmaped region to be locked in the same way as `mlock(2)`. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_LOCKED; /// Do not reserve swap space for this mapping. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd", target_os = "aix")))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NORESERVE; /// Populate page tables for a mapping. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_POPULATE; /// Only meaningful when used with `MAP_POPULATE`. Don't perform read-ahead. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NONBLOCK; /// Allocate the mapping using "huge pages." #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGETLB; /// Make use of 64KB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_64KB; /// Make use of 512KB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_512KB; /// Make use of 1MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_1MB; /// Make use of 2MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_2MB; /// Make use of 8MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_8MB; /// Make use of 16MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_16MB; /// Make use of 32MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_32MB; /// Make use of 256MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_256MB; /// Make use of 512MB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_512MB; /// Make use of 1GB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_1GB; /// Make use of 2GB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_2GB; /// Make use of 16GB huge page (must be supported by the system) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HUGE_16GB; /// Lock the mapped region into memory as with `mlock(2)`. #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_WIRED; /// Causes dirtied data in the specified range to be flushed to disk only when necessary. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NOSYNC; /// Rename private pages to a file. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_RENAME; /// Region may contain semaphores. #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_HASSEMAPHORE; /// Region grows down, like a stack. #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_STACK; /// Pages in this mapping are not retained in the kernel's memory cache. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_NOCACHE; /// Allows the W/X bit on the page, it's necessary on aarch64 architecture. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_JIT; /// Allows to use large pages, underlying alignment based on size. #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_ALIGNED_SUPER; /// Pages will be discarded in the core dumps. #[cfg(target_os = "openbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_CONCEAL; } } @@ -221,19 +187,15 @@ libc_bitflags! { pub struct MRemapFlags: c_int { /// Permit the kernel to relocate the mapping to a new virtual address, if necessary. #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MREMAP_MAYMOVE; /// Place the mapping at exactly the address specified in `new_address`. #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] MREMAP_FIXED; /// Place the mapping at exactly the address specified in `new_address`. #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_FIXED; /// Allows to duplicate the mapping to be able to apply different flags on the copy. #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] MAP_REMAPDUP; } } @@ -257,29 +219,23 @@ libc_enum! { MADV_DONTNEED, /// Free up a given range of pages and its associated backing store. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_REMOVE, /// Do not make pages in this range available to the child after a `fork(2)`. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DONTFORK, /// Undo the effect of `MADV_DONTFORK`. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DOFORK, /// Poison the given pages. /// /// Subsequent references to those pages are treated like hardware memory corruption. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_HWPOISON, /// Enable Kernel Samepage Merging (KSM) for the given pages. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_MERGEABLE, /// Undo the effect of `MADV_MERGEABLE` #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_UNMERGEABLE, /// Preserve the memory of each page but offline the original page. #[cfg(any(target_os = "android", @@ -295,67 +251,51 @@ libc_enum! { MADV_SOFT_OFFLINE, /// Enable Transparent Huge Pages (THP) for pages in the given range. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_HUGEPAGE, /// Undo the effect of `MADV_HUGEPAGE`. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_NOHUGEPAGE, /// Exclude the given range from a core dump. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DONTDUMP, /// Undo the effect of an earlier `MADV_DONTDUMP`. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_DODUMP, /// Specify that the application no longer needs the pages in the given range. #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE, /// Request that the system not flush the current range to disk unless it needs to. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_NOSYNC, /// Undoes the effects of `MADV_NOSYNC` for any future pages dirtied within the given range. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_AUTOSYNC, /// Region is not included in a core file. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_NOCORE, /// Include region in a core file #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_CORE, /// This process should not be killed when swap space is exhausted. #[cfg(any(target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_PROTECT, /// Invalidate the hardware page table for the given region. #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_INVAL, /// Set the offset of the page directory page to `value` for the virtual page table. #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_SETMAP, /// Indicates that the application will not need the data in the given range. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_ZERO_WIRED_PAGES, /// Pages can be reused (by anyone). #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE_REUSABLE, /// Caller wants to reuse those pages. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MADV_FREE_REUSE, // Darwin doesn't document this flag's behavior. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(missing_docs)] MADV_CAN_REUSE, } @@ -370,11 +310,9 @@ libc_bitflags! { MS_INVALIDATE; /// Invalidate pages, but leave them mapped. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MS_KILLPAGES; /// Deactivate pages, but leave them mapped. #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] MS_DEACTIVATE; /// Perform an update and wait for it to complete. MS_SYNC; diff --git a/src/sys/mod.rs b/src/sys/mod.rs index f43d8787eb..276d4760fd 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -170,7 +170,6 @@ feature! { } #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] #[allow(missing_docs)] pub mod sysinfo; diff --git a/src/sys/personality.rs b/src/sys/personality.rs index 30231dd7b8..a4cfb5ef4f 100644 --- a/src/sys/personality.rs +++ b/src/sys/personality.rs @@ -21,7 +21,6 @@ libc_bitflags! { ADDR_LIMIT_3GB; /// User-space function pointers to signal handlers point to descriptors. #[cfg(not(any(target_env = "musl", target_env = "uclibc")))] - #[cfg_attr(docsrs, doc(cfg(all())))] FDPIC_FUNCPTRS; /// Map page 0 as read-only. MMAP_PAGE_ZERO; @@ -43,7 +42,6 @@ libc_bitflags! { /// /// [`uname(2)`]: https://man7.org/linux/man-pages/man2/uname.2.html #[cfg(not(any(target_env = "musl", target_env = "uclibc")))] - #[cfg_attr(docsrs, doc(cfg(all())))] UNAME26; /// No effects. WHOLE_SECONDS; diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index ba267c6577..4c382446f7 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -30,12 +30,10 @@ libc_enum! { PT_READ_I, PT_READ_D, #[cfg(target_os = "macos")] - #[cfg_attr(docsrs, doc(cfg(all())))] PT_READ_U, PT_WRITE_I, PT_WRITE_D, #[cfg(target_os = "macos")] - #[cfg_attr(docsrs, doc(cfg(all())))] PT_WRITE_U, PT_CONTINUE, PT_KILL, @@ -49,13 +47,10 @@ libc_enum! { PT_ATTACH, PT_DETACH, #[cfg(target_os = "macos")] - #[cfg_attr(docsrs, doc(cfg(all())))] PT_SIGEXC, #[cfg(target_os = "macos")] - #[cfg_attr(docsrs, doc(cfg(all())))] PT_THUPDATE, #[cfg(target_os = "macos")] - #[cfg_attr(docsrs, doc(cfg(all())))] PT_ATTACHEXC } } diff --git a/src/sys/ptrace/linux.rs b/src/sys/ptrace/linux.rs index 17da41af06..f1ada80c27 100644 --- a/src/sys/ptrace/linux.rs +++ b/src/sys/ptrace/linux.rs @@ -120,10 +120,8 @@ libc_enum! { target_arch = "mips64r6"))))] PTRACE_SETREGSET, #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] PTRACE_SEIZE, #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] PTRACE_INTERRUPT, #[cfg(all(target_os = "linux", not(any(target_arch = "mips", target_arch = "mips32r6", @@ -401,7 +399,6 @@ pub fn attach(pid: Pid) -> Result<()> { /// /// Attaches to the process specified in pid, making it a tracee of the calling process. #[cfg(target_os = "linux")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn seize(pid: Pid, options: Options) -> Result<()> { unsafe { ptrace_other( @@ -448,7 +445,6 @@ pub fn cont>>(pid: Pid, sig: T) -> Result<()> { /// /// This request is equivalent to `ptrace(PTRACE_INTERRUPT, ...)` #[cfg(target_os = "linux")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn interrupt(pid: Pid) -> Result<()> { unsafe { ptrace_other( diff --git a/src/sys/resource.rs b/src/sys/resource.rs index a040774c58..da9e3000e9 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -56,7 +56,6 @@ libc_enum! { #[non_exhaustive] pub enum Resource { #[cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum amount (in bytes) of virtual memory the process is /// allowed to map. RLIMIT_AS, @@ -75,12 +74,10 @@ libc_enum! { RLIMIT_STACK, #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum number of kqueues this user id is allowed to create. RLIMIT_KQUEUES, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// A limit on the combined number of flock locks and fcntl leases that /// this process may establish. RLIMIT_LOCKS, @@ -92,19 +89,16 @@ libc_enum! { target_os = "linux", target_os = "netbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum size (in bytes) which a process may lock into memory /// using the mlock(2) system call. RLIMIT_MEMLOCK, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// A limit on the number of bytes that can be allocated for POSIX /// message queues for the real user ID of the calling process. RLIMIT_MSGQUEUE, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// A ceiling to which the process's nice value can be raised using /// setpriority or nice. RLIMIT_NICE, @@ -117,12 +111,10 @@ libc_enum! { target_os = "linux", target_os = "aix", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum number of simultaneous processes for this user id. RLIMIT_NPROC, #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum number of pseudo-terminals this user id is allowed to /// create. RLIMIT_NPTS, @@ -134,43 +126,36 @@ libc_enum! { target_os = "linux", target_os = "aix", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// When there is memory pressure and swap is available, prioritize /// eviction of a process' resident pages beyond this amount (in bytes). RLIMIT_RSS, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// A ceiling on the real-time priority that may be set for this process /// using sched_setscheduler and sched_set‐ param. RLIMIT_RTPRIO, #[cfg(any(target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// A limit (in microseconds) on the amount of CPU time that a process /// scheduled under a real-time scheduling policy may con‐ sume without /// making a blocking system call. RLIMIT_RTTIME, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// A limit on the number of signals that may be queued for the real /// user ID of the calling process. RLIMIT_SIGPENDING, #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum size (in bytes) of socket buffer usage for this user. RLIMIT_SBSIZE, #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum size (in bytes) of the swap space that may be reserved /// or used by all of this user id's processes. RLIMIT_SWAP, #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] /// An alias for RLIMIT_AS. RLIMIT_VMEM, } @@ -279,7 +264,6 @@ libc_enum! { RUSAGE_CHILDREN, #[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Resource usage for the calling thread. RUSAGE_THREAD, } diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 7e4ee74210..0959db73fd 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -22,7 +22,6 @@ use crate::Result; /// /// For more information, see [the sendfile(2) man page.](https://man7.org/linux/man-pages/man2/sendfile.2.html) #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn sendfile( out_fd: F1, in_fd: F2, @@ -56,7 +55,6 @@ pub fn sendfile( /// /// For more information, see [the sendfile(2) man page.](https://man7.org/linux/man-pages/man2/sendfile.2.html) #[cfg(target_os = "linux")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn sendfile64( out_fd: F1, in_fd: F2, diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 408471143f..d9f2e7bc4a 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -99,12 +99,10 @@ libc_enum! { SIGWINCH, /// Input/output possible signal #[cfg(not(target_os = "haiku"))] - #[cfg_attr(docsrs, doc(cfg(all())))] SIGIO, #[cfg(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux", target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Power failure imminent. SIGPWR, /// Bad system call @@ -112,14 +110,12 @@ libc_enum! { #[cfg(not(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux", target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Emulator trap SIGEMT, #[cfg(not(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux", target_os = "redox", target_os = "haiku", target_os = "aix")))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Information request SIGINFO, } @@ -594,7 +590,6 @@ impl SigSet { /// Suspends execution of the calling thread until one of the signals in the /// signal mask becomes pending, and returns the accepted signal. #[cfg(not(target_os = "redox"))] // RedoxFS does not yet support sigwait - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn wait(&self) -> Result { use std::convert::TryFrom; @@ -744,7 +739,6 @@ pub enum SigHandler { /// Use the given signal-catching function, which takes in the signal, information about how /// the signal was generated, and a pointer to the threads `ucontext_t`. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] SigAction(extern fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void)) } @@ -1116,7 +1110,6 @@ pub enum SigevNotify { // Note: SIGEV_THREAD is not implemented, but could be if desired. /// Notify by delivering an event to a kqueue. #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] SigevKevent { /// File descriptor of the kqueue to notify. kq: RawFd, @@ -1125,7 +1118,6 @@ pub enum SigevNotify { }, /// Notify by delivering an event to a kqueue, with optional event flags set #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] #[cfg(feature = "event")] SigevKeventFlags { /// File descriptor of the kqueue to notify. @@ -1141,7 +1133,6 @@ pub enum SigevNotify { target_env = "gnu", target_env = "uclibc", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] SigevThreadId { /// Signal to send signal: Signal, @@ -1159,7 +1150,6 @@ pub enum SigevNotify { target_os = "openbsd", target_os = "redox" )))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod sigevent { feature! { #![any(feature = "aio", feature = "signal")] diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index f973bfaedb..c896c63827 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -73,7 +73,6 @@ pub enum AddressFamily { Inet6 = libc::AF_INET6, /// Kernel user interface device (see [`netlink(7)`](https://man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Netlink = libc::AF_NETLINK, /// Kernel interface for interacting with the routing table #[cfg(not(any( @@ -90,19 +89,15 @@ pub enum AddressFamily { target_os = "fuchsia", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Packet = libc::AF_PACKET, /// KEXT Controls and Notifications #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] System = libc::AF_SYSTEM, /// Amateur radio AX.25 protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ax25 = libc::AF_AX25, /// IPX - Novell protocols #[cfg(not(any(target_os = "aix", target_os = "redox")))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ipx = libc::AF_IPX, /// AppleTalk #[cfg(not(target_os = "redox"))] @@ -110,96 +105,76 @@ pub enum AddressFamily { /// AX.25 packet layer protocol. /// (see [netrom(4)](https://www.unix.com/man-page/linux/4/netrom/)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetRom = libc::AF_NETROM, /// Can't be used for creating sockets; mostly used for bridge /// links in /// [rtnetlink(7)](https://man7.org/linux/man-pages/man7/rtnetlink.7.html) /// protocol commands. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Bridge = libc::AF_BRIDGE, /// Access to raw ATM PVCs #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] AtmPvc = libc::AF_ATMPVC, /// ITU-T X.25 / ISO-8208 protocol (see [`x25(7)`](https://man7.org/linux/man-pages/man7/x25.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] X25 = libc::AF_X25, /// RATS (Radio Amateur Telecommunications Society) Open /// Systems environment (ROSE) AX.25 packet layer protocol. /// (see [netrom(4)](https://www.unix.com/man-page/linux/4/netrom/)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Rose = libc::AF_ROSE, /// DECet protocol sockets. #[cfg(not(any(target_os = "haiku", target_os = "redox")))] Decnet = libc::AF_DECnet, /// Reserved for "802.2LLC project"; never used. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetBeui = libc::AF_NETBEUI, /// This was a short-lived (between Linux 2.1.30 and /// 2.1.99pre2) protocol family for firewall upcalls. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Security = libc::AF_SECURITY, /// Key management protocol. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Key = libc::AF_KEY, #[allow(missing_docs)] // Not documented anywhere that I can find #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ash = libc::AF_ASH, /// Acorn Econet protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Econet = libc::AF_ECONET, /// Access to ATM Switched Virtual Circuits #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] AtmSvc = libc::AF_ATMSVC, /// Reliable Datagram Sockets (RDS) protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Rds = libc::AF_RDS, /// IBM SNA #[cfg(not(any(target_os = "haiku", target_os = "redox")))] Sna = libc::AF_SNA, /// Socket interface over IrDA #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Irda = libc::AF_IRDA, /// Generic PPP transport layer, for setting up L2 tunnels (L2TP and PPPoE) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Pppox = libc::AF_PPPOX, /// Legacy protocol for wide area network (WAN) connectivity that was used /// by Sangoma WAN cards #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Wanpipe = libc::AF_WANPIPE, /// Logical link control (IEEE 802.2 LLC) protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Llc = libc::AF_LLC, /// InfiniBand native addressing #[cfg(all(target_os = "linux", not(target_env = "uclibc")))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ib = libc::AF_IB, /// Multiprotocol Label Switching #[cfg(all(target_os = "linux", not(target_env = "uclibc")))] - #[cfg_attr(docsrs, doc(cfg(all())))] Mpls = libc::AF_MPLS, /// Controller Area Network automotive bus protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Can = libc::AF_CAN, /// TIPC, "cluster domain sockets" protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Tipc = libc::AF_TIPC, /// Bluetooth low-level socket protocol #[cfg(not(any( @@ -209,16 +184,13 @@ pub enum AddressFamily { target_os = "solaris", target_os = "redox", )))] - #[cfg_attr(docsrs, doc(cfg(all())))] Bluetooth = libc::AF_BLUETOOTH, /// IUCV (inter-user communication vehicle) z/VM protocol for /// hypervisor-guest interaction #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Iucv = libc::AF_IUCV, /// Rx, Andrew File System remote procedure call protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] RxRpc = libc::AF_RXRPC, /// New "modular ISDN" driver interface protocol #[cfg(not(any( @@ -228,28 +200,22 @@ pub enum AddressFamily { target_os = "haiku", target_os = "redox", )))] - #[cfg_attr(docsrs, doc(cfg(all())))] Isdn = libc::AF_ISDN, /// Nokia cellular modem IPC/RPC interface #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Phonet = libc::AF_PHONET, /// IEEE 802.15.4 WPAN (wireless personal area network) raw packet protocol #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ieee802154 = libc::AF_IEEE802154, /// Ericsson's Communication CPU to Application CPU interface (CAIF) /// protocol. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Caif = libc::AF_CAIF, /// Interface to kernel crypto API #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Alg = libc::AF_ALG, /// Near field communication #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] Nfc = libc::AF_NFC, /// VMWare VSockets protocol for hypervisor-guest interaction. #[cfg(any( @@ -257,7 +223,6 @@ pub enum AddressFamily { target_os = "linux", target_os = "macos" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Vsock = libc::AF_VSOCK, /// ARPANet IMP addresses #[cfg(any( @@ -267,7 +232,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] ImpLink = libc::AF_IMPLINK, /// PUP protocols, e.g. BSP #[cfg(any( @@ -277,7 +241,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Pup = libc::AF_PUP, /// MIT CHAOS protocols #[cfg(any( @@ -287,11 +250,9 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Chaos = libc::AF_CHAOS, /// Novell and Xerox protocol #[cfg(any(apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ns = libc::AF_NS, #[allow(missing_docs)] // Not documented anywhere that I can find #[cfg(any( @@ -301,7 +262,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Iso = libc::AF_ISO, /// Bell Labs virtual circuit switch ? #[cfg(any( @@ -311,7 +271,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Datakit = libc::AF_DATAKIT, /// CCITT protocols, X.25 etc #[cfg(any( @@ -321,7 +280,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Ccitt = libc::AF_CCITT, /// DEC Direct data link interface #[cfg(any( @@ -331,7 +289,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Dli = libc::AF_DLI, #[allow(missing_docs)] // Not documented anywhere that I can find #[cfg(any( @@ -341,7 +298,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Lat = libc::AF_LAT, /// NSC Hyperchannel #[cfg(any( @@ -351,7 +307,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Hylink = libc::AF_HYLINK, /// Link layer interface #[cfg(any( @@ -362,7 +317,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Link = libc::AF_LINK, /// connection-oriented IP, aka ST II #[cfg(any( @@ -372,7 +326,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Coip = libc::AF_COIP, /// Computer Network Technology #[cfg(any( @@ -382,7 +335,6 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Cnt = libc::AF_CNT, /// Native ATM access #[cfg(any( @@ -392,11 +344,9 @@ pub enum AddressFamily { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] Natm = libc::AF_NATM, /// Unspecified address family, (see [`getaddrinfo(3)`](https://man7.org/linux/man-pages/man3/getaddrinfo.3.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] Unspec = libc::AF_UNSPEC, } @@ -560,7 +510,6 @@ impl UnixAddr { /// This is a Linux-specific extension, primarily used to allow chrooted /// processes to communicate with processes having a different filesystem view. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms pub fn new_abstract(path: &[u8]) -> Result { unsafe { @@ -591,7 +540,6 @@ impl UnixAddr { /// Create a new `sockaddr_un` representing an "unnamed" unix socket address. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn new_unnamed() -> UnixAddr { let ret = libc::sockaddr_un { sun_family: AddressFamily::Unix as sa_family_t, @@ -653,7 +601,6 @@ impl UnixAddr { /// For abstract sockets only the bare name is returned, without the /// leading NUL byte. `None` is returned for unnamed or path-backed sockets. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn as_abstract(&self) -> Option<&[u8]> { match self.kind() { UnixAddrKind::Abstract(name) => Some(name), @@ -663,7 +610,6 @@ impl UnixAddr { /// Check if this address is an "unnamed" unix socket address. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] #[inline] pub fn is_unnamed(&self) -> bool { matches!(self.kind(), UnixAddrKind::Unnamed) @@ -1277,7 +1223,6 @@ impl std::str::FromStr for SockaddrIn6 { #[repr(C)] pub union SockaddrStorage { #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] alg: AlgAddr, #[cfg(all(feature = "net", not(target_os = "redox")))] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -1298,7 +1243,6 @@ pub union SockaddrStorage { target_os = "linux", target_os = "macos" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] vsock: VsockAddr, } impl private::SockaddrLikePriv for SockaddrStorage {} @@ -1570,7 +1514,6 @@ impl SockaddrStorage { target_os = "linux", target_os = "macos" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] accessors! {as_vsock_addr, as_vsock_addr_mut, VsockAddr, AddressFamily::Vsock, libc::sockaddr_vm, vsock} } @@ -1769,7 +1712,6 @@ pub(super) mod private { } #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub mod netlink { use super::*; use crate::sys::socket::addr::AddressFamily; @@ -1843,7 +1785,6 @@ pub mod netlink { } #[cfg(any(target_os = "android", target_os = "linux"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub mod alg { use super::*; use libc::{sockaddr_alg, AF_ALG}; @@ -2072,7 +2013,6 @@ pub mod sys_control { } #[cfg(any(target_os = "android", target_os = "linux", target_os = "fuchsia"))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod datalink { feature! { #![feature = "net"] @@ -2175,7 +2115,6 @@ mod datalink { target_os = "aix", target_os = "openbsd" ))] -#[cfg_attr(docsrs, doc(cfg(all())))] mod datalink { feature! { #![feature = "net"] @@ -2289,7 +2228,6 @@ mod datalink { } #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub mod vsock { use super::*; use crate::sys::socket::addr::AddressFamily; diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 2d94b47aea..5a3134956b 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -139,96 +139,78 @@ pub enum SockProtocol { /// Allows applications to configure and control a KEXT /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] KextControl = libc::SYSPROTO_CONTROL, /// Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link // parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkRoute = libc::NETLINK_ROUTE, /// Reserved for user-mode socket protocols /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkUserSock = libc::NETLINK_USERSOCK, /// Query information about sockets of various protocol families from the kernel /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkSockDiag = libc::NETLINK_SOCK_DIAG, /// Netfilter/iptables ULOG. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkNFLOG = libc::NETLINK_NFLOG, /// SELinux event notifications. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkSELinux = libc::NETLINK_SELINUX, /// Open-iSCSI /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkISCSI = libc::NETLINK_ISCSI, /// Auditing /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkAudit = libc::NETLINK_AUDIT, /// Access to FIB lookup from user space /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkFIBLookup = libc::NETLINK_FIB_LOOKUP, /// Netfilter subsystem /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkNetFilter = libc::NETLINK_NETFILTER, /// SCSI Transports /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkSCSITransport = libc::NETLINK_SCSITRANSPORT, /// Infiniband RDMA /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkRDMA = libc::NETLINK_RDMA, /// Transport IPv6 packets from netfilter to user space. Used by ip6_queue kernel module. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkIPv6Firewall = libc::NETLINK_IP6_FW, /// DECnet routing messages /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkDECNetRoutingMessage = libc::NETLINK_DNRTMSG, /// Kernel messages to user space /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkKObjectUEvent = libc::NETLINK_KOBJECT_UEVENT, /// Generic netlink family for simplified netlink usage. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkGeneric = libc::NETLINK_GENERIC, /// Netlink interface to request information about ciphers registered with the kernel crypto API as well as allow /// configuration of the kernel crypto API. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NetlinkCrypto = libc::NETLINK_CRYPTO, /// Non-DIX type protocol number defined for the Ethernet IEEE 802.3 interface that allows packets of all protocols /// defined in the interface to be received. /// ([ref](https://man7.org/linux/man-pages/man7/packet.7.html)) // The protocol number is fed into the socket syscall in network byte order. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] EthAll = (libc::ETH_P_ALL as u16).to_be() as i32, /// ICMP protocol ([icmp(7)](https://man7.org/linux/man-pages/man7/icmp.7.html)) Icmp = libc::IPPROTO_ICMP, @@ -240,21 +222,18 @@ impl SockProtocol { /// The Controller Area Network raw socket protocol /// ([ref](https://docs.kernel.org/networking/can.html#how-to-use-socketcan)) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(non_upper_case_globals)] pub const CanRaw: SockProtocol = SockProtocol::Icmp; // Matches libc::CAN_RAW /// The Controller Area Network broadcast manager protocol /// ([ref](https://docs.kernel.org/networking/can.html#how-to-use-socketcan)) #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(non_upper_case_globals)] pub const CanBcm: SockProtocol = SockProtocol::NetlinkUserSock; // Matches libc::CAN_BCM /// Allows applications and other KEXTs to be notified when certain kernel events occur /// ([ref](https://developer.apple.com/library/content/documentation/Darwin/Conceptual/NKEConceptual/control/control.html)) #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(non_upper_case_globals)] pub const KextEvent: SockProtocol = SockProtocol::Icmp; // Matches libc::SYSPROTO_EVENT } @@ -295,7 +274,6 @@ libc_bitflags! { target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] SOCK_NONBLOCK; /// Set close-on-exec on the new descriptor #[cfg(any(target_os = "android", @@ -305,16 +283,13 @@ libc_bitflags! { target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] SOCK_CLOEXEC; /// Return `EPIPE` instead of raising `SIGPIPE` #[cfg(target_os = "netbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] SOCK_NOSIGPIPE; /// For domains `AF_INET(6)`, only allow `connect(2)`, `sendto(2)`, or `sendmsg(2)` /// to the DNS port (typically 53) #[cfg(target_os = "openbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] SOCK_DNS; } } @@ -345,7 +320,6 @@ libc_bitflags! { /// the calling process and as well as other processes that hold /// file descriptors referring to the same open file description. #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MSG_DONTWAIT; /// Receive flags: Control Data was discarded (buffer too small) MSG_CTRUNC; @@ -365,7 +339,6 @@ libc_bitflags! { /// the socket error queue. (For more details, see /// [recvfrom(2)](https://linux.die.net/man/2/recvfrom)) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MSG_ERRQUEUE; /// Set the `close-on-exec` flag for the file descriptor received via a UNIX domain /// file descriptor using the `SCM_RIGHTS` operation (described in @@ -380,7 +353,6 @@ libc_bitflags! { target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MSG_CMSG_CLOEXEC; /// Requests not to send `SIGPIPE` errors when the other end breaks the connection. /// (For more details, see [send(2)](https://linux.die.net/man/2/send)). @@ -394,7 +366,6 @@ libc_bitflags! { target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MSG_NOSIGNAL; /// Turns on [`MSG_DONTWAIT`] after the first message has been received (only for /// `recvmmsg()`). @@ -405,7 +376,6 @@ libc_bitflags! { target_os = "freebsd", target_os = "openbsd", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MSG_WAITFORONE; } } @@ -704,11 +674,9 @@ pub enum ControlMessageOwned { ScmRights(Vec), /// Received version of [`ControlMessage::ScmCredentials`] #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ScmCredentials(UnixCredentials), /// Received version of [`ControlMessage::ScmCreds`] #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ScmCreds(UnixCredentials), /// A message of type `SCM_TIMESTAMP`, containing the time the /// packet was received by the kernel. @@ -777,7 +745,6 @@ pub enum ControlMessageOwned { /// /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ScmTimestampns(TimeSpec), #[cfg(any( target_os = "android", @@ -849,7 +816,6 @@ pub enum ControlMessageOwned { /// `RxqOvfl` socket option should be enabled on a socket /// to allow receiving the drop counter. #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] RxqOvfl(u32), /// Socket error queue control messages read with the `MSG_ERRQUEUE` flag. @@ -1114,7 +1080,6 @@ pub enum ControlMessage<'a> { /// For further information, please refer to the /// [`unix(7)`](https://man7.org/linux/man-pages/man7/unix.7.html) man page. #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ScmCredentials(&'a UnixCredentials), /// A message of type `SCM_CREDS`, containing the pid, uid, euid, gid and groups of /// a process connected to the socket. @@ -1129,7 +1094,6 @@ pub enum ControlMessage<'a> { /// For further information, please refer to the /// [`unix(4)`](https://www.freebsd.org/cgi/man.cgi?query=unix) man page. #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ScmCreds, /// Set IV for `AF_ALG` crypto API. @@ -1140,7 +1104,6 @@ pub enum ControlMessage<'a> { target_os = "android", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] AlgSetIv(&'a [u8]), /// Set crypto operation for `AF_ALG` crypto API. It may be one of /// `ALG_OP_ENCRYPT` or `ALG_OP_DECRYPT` @@ -1151,7 +1114,6 @@ pub enum ControlMessage<'a> { target_os = "android", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] AlgSetOp(&'a libc::c_int), /// Set the length of associated authentication data (AAD) (applicable only to AEAD algorithms) /// for `AF_ALG` crypto API. @@ -1162,7 +1124,6 @@ pub enum ControlMessage<'a> { target_os = "android", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] AlgSetAeadAssoclen(&'a u32), /// UDP GSO makes it possible for applications to generate network packets @@ -1235,7 +1196,6 @@ pub enum ControlMessage<'a> { /// socket between the last recieved packet and this /// received packet. #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] RxqOvfl(&'a u32), /// Configure the transmission time of packets. diff --git a/src/sys/stat.rs b/src/sys/stat.rs index cc15495baf..84a14f53d3 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -83,7 +83,6 @@ pub type type_of_file_flag = c_ulong; ))] libc_bitflags! { /// File flags. - #[cfg_attr(docsrs, doc(cfg(all())))] pub struct FileFlag: type_of_file_flag { /// The file may only be appended to. SF_APPEND; @@ -183,7 +182,6 @@ pub fn mknod( /// Create a special or ordinary file, relative to a given directory. #[cfg(not(any(apple_targets, target_os = "redox", target_os = "haiku")))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn mknodat( dirfd: Option, path: &P, @@ -205,19 +203,16 @@ pub fn mknodat( } #[cfg(target_os = "linux")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub const fn major(dev: dev_t) -> u64 { ((dev >> 32) & 0xffff_f000) | ((dev >> 8) & 0x0000_0fff) } #[cfg(target_os = "linux")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub const fn minor(dev: dev_t) -> u64 { ((dev >> 12) & 0xffff_ff00) | ((dev) & 0x0000_00ff) } #[cfg(target_os = "linux")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub const fn makedev(major: u64, minor: u64) -> dev_t { ((major & 0xffff_f000) << 32) | ((major & 0x0000_0fff) << 8) @@ -262,7 +257,6 @@ pub fn fstat(fd: RawFd) -> Result { } #[cfg(not(target_os = "redox"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn fstatat( dirfd: Option, pathname: &P, @@ -319,7 +313,6 @@ pub enum FchmodatFlags { /// /// [fchmodat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fchmodat.html). #[cfg(not(target_os = "redox"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn fchmodat( dirfd: Option, path: &P, @@ -382,7 +375,6 @@ pub fn utimes( target_os = "freebsd", target_os = "netbsd" ))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn lutimes( path: &P, atime: &TimeVal, @@ -434,7 +426,6 @@ pub enum UtimensatFlags { /// /// [utimensat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/utimens.html). #[cfg(not(target_os = "redox"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn utimensat( dirfd: Option, path: &P, @@ -460,7 +451,6 @@ pub fn utimensat( } #[cfg(not(target_os = "redox"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn mkdirat( fd: Option, path: &P, diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index 52e2a6b43b..a98909b61e 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -26,11 +26,9 @@ use crate::{errno::Errno, NixPath, Result}; /// Identifies a mounted file system #[cfg(target_os = "android")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub type fsid_t = libc::__fsid_t; /// Identifies a mounted file system #[cfg(not(target_os = "android"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub type fsid_t = libc::fsid_t; cfg_if! { @@ -304,14 +302,12 @@ impl Statfs { target_os = "dragonfly", apple_targets, )))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn filesystem_type(&self) -> FsType { FsType(self.0.f_type) } /// Magic code defining system type #[cfg(not(any(target_os = "linux", target_os = "android")))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn filesystem_type_name(&self) -> &str { let c_str = unsafe { CStr::from_ptr(self.0.f_fstypename.as_ptr()) }; c_str.to_str().unwrap() @@ -319,21 +315,18 @@ impl Statfs { /// Optimal transfer block size #[cfg(apple_targets)] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> i32 { self.0.f_iosize } /// Optimal transfer block size #[cfg(target_os = "openbsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> u32 { self.0.f_iosize } /// Optimal transfer block size #[cfg(all(target_os = "linux", target_arch = "s390x"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> u32 { self.0.f_bsize } @@ -343,7 +336,6 @@ impl Statfs { target_os = "android", all(target_os = "linux", target_env = "musl") ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> libc::c_ulong { self.0.f_bsize } @@ -357,35 +349,30 @@ impl Statfs { target_env = "uclibc" )) ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> libc::__fsword_t { self.0.f_bsize } /// Optimal transfer block size #[cfg(all(target_os = "linux", target_env = "uclibc"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> libc::c_int { self.0.f_bsize } /// Optimal transfer block size #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> libc::c_long { self.0.f_iosize } /// Optimal transfer block size #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> u64 { self.0.f_iosize } /// Size of a block #[cfg(any(apple_targets, target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> u32 { self.0.f_bsize } @@ -393,7 +380,6 @@ impl Statfs { /// Size of a block // f_bsize on linux: https://github.com/torvalds/linux/blob/master/fs/nfs/super.c#L471 #[cfg(all(target_os = "linux", target_arch = "s390x"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> u32 { self.0.f_bsize } @@ -401,7 +387,6 @@ impl Statfs { /// Size of a block // f_bsize on linux: https://github.com/torvalds/linux/blob/master/fs/nfs/super.c#L471 #[cfg(all(target_os = "linux", target_env = "musl"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> libc::c_ulong { self.0.f_bsize } @@ -409,7 +394,6 @@ impl Statfs { /// Size of a block // f_bsize on linux: https://github.com/torvalds/linux/blob/master/fs/nfs/super.c#L471 #[cfg(all(target_os = "linux", target_env = "uclibc"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> libc::c_int { self.0.f_bsize } @@ -424,28 +408,24 @@ impl Statfs { target_env = "uclibc" )) ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> libc::__fsword_t { self.0.f_bsize } /// Size of a block #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> u64 { self.0.f_bsize } /// Size of a block #[cfg(target_os = "android")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> libc::c_ulong { self.0.f_bsize } /// Size of a block #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> libc::c_long { self.0.f_bsize } @@ -461,7 +441,6 @@ impl Statfs { target_os = "openbsd" ) ))] - #[cfg_attr(docsrs, doc(cfg(all())))] #[allow(clippy::unnecessary_cast)] // Not unnecessary on all arches pub fn flags(&self) -> MntFlags { MntFlags::from_bits_truncate(self.0.f_flags as i32) @@ -471,35 +450,30 @@ impl Statfs { // The f_flags field exists on Android and Fuchsia too, but without man // pages I can't tell if it can be cast to FsFlags. #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn flags(&self) -> FsFlags { FsFlags::from_bits_truncate(self.0.f_flags as libc::c_ulong) } /// Maximum length of filenames #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> u32 { self.0.f_namemax } /// Maximum length of filenames #[cfg(all(target_os = "linux", target_arch = "s390x"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> u32 { self.0.f_namelen } /// Maximum length of filenames #[cfg(all(target_os = "linux", target_env = "musl"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> libc::c_ulong { self.0.f_namelen } /// Maximum length of filenames #[cfg(all(target_os = "linux", target_env = "uclibc"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> libc::c_int { self.0.f_namelen } @@ -513,14 +487,12 @@ impl Statfs { target_env = "uclibc" )) ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> libc::__fsword_t { self.0.f_namelen } /// Maximum length of filenames #[cfg(target_os = "android")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> libc::c_ulong { self.0.f_namelen } @@ -534,21 +506,18 @@ impl Statfs { target_os = "openbsd", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks(&self) -> u64 { self.0.f_blocks } /// Total data blocks in filesystem #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks(&self) -> libc::c_long { self.0.f_blocks } /// Total data blocks in filesystem #[cfg(target_os = "emscripten")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks(&self) -> u32 { self.0.f_blocks } @@ -562,21 +531,18 @@ impl Statfs { target_os = "openbsd", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_free(&self) -> u64 { self.0.f_bfree } /// Free blocks in filesystem #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_free(&self) -> libc::c_long { self.0.f_bfree } /// Free blocks in filesystem #[cfg(target_os = "emscripten")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_free(&self) -> u32 { self.0.f_bfree } @@ -588,28 +554,24 @@ impl Statfs { target_os = "fuchsia", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_available(&self) -> u64 { self.0.f_bavail } /// Free blocks available to unprivileged user #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_available(&self) -> libc::c_long { self.0.f_bavail } /// Free blocks available to unprivileged user #[cfg(any(target_os = "freebsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_available(&self) -> i64 { self.0.f_bavail } /// Free blocks available to unprivileged user #[cfg(target_os = "emscripten")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn blocks_available(&self) -> u32 { self.0.f_bavail } @@ -623,21 +585,18 @@ impl Statfs { target_os = "openbsd", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files(&self) -> u64 { self.0.f_files } /// Total file nodes in filesystem #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files(&self) -> libc::c_long { self.0.f_files } /// Total file nodes in filesystem #[cfg(target_os = "emscripten")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files(&self) -> u32 { self.0.f_files } @@ -650,28 +609,24 @@ impl Statfs { target_os = "openbsd", target_os = "linux", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files_free(&self) -> u64 { self.0.f_ffree } /// Free file nodes in filesystem #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files_free(&self) -> libc::c_long { self.0.f_ffree } /// Free file nodes in filesystem #[cfg(target_os = "freebsd")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files_free(&self) -> i64 { self.0.f_ffree } /// Free file nodes in filesystem #[cfg(target_os = "emscripten")] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn files_free(&self) -> u32 { self.0.f_ffree } diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 35424e5e27..88fb2cd4ec 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -22,43 +22,33 @@ libc_bitflags!( ST_NOSUID; /// Do not interpret character or block-special devices #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_NODEV; /// Do not allow execution of binaries on the filesystem #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_NOEXEC; /// All IO should be done synchronously #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_SYNCHRONOUS; /// Allow mandatory locks on the filesystem #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_MANDLOCK; /// Write on file/directory/symlink #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_WRITE; /// Append-only file #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_APPEND; /// Immutable file #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_IMMUTABLE; /// Do not update access times on files #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_NOATIME; /// Do not update access times on files #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_NODIRATIME; /// Update access time relative to modify/change time #[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"))))] - #[cfg_attr(docsrs, doc(cfg(all())))] ST_RELATIME; } ); @@ -120,7 +110,6 @@ impl Statvfs { /// Get the mount flags #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn flags(&self) -> FsFlags { FsFlags::from_bits_truncate(self.0.f_flag) } diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 85d27bcd52..fa27801bac 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -370,7 +370,6 @@ libc_enum! { target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B7200, B9600, #[cfg(any(target_os = "dragonfly", @@ -378,7 +377,6 @@ libc_enum! { target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B14400, B19200, #[cfg(any(target_os = "dragonfly", @@ -386,30 +384,23 @@ libc_enum! { target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B28800, B38400, #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B57600, #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B76800, #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B115200, #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B153600, #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B230400, #[cfg(any(target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B307200, #[cfg(any(target_os = "android", target_os = "freebsd", @@ -417,13 +408,10 @@ libc_enum! { target_os = "linux", target_os = "netbsd", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B460800, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B500000, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B576000, #[cfg(any(target_os = "android", target_os = "freebsd", @@ -431,31 +419,22 @@ libc_enum! { target_os = "linux", target_os = "netbsd", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B921600, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B1000000, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B1152000, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B1500000, #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] B2000000, #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "sparc64"))))] - #[cfg_attr(docsrs, doc(cfg(all())))] B2500000, #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "sparc64"))))] - #[cfg_attr(docsrs, doc(cfg(all())))] B3000000, #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "sparc64"))))] - #[cfg_attr(docsrs, doc(cfg(all())))] B3500000, #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "sparc64"))))] - #[cfg_attr(docsrs, doc(cfg(all())))] B4000000, } impl TryFrom @@ -540,7 +519,6 @@ libc_enum! { #[non_exhaustive] pub enum SpecialCharacterIndices { #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] VDISCARD, #[cfg(any(target_os = "dragonfly", target_os = "freebsd", @@ -550,7 +528,6 @@ libc_enum! { target_os = "openbsd", target_os = "aix", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] VDSUSP, VEOF, VEOL, @@ -560,14 +537,12 @@ libc_enum! { target_os = "freebsd", target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] VERASE2, VINTR, VKILL, VLNEXT, #[cfg(not(any(all(target_os = "linux", target_arch = "sparc64"), target_os = "illumos", target_os = "solaris", target_os = "aix")))] - #[cfg_attr(docsrs, doc(cfg(all())))] VMIN, VQUIT, VREPRINT, @@ -579,25 +554,19 @@ libc_enum! { target_os = "netbsd", target_os = "openbsd", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] VSTATUS, VSTOP, VSUSP, #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] VSWTC, #[cfg(any(target_os = "haiku", target_os = "illumos", target_os = "solaris"))] - #[cfg_attr(docsrs, doc(cfg(all())))] VSWTCH, #[cfg(not(any(all(target_os = "linux", target_arch = "sparc64"), target_os = "illumos", target_os = "solaris", target_os = "aix")))] - #[cfg_attr(docsrs, doc(cfg(all())))] VTIME, #[cfg(not(target_os = "aix"))] - #[cfg_attr(docsrs, doc(cfg(all())))] VWERASE, #[cfg(target_os = "dragonfly")] - #[cfg_attr(docsrs, doc(cfg(all())))] VCHECKPT, } } @@ -624,7 +593,6 @@ pub use libc::NCCS; target_os = "netbsd", target_os = "openbsd" ))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub use libc::_POSIX_VDISABLE; libc_bitflags! { @@ -642,13 +610,10 @@ libc_bitflags! { IXON; IXOFF; #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IXANY; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] IMAXBEL; #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IUTF8; } } @@ -661,7 +626,6 @@ libc_bitflags! { target_os = "haiku", target_os = "linux", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] OLCUC; ONLCR; OCRNL as tcflag_t; @@ -671,128 +635,102 @@ libc_bitflags! { target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] - OFILL as tcflag_t; - #[cfg(any(target_os = "android", - target_os = "haiku", - target_os = "linux", - apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] OFDEL as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] NL0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] NL1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] CR0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] CR1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] CR2 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] CR3 as tcflag_t; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] TAB0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] TAB1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] TAB2 as tcflag_t; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] TAB3 as tcflag_t; #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] XTABS; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] BS0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] BS1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] VT0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] VT1 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] FF0 as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] FF1 as tcflag_t; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] OXTABS; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ONOEOT as tcflag_t; // Bitmasks for use with OutputFlags to select specific settings @@ -803,38 +741,32 @@ libc_bitflags! { target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] NLDLY as tcflag_t; // FIXME: Datatype needs to be corrected in libc for mac #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] CRDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] TABDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] BSDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] VTDLY as tcflag_t; #[cfg(any(target_os = "android", target_os = "haiku", target_os = "linux", apple_targets))] - #[cfg_attr(docsrs, doc(cfg(all())))] FFDLY as tcflag_t; } } @@ -847,7 +779,6 @@ libc_bitflags! { apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CIGNORE; CS5; CS6; @@ -860,54 +791,43 @@ libc_bitflags! { HUPCL; CLOCAL; #[cfg(not(any(target_os = "redox", target_os = "aix")))] - #[cfg_attr(docsrs, doc(cfg(all())))] CRTSCTS; #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CBAUD; #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "mips"))))] - #[cfg_attr(docsrs, doc(cfg(all())))] CMSPAR; #[cfg(any(target_os = "android", all(target_os = "linux", not(any(target_arch = "powerpc", target_arch = "powerpc64")))))] CIBAUD; #[cfg(any(target_os = "android", target_os = "linux"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CBAUDEX; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] MDMBUF; #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CHWFLOW; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CCTS_OFLOW; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CRTS_IFLOW; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CDTR_IFLOW; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CDSR_OFLOW; #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] CCAR_OFLOW; // Bitmasks for use with ControlFlags to select specific settings @@ -922,17 +842,14 @@ libc_bitflags! { /// Flags for setting any local modes pub struct LocalFlags: tcflag_t { #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ECHOKE; ECHOE; ECHOK; ECHO; ECHONL; #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ECHOPRT; #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ECHOCTL; ISIG; ICANON; @@ -941,25 +858,20 @@ libc_bitflags! { apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ALTWERASE; IEXTEN; #[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "aix")))] - #[cfg_attr(docsrs, doc(cfg(all())))] EXTPROC; TOSTOP; #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] FLUSHO; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", apple_targets, target_os = "netbsd", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] NOKERNINFO; #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] PENDIN; NOFLSH; } @@ -1103,7 +1015,6 @@ pub fn cfmakeraw(termios: &mut Termios) { /// /// Note that this is a non-standard function, available on FreeBSD. #[cfg(target_os = "freebsd")] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn cfmakesane(termios: &mut Termios) { let inner_termios = unsafe { termios.get_libc_termios_mut() }; unsafe { diff --git a/src/sys/uio.rs b/src/sys/uio.rs index 3744902489..7b9d844256 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -54,7 +54,6 @@ pub fn readv(fd: Fd, iov: &mut [IoSliceMut<'_>]) -> Result { /// /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) #[cfg(not(any(target_os = "redox", target_os = "haiku")))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn pwritev( fd: Fd, iov: &[IoSlice<'_>], @@ -84,7 +83,6 @@ pub fn pwritev( /// /// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html) #[cfg(not(any(target_os = "redox", target_os = "haiku")))] -#[cfg_attr(docsrs, doc(cfg(all())))] // Clippy doesn't know that we need to pass iov mutably only because the // mutation happens after converting iov to a pointer #[allow(clippy::needless_pass_by_ref_mut)] @@ -152,7 +150,6 @@ pub fn pread(fd: Fd, buf: &mut [u8], offset: off_t) -> Result { /// is used with [`process_vm_readv`](fn.process_vm_readv.html) /// and [`process_vm_writev`](fn.process_vm_writev.html). #[cfg(any(target_os = "linux", target_os = "android"))] -#[cfg_attr(docsrs, doc(cfg(all())))] #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct RemoteIoVec { diff --git a/src/sys/wait.rs b/src/sys/wait.rs index 62928bf042..c97dc45539 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -31,7 +31,6 @@ libc_bitflags!( target_os = "linux", target_os = "redox", target_os = "netbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] WEXITED; /// Report the status of selected processes that have continued from a /// job control stop by receiving a @@ -45,7 +44,6 @@ libc_bitflags!( target_os = "linux", target_os = "redox", target_os = "netbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] WSTOPPED; /// Don't reap, just poll status. #[cfg(any(target_os = "android", @@ -55,19 +53,15 @@ libc_bitflags!( target_os = "linux", target_os = "redox", target_os = "netbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] WNOWAIT; /// Don't wait on children of other threads in this group #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] __WNOTHREAD; /// Wait on all children, regardless of type #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] __WALL; /// Wait for "clone" children only. #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] __WCLONE; } ); @@ -105,7 +99,6 @@ pub enum WaitStatus { /// [`nix::sys::ptrace`]: ../ptrace/index.html /// [`ptrace`(2)]: https://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] - #[cfg_attr(docsrs, doc(cfg(all())))] PtraceEvent(Pid, Signal, c_int), /// The traced process was stopped by execution of a system call, /// and `PTRACE_O_TRACESYSGOOD` is in effect. See [`ptrace`(2)] for @@ -113,7 +106,6 @@ pub enum WaitStatus { /// /// [`ptrace`(2)]: https://man7.org/linux/man-pages/man2/ptrace.2.html #[cfg(any(target_os = "linux", target_os = "android"))] - #[cfg_attr(docsrs, doc(cfg(all())))] PtraceSyscall(Pid), /// The process was previously stopped but has resumed execution /// after receiving a `SIGCONT` signal. This is only reported if diff --git a/src/time.rs b/src/time.rs index e35e29d9ce..ba7fc9f586 100644 --- a/src/time.rs +++ b/src/time.rs @@ -35,7 +35,6 @@ impl ClockId { target_os = "android", target_os = "emscripten", ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn pid_cpu_clock_id(pid: Pid) -> Result { clock_getcpuclockid(pid) } @@ -43,7 +42,6 @@ impl ClockId { /// Returns resolution of the clock id #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn res(self) -> Result { clock_getres(self) } @@ -55,7 +53,6 @@ impl ClockId { /// Sets time to `timespec` on the clock id #[cfg(not(any(apple_targets, target_os = "redox", target_os = "hermit",)))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub fn set_time(self, timespec: TimeSpec) -> Result<()> { clock_settime(self, timespec) } @@ -71,7 +68,6 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_BOOTTIME: ClockId = ClockId(libc::CLOCK_BOOTTIME); #[cfg(any( target_os = "android", @@ -79,7 +75,6 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_BOOTTIME_ALARM: ClockId = ClockId(libc::CLOCK_BOOTTIME_ALARM); pub const CLOCK_MONOTONIC: ClockId = ClockId(libc::CLOCK_MONOTONIC); @@ -89,15 +84,12 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_MONOTONIC_COARSE: ClockId = ClockId(libc::CLOCK_MONOTONIC_COARSE); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_MONOTONIC_FAST: ClockId = ClockId(libc::CLOCK_MONOTONIC_FAST); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_MONOTONIC_PRECISE: ClockId = ClockId(libc::CLOCK_MONOTONIC_PRECISE); #[cfg(any( @@ -106,7 +98,6 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_MONOTONIC_RAW: ClockId = ClockId(libc::CLOCK_MONOTONIC_RAW); #[cfg(any( target_os = "android", @@ -118,11 +109,9 @@ impl ClockId { target_os = "redox", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_PROCESS_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_PROCESS_CPUTIME_ID); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_PROF: ClockId = ClockId(libc::CLOCK_PROF); pub const CLOCK_REALTIME: ClockId = ClockId(libc::CLOCK_REALTIME); #[cfg(any( @@ -131,7 +120,6 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_REALTIME_ALARM: ClockId = ClockId(libc::CLOCK_REALTIME_ALARM); #[cfg(any( @@ -140,25 +128,20 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_REALTIME_COARSE: ClockId = ClockId(libc::CLOCK_REALTIME_COARSE); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_REALTIME_FAST: ClockId = ClockId(libc::CLOCK_REALTIME_FAST); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_REALTIME_PRECISE: ClockId = ClockId(libc::CLOCK_REALTIME_PRECISE); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_SECOND: ClockId = ClockId(libc::CLOCK_SECOND); #[cfg(any( target_os = "emscripten", target_os = "fuchsia", all(target_os = "linux", target_env = "musl") ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_SGI_CYCLE: ClockId = ClockId(libc::CLOCK_SGI_CYCLE); #[cfg(any( target_os = "android", @@ -166,7 +149,6 @@ impl ClockId { target_os = "fuchsia", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_TAI: ClockId = ClockId(libc::CLOCK_TAI); #[cfg(any( target_os = "android", @@ -177,21 +159,16 @@ impl ClockId { target_os = "dragonfly", target_os = "linux" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_THREAD_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_THREAD_CPUTIME_ID); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_UPTIME: ClockId = ClockId(libc::CLOCK_UPTIME); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_UPTIME_FAST: ClockId = ClockId(libc::CLOCK_UPTIME_FAST); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_UPTIME_PRECISE: ClockId = ClockId(libc::CLOCK_UPTIME_PRECISE); #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub const CLOCK_VIRTUAL: ClockId = ClockId(libc::CLOCK_VIRTUAL); } @@ -216,7 +193,6 @@ impl std::fmt::Display for ClockId { /// Get the resolution of the specified clock, (see /// [clock_getres(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_getres.html)). #[cfg(not(target_os = "redox"))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn clock_getres(clock_id: ClockId) -> Result { let mut c_time: MaybeUninit = MaybeUninit::uninit(); let ret = @@ -240,7 +216,6 @@ pub fn clock_gettime(clock_id: ClockId) -> Result { /// Set the time of the specified clock, (see /// [clock_settime(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_settime.html)). #[cfg(not(any(apple_targets, target_os = "redox", target_os = "hermit",)))] -#[cfg_attr(docsrs, doc(cfg(all())))] pub fn clock_settime(clock_id: ClockId, timespec: TimeSpec) -> Result<()> { let ret = unsafe { libc::clock_settime(clock_id.as_raw(), timespec.as_ref()) }; diff --git a/src/unistd.rs b/src/unistd.rs index 9397d41ba9..b3db3cfb83 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -2016,7 +2016,6 @@ pub enum PathconfVar { ))] /// Minimum number of bits needed to represent, as a signed integer value, /// the maximum size of a regular file allowed in the specified directory. - #[cfg_attr(docsrs, doc(cfg(all())))] FILESIZEBITS = libc::_PC_FILESIZEBITS, /// Maximum number of links to a single file. LINK_MAX = libc::_PC_LINK_MAX, @@ -2047,7 +2046,6 @@ pub enum PathconfVar { target_os = "redox", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Symbolic links can be created. POSIX2_SYMLINKS = libc::_PC_2_SYMLINKS, #[cfg(any( @@ -2058,7 +2056,6 @@ pub enum PathconfVar { target_os = "openbsd", target_os = "redox" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Minimum number of bytes of storage actually allocated for any portion of /// a file. POSIX_ALLOC_SIZE_MIN = libc::_PC_ALLOC_SIZE_MIN, @@ -2069,7 +2066,6 @@ pub enum PathconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Recommended increment for file transfer sizes between the /// `POSIX_REC_MIN_XFER_SIZE` and `POSIX_REC_MAX_XFER_SIZE` values. POSIX_REC_INCR_XFER_SIZE = libc::_PC_REC_INCR_XFER_SIZE, @@ -2081,7 +2077,6 @@ pub enum PathconfVar { target_os = "openbsd", target_os = "redox" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Maximum recommended file transfer size. POSIX_REC_MAX_XFER_SIZE = libc::_PC_REC_MAX_XFER_SIZE, #[cfg(any( @@ -2092,7 +2087,6 @@ pub enum PathconfVar { target_os = "openbsd", target_os = "redox" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Minimum recommended file transfer size. POSIX_REC_MIN_XFER_SIZE = libc::_PC_REC_MIN_XFER_SIZE, #[cfg(any( @@ -2103,7 +2097,6 @@ pub enum PathconfVar { target_os = "openbsd", target_os = "redox" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Recommended file transfer buffer alignment. POSIX_REC_XFER_ALIGN = libc::_PC_REC_XFER_ALIGN, #[cfg(any( @@ -2117,7 +2110,6 @@ pub enum PathconfVar { target_os = "redox", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Maximum number of bytes in a symbolic link. SYMLINK_MAX = libc::_PC_SYMLINK_MAX, /// The use of `chown` and `fchown` is restricted to a process with @@ -2140,7 +2132,6 @@ pub enum PathconfVar { target_os = "redox", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Asynchronous input or output operations may be performed for the /// associated file. _POSIX_ASYNC_IO = libc::_PC_ASYNC_IO, @@ -2154,7 +2145,6 @@ pub enum PathconfVar { target_os = "redox", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Prioritized input or output operations may be performed for the /// associated file. _POSIX_PRIO_IO = libc::_PC_PRIO_IO, @@ -2169,12 +2159,10 @@ pub enum PathconfVar { target_os = "redox", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Synchronized input or output operations may be performed for the /// associated file. _POSIX_SYNC_IO = libc::_PC_SYNC_IO, #[cfg(any(target_os = "dragonfly", target_os = "openbsd"))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The resolution in nanoseconds for all file timestamps. _POSIX_TIMESTAMP_RESOLUTION = libc::_PC_TIMESTAMP_RESOLUTION, } @@ -2278,12 +2266,10 @@ pub enum SysconfVar { /// Maximum number of I/O operations in a single list I/O call supported by /// the implementation. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] AIO_LISTIO_MAX = libc::_SC_AIO_LISTIO_MAX, /// Maximum number of outstanding asynchronous I/O operations supported by /// the implementation. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] AIO_MAX = libc::_SC_AIO_MAX, #[cfg(any( target_os = "android", @@ -2293,7 +2279,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The maximum amount by which a process can decrease its asynchronous I/O /// priority level from its own scheduling priority. AIO_PRIO_DELTA_MAX = libc::_SC_AIO_PRIO_DELTA_MAX, @@ -2301,23 +2286,18 @@ pub enum SysconfVar { ARG_MAX = libc::_SC_ARG_MAX, /// Maximum number of functions that may be registered with `atexit`. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] ATEXIT_MAX = libc::_SC_ATEXIT_MAX, /// Maximum obase values allowed by the bc utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] BC_BASE_MAX = libc::_SC_BC_BASE_MAX, /// Maximum number of elements permitted in an array by the bc utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] BC_DIM_MAX = libc::_SC_BC_DIM_MAX, /// Maximum scale value allowed by the bc utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] BC_SCALE_MAX = libc::_SC_BC_SCALE_MAX, /// Maximum length of a string constant accepted by the bc utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] BC_STRING_MAX = libc::_SC_BC_STRING_MAX, /// Maximum number of simultaneous processes per real user ID. CHILD_MAX = libc::_SC_CHILD_MAX, @@ -2326,16 +2306,13 @@ pub enum SysconfVar { /// Maximum number of weights that can be assigned to an entry of the /// LC_COLLATE order keyword in the locale definition file #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] COLL_WEIGHTS_MAX = libc::_SC_COLL_WEIGHTS_MAX, /// Maximum number of timer expiration overruns. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] DELAYTIMER_MAX = libc::_SC_DELAYTIMER_MAX, /// Maximum number of expressions that can be nested within parentheses by /// the expr utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] EXPR_NEST_MAX = libc::_SC_EXPR_NEST_MAX, #[cfg(any( target_os = "dragonfly", @@ -2347,21 +2324,18 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Maximum length of a host name (not including the terminating null) as /// returned from the `gethostname` function HOST_NAME_MAX = libc::_SC_HOST_NAME_MAX, /// Maximum number of iovec structures that one process has available for /// use with `readv` or `writev`. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] IOV_MAX = libc::_SC_IOV_MAX, /// Unless otherwise noted, the maximum length, in bytes, of a utility's /// input line (either standard input or another file), when the utility is /// described as processing text files. The length includes room for the /// trailing newline. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] LINE_MAX = libc::_SC_LINE_MAX, /// Maximum length of a login name. #[cfg(not(target_os = "haiku"))] @@ -2370,19 +2344,15 @@ pub enum SysconfVar { NGROUPS_MAX = libc::_SC_NGROUPS_MAX, /// Initial size of `getgrgid_r` and `getgrnam_r` data buffers #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] GETGR_R_SIZE_MAX = libc::_SC_GETGR_R_SIZE_MAX, /// Initial size of `getpwuid_r` and `getpwnam_r` data buffers #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] GETPW_R_SIZE_MAX = libc::_SC_GETPW_R_SIZE_MAX, /// The maximum number of open message queue descriptors a process may hold. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] MQ_OPEN_MAX = libc::_SC_MQ_OPEN_MAX, /// The maximum number of message priorities supported by the implementation. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] MQ_PRIO_MAX = libc::_SC_MQ_PRIO_MAX, /// A value one greater than the maximum value that the system may assign to /// a newly-created file descriptor. @@ -2394,7 +2364,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Advisory Information option. _POSIX_ADVISORY_INFO = libc::_SC_ADVISORY_INFO, #[cfg(any( @@ -2407,12 +2376,10 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports barriers. _POSIX_BARRIERS = libc::_SC_BARRIERS, /// The implementation supports asynchronous input and output. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_ASYNCHRONOUS_IO = libc::_SC_ASYNCHRONOUS_IO, #[cfg(any( target_os = "dragonfly", @@ -2424,7 +2391,6 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports clock selection. _POSIX_CLOCK_SELECTION = libc::_SC_CLOCK_SELECTION, #[cfg(any( @@ -2437,12 +2403,10 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Process CPU-Time Clocks option. _POSIX_CPUTIME = libc::_SC_CPUTIME, /// The implementation supports the File Synchronization option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_FSYNC = libc::_SC_FSYNC, #[cfg(any( target_os = "dragonfly", @@ -2453,36 +2417,28 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the IPv6 option. _POSIX_IPV6 = libc::_SC_IPV6, /// The implementation supports job control. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_JOB_CONTROL = libc::_SC_JOB_CONTROL, /// The implementation supports memory mapped Files. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MAPPED_FILES = libc::_SC_MAPPED_FILES, /// The implementation supports the Process Memory Locking option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MEMLOCK = libc::_SC_MEMLOCK, /// The implementation supports the Range Memory Locking option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MEMLOCK_RANGE = libc::_SC_MEMLOCK_RANGE, /// The implementation supports memory protection. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MEMORY_PROTECTION = libc::_SC_MEMORY_PROTECTION, /// The implementation supports the Message Passing option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MESSAGE_PASSING = libc::_SC_MESSAGE_PASSING, /// The implementation supports the Monotonic Clock option. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_MONOTONIC_CLOCK = libc::_SC_MONOTONIC_CLOCK, #[cfg(any( target_os = "android", @@ -2494,12 +2450,10 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Prioritized Input and Output option. _POSIX_PRIORITIZED_IO = libc::_SC_PRIORITIZED_IO, /// The implementation supports the Process Scheduling option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_PRIORITY_SCHEDULING = libc::_SC_PRIORITY_SCHEDULING, #[cfg(any( target_os = "dragonfly", @@ -2510,7 +2464,6 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Raw Sockets option. _POSIX_RAW_SOCKETS = libc::_SC_RAW_SOCKETS, #[cfg(any( @@ -2523,7 +2476,6 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports read-write locks. _POSIX_READER_WRITER_LOCKS = libc::_SC_READER_WRITER_LOCKS, #[cfg(any( @@ -2534,7 +2486,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports realtime signals. _POSIX_REALTIME_SIGNALS = libc::_SC_REALTIME_SIGNALS, #[cfg(any( @@ -2547,20 +2498,16 @@ pub enum SysconfVar { target_os = "openbsd", target_os = "solaris" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Regular Expression Handling option. _POSIX_REGEXP = libc::_SC_REGEXP, /// Each process has a saved set-user-ID and a saved set-group-ID. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SAVED_IDS = libc::_SC_SAVED_IDS, /// The implementation supports semaphores. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SEMAPHORES = libc::_SC_SEMAPHORES, /// The implementation supports the Shared Memory Objects option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SHARED_MEMORY_OBJECTS = libc::_SC_SHARED_MEMORY_OBJECTS, #[cfg(any( target_os = "dragonfly", @@ -2570,7 +2517,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the POSIX shell. _POSIX_SHELL = libc::_SC_SHELL, #[cfg(any( @@ -2581,7 +2527,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Spawn option. _POSIX_SPAWN = libc::_SC_SPAWN, #[cfg(any( @@ -2592,7 +2537,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports spin locks. _POSIX_SPIN_LOCKS = libc::_SC_SPIN_LOCKS, #[cfg(any( @@ -2602,7 +2546,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Process Sporadic Server option. _POSIX_SPORADIC_SERVER = libc::_SC_SPORADIC_SERVER, #[cfg(any( @@ -2610,19 +2553,15 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SS_REPL_MAX = libc::_SC_SS_REPL_MAX, /// The implementation supports the Synchronized Input and Output option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_SYNCHRONIZED_IO = libc::_SC_SYNCHRONIZED_IO, /// The implementation supports the Thread Stack Address Attribute option. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_ATTR_STACKADDR = libc::_SC_THREAD_ATTR_STACKADDR, /// The implementation supports the Thread Stack Size Attribute option. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_ATTR_STACKSIZE = libc::_SC_THREAD_ATTR_STACKSIZE, #[cfg(any( apple_targets, @@ -2630,21 +2569,17 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Thread CPU-Time Clocks option. _POSIX_THREAD_CPUTIME = libc::_SC_THREAD_CPUTIME, /// The implementation supports the Non-Robust Mutex Priority Inheritance /// option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_PRIO_INHERIT = libc::_SC_THREAD_PRIO_INHERIT, /// The implementation supports the Non-Robust Mutex Priority Protection option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_PRIO_PROTECT = libc::_SC_THREAD_PRIO_PROTECT, /// The implementation supports the Thread Execution Scheduling option. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_PRIORITY_SCHEDULING = libc::_SC_THREAD_PRIORITY_SCHEDULING, #[cfg(any( target_os = "dragonfly", @@ -2654,7 +2589,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Thread Process-Shared Synchronization /// option. _POSIX_THREAD_PROCESS_SHARED = libc::_SC_THREAD_PROCESS_SHARED, @@ -2663,7 +2597,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Robust Mutex Priority Inheritance option. _POSIX_THREAD_ROBUST_PRIO_INHERIT = libc::_SC_THREAD_ROBUST_PRIO_INHERIT, #[cfg(any( @@ -2671,12 +2604,10 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Robust Mutex Priority Protection option. _POSIX_THREAD_ROBUST_PRIO_PROTECT = libc::_SC_THREAD_ROBUST_PRIO_PROTECT, /// The implementation supports thread-safe functions. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREAD_SAFE_FUNCTIONS = libc::_SC_THREAD_SAFE_FUNCTIONS, #[cfg(any( target_os = "dragonfly", @@ -2685,12 +2616,10 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Thread Sporadic Server option. _POSIX_THREAD_SPORADIC_SERVER = libc::_SC_THREAD_SPORADIC_SERVER, /// The implementation supports threads. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_THREADS = libc::_SC_THREADS, #[cfg(any( target_os = "dragonfly", @@ -2699,12 +2628,10 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports timeouts. _POSIX_TIMEOUTS = libc::_SC_TIMEOUTS, /// The implementation supports timers. #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TIMERS = libc::_SC_TIMERS, #[cfg(any( target_os = "dragonfly", @@ -2713,7 +2640,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Trace option. _POSIX_TRACE = libc::_SC_TRACE, #[cfg(any( @@ -2723,7 +2649,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Trace Event Filter option. _POSIX_TRACE_EVENT_FILTER = libc::_SC_TRACE_EVENT_FILTER, #[cfg(any( @@ -2731,7 +2656,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TRACE_EVENT_NAME_MAX = libc::_SC_TRACE_EVENT_NAME_MAX, #[cfg(any( target_os = "dragonfly", @@ -2740,7 +2664,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Trace Inherit option. _POSIX_TRACE_INHERIT = libc::_SC_TRACE_INHERIT, #[cfg(any( @@ -2750,7 +2673,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Trace Log option. _POSIX_TRACE_LOG = libc::_SC_TRACE_LOG, #[cfg(any( @@ -2758,21 +2680,18 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TRACE_NAME_MAX = libc::_SC_TRACE_NAME_MAX, #[cfg(any( apple_targets, target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TRACE_SYS_MAX = libc::_SC_TRACE_SYS_MAX, #[cfg(any( apple_targets, target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX_TRACE_USER_EVENT_MAX = libc::_SC_TRACE_USER_EVENT_MAX, #[cfg(any( target_os = "dragonfly", @@ -2781,7 +2700,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Typed Memory Objects option. _POSIX_TYPED_MEMORY_OBJECTS = libc::_SC_TYPED_MEMORY_OBJECTS, /// Integer value indicating version of this standard (C-language binding) @@ -2796,7 +2714,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation provides a C-language compilation environment with /// 32-bit `int`, `long`, `pointer`, and `off_t` types. _POSIX_V6_ILP32_OFF32 = libc::_SC_V6_ILP32_OFF32, @@ -2808,7 +2725,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation provides a C-language compilation environment with /// 32-bit `int`, `long`, and pointer types and an `off_t` type using at /// least 64 bits. @@ -2821,7 +2737,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation provides a C-language compilation environment with /// 32-bit `int` and 64-bit `long`, `pointer`, and `off_t` types. _POSIX_V6_LP64_OFF64 = libc::_SC_V6_LP64_OFF64, @@ -2833,35 +2748,28 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation provides a C-language compilation environment with an /// `int` type using at least 32 bits and `long`, pointer, and `off_t` types /// using at least 64 bits. _POSIX_V6_LPBIG_OFFBIG = libc::_SC_V6_LPBIG_OFFBIG, /// The implementation supports the C-Language Binding option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_C_BIND = libc::_SC_2_C_BIND, /// The implementation supports the C-Language Development Utilities option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_C_DEV = libc::_SC_2_C_DEV, /// The implementation supports the Terminal Characteristics option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_CHAR_TERM = libc::_SC_2_CHAR_TERM, /// The implementation supports the FORTRAN Development Utilities option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_FORT_DEV = libc::_SC_2_FORT_DEV, /// The implementation supports the FORTRAN Runtime Utilities option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_FORT_RUN = libc::_SC_2_FORT_RUN, /// The implementation supports the creation of locales by the localedef /// utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_LOCALEDEF = libc::_SC_2_LOCALEDEF, #[cfg(any( target_os = "dragonfly", @@ -2871,7 +2779,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Batch Environment Services and Utilities /// option. _POSIX2_PBS = libc::_SC_2_PBS, @@ -2883,7 +2790,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Batch Accounting option. _POSIX2_PBS_ACCOUNTING = libc::_SC_2_PBS_ACCOUNTING, #[cfg(any( @@ -2894,7 +2800,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Batch Checkpoint/Restart option. _POSIX2_PBS_CHECKPOINT = libc::_SC_2_PBS_CHECKPOINT, #[cfg(any( @@ -2905,7 +2810,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Locate Batch Job Request option. _POSIX2_PBS_LOCATE = libc::_SC_2_PBS_LOCATE, #[cfg(any( @@ -2916,7 +2820,6 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Batch Job Message Request option. _POSIX2_PBS_MESSAGE = libc::_SC_2_PBS_MESSAGE, #[cfg(any( @@ -2927,21 +2830,17 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Track Batch Job Request option. _POSIX2_PBS_TRACK = libc::_SC_2_PBS_TRACK, /// The implementation supports the Software Development Utilities option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_SW_DEV = libc::_SC_2_SW_DEV, /// The implementation supports the User Portability Utilities option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_UPE = libc::_SC_2_UPE, /// Integer value indicating version of the Shell and Utilities volume of /// POSIX.1 to which the implementation conforms. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _POSIX2_VERSION = libc::_SC_2_VERSION, /// The size of a system page in bytes. /// @@ -2949,16 +2848,12 @@ pub enum SysconfVar { /// enum constants to have the same value, so nix omits `PAGESIZE`. PAGE_SIZE = libc::_SC_PAGE_SIZE, #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_DESTRUCTOR_ITERATIONS = libc::_SC_THREAD_DESTRUCTOR_ITERATIONS, #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_KEYS_MAX = libc::_SC_THREAD_KEYS_MAX, #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_STACK_MIN = libc::_SC_THREAD_STACK_MIN, #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] PTHREAD_THREADS_MAX = libc::_SC_THREAD_THREADS_MAX, #[cfg(not(target_os = "haiku"))] RE_DUP_MAX = libc::_SC_RE_DUP_MAX, @@ -2970,10 +2865,8 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] RTSIG_MAX = libc::_SC_RTSIG_MAX, #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] SEM_NSEMS_MAX = libc::_SC_SEM_NSEMS_MAX, #[cfg(any( target_os = "android", @@ -2983,7 +2876,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] SEM_VALUE_MAX = libc::_SC_SEM_VALUE_MAX, #[cfg(any( target_os = "android", @@ -2993,7 +2885,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] SIGQUEUE_MAX = libc::_SC_SIGQUEUE_MAX, STREAM_MAX = libc::_SC_STREAM_MAX, #[cfg(any( @@ -3004,10 +2895,8 @@ pub enum SysconfVar { target_os = "netbsd", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] SYMLOOP_MAX = libc::_SC_SYMLOOP_MAX, #[cfg(not(target_os = "redox"))] - #[cfg_attr(docsrs, doc(cfg(all())))] TIMER_MAX = libc::_SC_TIMER_MAX, TTY_NAME_MAX = libc::_SC_TTY_NAME_MAX, TZNAME_MAX = libc::_SC_TZNAME_MAX, @@ -3019,7 +2908,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the X/Open Encryption Option Group. _XOPEN_CRYPT = libc::_SC_XOPEN_CRYPT, #[cfg(any( @@ -3030,7 +2918,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the Issue 4, Version 2 Enhanced /// Internationalization Option Group. _XOPEN_ENH_I18N = libc::_SC_XOPEN_ENH_I18N, @@ -3042,7 +2929,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] _XOPEN_LEGACY = libc::_SC_XOPEN_LEGACY, #[cfg(any( target_os = "android", @@ -3052,7 +2938,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the X/Open Realtime Option Group. _XOPEN_REALTIME = libc::_SC_XOPEN_REALTIME, #[cfg(any( @@ -3063,13 +2948,11 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the X/Open Realtime Threads Option Group. _XOPEN_REALTIME_THREADS = libc::_SC_XOPEN_REALTIME_THREADS, /// The implementation supports the Issue 4, Version 2 Shared Memory Option /// Group. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] - #[cfg_attr(docsrs, doc(cfg(all())))] _XOPEN_SHM = libc::_SC_XOPEN_SHM, #[cfg(any( target_os = "dragonfly", @@ -3078,7 +2961,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the XSI STREAMS Option Group. _XOPEN_STREAMS = libc::_SC_XOPEN_STREAMS, #[cfg(any( @@ -3089,7 +2971,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// The implementation supports the XSI option _XOPEN_UNIX = libc::_SC_XOPEN_UNIX, #[cfg(any( @@ -3100,7 +2981,6 @@ pub enum SysconfVar { target_os = "linux", target_os = "openbsd" ))] - #[cfg_attr(docsrs, doc(cfg(all())))] /// Integer value indicating version of the X/Open Portability Guide to /// which the implementation conforms. _XOPEN_VERSION = libc::_SC_XOPEN_VERSION, @@ -3419,7 +3299,6 @@ pub struct User { target_os = "linux", target_os = "solaris" )))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub class: CString, /// Last password change #[cfg(not(any( @@ -3431,7 +3310,6 @@ pub struct User { target_os = "linux", target_os = "solaris" )))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub change: libc::time_t, /// Expiration time of account #[cfg(not(any( @@ -3443,7 +3321,6 @@ pub struct User { target_os = "linux", target_os = "solaris" )))] - #[cfg_attr(docsrs, doc(cfg(all())))] pub expire: libc::time_t, } From 6f396869a999e9f93a8796013d07b9599e2387a2 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 19 Nov 2023 23:18:10 +0800 Subject: [PATCH 041/140] refactor: enable lint unsafe_op_in_unsafe_fn (#2180) --- src/env.rs | 2 +- src/errno.rs | 12 ++--- src/ifaddrs.rs | 26 ++++----- src/lib.rs | 1 + src/pty.rs | 8 +-- src/sched.rs | 24 +++++---- src/sys/inotify.rs | 2 +- src/sys/ioctl/mod.rs | 68 +++++++++++++++++------- src/sys/mman.rs | 80 ++++++++++++++++++---------- src/sys/ptrace/bsd.rs | 16 +++--- src/sys/ptrace/linux.rs | 22 ++++---- src/sys/signal.rs | 46 ++++++++-------- src/sys/socket/addr.rs | 107 +++++++++++++++++++------------------- src/sys/socket/mod.rs | 94 ++++++++++++++++++--------------- src/sys/socket/sockopt.rs | 10 ++-- src/sys/timerfd.rs | 2 +- src/sys/wait.rs | 4 +- src/unistd.rs | 12 ++--- 18 files changed, 308 insertions(+), 228 deletions(-) diff --git a/src/env.rs b/src/env.rs index 95177a1d2a..e4ad0a628a 100644 --- a/src/env.rs +++ b/src/env.rs @@ -46,7 +46,7 @@ pub unsafe fn clearenv() -> std::result::Result<(), ClearEnvError> { target_os = "linux", target_os = "android", target_os = "emscripten"))] { - let ret = libc::clearenv(); + let ret = unsafe { libc::clearenv() }; } else { use std::env; for (name, _) in env::vars_os() { diff --git a/src/errno.rs b/src/errno.rs index 6b69ccac00..869413eaf5 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -10,32 +10,32 @@ cfg_if! { if #[cfg(any(target_os = "freebsd", apple_targets,))] { unsafe fn errno_location() -> *mut c_int { - libc::__error() + unsafe { libc::__error() } } } else if #[cfg(any(target_os = "android", target_os = "netbsd", target_os = "openbsd"))] { unsafe fn errno_location() -> *mut c_int { - libc::__errno() + unsafe { libc::__errno() } } } else if #[cfg(any(target_os = "linux", target_os = "redox", target_os = "dragonfly", target_os = "fuchsia"))] { unsafe fn errno_location() -> *mut c_int { - libc::__errno_location() + unsafe { libc::__errno_location() } } } else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] { unsafe fn errno_location() -> *mut c_int { - libc::___errno() + unsafe { libc::___errno() } } } else if #[cfg(any(target_os = "haiku",))] { unsafe fn errno_location() -> *mut c_int { - libc::_errnop() + unsafe { libc::_errnop() } } } else if #[cfg(any(target_os = "aix"))] { unsafe fn errno_location() -> *mut c_int { - libc::_Errno() + unsafe { libc::_Errno() } } } } diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index 75795dfe9e..e90b26d012 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -62,22 +62,24 @@ unsafe fn workaround_xnu_bug(info: &libc::ifaddrs) -> Option { let mut dst_sock = mem::MaybeUninit::::zeroed(); - // memcpy only sa_len bytes, assume the rest is zero - std::ptr::copy_nonoverlapping( - src_sock as *const u8, - dst_sock.as_mut_ptr().cast(), - (*src_sock).sa_len.into(), - ); - - // Initialize ss_len to sizeof(libc::sockaddr_storage). - (*dst_sock.as_mut_ptr()).ss_len = - u8::try_from(mem::size_of::()).unwrap(); - let dst_sock = dst_sock.assume_init(); + let dst_sock = unsafe { + // memcpy only sa_len bytes, assume the rest is zero + std::ptr::copy_nonoverlapping( + src_sock as *const u8, + dst_sock.as_mut_ptr().cast(), + (*src_sock).sa_len.into(), + ); + + // Initialize ss_len to sizeof(libc::sockaddr_storage). + (*dst_sock.as_mut_ptr()).ss_len = + u8::try_from(mem::size_of::()).unwrap(); + dst_sock.assume_init() + }; let dst_sock_ptr = &dst_sock as *const libc::sockaddr_storage as *const libc::sockaddr; - SockaddrStorage::from_raw(dst_sock_ptr, None) + unsafe { SockaddrStorage::from_raw(dst_sock_ptr, None) } } impl InterfaceAddress { diff --git a/src/lib.rs b/src/lib.rs index 7bf5ce983c..467b839d56 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -89,6 +89,7 @@ #![warn(missing_docs)] #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(clippy::cast_ptr_alignment)] +#![deny(unsafe_op_in_unsafe_fn)] // Re-exported external crates pub use libc; diff --git a/src/pty.rs b/src/pty.rs index 3cbb118ac5..0b5f3e1085 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -169,12 +169,12 @@ pub fn posix_openpt(flags: fcntl::OFlag) -> Result { /// For a threadsafe and non-`unsafe` alternative on Linux, see `ptsname_r()`. #[inline] pub unsafe fn ptsname(fd: &PtyMaster) -> Result { - let name_ptr = libc::ptsname(fd.as_raw_fd()); + let name_ptr = unsafe { libc::ptsname(fd.as_raw_fd()) }; if name_ptr.is_null() { return Err(Errno::last()); } - let name = CStr::from_ptr(name_ptr); + let name = unsafe { CStr::from_ptr(name_ptr) }; Ok(name.to_string_lossy().into_owned()) } @@ -341,7 +341,7 @@ pub unsafe fn forkpty<'a, 'b, T: Into>, U: Into ForkResult::Child, @@ -349,7 +349,7 @@ pub unsafe fn forkpty<'a, 'b, T: Into>, U: Into isize>) -> i32, - ), - ptr_aligned as *mut c_void, - combined, - &mut cb as *mut _ as *mut c_void, - ); + let res = unsafe { + let ptr = stack.as_mut_ptr().add(stack.len()); + let ptr_aligned = ptr.sub(ptr as usize % 16); + libc::clone( + mem::transmute( + callback + as extern "C" fn(*mut Box isize>) -> i32, + ), + ptr_aligned as *mut c_void, + combined, + &mut cb as *mut _ as *mut c_void, + ) + }; Errno::result(res).map(Pid::from_raw) } diff --git a/src/sys/inotify.rs b/src/sys/inotify.rs index a3a037689f..9cbeb53973 100644 --- a/src/sys/inotify.rs +++ b/src/sys/inotify.rs @@ -244,7 +244,7 @@ impl Inotify { impl FromRawFd for Inotify { unsafe fn from_raw_fd(fd: RawFd) -> Self { Inotify { - fd: OwnedFd::from_raw_fd(fd), + fd: unsafe { OwnedFd::from_raw_fd(fd) }, } } } diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index 1eda874966..9694f204f6 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -72,7 +72,7 @@ //! # const SPI_IOC_MAGIC: u8 = b'k'; // Defined in linux/spi/spidev.h //! # const SPI_IOC_TYPE_MODE: u8 = 1; //! pub unsafe fn spi_read_mode(fd: c_int, data: *mut u8) -> Result { -//! let res = libc::ioctl(fd, request_code_read!(SPI_IOC_MAGIC, SPI_IOC_TYPE_MODE, mem::size_of::()), data); +//! let res = unsafe { libc::ioctl(fd, request_code_read!(SPI_IOC_MAGIC, SPI_IOC_TYPE_MODE, mem::size_of::()), data) }; //! Errno::result(res) //! } //! # fn main() {} @@ -179,9 +179,13 @@ //! # const SPI_IOC_TYPE_MESSAGE: u8 = 0; //! # pub struct spi_ioc_transfer(u64); //! pub unsafe fn spi_message(fd: c_int, data: &mut [spi_ioc_transfer]) -> Result { -//! let res = libc::ioctl(fd, -//! request_code_write!(SPI_IOC_MAGIC, SPI_IOC_TYPE_MESSAGE, data.len() * mem::size_of::()), -//! data.as_ptr()); +//! let res = unsafe { +//! libc::ioctl( +//! fd, +//! request_code_write!(SPI_IOC_MAGIC, SPI_IOC_TYPE_MESSAGE, data.len() * mem::size_of::()), +//! data +//! ) +//! }; //! Errno::result(res) //! } //! # fn main() {} @@ -303,7 +307,9 @@ macro_rules! ioctl_none { $(#[$attr])* pub unsafe fn $name(fd: $crate::libc::c_int) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_none!($ioty, $nr) as $crate::sys::ioctl::ioctl_num_type)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_none!($ioty, $nr) as $crate::sys::ioctl::ioctl_num_type)) + } } ) } @@ -343,7 +349,9 @@ macro_rules! ioctl_none_bad { $(#[$attr])* pub unsafe fn $name(fd: $crate::libc::c_int) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type)) + } } ) } @@ -381,7 +389,9 @@ macro_rules! ioctl_read { pub unsafe fn $name(fd: $crate::libc::c_int, data: *mut $ty) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_read!($ioty, $nr, ::std::mem::size_of::<$ty>()) as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_read!($ioty, $nr, ::std::mem::size_of::<$ty>()) as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -417,7 +427,9 @@ macro_rules! ioctl_read_bad { pub unsafe fn $name(fd: $crate::libc::c_int, data: *mut $ty) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -454,7 +466,9 @@ macro_rules! ioctl_write_ptr { pub unsafe fn $name(fd: $crate::libc::c_int, data: *const $ty) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of::<$ty>()) as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of::<$ty>()) as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -490,7 +504,9 @@ macro_rules! ioctl_write_ptr_bad { pub unsafe fn $name(fd: $crate::libc::c_int, data: *const $ty) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -531,7 +547,9 @@ cfg_if! { pub unsafe fn $name(fd: $crate::libc::c_int, data: $crate::sys::ioctl::ioctl_param_type) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write_int!($ioty, $nr) as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write_int!($ioty, $nr) as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -572,7 +590,9 @@ cfg_if! { pub unsafe fn $name(fd: $crate::libc::c_int, data: $crate::sys::ioctl::ioctl_param_type) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of::<$crate::libc::c_int>()) as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of::<$crate::libc::c_int>()) as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -616,7 +636,9 @@ macro_rules! ioctl_write_int_bad { pub unsafe fn $name(fd: $crate::libc::c_int, data: $crate::libc::c_int) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -653,7 +675,9 @@ macro_rules! ioctl_readwrite { pub unsafe fn $name(fd: $crate::libc::c_int, data: *mut $ty) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_readwrite!($ioty, $nr, ::std::mem::size_of::<$ty>()) as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_readwrite!($ioty, $nr, ::std::mem::size_of::<$ty>()) as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -681,7 +705,9 @@ macro_rules! ioctl_readwrite_bad { pub unsafe fn $name(fd: $crate::libc::c_int, data: *mut $ty) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, $nr as $crate::sys::ioctl::ioctl_num_type, data)) + } } ) } @@ -710,7 +736,9 @@ macro_rules! ioctl_read_buf { pub unsafe fn $name(fd: $crate::libc::c_int, data: &mut [$ty]) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_read!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_mut_ptr())) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_read!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_mut_ptr())) + } } ) } @@ -749,7 +777,9 @@ macro_rules! ioctl_write_buf { pub unsafe fn $name(fd: $crate::libc::c_int, data: &[$ty]) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_ptr())) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_write!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_ptr())) + } } ) } @@ -778,7 +808,9 @@ macro_rules! ioctl_readwrite_buf { pub unsafe fn $name(fd: $crate::libc::c_int, data: &mut [$ty]) -> $crate::Result<$crate::libc::c_int> { - convert_ioctl_res!($crate::libc::ioctl(fd, request_code_readwrite!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_mut_ptr())) + unsafe { + convert_ioctl_res!($crate::libc::ioctl(fd, request_code_readwrite!($ioty, $nr, ::std::mem::size_of_val(data)) as $crate::sys::ioctl::ioctl_num_type, data.as_mut_ptr())) + } } ) } diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 4230014e8e..289bdda942 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -8,8 +8,11 @@ use crate::Result; #[cfg(feature = "fs")] use crate::{fcntl::OFlag, sys::stat::Mode}; use libc::{self, c_int, c_void, off_t, size_t}; -use std::{num::NonZeroUsize, os::unix::io::{AsRawFd, AsFd}}; use std::ptr::NonNull; +use std::{ + num::NonZeroUsize, + os::unix::io::{AsFd, AsRawFd}, +}; libc_bitflags! { /// Desired memory protection of a memory mapping. @@ -170,7 +173,9 @@ impl MapFlags { // will be released #[cfg(target_os = "linux")] #[cfg_attr(docsrs, doc(cfg(all())))] - pub fn map_hugetlb_with_size_log2(huge_page_size_log2: u32) -> Option { + pub fn map_hugetlb_with_size_log2( + huge_page_size_log2: u32, + ) -> Option { if (16..=63).contains(&huge_page_size_log2) { let flag = libc::MAP_HUGETLB | (huge_page_size_log2 << libc::MAP_HUGE_SHIFT) as i32; @@ -341,7 +346,7 @@ libc_bitflags! { /// /// [`mlock(2)`]: https://man7.org/linux/man-pages/man2/mlock.2.html pub unsafe fn mlock(addr: NonNull, length: size_t) -> Result<()> { - Errno::result(libc::mlock(addr.as_ptr(), length)).map(drop) + unsafe { Errno::result(libc::mlock(addr.as_ptr(), length)).map(drop) } } /// Unlocks all memory pages that contain part of the address range with @@ -354,7 +359,7 @@ pub unsafe fn mlock(addr: NonNull, length: size_t) -> Result<()> { /// /// [`munlock(2)`]: https://man7.org/linux/man-pages/man2/munlock.2.html pub unsafe fn munlock(addr: NonNull, length: size_t) -> Result<()> { - Errno::result(libc::munlock(addr.as_ptr(), length)).map(drop) + unsafe { Errno::result(libc::munlock(addr.as_ptr(), length)).map(drop) } } /// Locks all memory pages mapped into this process' address space. @@ -397,17 +402,17 @@ pub unsafe fn mmap( let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void); let fd = f.as_fd().as_raw_fd(); - let ret = - libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), fd, offset); + let ret = unsafe { + libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), fd, offset) + }; if ret == libc::MAP_FAILED { Err(Errno::last()) - } - else { + } else { // SAFETY: `libc::mmap` returns a valid non-null pointer or `libc::MAP_FAILED`, thus `ret` // will be non-null here. Ok(unsafe { NonNull::new_unchecked(ret) }) - } + } } /// Create an anonymous memory mapping. @@ -429,7 +434,9 @@ pub unsafe fn mmap_anonymous( let ptr = addr.map_or(std::ptr::null_mut(), |a| a.get() as *mut c_void); let flags = MapFlags::MAP_ANONYMOUS | flags; - let ret = libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), -1, 0); + let ret = unsafe { + libc::mmap(ptr, length.into(), prot.bits(), flags.bits(), -1, 0) + }; if ret == libc::MAP_FAILED { Err(Errno::last()) @@ -456,21 +463,29 @@ pub unsafe fn mremap( new_address: Option>, ) -> Result> { #[cfg(target_os = "linux")] - let ret = libc::mremap( - addr.as_ptr(), - old_size, - new_size, - flags.bits(), - new_address.map(NonNull::as_ptr).unwrap_or(std::ptr::null_mut()), - ); + let ret = unsafe { + libc::mremap( + addr.as_ptr(), + old_size, + new_size, + flags.bits(), + new_address + .map(NonNull::as_ptr) + .unwrap_or(std::ptr::null_mut()), + ) + }; #[cfg(target_os = "netbsd")] - let ret = libc::mremap( - addr.as_ptr(), - old_size, - new_address.map(NonNull::as_ptr).unwrap_or(std::ptr::null_mut()), - new_size, - flags.bits(), - ); + let ret = unsafe { + libc::mremap( + addr.as_ptr(), + old_size, + new_address + .map(NonNull::as_ptr) + .unwrap_or(std::ptr::null_mut()), + new_size, + flags.bits(), + ) + }; if ret == libc::MAP_FAILED { Err(Errno::last()) @@ -490,7 +505,7 @@ pub unsafe fn mremap( /// /// [`munmap(2)`]: https://man7.org/linux/man-pages/man2/munmap.2.html pub unsafe fn munmap(addr: NonNull, len: size_t) -> Result<()> { - Errno::result(libc::munmap(addr.as_ptr(), len)).map(drop) + unsafe { Errno::result(libc::munmap(addr.as_ptr(), len)).map(drop) } } /// give advice about use of memory @@ -506,7 +521,10 @@ pub unsafe fn madvise( length: size_t, advise: MmapAdvise, ) -> Result<()> { - Errno::result(libc::madvise(addr.as_ptr(), length, advise as i32)).map(drop) + unsafe { + Errno::result(libc::madvise(addr.as_ptr(), length, advise as i32)) + .map(drop) + } } /// Set protection of memory mapping. @@ -541,7 +559,10 @@ pub unsafe fn mprotect( length: size_t, prot: ProtFlags, ) -> Result<()> { - Errno::result(libc::mprotect(addr.as_ptr(), length, prot.bits())).map(drop) + unsafe { + Errno::result(libc::mprotect(addr.as_ptr(), length, prot.bits())) + .map(drop) + } } /// synchronize a mapped region @@ -557,7 +578,10 @@ pub unsafe fn msync( length: size_t, flags: MsFlags, ) -> Result<()> { - Errno::result(libc::msync(addr.as_ptr(), length, flags.bits())).map(drop) + unsafe { + Errno::result(libc::msync(addr.as_ptr(), length, flags.bits())) + .map(drop) + } } #[cfg(not(target_os = "android"))] diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index 4c382446f7..2945d5cdd1 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -61,13 +61,15 @@ unsafe fn ptrace_other( addr: AddressType, data: c_int, ) -> Result { - Errno::result(libc::ptrace( - request as RequestType, - libc::pid_t::from(pid), - addr, - data, - )) - .map(|_| 0) + unsafe { + Errno::result(libc::ptrace( + request as RequestType, + libc::pid_t::from(pid), + addr, + data, + )) + .map(|_| 0) + } } /// Sets the process as traceable, as with `ptrace(PT_TRACEME, ...)` diff --git a/src/sys/ptrace/linux.rs b/src/sys/ptrace/linux.rs index f1ada80c27..26544e134b 100644 --- a/src/sys/ptrace/linux.rs +++ b/src/sys/ptrace/linux.rs @@ -278,13 +278,15 @@ unsafe fn ptrace_other( addr: AddressType, data: *mut c_void, ) -> Result { - Errno::result(libc::ptrace( - request as RequestType, - libc::pid_t::from(pid), - addr, - data, - )) - .map(|_| 0) + unsafe { + Errno::result(libc::ptrace( + request as RequestType, + libc::pid_t::from(pid), + addr, + data, + )) + .map(|_| 0) + } } /// Set options, as with `ptrace(PTRACE_SETOPTIONS, ...)`. @@ -551,7 +553,7 @@ pub unsafe fn write( addr: AddressType, data: *mut c_void, ) -> Result<()> { - ptrace_other(Request::PTRACE_POKEDATA, pid, addr, data).map(drop) + unsafe { ptrace_other(Request::PTRACE_POKEDATA, pid, addr, data).map(drop) } } /// Reads a word from a user area at `offset`, as with ptrace(PTRACE_PEEKUSER, ...). @@ -572,5 +574,7 @@ pub unsafe fn write_user( offset: AddressType, data: *mut c_void, ) -> Result<()> { - ptrace_other(Request::PTRACE_POKEUSER, pid, offset, data).map(drop) + unsafe { + ptrace_other(Request::PTRACE_POKEUSER, pid, offset, data).map(drop) + } } diff --git a/src/sys/signal.rs b/src/sys/signal.rs index d9f2e7bc4a..3250539969 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -757,23 +757,27 @@ impl SigAction { pub fn new(handler: SigHandler, flags: SaFlags, mask: SigSet) -> SigAction { #[cfg(not(target_os = "aix"))] unsafe fn install_sig(p: *mut libc::sigaction, handler: SigHandler) { - (*p).sa_sigaction = match handler { - SigHandler::SigDfl => libc::SIG_DFL, - SigHandler::SigIgn => libc::SIG_IGN, - SigHandler::Handler(f) => f as *const extern fn(libc::c_int) as usize, - #[cfg(not(target_os = "redox"))] - SigHandler::SigAction(f) => f as *const extern fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) as usize, - }; + unsafe { + (*p).sa_sigaction = match handler { + SigHandler::SigDfl => libc::SIG_DFL, + SigHandler::SigIgn => libc::SIG_IGN, + SigHandler::Handler(f) => f as *const extern fn(libc::c_int) as usize, + #[cfg(not(target_os = "redox"))] + SigHandler::SigAction(f) => f as *const extern fn(libc::c_int, *mut libc::siginfo_t, *mut libc::c_void) as usize, + }; + } } #[cfg(target_os = "aix")] unsafe fn install_sig(p: *mut libc::sigaction, handler: SigHandler) { - (*p).sa_union.__su_sigaction = match handler { - SigHandler::SigDfl => mem::transmute::(libc::SIG_DFL), - SigHandler::SigIgn => mem::transmute::(libc::SIG_IGN), - SigHandler::Handler(f) => mem::transmute::(f), - SigHandler::SigAction(f) => f, - }; + unsafe { + (*p).sa_union.__su_sigaction = match handler { + SigHandler::SigDfl => unsafe { mem::transmute::(libc::SIG_DFL) }, + SigHandler::SigIgn => unsafe { mem::transmute::(libc::SIG_IGN) }, + SigHandler::Handler(f) => unsafe { mem::transmute::(f) }, + SigHandler::SigAction(f) => f, + }; + } } let mut s = mem::MaybeUninit::::uninit(); @@ -878,11 +882,11 @@ impl SigAction { pub unsafe fn sigaction(signal: Signal, sigaction: &SigAction) -> Result { let mut oldact = mem::MaybeUninit::::uninit(); - let res = libc::sigaction(signal as libc::c_int, + let res = unsafe { libc::sigaction(signal as libc::c_int, &sigaction.sigaction as *const libc::sigaction, - oldact.as_mut_ptr()); + oldact.as_mut_ptr()) }; - Errno::result(res).map(|_| SigAction { sigaction: oldact.assume_init() }) + Errno::result(res).map(|_| SigAction { sigaction: unsafe { oldact.assume_init() } }) } /// Signal management (see [signal(3p)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/signal.html)) @@ -940,9 +944,9 @@ pub unsafe fn sigaction(signal: Signal, sigaction: &SigAction) -> Result Result { let signal = signal as libc::c_int; let res = match handler { - SigHandler::SigDfl => libc::signal(signal, libc::SIG_DFL), - SigHandler::SigIgn => libc::signal(signal, libc::SIG_IGN), - SigHandler::Handler(handler) => libc::signal(signal, handler as libc::sighandler_t), + SigHandler::SigDfl => unsafe { libc::signal(signal, libc::SIG_DFL) }, + SigHandler::SigIgn => unsafe { libc::signal(signal, libc::SIG_IGN) }, + SigHandler::Handler(handler) => unsafe { libc::signal(signal, handler as libc::sighandler_t) }, #[cfg(not(target_os = "redox"))] SigHandler::SigAction(_) => return Err(Errno::ENOTSUP), }; @@ -951,9 +955,7 @@ pub unsafe fn signal(signal: Signal, handler: SigHandler) -> Result libc::SIG_DFL => SigHandler::SigDfl, libc::SIG_IGN => SigHandler::SigIgn, p => SigHandler::Handler( - *(&p as *const usize - as *const extern fn(libc::c_int)) - as extern fn(libc::c_int)), + unsafe { *(&p as *const usize as *const extern fn(libc::c_int)) } as extern fn(libc::c_int)), } }) } diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index c896c63827..eb39d97f88 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -437,14 +437,17 @@ impl<'a> UnixAddrKind<'a> { } #[cfg(any(target_os = "android", target_os = "linux"))] if sun.sun_path[0] == 0 { - let name = slice::from_raw_parts( - sun.sun_path.as_ptr().add(1).cast(), - path_len - 1, - ); + let name = unsafe { + slice::from_raw_parts( + sun.sun_path.as_ptr().add(1).cast(), + path_len - 1, + ) + }; return Self::Abstract(name); } - let pathname = - slice::from_raw_parts(sun.sun_path.as_ptr().cast(), path_len); + let pathname = unsafe { + slice::from_raw_parts(sun.sun_path.as_ptr().cast(), path_len) + }; if pathname.last() == Some(&0) { // A trailing NUL is not considered part of the path, and it does // not need to be included in the addrlen passed to functions like @@ -674,10 +677,10 @@ impl SockaddrLike for UnixAddr { return None; } } - if (*addr).sa_family as i32 != libc::AF_UNIX { + if unsafe { (*addr).sa_family as i32 != libc::AF_UNIX } { return None; } - let mut su: libc::sockaddr_un = mem::zeroed(); + let mut su: libc::sockaddr_un = unsafe { mem::zeroed() }; let sup = &mut su as *mut libc::sockaddr_un as *mut u8; cfg_if! { if #[cfg(any(target_os = "android", @@ -690,11 +693,11 @@ impl SockaddrLike for UnixAddr { mem::size_of::() as libc::socklen_t ); } else { - let su_len = len.unwrap_or((*addr).sa_len as libc::socklen_t); + let su_len = unsafe { len.unwrap_or((*addr).sa_len as libc::socklen_t) }; } - }; - ptr::copy(addr as *const u8, sup, su_len as usize); - Some(Self::from_raw_parts(su, su_len as u8)) + } + unsafe { ptr::copy(addr as *const u8, sup, su_len as usize) }; + Some(unsafe { Self::from_raw_parts(su, su_len as u8) }) } fn size() -> libc::socklen_t @@ -996,10 +999,10 @@ impl SockaddrLike for SockaddrIn { return None; } } - if (*addr).sa_family as i32 != libc::AF_INET { + if unsafe { (*addr).sa_family as i32 != libc::AF_INET } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) })) } } @@ -1125,10 +1128,10 @@ impl SockaddrLike for SockaddrIn6 { return None; } } - if (*addr).sa_family as i32 != libc::AF_INET6 { + if unsafe { (*addr).sa_family as i32 != libc::AF_INET6 } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) })) } } @@ -1264,9 +1267,9 @@ impl SockaddrLike for SockaddrStorage { { None } else { - let mut ss: libc::sockaddr_storage = mem::zeroed(); + let mut ss: libc::sockaddr_storage = unsafe { mem::zeroed() }; let ssp = &mut ss as *mut libc::sockaddr_storage as *mut u8; - ptr::copy(addr as *const u8, ssp, len as usize); + unsafe { ptr::copy(addr as *const u8, ssp, len as usize) }; #[cfg(any( target_os = "android", target_os = "fuchsia", @@ -1276,9 +1279,11 @@ impl SockaddrLike for SockaddrStorage { if i32::from(ss.ss_family) == libc::AF_UNIX { // Safe because we UnixAddr is strictly smaller than // SockaddrStorage, and we just initialized the structure. - (*(&mut ss as *mut libc::sockaddr_storage - as *mut UnixAddr)) - .sun_len = len as u8; + unsafe { + (*(&mut ss as *mut libc::sockaddr_storage + as *mut UnixAddr)) + .sun_len = len as u8; + } } Some(Self { ss }) } @@ -1286,19 +1291,19 @@ impl SockaddrLike for SockaddrStorage { // If length is not available and addr is of a fixed-length type, // copy it. If addr is of a variable length type and len is not // available, then there's nothing we can do. - match (*addr).sa_family as i32 { + match unsafe { (*addr).sa_family as i32 } { #[cfg(any(target_os = "android", target_os = "linux"))] - libc::AF_ALG => { + libc::AF_ALG => unsafe { AlgAddr::from_raw(addr, l).map(|alg| Self { alg }) - } + }, #[cfg(feature = "net")] - libc::AF_INET => { + libc::AF_INET => unsafe { SockaddrIn::from_raw(addr, l).map(|sin| Self { sin }) - } + }, #[cfg(feature = "net")] - libc::AF_INET6 => { + libc::AF_INET6 => unsafe { SockaddrIn6::from_raw(addr, l).map(|sin6| Self { sin6 }) - } + }, #[cfg(any( target_os = "dragonfly", target_os = "freebsd", @@ -1309,34 +1314,30 @@ impl SockaddrLike for SockaddrStorage { target_os = "openbsd" ))] #[cfg(feature = "net")] - libc::AF_LINK => { + libc::AF_LINK => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) } #[cfg(any(target_os = "android", target_os = "linux"))] - libc::AF_NETLINK => { + libc::AF_NETLINK => unsafe { NetlinkAddr::from_raw(addr, l).map(|nl| Self { nl }) - } + }, #[cfg(any( target_os = "android", target_os = "fuchsia", target_os = "linux" ))] #[cfg(feature = "net")] - libc::AF_PACKET => { + libc::AF_PACKET => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) } #[cfg(all(feature = "ioctl", apple_targets))] - libc::AF_SYSTEM => { + libc::AF_SYSTEM => unsafe { SysControlAddr::from_raw(addr, l).map(|sctl| Self { sctl }) } - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] - libc::AF_VSOCK => { + #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos" ))] + libc::AF_VSOCK => unsafe { VsockAddr::from_raw(addr, l).map(|vsock| Self { vsock }) - } + }, _ => None, } } @@ -1362,7 +1363,7 @@ impl SockaddrLike for SockaddrStorage { new_length: usize, ) -> std::result::Result<(), SocketAddressLengthNotDynamic> { match self.as_unix_addr_mut() { - Some(addr) => addr.set_length(new_length), + Some(addr) => unsafe { addr.set_length(new_length) }, None => Err(SocketAddressLengthNotDynamic), } } @@ -1764,10 +1765,10 @@ pub mod netlink { return None; } } - if (*addr).sa_family as i32 != libc::AF_NETLINK { + if unsafe { (*addr).sa_family as i32 != libc::AF_NETLINK } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) })) } } @@ -1812,10 +1813,10 @@ pub mod alg { return None; } } - if (*addr).sa_family as i32 != libc::AF_ALG { + if unsafe { (*addr).sa_family as i32 != libc::AF_ALG } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) })) } } @@ -1948,10 +1949,10 @@ pub mod sys_control { return None; } } - if (*addr).sa_family as i32 != libc::AF_SYSTEM { + if unsafe { (*addr).sa_family as i32 != libc::AF_SYSTEM } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) } )) } } @@ -2089,10 +2090,10 @@ mod datalink { return None; } } - if (*addr).sa_family as i32 != libc::AF_PACKET { + if unsafe { (*addr).sa_family as i32 != libc::AF_PACKET } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) })) } } @@ -2212,10 +2213,10 @@ mod datalink { return None; } } - if (*addr).sa_family as i32 != libc::AF_LINK { + if unsafe { (*addr).sa_family as i32 != libc::AF_LINK } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + Some(Self(unsafe { ptr::read_unaligned(addr as *const _) })) } } @@ -2258,10 +2259,10 @@ pub mod vsock { return None; } } - if (*addr).sa_family as i32 != libc::AF_VSOCK { + if unsafe { (*addr).sa_family as i32 != libc::AF_VSOCK } { return None; } - Some(Self(ptr::read_unaligned(addr as *const _))) + unsafe { Some(Self(ptr::read_unaligned(addr as *const _))) } } } diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 5a3134956b..76e09641c0 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -889,7 +889,7 @@ impl ControlMessageOwned { #[allow(clippy::cast_ptr_alignment)] unsafe fn decode_from(header: &cmsghdr) -> ControlMessageOwned { - let p = CMSG_DATA(header); + let p = unsafe { CMSG_DATA(header) }; // The cast is not unnecessary on all platforms. #[allow(clippy::unnecessary_cast)] let len = header as *const _ as usize + header.cmsg_len as usize @@ -899,39 +899,41 @@ impl ControlMessageOwned { let n = len / mem::size_of::(); let mut fds = Vec::with_capacity(n); for i in 0..n { - let fdp = (p as *const RawFd).add(i); - fds.push(ptr::read_unaligned(fdp)); + unsafe { + let fdp = (p as *const RawFd).add(i); + fds.push(ptr::read_unaligned(fdp)); + } } ControlMessageOwned::ScmRights(fds) }, #[cfg(any(target_os = "android", target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_CREDENTIALS) => { - let cred: libc::ucred = ptr::read_unaligned(p as *const _); + let cred: libc::ucred = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmCredentials(cred.into()) } #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] (libc::SOL_SOCKET, libc::SCM_CREDS) => { - let cred: libc::cmsgcred = ptr::read_unaligned(p as *const _); + let cred: libc::cmsgcred = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmCreds(cred.into()) } #[cfg(not(any(target_os = "aix", target_os = "haiku")))] (libc::SOL_SOCKET, libc::SCM_TIMESTAMP) => { - let tv: libc::timeval = ptr::read_unaligned(p as *const _); + let tv: libc::timeval = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmTimestamp(TimeVal::from(tv)) }, #[cfg(any(target_os = "android", target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_TIMESTAMPNS) => { - let ts: libc::timespec = ptr::read_unaligned(p as *const _); + let ts: libc::timespec = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmTimestampns(TimeSpec::from(ts)) } #[cfg(any(target_os = "android", target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_TIMESTAMPING) => { let tp = p as *const libc::timespec; - let ts: libc::timespec = ptr::read_unaligned(tp); + let ts: libc::timespec = unsafe { ptr::read_unaligned(tp) }; let system = TimeSpec::from(ts); - let ts: libc::timespec = ptr::read_unaligned(tp.add(1)); + let ts: libc::timespec = unsafe { ptr::read_unaligned(tp.add(1)) }; let hw_trans = TimeSpec::from(ts); - let ts: libc::timespec = ptr::read_unaligned(tp.add(2)); + let ts: libc::timespec = unsafe { ptr::read_unaligned(tp.add(2)) }; let hw_raw = TimeSpec::from(ts); let timestamping = Timestamps { system, hw_trans, hw_raw }; ControlMessageOwned::ScmTimestampsns(timestamping) @@ -944,7 +946,7 @@ impl ControlMessageOwned { ))] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_PKTINFO) => { - let info = ptr::read_unaligned(p as *const libc::in6_pktinfo); + let info = unsafe { ptr::read_unaligned(p as *const libc::in6_pktinfo) }; ControlMessageOwned::Ipv6PacketInfo(info) } #[cfg(any( @@ -955,7 +957,7 @@ impl ControlMessageOwned { ))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_PKTINFO) => { - let info = ptr::read_unaligned(p as *const libc::in_pktinfo); + let info = unsafe { ptr::read_unaligned(p as *const libc::in_pktinfo) }; ControlMessageOwned::Ipv4PacketInfo(info) } #[cfg(any( @@ -966,7 +968,7 @@ impl ControlMessageOwned { ))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVIF) => { - let dl = ptr::read_unaligned(p as *const libc::sockaddr_dl); + let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_dl) }; ControlMessageOwned::Ipv4RecvIf(dl) }, #[cfg(any( @@ -977,51 +979,51 @@ impl ControlMessageOwned { ))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVDSTADDR) => { - let dl = ptr::read_unaligned(p as *const libc::in_addr); + let dl = unsafe { ptr::read_unaligned(p as *const libc::in_addr) }; ControlMessageOwned::Ipv4RecvDstAddr(dl) }, #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_ORIGDSTADDR) => { - let dl = ptr::read_unaligned(p as *const libc::sockaddr_in); + let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_in) }; ControlMessageOwned::Ipv4OrigDstAddr(dl) }, #[cfg(target_os = "linux")] #[cfg(feature = "net")] (libc::SOL_UDP, libc::UDP_GRO) => { - let gso_size: u16 = ptr::read_unaligned(p as *const _); + let gso_size: u16 = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::UdpGroSegments(gso_size) }, #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] (libc::SOL_SOCKET, libc::SO_RXQ_OVFL) => { - let drop_counter = ptr::read_unaligned(p as *const u32); + let drop_counter = unsafe { ptr::read_unaligned(p as *const u32) }; ControlMessageOwned::RxqOvfl(drop_counter) }, #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVERR) => { - let (err, addr) = Self::recv_err_helper::(p, len); + let (err, addr) = unsafe { Self::recv_err_helper::(p, len) }; ControlMessageOwned::Ipv4RecvErr(err, addr) }, #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_RECVERR) => { - let (err, addr) = Self::recv_err_helper::(p, len); + let (err, addr) = unsafe { Self::recv_err_helper::(p, len) }; ControlMessageOwned::Ipv6RecvErr(err, addr) }, #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_ORIGDSTADDR) => { - let dl = ptr::read_unaligned(p as *const libc::sockaddr_in6); + let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_in6) }; ControlMessageOwned::Ipv6OrigDstAddr(dl) }, #[cfg(any(target_os = "linux"))] (libc::SOL_TLS, libc::TLS_GET_RECORD_TYPE) => { - let content_type = ptr::read_unaligned(p as *const u8); + let content_type = unsafe { ptr::read_unaligned(p as *const u8) }; ControlMessageOwned::TlsGetRecordType(content_type.into()) }, (_, _) => { - let sl = std::slice::from_raw_parts(p, len); + let sl = unsafe { std::slice::from_raw_parts(p, len) }; let ucmsg = UnknownCmsg(*header, Vec::::from(sl)); ControlMessageOwned::Unknown(ucmsg) } @@ -1033,18 +1035,18 @@ impl ControlMessageOwned { #[allow(clippy::cast_ptr_alignment)] // False positive unsafe fn recv_err_helper(p: *mut libc::c_uchar, len: usize) -> (libc::sock_extended_err, Option) { let ee = p as *const libc::sock_extended_err; - let err = ptr::read_unaligned(ee); + let err = unsafe { ptr::read_unaligned(ee) }; // For errors originating on the network, SO_EE_OFFENDER(ee) points inside the p[..len] // CMSG_DATA buffer. For local errors, there is no address included in the control // message, and SO_EE_OFFENDER(ee) points beyond the end of the buffer. So, we need to // validate that the address object is in-bounds before we attempt to copy it. - let addrp = libc::SO_EE_OFFENDER(ee) as *const T; + let addrp = unsafe { libc::SO_EE_OFFENDER(ee) as *const T }; - if addrp.offset(1) as usize - (p as usize) > len { + if unsafe { addrp.offset(1) } as usize - (p as usize) > len { (err, None) } else { - (err, Some(ptr::read_unaligned(addrp))) + (err, Some(unsafe { ptr::read_unaligned(addrp) })) } } } @@ -1482,10 +1484,12 @@ impl<'a> ControlMessage<'a> { // Unsafe: cmsg must point to a valid cmsghdr with enough space to // encode self. unsafe fn encode_into(&self, cmsg: *mut cmsghdr) { - (*cmsg).cmsg_level = self.cmsg_level(); - (*cmsg).cmsg_type = self.cmsg_type(); - (*cmsg).cmsg_len = self.cmsg_len(); - self.copy_to_cmsg_data(CMSG_DATA(cmsg)); + unsafe { + (*cmsg).cmsg_level = self.cmsg_level(); + (*cmsg).cmsg_type = self.cmsg_type(); + (*cmsg).cmsg_len = self.cmsg_len(); + self.copy_to_cmsg_data( CMSG_DATA(cmsg) ); + } } } @@ -1993,19 +1997,23 @@ unsafe fn read_mhdr<'a, 'i, S>( // The cast is not unnecessary on all platforms. #[allow(clippy::unnecessary_cast)] let cmsghdr = { - if mhdr.msg_controllen > 0 { + let ptr = if mhdr.msg_controllen > 0 { debug_assert!(!mhdr.msg_control.is_null()); debug_assert!(msg_controllen >= mhdr.msg_controllen as usize); - CMSG_FIRSTHDR(&mhdr as *const msghdr) + unsafe { CMSG_FIRSTHDR(&mhdr as *const msghdr) } } else { ptr::null() - }.as_ref() + }; + + unsafe { + ptr.as_ref() + } }; // Ignore errors if this socket address has statically-known length // // This is to ensure that unix socket addresses have their length set appropriately. - let _ = address.set_length(mhdr.msg_namelen as usize); + let _ = unsafe { address.set_length(mhdr.msg_namelen as usize) }; RecvMsg { bytes: r as usize, @@ -2042,14 +2050,16 @@ unsafe fn pack_mhdr_to_receive( // initialize it. let mut mhdr = mem::MaybeUninit::::zeroed(); let p = mhdr.as_mut_ptr(); - (*p).msg_name = address as *mut c_void; - (*p).msg_namelen = S::size(); - (*p).msg_iov = iov_buffer as *mut iovec; - (*p).msg_iovlen = iov_buffer_len as _; - (*p).msg_control = cmsg_buffer as *mut c_void; - (*p).msg_controllen = cmsg_capacity as _; - (*p).msg_flags = 0; - mhdr.assume_init() + unsafe { + (*p).msg_name = address as *mut c_void; + (*p).msg_namelen = S::size(); + (*p).msg_iov = iov_buffer as *mut iovec; + (*p).msg_iovlen = iov_buffer_len as _; + (*p).msg_control = cmsg_buffer as *mut c_void; + (*p).msg_controllen = cmsg_capacity as _; + (*p).msg_flags = 0; + mhdr.assume_init() + } } fn pack_mhdr_to_send<'a, I, C, S>( diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 07a0ac4ed5..511babf8d8 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -1164,7 +1164,7 @@ impl Get for GetStruct { mem::size_of::(), "invalid getsockopt implementation" ); - self.val.assume_init() + unsafe { self.val.assume_init() } } } @@ -1215,7 +1215,7 @@ impl Get for GetBool { mem::size_of::(), "invalid getsockopt implementation" ); - self.val.assume_init() != 0 + unsafe { self.val.assume_init() != 0 } } } @@ -1268,7 +1268,7 @@ impl Get for GetU8 { mem::size_of::(), "invalid getsockopt implementation" ); - self.val.assume_init() + unsafe { self.val.assume_init() } } } @@ -1319,7 +1319,7 @@ impl Get for GetUsize { mem::size_of::(), "invalid getsockopt implementation" ); - self.val.assume_init() as usize + unsafe { self.val.assume_init() as usize } } } @@ -1366,7 +1366,7 @@ impl> Get for GetOsString { unsafe fn assume_init(self) -> OsString { let len = self.len as usize; - let mut v = self.val.assume_init(); + let mut v = unsafe { self.val.assume_init() }; OsStr::from_bytes(&v.as_mut()[0..len]).to_owned() } } diff --git a/src/sys/timerfd.rs b/src/sys/timerfd.rs index c4337c9dfa..68b06d6322 100644 --- a/src/sys/timerfd.rs +++ b/src/sys/timerfd.rs @@ -53,7 +53,7 @@ impl AsFd for TimerFd { impl FromRawFd for TimerFd { unsafe fn from_raw_fd(fd: RawFd) -> Self { TimerFd { - fd: OwnedFd::from_raw_fd(fd), + fd: unsafe { OwnedFd::from_raw_fd(fd) }, } } } diff --git a/src/sys/wait.rs b/src/sys/wait.rs index c97dc45539..65940713c3 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -248,7 +248,7 @@ impl WaitStatus { all(target_os = "linux", not(target_env = "uclibc")), ))] unsafe fn from_siginfo(siginfo: &libc::siginfo_t) -> Result { - let si_pid = siginfo.si_pid(); + let si_pid = unsafe { siginfo.si_pid() }; if si_pid == 0 { return Ok(WaitStatus::StillAlive); } @@ -256,7 +256,7 @@ impl WaitStatus { assert_eq!(siginfo.si_signo, libc::SIGCHLD); let pid = Pid::from_raw(si_pid); - let si_status = siginfo.si_status(); + let si_status = unsafe { siginfo.si_status() }; let status = match siginfo.si_code { libc::CLD_EXITED => WaitStatus::Exited(pid, si_status), diff --git a/src/unistd.rs b/src/unistd.rs index b3db3cfb83..1148eeb977 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -293,7 +293,7 @@ impl ForkResult { #[inline] pub unsafe fn fork() -> Result { use self::ForkResult::*; - let res = libc::fork(); + let res = unsafe { libc::fork() }; Errno::result(res).map(|res| match res { 0 => Child, @@ -3508,7 +3508,7 @@ impl User { } else { // SAFETY: `f` guarantees that `pwd` is initialized if `res` // is not null. - let pwd = pwd.assume_init(); + let pwd = unsafe { pwd.assume_init() }; return Ok(Some(User::from(&pwd))); } } else if Errno::last() == Errno::ERANGE { @@ -3618,11 +3618,11 @@ impl Group { let mut ret = Vec::new(); for i in 0.. { - let u = mem.offset(i); - if (*u).is_null() { + let u = unsafe { mem.offset(i) }; + if unsafe { (*u).is_null() } { break; } else { - let s = CStr::from_ptr(*u).to_string_lossy().into_owned(); + let s = unsafe {CStr::from_ptr(*u).to_string_lossy().into_owned()}; ret.push(s); } } @@ -3667,7 +3667,7 @@ impl Group { } else { // SAFETY: `f` guarantees that `grp` is initialized if `res` // is not null. - let grp = grp.assume_init(); + let grp = unsafe { grp.assume_init() }; return Ok(Some(Group::from(&grp))); } } else if Errno::last() == Errno::ERANGE { From dbdcfed86e18673c71b54d4c4cd7be289441843c Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Sun, 19 Nov 2023 22:18:35 +0000 Subject: [PATCH 042/140] termios: enabling supported SpecialCharacterIndices on haiku. (#2195) * termios: enabling supported SpecialCharacterIndices on haiku. * changelog entry --- changelog/2195.added.md | 1 + src/sys/termios.rs | 12 +++++++----- 2 files changed, 8 insertions(+), 5 deletions(-) create mode 100644 changelog/2195.added.md diff --git a/changelog/2195.added.md b/changelog/2195.added.md new file mode 100644 index 0000000000..c523f22fd1 --- /dev/null +++ b/changelog/2195.added.md @@ -0,0 +1 @@ +Added `SpecialCharacterindices` support for haiku. diff --git a/src/sys/termios.rs b/src/sys/termios.rs index fa27801bac..6620cd6a14 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -512,13 +512,12 @@ libc_enum! { } // TODO: Make this usable directly as a slice index. -#[cfg(not(target_os = "haiku"))] libc_enum! { /// Indices into the `termios.c_cc` array for special characters. #[repr(usize)] #[non_exhaustive] pub enum SpecialCharacterIndices { - #[cfg(not(target_os = "aix"))] + #[cfg(not(any(target_os = "aix", target_os = "haiku")))] VDISCARD, #[cfg(any(target_os = "dragonfly", target_os = "freebsd", @@ -540,11 +539,13 @@ libc_enum! { VERASE2, VINTR, VKILL, + #[cfg(not(target_os = "haiku"))] VLNEXT, #[cfg(not(any(all(target_os = "linux", target_arch = "sparc64"), - target_os = "illumos", target_os = "solaris", target_os = "aix")))] + target_os = "illumos", target_os = "solaris", target_os = "aix", target_os = "haiku")))] VMIN, VQUIT, + #[cfg(not(target_os = "haiku"))] VREPRINT, VSTART, #[cfg(any(target_os = "dragonfly", @@ -562,9 +563,9 @@ libc_enum! { #[cfg(any(target_os = "haiku", target_os = "illumos", target_os = "solaris"))] VSWTCH, #[cfg(not(any(all(target_os = "linux", target_arch = "sparc64"), - target_os = "illumos", target_os = "solaris", target_os = "aix")))] + target_os = "illumos", target_os = "solaris", target_os = "aix", target_os = "haiku")))] VTIME, - #[cfg(not(target_os = "aix"))] + #[cfg(not(any(target_os = "aix", target_os = "haiku")))] VWERASE, #[cfg(target_os = "dragonfly")] VCHECKPT, @@ -576,6 +577,7 @@ libc_enum! { target_os = "illumos", target_os = "solaris", target_os = "aix", + target_os = "haiku", ))] impl SpecialCharacterIndices { pub const VMIN: SpecialCharacterIndices = SpecialCharacterIndices::VEOF; From a96a31ee33ea53d9e0cdebac67fb802b1fe41c44 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Wed, 22 Nov 2023 17:45:28 -0700 Subject: [PATCH 043/140] Temporarily disable armv7-unknown-linux-uclibceabihf in CI (#2201) Issue #2200 --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e07d2572ff..9338285e94 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -267,7 +267,9 @@ jobs: include: - target: x86_64-unknown-dragonfly - target: x86_64-unknown-openbsd - - target: armv7-unknown-linux-uclibceabihf + # Temporarily disable armv7-unknown-linux-uclibceabihf + # https://github.com/nix-rust/nix/issues/2200 + #- target: armv7-unknown-linux-uclibceabihf - target: x86_64-unknown-haiku steps: - name: checkout From a0018694c0226c0f3fbb3f5fa9268a54feca42b2 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Thu, 23 Nov 2023 01:04:50 +0000 Subject: [PATCH 044/140] sys::sendfile enable it on solaris based systems (#2198) * sys::sendfile enable it on solaris based systems * changelog entry --- changelog/2198.added.md | 1 + src/sys/mod.rs | 2 ++ src/sys/sendfile.rs | 5 +++-- 3 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 changelog/2198.added.md diff --git a/changelog/2198.added.md b/changelog/2198.added.md new file mode 100644 index 0000000000..93d3c50c52 --- /dev/null +++ b/changelog/2198.added.md @@ -0,0 +1 @@ +Added `sys::sendfile` support for solaris/illumos. diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 276d4760fd..122bc44b7f 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -124,6 +124,8 @@ feature! { target_os = "freebsd", apple_targets, target_os = "linux", + target_os = "solaris", + target_os = "illumos", ))] feature! { #![feature = "zerocopy"] diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 0959db73fd..6e2e0ace90 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -20,8 +20,9 @@ use crate::Result; /// /// `in_fd` must support `mmap`-like operations and therefore cannot be a socket. /// -/// For more information, see [the sendfile(2) man page.](https://man7.org/linux/man-pages/man2/sendfile.2.html) -#[cfg(any(target_os = "android", target_os = "linux"))] +/// For more information, see [the sendfile(2) man page.](https://man7.org/linux/man-pages/man2/sendfile.2.html) for Linux, +/// see [the sendfile(2) man page.](https://docs.oracle.com/cd/E88353_01/html/E37843/sendfile-3c.html) for Solaris. +#[cfg(any(target_os = "android", target_os = "linux", target_os = "solaris", target_os = "illumos"))] pub fn sendfile( out_fd: F1, in_fd: F2, From 7e16e32c935adb294ef6edc40b4ac52456d8a88e Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Thu, 23 Nov 2023 01:15:30 +0000 Subject: [PATCH 045/140] feat: Safer poll timeout (#1876) --- changelog/1876.changed.md | 1 + src/poll.rs | 248 ++++++++++++++++++++++++++++++++++++-- test/test_poll.rs | 6 +- 3 files changed, 243 insertions(+), 12 deletions(-) create mode 100644 changelog/1876.changed.md diff --git a/changelog/1876.changed.md b/changelog/1876.changed.md new file mode 100644 index 0000000000..858f228396 --- /dev/null +++ b/changelog/1876.changed.md @@ -0,0 +1 @@ +`poll` now takes `PollTimeout` replacing `libc::c_int`. \ No newline at end of file diff --git a/src/poll.rs b/src/poll.rs index 9462691aa0..4bc1a4b392 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -1,9 +1,9 @@ //! Wait for events to trigger on specific file descriptors use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd}; +use std::time::Duration; use crate::errno::Errno; use crate::Result; - /// This is a wrapper around `libc::pollfd`. /// /// It's meant to be used as an argument to the [`poll`](fn.poll.html) and @@ -27,13 +27,13 @@ impl<'fd> PollFd<'fd> { /// ```no_run /// # use std::os::unix::io::{AsFd, AsRawFd, FromRawFd}; /// # use nix::{ - /// # poll::{PollFd, PollFlags, poll}, + /// # poll::{PollTimeout, PollFd, PollFlags, poll}, /// # unistd::{pipe, read} /// # }; /// let (r, w) = pipe().unwrap(); /// let pfd = PollFd::new(r.as_fd(), PollFlags::POLLIN); /// let mut fds = [pfd]; - /// poll(&mut fds, -1).unwrap(); + /// poll(&mut fds, PollTimeout::NONE).unwrap(); /// let mut buf = [0u8; 80]; /// read(r.as_raw_fd(), &mut buf[..]); /// ``` @@ -175,6 +175,229 @@ libc_bitflags! { } } +/// Timeout argument for [`poll`]. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub struct PollTimeout(i32); + +impl PollTimeout { + /// Blocks indefinitely. + /// + /// > Specifying a negative value in timeout means an infinite timeout. + pub const NONE: Self = Self(-1); + /// Returns immediately. + /// + /// > Specifying a timeout of zero causes poll() to return immediately, even if no file + /// > descriptors are ready. + pub const ZERO: Self = Self(0); + /// Blocks for at most [`std::i32::MAX`] milliseconds. + pub const MAX: Self = Self(i32::MAX); + /// Returns if `self` equals [`PollTimeout::NONE`]. + pub fn is_none(&self) -> bool { + // > Specifying a negative value in timeout means an infinite timeout. + *self <= Self::NONE + } + /// Returns if `self` does not equal [`PollTimeout::NONE`]. + pub fn is_some(&self) -> bool { + !self.is_none() + } + /// Returns the timeout in milliseconds if there is some, otherwise returns `None`. + pub fn as_millis(&self) -> Option { + self.is_some().then_some(u32::try_from(self.0).unwrap()) + } + /// Returns the timeout as a `Duration` if there is some, otherwise returns `None`. + pub fn timeout(&self) -> Option { + self.as_millis() + .map(|x| Duration::from_millis(u64::from(x))) + } +} + +/// Error type for integer conversions into `PollTimeout`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PollTimeoutTryFromError { + /// Passing a value less than -1 is invalid on some systems, see + /// . + TooNegative, + /// Passing a value greater than `i32::MAX` is invalid. + TooPositive, +} + +impl std::fmt::Display for PollTimeoutTryFromError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooNegative => write!(f, "Passed a negative timeout less than -1."), + Self::TooPositive => write!(f, "Passed a positive timeout greater than `i32::MAX` milliseconds.") + } + } +} + +impl std::error::Error for PollTimeoutTryFromError {} + +impl> From> for PollTimeout { + fn from(x: Option) -> Self { + x.map_or(Self::NONE, |x| x.into()) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: Duration) -> std::result::Result { + Ok(Self( + i32::try_from(x.as_millis()) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: u128) -> std::result::Result { + Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: u64) -> std::result::Result { + Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: u32) -> std::result::Result { + Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl From for PollTimeout { + fn from(x: u16) -> Self { + Self(i32::from(x)) + } +} +impl From for PollTimeout { + fn from(x: u8) -> Self { + Self(i32::from(x)) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i128) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i64) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i32) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self(x)), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i16) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self(i32::from(x))), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i8) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self(i32::from(x))), + } + } +} +impl TryFrom for Duration { + type Error = (); + fn try_from(x: PollTimeout) -> std::result::Result { + x.timeout().ok_or(()) + } +} +impl TryFrom for u128 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u64 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u32 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u16 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u8 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl From for i128 { + fn from(x: PollTimeout) -> Self { + Self::from(x.0) + } +} +impl From for i64 { + fn from(x: PollTimeout) -> Self { + Self::from(x.0) + } +} +impl From for i32 { + fn from(x: PollTimeout) -> Self { + x.0 + } +} +impl TryFrom for i16 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for i8 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} + /// `poll` waits for one of a set of file descriptors to become ready to perform I/O. /// ([`poll(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html)) /// @@ -191,13 +414,20 @@ libc_bitflags! { /// /// Note that the timeout interval will be rounded up to the system clock /// granularity, and kernel scheduling delays mean that the blocking -/// interval may overrun by a small amount. Specifying a negative value -/// in timeout means an infinite timeout. Specifying a timeout of zero -/// causes `poll()` to return immediately, even if no file descriptors are -/// ready. -pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result { +/// interval may overrun by a small amount. Specifying a [`PollTimeout::NONE`] +/// in timeout means an infinite timeout. Specifying a timeout of +/// [`PollTimeout::ZERO`] causes `poll()` to return immediately, even if no file +/// descriptors are ready. +pub fn poll>( + fds: &mut [PollFd], + timeout: T, +) -> Result { let res = unsafe { - libc::poll(fds.as_mut_ptr().cast(), fds.len() as libc::nfds_t, timeout) + libc::poll( + fds.as_mut_ptr().cast(), + fds.len() as libc::nfds_t, + i32::from(timeout.into()), + ) }; Errno::result(res) diff --git a/test/test_poll.rs b/test/test_poll.rs index fb4291721d..4227f59994 100644 --- a/test/test_poll.rs +++ b/test/test_poll.rs @@ -1,6 +1,6 @@ use nix::{ errno::Errno, - poll::{poll, PollFd, PollFlags}, + poll::{poll, PollFd, PollFlags, PollTimeout}, unistd::{pipe, write}, }; use std::os::unix::io::{AsFd, BorrowedFd}; @@ -23,14 +23,14 @@ fn test_poll() { let mut fds = [PollFd::new(r.as_fd(), PollFlags::POLLIN)]; // Poll an idle pipe. Should timeout - let nfds = loop_while_eintr!(poll(&mut fds, 100)); + let nfds = loop_while_eintr!(poll(&mut fds, PollTimeout::from(100u8))); assert_eq!(nfds, 0); assert!(!fds[0].revents().unwrap().contains(PollFlags::POLLIN)); write(&w, b".").unwrap(); // Poll a readable pipe. Should return an event. - let nfds = poll(&mut fds, 100).unwrap(); + let nfds = poll(&mut fds, PollTimeout::from(100u8)).unwrap(); assert_eq!(nfds, 1); assert!(fds[0].revents().unwrap().contains(PollFlags::POLLIN)); } From 755c66d27518a5dcdb708a00a9af473a5215c971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Deharbe?= Date: Thu, 23 Nov 2023 03:49:57 +0100 Subject: [PATCH 046/140] Add fanotify API wrappers (#2194) * Add fanotify API wrappers * Review/fix enum comments * Rename has_compile_version to check_version * Fix lint unsafe_block_in_unsafe_fn * Rename fanotify OFlags to EventFFlags * Use existing function at_rawfd from fcntl * Add missing feature guard for docs * Change FanotifyEvent struct to a simple wrapper over libc structure * Change FanotifyResponse struct to a simple wrapper over libc structure * Cast pointer with function 'cast' instead of 'as' * Add FAN_REPORT_PIDFD and FAN_REPORT_TID fanotify init flags --- Cargo.toml | 1 + changelog/2194.added.md | 1 + src/fcntl.rs | 11 +- src/lib.rs | 2 + src/sys/fanotify.rs | 412 ++++++++++++++++++++++++++++++++++++++ src/sys/mod.rs | 6 + test/sys/mod.rs | 2 + test/sys/test_fanotify.rs | 154 ++++++++++++++ 8 files changed, 586 insertions(+), 3 deletions(-) create mode 100644 changelog/2194.added.md create mode 100644 src/sys/fanotify.rs create mode 100644 test/sys/test_fanotify.rs diff --git a/Cargo.toml b/Cargo.toml index dbcb99e277..aa365449e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ aio = ["pin-utils"] dir = ["fs"] env = [] event = [] +fanotify = [] feature = [] fs = [] hostname = [] diff --git a/changelog/2194.added.md b/changelog/2194.added.md new file mode 100644 index 0000000000..18e39b1ccd --- /dev/null +++ b/changelog/2194.added.md @@ -0,0 +1 @@ +Added new fanotify API: wrappers for `fanotify_init` and `fanotify_mark` diff --git a/src/fcntl.rs b/src/fcntl.rs index 7910cc9b7d..d327c4b22a 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -64,10 +64,14 @@ libc_bitflags! { } } -#[cfg(any(feature = "fs", feature = "term"))] +#[cfg(any( + feature = "fs", + feature = "term", + all(feature = "fanotify", target_os = "linux") +))] libc_bitflags!( /// Configuration options for opened files. - #[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "term"))))] + #[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "term", all(feature = "fanotify", target_os = "linux")))))] pub struct OFlag: c_int { /// Mask for the access mode of the file. O_ACCMODE; @@ -194,7 +198,8 @@ libc_bitflags!( /// Computes the raw fd consumed by a function of the form `*at`. #[cfg(any( all(feature = "fs", not(target_os = "redox")), - all(feature = "process", any(target_os = "android", target_os = "linux")) + all(feature = "process", any(target_os = "android", target_os = "linux")), + all(feature = "fanotify", target_os = "linux") ))] pub(crate) fn at_rawfd(fd: Option) -> raw::c_int { fd.unwrap_or(libc::AT_FDCWD) diff --git a/src/lib.rs b/src/lib.rs index 467b839d56..62220a822f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ //! * `dir` - Stuff relating to directory iteration //! * `env` - Manipulate environment variables //! * `event` - Event-driven APIs, like `kqueue` and `epoll` +//! * `fanotify` - Linux's `fanotify` filesystem events monitoring API //! * `feature` - Query characteristics of the OS at runtime //! * `fs` - File system functionality //! * `hostname` - Get and set the system's hostname @@ -53,6 +54,7 @@ feature = "dir", feature = "env", feature = "event", + feature = "fanotify", feature = "feature", feature = "fs", feature = "hostname", diff --git a/src/sys/fanotify.rs b/src/sys/fanotify.rs new file mode 100644 index 0000000000..a089d78df8 --- /dev/null +++ b/src/sys/fanotify.rs @@ -0,0 +1,412 @@ +//! Monitoring API for filesystem events. +//! +//! Fanotify is a Linux-only API to monitor filesystems events. +//! +//! Additional capabilities compared to the `inotify` API include the ability to +//! monitor all of the objects in a mounted filesystem, the ability to make +//! access permission decisions, and the possibility to read or modify files +//! before access by other applications. +//! +//! For more documentation, please read +//! [fanotify(7)](https://man7.org/linux/man-pages/man7/fanotify.7.html). + +use crate::{NixPath, Result}; +use crate::errno::Errno; +use crate::fcntl::{OFlag, at_rawfd}; +use crate::unistd::{close, read, write}; +use std::marker::PhantomData; +use std::mem::{MaybeUninit, size_of}; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd}; +use std::ptr; + +libc_bitflags! { + /// Mask for defining which events shall be listened with + /// [`fanotify_mark`](fn.fanotify_mark.html) and for querying notifications. + pub struct MaskFlags: u64 { + /// File was accessed. + FAN_ACCESS; + /// File was modified. + FAN_MODIFY; + /// Metadata has changed. Since Linux 5.1. + FAN_ATTRIB; + /// Writtable file was closed. + FAN_CLOSE_WRITE; + /// Unwrittable file was closed. + FAN_CLOSE_NOWRITE; + /// File was opened. + FAN_OPEN; + /// File was moved from X. Since Linux 5.1. + FAN_MOVED_FROM; + /// File was moved to Y. Since Linux 5.1. + FAN_MOVED_TO; + /// Subfile was created. Since Linux 5.1. + FAN_CREATE; + /// Subfile was deleted. Since Linux 5.1. + FAN_DELETE; + /// Self was deleted. Since Linux 5.1. + FAN_DELETE_SELF; + /// Self was moved. Since Linux 5.1. + FAN_MOVE_SELF; + /// File was opened for execution. Since Linux 5.0. + FAN_OPEN_EXEC; + + /// Event queue overflowed. + FAN_Q_OVERFLOW; + /// Filesystem error. Since Linux 5.16. + FAN_FS_ERROR; + + /// Permission to open file was requested. + FAN_OPEN_PERM; + /// Permission to access file was requested. + FAN_ACCESS_PERM; + /// Permission to open file for execution was requested. Since Linux + /// 5.0. + FAN_OPEN_EXEC_PERM; + + /// Interested in child events. + FAN_EVENT_ON_CHILD; + + /// File was renamed. Since Linux 5.17. + FAN_RENAME; + + /// Event occurred against dir. + FAN_ONDIR; + + /// Combination of `FAN_CLOSE_WRITE` and `FAN_CLOSE_NOWRITE`. + FAN_CLOSE; + /// Combination of `FAN_MOVED_FROM` and `FAN_MOVED_TO`. + FAN_MOVE; + } +} + +libc_bitflags! { + /// Configuration options for [`fanotify_init`](fn.fanotify_init.html). + pub struct InitFlags: libc::c_uint { + /// Close-on-exec flag set on the file descriptor. + FAN_CLOEXEC; + /// Nonblocking flag set on the file descriptor. + FAN_NONBLOCK; + + /// Receipt of events notifications. + FAN_CLASS_NOTIF; + /// Receipt of events for permission decisions, after they contain final + /// data. + FAN_CLASS_CONTENT; + /// Receipt of events for permission decisions, before they contain + /// final data. + FAN_CLASS_PRE_CONTENT; + + /// Remove the limit of 16384 events for the event queue. + FAN_UNLIMITED_QUEUE; + /// Remove the limit of 8192 marks. + FAN_UNLIMITED_MARKS; + + /// Make `FanotifyEvent::pid` return pidfd. Since Linux 5.15. + FAN_REPORT_PIDFD; + /// Make `FanotifyEvent::pid` return thread id. Since Linux 4.20. + FAN_REPORT_TID; + } +} + +libc_bitflags! { + /// File status flags for fanotify events file descriptors. + pub struct EventFFlags: libc::c_uint { + /// Read only access. + O_RDONLY as libc::c_uint; + /// Write only access. + O_WRONLY as libc::c_uint; + /// Read and write access. + O_RDWR as libc::c_uint; + /// Support for files exceeded 2 GB. + O_LARGEFILE as libc::c_uint; + /// Close-on-exec flag for the file descriptor. Since Linux 3.18. + O_CLOEXEC as libc::c_uint; + /// Append mode for the file descriptor. + O_APPEND as libc::c_uint; + /// Synchronized I/O data integrity completion. + O_DSYNC as libc::c_uint; + /// No file last access time update. + O_NOATIME as libc::c_uint; + /// Nonblocking mode for the file descriptor. + O_NONBLOCK as libc::c_uint; + /// Synchronized I/O file integrity completion. + O_SYNC as libc::c_uint; + } +} + +impl TryFrom for EventFFlags { + type Error = Errno; + + fn try_from(o_flag: OFlag) -> Result { + EventFFlags::from_bits(o_flag.bits() as u32).ok_or(Errno::EINVAL) + } +} + +impl From for OFlag { + fn from(event_f_flags: EventFFlags) -> Self { + OFlag::from_bits_retain(event_f_flags.bits() as i32) + } +} + +libc_bitflags! { + /// Configuration options for [`fanotify_mark`](fn.fanotify_mark.html). + pub struct MarkFlags: libc::c_uint { + /// Add the events to the marks. + FAN_MARK_ADD; + /// Remove the events to the marks. + FAN_MARK_REMOVE; + /// Don't follow symlinks, mark them. + FAN_MARK_DONT_FOLLOW; + /// Raise an error if filesystem to be marked is not a directory. + FAN_MARK_ONLYDIR; + /// Events added to or removed from the marks. + FAN_MARK_IGNORED_MASK; + /// Ignore mask shall survive modify events. + FAN_MARK_IGNORED_SURV_MODIFY; + /// Remove all marks. + FAN_MARK_FLUSH; + /// Do not pin inode object in the inode cache. Since Linux 5.19. + FAN_MARK_EVICTABLE; + /// Events added to or removed from the marks. Since Linux 6.0. + FAN_MARK_IGNORE; + + /// Default flag. + FAN_MARK_INODE; + /// Mark the mount specified by pathname. + FAN_MARK_MOUNT; + /// Mark the filesystem specified by pathname. Since Linux 4.20. + FAN_MARK_FILESYSTEM; + + /// Combination of `FAN_MARK_IGNORE` and `FAN_MARK_IGNORED_SURV_MODIFY`. + FAN_MARK_IGNORE_SURV; + } +} + +/// Compile version number of fanotify API. +pub const FANOTIFY_METADATA_VERSION: u8 = libc::FANOTIFY_METADATA_VERSION; + +/// Abstract over `libc::fanotify_event_metadata`, which represents an event +/// received via `Fanotify::read_events`. +// Is not Clone due to fd field, to avoid use-after-close scenarios. +#[derive(Debug, Eq, Hash, PartialEq)] +#[repr(transparent)] +#[allow(missing_copy_implementations)] +pub struct FanotifyEvent(libc::fanotify_event_metadata); + +impl FanotifyEvent { + /// Version number for the structure. It must be compared to + /// `FANOTIFY_METADATA_VERSION` to verify compile version and runtime + /// version does match. It can be done with the + /// `FanotifyEvent::check_version` method. + pub fn version(&self) -> u8 { + self.0.vers + } + + /// Checks that compile fanotify API version is equal to the version of the + /// event. + pub fn check_version(&self) -> bool { + self.version() == FANOTIFY_METADATA_VERSION + } + + /// Mask flags of the events. + pub fn mask(&self) -> MaskFlags { + MaskFlags::from_bits_truncate(self.0.mask) + } + + /// The file descriptor of the event. If the value is `None` when reading + /// from the fanotify group, this event is to notify that a group queue + /// overflow occured. + pub fn fd(&self) -> Option { + if self.0.fd == libc::FAN_NOFD { + None + } else { + // SAFETY: self.0.fd will be opened for the lifetime of `Self`, + // which is longer than the lifetime of the returned BorrowedFd, so + // it is safe. + Some(unsafe { BorrowedFd::borrow_raw(self.0.fd) }) + } + } + + /// PID of the process that caused the event. TID in case flag + /// `FAN_REPORT_TID` was set at group initialization. + pub fn pid(&self) -> i32 { + self.0.pid + } +} + +impl Drop for FanotifyEvent { + fn drop(&mut self) { + let e = close(self.0.fd); + if !std::thread::panicking() && e == Err(Errno::EBADF) { + panic!("Closing an invalid file descriptor!"); + }; + } +} + +/// Abstraction over the structure to be sent to allow or deny a given event. +#[derive(Debug)] +#[repr(transparent)] +pub struct FanotifyResponse<'a> { + inner: libc::fanotify_response, + _borrowed_fd: PhantomData>, +} + +impl<'a> FanotifyResponse<'a> { + /// Create a new response. + pub fn new(fd: BorrowedFd<'a>, response: Response) -> Self { + Self { + inner: libc::fanotify_response { + fd: fd.as_raw_fd(), + response: response.bits(), + }, + _borrowed_fd: PhantomData, + } + } +} + +libc_bitflags! { + /// Response to be wrapped in `FanotifyResponse` and sent to the `Fanotify` + /// group to allow or deny an event. + pub struct Response: u32 { + /// Allow the event. + FAN_ALLOW; + /// Deny the event. + FAN_DENY; + } +} + +/// A fanotify group. This is also a file descriptor that can feed to other +/// interfaces consuming file descriptors. +#[derive(Debug)] +pub struct Fanotify { + fd: OwnedFd, +} + +impl Fanotify { + /// Initialize a new fanotify group. + /// + /// Returns a Result containing a Fanotify instance. + /// + /// For more information, see [fanotify_init(2)](https://man7.org/linux/man-pages/man7/fanotify_init.2.html). + pub fn init(flags: InitFlags, event_f_flags: EventFFlags) -> Result { + let res = Errno::result(unsafe { + libc::fanotify_init(flags.bits(), event_f_flags.bits()) + }); + res.map(|fd| Fanotify { fd: unsafe { OwnedFd::from_raw_fd(fd) }}) + } + + /// Add, remove, or modify an fanotify mark on a filesystem object. + /// If `dirfd` is `None`, `AT_FDCWD` is used. + /// + /// Returns a Result containing either `()` on success or errno otherwise. + /// + /// For more information, see [fanotify_mark(2)](https://man7.org/linux/man-pages/man7/fanotify_mark.2.html). + pub fn mark( + &self, + flags: MarkFlags, + mask: MaskFlags, + dirfd: Option, + path: Option<&P>, + ) -> Result<()> { + fn with_opt_nix_path(p: Option<&P>, f: F) -> Result + where + P: ?Sized + NixPath, + F: FnOnce(*const libc::c_char) -> T, + { + match p { + Some(path) => path.with_nix_path(|p_str| f(p_str.as_ptr())), + None => Ok(f(std::ptr::null())), + } + } + + let res = with_opt_nix_path(path, |p| unsafe { + libc::fanotify_mark( + self.fd.as_raw_fd(), + flags.bits(), + mask.bits(), + at_rawfd(dirfd), + p, + ) + })?; + + Errno::result(res).map(|_| ()) + } + + /// Read incoming events from the fanotify group. + /// + /// Returns a Result containing either a `Vec` of events on success or errno + /// otherwise. + /// + /// # Errors + /// + /// Possible errors can be those that are explicitly listed in + /// [fanotify(2)](https://man7.org/linux/man-pages/man7/fanotify.2.html) in + /// addition to the possible errors caused by `read` call. + /// In particular, `EAGAIN` is returned when no event is available on a + /// group that has been initialized with the flag `InitFlags::FAN_NONBLOCK`, + /// thus making this method nonblocking. + pub fn read_events(&self) -> Result> { + let metadata_size = size_of::(); + const BUFSIZ: usize = 4096; + let mut buffer = [0u8; BUFSIZ]; + let mut events = Vec::new(); + let mut offset = 0; + + let nread = read(self.fd.as_raw_fd(), &mut buffer)?; + + while (nread - offset) >= metadata_size { + let metadata = unsafe { + let mut metadata = + MaybeUninit::::uninit(); + ptr::copy_nonoverlapping( + buffer.as_ptr().add(offset), + metadata.as_mut_ptr().cast(), + (BUFSIZ - offset).min(metadata_size), + ); + metadata.assume_init() + }; + + events.push(FanotifyEvent(metadata)); + offset += metadata.event_len as usize; + } + + Ok(events) + } + + /// Write an event response on the fanotify group. + /// + /// Returns a Result containing either `()` on success or errno otherwise. + /// + /// # Errors + /// + /// Possible errors can be those that are explicitly listed in + /// [fanotify(2)](https://man7.org/linux/man-pages/man7/fanotify.2.html) in + /// addition to the possible errors caused by `write` call. + /// In particular, `EAGAIN` or `EWOULDBLOCK` is returned when no event is + /// available on a group that has been initialized with the flag + /// `InitFlags::FAN_NONBLOCK`, thus making this method nonblocking. + pub fn write_response(&self, response: FanotifyResponse) -> Result<()> { + write( + self.fd.as_fd(), + unsafe { + std::slice::from_raw_parts( + (&response.inner as *const libc::fanotify_response).cast(), + size_of::(), + ) + }, + )?; + Ok(()) + } +} + +impl FromRawFd for Fanotify { + unsafe fn from_raw_fd(fd: RawFd) -> Self { + Fanotify { fd: unsafe { OwnedFd::from_raw_fd(fd) }} + } +} + +impl AsFd for Fanotify { + fn as_fd(&'_ self) -> BorrowedFd<'_> { + self.fd.as_fd() + } +} diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 122bc44b7f..7157f3a79a 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -30,6 +30,12 @@ feature! { pub mod eventfd; } +#[cfg(target_os = "linux")] +feature! { + #![feature = "fanotify"] + pub mod fanotify; +} + #[cfg(any( target_os = "android", target_os = "dragonfly", diff --git a/test/sys/mod.rs b/test/sys/mod.rs index ae4ff953fe..43bb0bfaae 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -43,6 +43,8 @@ mod test_wait; #[cfg(any(target_os = "android", target_os = "linux"))] mod test_epoll; #[cfg(target_os = "linux")] +mod test_fanotify; +#[cfg(target_os = "linux")] mod test_inotify; mod test_pthread; #[cfg(any( diff --git a/test/sys/test_fanotify.rs b/test/sys/test_fanotify.rs new file mode 100644 index 0000000000..9fd23395ae --- /dev/null +++ b/test/sys/test_fanotify.rs @@ -0,0 +1,154 @@ +use crate::*; +use nix::sys::fanotify::{ + EventFFlags, Fanotify, FanotifyResponse, InitFlags, MarkFlags, MaskFlags, + Response, +}; +use std::fs::{read_link, File, OpenOptions}; +use std::io::ErrorKind; +use std::io::{Read, Write}; +use std::os::fd::AsRawFd; +use std::thread; + +#[test] +/// Run fanotify tests sequentially to avoid tmp files races +pub fn test_fanotify() { + require_capability!("test_fanotify", CAP_SYS_ADMIN); + + test_fanotify_notifications(); + test_fanotify_responses(); +} + +fn test_fanotify_notifications() { + let group = + Fanotify::init(InitFlags::FAN_CLASS_NOTIF, EventFFlags::O_RDONLY) + .unwrap(); + let tempdir = tempfile::tempdir().unwrap(); + + group + .mark( + MarkFlags::FAN_MARK_ADD | MarkFlags::FAN_MARK_MOUNT, + MaskFlags::FAN_OPEN | MaskFlags::FAN_MODIFY | MaskFlags::FAN_CLOSE, + None, + Some(tempdir.path()), + ) + .unwrap(); + + let tempfile = tempdir.path().join("test"); + + // create test file + File::create(&tempfile).unwrap(); + + let [event] = &group.read_events().unwrap()[..] else { + panic!("should have read exactly one event"); + }; + assert!(event.check_version()); + assert_eq!( + event.mask(), + MaskFlags::FAN_OPEN | MaskFlags::FAN_CLOSE_WRITE + ); + let fd_opt = event.fd(); + let fd = fd_opt.as_ref().unwrap(); + let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); + assert_eq!(path, tempfile); + + // modify test file + { + let mut f = OpenOptions::new().write(true).open(&tempfile).unwrap(); + f.write_all(b"hello").unwrap(); + } + + let [event] = &group.read_events().unwrap()[..] else { + panic!("should have read exactly one event"); + }; + assert!(event.check_version()); + assert_eq!( + event.mask(), + MaskFlags::FAN_OPEN + | MaskFlags::FAN_MODIFY + | MaskFlags::FAN_CLOSE_WRITE + ); + let fd_opt = event.fd(); + let fd = fd_opt.as_ref().unwrap(); + let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); + assert_eq!(path, tempfile); + + // read test file + { + let mut f = File::open(&tempfile).unwrap(); + let mut s = String::new(); + f.read_to_string(&mut s).unwrap(); + } + + let [event] = &group.read_events().unwrap()[..] else { + panic!("should have read exactly one event"); + }; + assert!(event.check_version()); + assert_eq!( + event.mask(), + MaskFlags::FAN_OPEN | MaskFlags::FAN_CLOSE_NOWRITE + ); + let fd_opt = event.fd(); + let fd = fd_opt.as_ref().unwrap(); + let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); + assert_eq!(path, tempfile); +} + +fn test_fanotify_responses() { + let group = + Fanotify::init(InitFlags::FAN_CLASS_CONTENT, EventFFlags::O_RDONLY) + .unwrap(); + let tempdir = tempfile::tempdir().unwrap(); + + group + .mark( + MarkFlags::FAN_MARK_ADD | MarkFlags::FAN_MARK_MOUNT, + MaskFlags::FAN_OPEN_PERM, + None, + Some(tempdir.path()), + ) + .unwrap(); + + let tempfile = tempdir.path().join("test"); + let tempfname = tempfile.clone(); + + let file_thread = thread::spawn(move || { + // first try, should fail + let Err(err) = File::create(&tempfile) else { + panic!("first open is denied, should return error"); + }; + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + + // second try, should succeed + File::create(&tempfile).unwrap(); + }); + + // Deny the first open try + let [event] = &group.read_events().unwrap()[..] else { + panic!("should have read exactly one event"); + }; + assert!(event.check_version()); + assert_eq!(event.mask(), MaskFlags::FAN_OPEN_PERM); + let fd_opt = event.fd(); + let fd = fd_opt.as_ref().unwrap(); + let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); + assert_eq!(path, tempfname); + group + .write_response(FanotifyResponse::new(*fd, Response::FAN_DENY)) + .unwrap(); + + //// Allow the second open try + let [event] = &group.read_events().unwrap()[..] else { + panic!("should have read exactly one event"); + }; + assert!(event.check_version()); + assert_eq!(event.mask(), MaskFlags::FAN_OPEN_PERM); + let fd_opt = event.fd(); + let fd = fd_opt.as_ref().unwrap(); + let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); + assert_eq!(path, tempfname); + group + .write_response(FanotifyResponse::new(*fd, Response::FAN_ALLOW)) + .unwrap(); + + file_thread.join().unwrap(); +} From 15fb5173652b444b3ddc5e9c3637746f27928b1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Deharbe?= Date: Thu, 23 Nov 2023 18:20:09 +0100 Subject: [PATCH 047/140] fix(vendor): declare build.rs as included file in Cargo.toml (#2204) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index aa365449e7..f36c819723 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ authors = ["The nix-rust Project Developers"] repository = "https://github.com/nix-rust/nix" license = "MIT" categories = ["os::unix-apis"] -include = ["src/**/*", "test/**/*", "LICENSE", "README.md", "CHANGELOG.md"] +include = ["build.rs", "src/**/*", "test/**/*", "LICENSE", "README.md", "CHANGELOG.md"] [package.metadata.docs.rs] all-features = true From c1147c62ceb3f3ca392bb307db46fd6a7247a9f3 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 24 Nov 2023 01:35:01 +0800 Subject: [PATCH 048/140] docs: document ptr type casting in CONVENTIONS.md (#2197) * docs: document ptr type casting in CONVENTIONS.md * rephrase it * rephrase it Co-authored-by: Alan Somers --------- Co-authored-by: Alan Somers --- CONVENTIONS.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 2461085eb6..695d3d9aa8 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -84,3 +84,13 @@ the variable. [enum]: https://doc.rust-lang.org/reference.html#enumerations [libc]: https://crates.io/crates/libc/ [std_MaybeUninit]: https://doc.rust-lang.org/stable/std/mem/union.MaybeUninit.html + +## Pointer type casting + +We prefer [`cast()`], [`cast_mut()`] and [`cast_const()`] to cast pointer types +over the `as` keyword because it is much more difficult to accidentally change +type or mutability that way. + +[`cast()`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast +[`cast_mut()`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast_mut +[`cast_const()`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast_const From 3541bdd9b1056a9e1dfbe9fb195ace9ec882c21a Mon Sep 17 00:00:00 2001 From: recatek Date: Fri, 24 Nov 2023 22:07:34 -0500 Subject: [PATCH 049/140] Added FreeBSD's SCM_REALTIME and SCM_MONOTONIC into sys::socket::ControlMessageOwned (#2187) * Added FreeBSD's SCM_REALTIME and SCM_MONOTONIC into sys::socket::ControlMessageOwned. * Creating a SocketTimestamp enum for the SO_TS_CLOCK setsockopt for FreeBSD. * Fixing whitespace * Fixing CI error on cfg attributes * Removing legacy doc attributes * Formatting cleanup * Updating changelog * Adding tests for new TsClock setsockopt enum and the two new packet timestamp control messages for FreeBSD * Replacing an assert_eq with an assert in new tests. * Removing qemu ignore for new FreeBSD tests * Giving new FreeBSD timestamping tests each a unique socket * Updating monotonic packet timestamp test to account for monotonicity * Moving test ports again to line up with changes in #2196 * Attempting checks again * Wrapping ptr::read_unaligned calls in unsafe blocks --- changelog/2187.added.md | 2 + src/sys/socket/mod.rs | 45 +++++++++++++- src/sys/socket/sockopt.rs | 2 +- test/sys/test_socket.rs | 120 ++++++++++++++++++++++++++++++++++++++ test/sys/test_sockopt.rs | 113 +++++++++++++++++++++++++++++++++++ 5 files changed, 280 insertions(+), 2 deletions(-) create mode 100644 changelog/2187.added.md diff --git a/changelog/2187.added.md b/changelog/2187.added.md new file mode 100644 index 0000000000..a13ef70990 --- /dev/null +++ b/changelog/2187.added.md @@ -0,0 +1,2 @@ +- Added the `::nix::sys::socket::SocketTimestamp` enum for configuring the `TsClock` (a.k.a `SO_TS_CLOCK`) sockopt +- Added FreeBSD's `ScmRealtime` and `ScmMonotonic` as new options in `::nix::sys::socket::ControlMessageOwned` \ No newline at end of file diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 76e09641c0..ccfbe5835e 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1,7 +1,11 @@ //! Socket interface functions //! //! [Further reading](https://man7.org/linux/man-pages/man7/socket.7.html) -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(any( + target_os = "android", + target_os = "freebsd", + target_os = "linux" +))] #[cfg(feature = "uio")] use crate::sys::time::TimeSpec; #[cfg(not(target_os = "redox"))] @@ -380,6 +384,25 @@ libc_bitflags! { } } +#[cfg(target_os = "freebsd")] +libc_enum! { + /// A selector for which clock to use when generating packet timestamps. + /// Used when setting [`TsClock`](crate::sys::socket::sockopt::TsClock) on a socket. + /// (For more details, see [setsockopt(2)](https://man.freebsd.org/cgi/man.cgi?setsockopt)). + #[repr(i32)] + #[non_exhaustive] + pub enum SocketTimestamp { + /// Microsecond resolution, realtime. This is the default. + SO_TS_REALTIME_MICRO, + /// Sub-nanosecond resolution, realtime. + SO_TS_BINTIME, + /// Nanosecond resolution, realtime. + SO_TS_REALTIME, + /// Nanosecond resolution, monotonic. + SO_TS_MONOTONIC, + } +} + cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { /// Unix credentials of the sending process. @@ -746,6 +769,16 @@ pub enum ControlMessageOwned { /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) #[cfg(any(target_os = "android", target_os = "linux"))] ScmTimestampns(TimeSpec), + /// Realtime clock timestamp + /// + /// [Further reading](https://man.freebsd.org/cgi/man.cgi?setsockopt) + #[cfg(target_os = "freebsd")] + ScmRealtime(TimeSpec), + /// Monotonic clock timestamp + /// + /// [Further reading](https://man.freebsd.org/cgi/man.cgi?setsockopt) + #[cfg(target_os = "freebsd")] + ScmMonotonic(TimeSpec), #[cfg(any( target_os = "android", apple_targets, @@ -926,6 +959,16 @@ impl ControlMessageOwned { let ts: libc::timespec = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmTimestampns(TimeSpec::from(ts)) } + #[cfg(target_os = "freebsd")] + (libc::SOL_SOCKET, libc::SCM_REALTIME) => { + let ts: libc::timespec = unsafe { ptr::read_unaligned(p as *const _) }; + ControlMessageOwned::ScmRealtime(TimeSpec::from(ts)) + } + #[cfg(target_os = "freebsd")] + (libc::SOL_SOCKET, libc::SCM_MONOTONIC) => { + let ts: libc::timespec = unsafe { ptr::read_unaligned(p as *const _) }; + ControlMessageOwned::ScmMonotonic(TimeSpec::from(ts)) + } #[cfg(any(target_os = "android", target_os = "linux"))] (libc::SOL_SOCKET, libc::SCM_TIMESTAMPING) => { let tp = p as *const libc::timespec; diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 511babf8d8..e2f8a5a860 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -721,7 +721,7 @@ sockopt_impl!( Both, libc::SOL_SOCKET, libc::SO_TS_CLOCK, - i32 + super::SocketTimestamp ); #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 19b17fec46..3959f3facf 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -72,6 +72,126 @@ pub fn test_timestamping() { assert!(std::time::Duration::from(diff).as_secs() < 60); } +#[cfg(target_os = "freebsd")] +#[test] +pub fn test_timestamping_realtime() { + use nix::sys::socket::{ + recvmsg, sendmsg, setsockopt, socket, sockopt::ReceiveTimestamp, + sockopt::TsClock, ControlMessageOwned, MsgFlags, SockFlag, SockType, + SockaddrIn, SocketTimestamp, + }; + use std::io::{IoSlice, IoSliceMut}; + + let sock_addr = SockaddrIn::from_str("127.0.0.1:6792").unwrap(); + + let ssock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("send socket failed"); + + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + nix::sys::socket::bind(rsock.as_raw_fd(), &sock_addr).unwrap(); + + setsockopt(&rsock, ReceiveTimestamp, &true).unwrap(); + setsockopt(&rsock, TsClock, &SocketTimestamp::SO_TS_REALTIME).unwrap(); + + let sbuf = [0u8; 2048]; + let mut rbuf = [0u8; 2048]; + let flags = MsgFlags::empty(); + let iov1 = [IoSlice::new(&sbuf)]; + let mut iov2 = [IoSliceMut::new(&mut rbuf)]; + + let mut cmsg = cmsg_space!(nix::sys::time::TimeVal); + sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap(); + let recv = + recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, Some(&mut cmsg), flags) + .unwrap(); + + let mut ts = None; + for c in recv.cmsgs() { + if let ControlMessageOwned::ScmRealtime(timeval) = c { + ts = Some(timeval); + } + } + let ts = ts.expect("ScmRealtime is present"); + let sys_time = + ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_REALTIME) + .unwrap(); + let diff = if ts > sys_time { + ts - sys_time + } else { + sys_time - ts + }; + assert!(std::time::Duration::from(diff).as_secs() < 60); +} + +#[cfg(target_os = "freebsd")] +#[test] +pub fn test_timestamping_monotonic() { + use nix::sys::socket::{ + recvmsg, sendmsg, setsockopt, socket, sockopt::ReceiveTimestamp, + sockopt::TsClock, ControlMessageOwned, MsgFlags, SockFlag, SockType, + SockaddrIn, SocketTimestamp, + }; + use std::io::{IoSlice, IoSliceMut}; + + let sock_addr = SockaddrIn::from_str("127.0.0.1:6803").unwrap(); + + let ssock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .expect("send socket failed"); + + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + nix::sys::socket::bind(rsock.as_raw_fd(), &sock_addr).unwrap(); + + setsockopt(&rsock, ReceiveTimestamp, &true).unwrap(); + setsockopt(&rsock, TsClock, &SocketTimestamp::SO_TS_MONOTONIC).unwrap(); + + let sbuf = [0u8; 2048]; + let mut rbuf = [0u8; 2048]; + let flags = MsgFlags::empty(); + let iov1 = [IoSlice::new(&sbuf)]; + let mut iov2 = [IoSliceMut::new(&mut rbuf)]; + + let mut cmsg = cmsg_space!(nix::sys::time::TimeVal); + sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap(); + let recv = + recvmsg::<()>(rsock.as_raw_fd(), &mut iov2, Some(&mut cmsg), flags) + .unwrap(); + + let mut ts = None; + for c in recv.cmsgs() { + if let ControlMessageOwned::ScmMonotonic(timeval) = c { + ts = Some(timeval); + } + } + let ts = ts.expect("ScmMonotonic is present"); + let sys_time = + ::nix::time::clock_gettime(::nix::time::ClockId::CLOCK_MONOTONIC) + .unwrap(); + let diff = sys_time - ts; // Monotonic clock sys_time must be greater + assert!(std::time::Duration::from(diff).as_secs() < 60); +} + #[test] pub fn test_path_to_sock_addr() { let path = "/foo/bar"; diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index a3100c99a8..0107deec36 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -436,3 +436,116 @@ fn test_ipv6_tclass() { setsockopt(&fd, sockopt::Ipv6TClass, &class).unwrap(); assert_eq!(getsockopt(&fd, sockopt::Ipv6TClass).unwrap(), class); } + +#[test] +#[cfg(target_os = "freebsd")] +fn test_receive_timestamp() { + let fd = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(&fd, sockopt::ReceiveTimestamp, &true).unwrap(); + assert!(getsockopt(&fd, sockopt::ReceiveTimestamp).unwrap()); +} + +#[test] +#[cfg(target_os = "freebsd")] +fn test_ts_clock_realtime_micro() { + use nix::sys::socket::SocketTimestamp; + + let fd = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + + // FreeBSD setsockopt docs say to set SO_TS_CLOCK after setting SO_TIMESTAMP. + setsockopt(&fd, sockopt::ReceiveTimestamp, &true).unwrap(); + + setsockopt( + &fd, + sockopt::TsClock, + &SocketTimestamp::SO_TS_REALTIME_MICRO, + ) + .unwrap(); + assert_eq!( + getsockopt(&fd, sockopt::TsClock).unwrap(), + SocketTimestamp::SO_TS_REALTIME_MICRO + ); +} + +#[test] +#[cfg(target_os = "freebsd")] +fn test_ts_clock_bintime() { + use nix::sys::socket::SocketTimestamp; + + let fd = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + + // FreeBSD setsockopt docs say to set SO_TS_CLOCK after setting SO_TIMESTAMP. + setsockopt(&fd, sockopt::ReceiveTimestamp, &true).unwrap(); + + setsockopt(&fd, sockopt::TsClock, &SocketTimestamp::SO_TS_BINTIME).unwrap(); + assert_eq!( + getsockopt(&fd, sockopt::TsClock).unwrap(), + SocketTimestamp::SO_TS_BINTIME + ); +} + +#[test] +#[cfg(target_os = "freebsd")] +fn test_ts_clock_realtime() { + use nix::sys::socket::SocketTimestamp; + + let fd = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + + // FreeBSD setsockopt docs say to set SO_TS_CLOCK after setting SO_TIMESTAMP. + setsockopt(&fd, sockopt::ReceiveTimestamp, &true).unwrap(); + + setsockopt(&fd, sockopt::TsClock, &SocketTimestamp::SO_TS_REALTIME) + .unwrap(); + assert_eq!( + getsockopt(&fd, sockopt::TsClock).unwrap(), + SocketTimestamp::SO_TS_REALTIME + ); +} + +#[test] +#[cfg(target_os = "freebsd")] +fn test_ts_clock_monotonic() { + use nix::sys::socket::SocketTimestamp; + + let fd = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + + // FreeBSD setsockopt docs say to set SO_TS_CLOCK after setting SO_TIMESTAMP. + setsockopt(&fd, sockopt::ReceiveTimestamp, &true).unwrap(); + + setsockopt(&fd, sockopt::TsClock, &SocketTimestamp::SO_TS_MONOTONIC) + .unwrap(); + assert_eq!( + getsockopt(&fd, sockopt::TsClock).unwrap(), + SocketTimestamp::SO_TS_MONOTONIC + ); +} From 28e2a5e236abf57b60cf7f08d4e5ab306a686095 Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Sat, 25 Nov 2023 03:19:54 +0000 Subject: [PATCH 050/140] feat: Safer epoll timeout (#2202) --- changelog/2202.changed.md | 1 + src/lib.rs | 3 + src/poll.rs | 226 +------------------------------------- src/poll_timeout.rs | 224 +++++++++++++++++++++++++++++++++++++ src/sys/epoll.rs | 15 +-- 5 files changed, 238 insertions(+), 231 deletions(-) create mode 100644 changelog/2202.changed.md create mode 100644 src/poll_timeout.rs diff --git a/changelog/2202.changed.md b/changelog/2202.changed.md new file mode 100644 index 0000000000..c1306d7f7e --- /dev/null +++ b/changelog/2202.changed.md @@ -0,0 +1 @@ +`Epoll::wait` now takes `EpollTimeout` replacing `isize`. \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 62220a822f..b8beaa56ec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -196,6 +196,9 @@ feature! { #[allow(missing_docs)] pub mod unistd; +#[cfg(any(feature = "poll", feature = "event"))] +mod poll_timeout; + use std::ffi::{CStr, CString, OsStr}; use std::mem::MaybeUninit; use std::os::unix::ffi::OsStrExt; diff --git a/src/poll.rs b/src/poll.rs index 4bc1a4b392..0144adbf0e 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -1,9 +1,10 @@ //! Wait for events to trigger on specific file descriptors use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd}; -use std::time::Duration; use crate::errno::Errno; +pub use crate::poll_timeout::PollTimeout; use crate::Result; + /// This is a wrapper around `libc::pollfd`. /// /// It's meant to be used as an argument to the [`poll`](fn.poll.html) and @@ -175,229 +176,6 @@ libc_bitflags! { } } -/// Timeout argument for [`poll`]. -#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] -pub struct PollTimeout(i32); - -impl PollTimeout { - /// Blocks indefinitely. - /// - /// > Specifying a negative value in timeout means an infinite timeout. - pub const NONE: Self = Self(-1); - /// Returns immediately. - /// - /// > Specifying a timeout of zero causes poll() to return immediately, even if no file - /// > descriptors are ready. - pub const ZERO: Self = Self(0); - /// Blocks for at most [`std::i32::MAX`] milliseconds. - pub const MAX: Self = Self(i32::MAX); - /// Returns if `self` equals [`PollTimeout::NONE`]. - pub fn is_none(&self) -> bool { - // > Specifying a negative value in timeout means an infinite timeout. - *self <= Self::NONE - } - /// Returns if `self` does not equal [`PollTimeout::NONE`]. - pub fn is_some(&self) -> bool { - !self.is_none() - } - /// Returns the timeout in milliseconds if there is some, otherwise returns `None`. - pub fn as_millis(&self) -> Option { - self.is_some().then_some(u32::try_from(self.0).unwrap()) - } - /// Returns the timeout as a `Duration` if there is some, otherwise returns `None`. - pub fn timeout(&self) -> Option { - self.as_millis() - .map(|x| Duration::from_millis(u64::from(x))) - } -} - -/// Error type for integer conversions into `PollTimeout`. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum PollTimeoutTryFromError { - /// Passing a value less than -1 is invalid on some systems, see - /// . - TooNegative, - /// Passing a value greater than `i32::MAX` is invalid. - TooPositive, -} - -impl std::fmt::Display for PollTimeoutTryFromError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::TooNegative => write!(f, "Passed a negative timeout less than -1."), - Self::TooPositive => write!(f, "Passed a positive timeout greater than `i32::MAX` milliseconds.") - } - } -} - -impl std::error::Error for PollTimeoutTryFromError {} - -impl> From> for PollTimeout { - fn from(x: Option) -> Self { - x.map_or(Self::NONE, |x| x.into()) - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: Duration) -> std::result::Result { - Ok(Self( - i32::try_from(x.as_millis()) - .map_err(|_| PollTimeoutTryFromError::TooPositive)?, - )) - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: u128) -> std::result::Result { - Ok(Self( - i32::try_from(x) - .map_err(|_| PollTimeoutTryFromError::TooPositive)?, - )) - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: u64) -> std::result::Result { - Ok(Self( - i32::try_from(x) - .map_err(|_| PollTimeoutTryFromError::TooPositive)?, - )) - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: u32) -> std::result::Result { - Ok(Self( - i32::try_from(x) - .map_err(|_| PollTimeoutTryFromError::TooPositive)?, - )) - } -} -impl From for PollTimeout { - fn from(x: u16) -> Self { - Self(i32::from(x)) - } -} -impl From for PollTimeout { - fn from(x: u8) -> Self { - Self(i32::from(x)) - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: i128) -> std::result::Result { - match x { - ..=-2 => Err(PollTimeoutTryFromError::TooNegative), - -1.. => Ok(Self( - i32::try_from(x) - .map_err(|_| PollTimeoutTryFromError::TooPositive)?, - )), - } - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: i64) -> std::result::Result { - match x { - ..=-2 => Err(PollTimeoutTryFromError::TooNegative), - -1.. => Ok(Self( - i32::try_from(x) - .map_err(|_| PollTimeoutTryFromError::TooPositive)?, - )), - } - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: i32) -> std::result::Result { - match x { - ..=-2 => Err(PollTimeoutTryFromError::TooNegative), - -1.. => Ok(Self(x)), - } - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: i16) -> std::result::Result { - match x { - ..=-2 => Err(PollTimeoutTryFromError::TooNegative), - -1.. => Ok(Self(i32::from(x))), - } - } -} -impl TryFrom for PollTimeout { - type Error = PollTimeoutTryFromError; - fn try_from(x: i8) -> std::result::Result { - match x { - ..=-2 => Err(PollTimeoutTryFromError::TooNegative), - -1.. => Ok(Self(i32::from(x))), - } - } -} -impl TryFrom for Duration { - type Error = (); - fn try_from(x: PollTimeout) -> std::result::Result { - x.timeout().ok_or(()) - } -} -impl TryFrom for u128 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} -impl TryFrom for u64 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} -impl TryFrom for u32 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} -impl TryFrom for u16 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} -impl TryFrom for u8 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} -impl From for i128 { - fn from(x: PollTimeout) -> Self { - Self::from(x.0) - } -} -impl From for i64 { - fn from(x: PollTimeout) -> Self { - Self::from(x.0) - } -} -impl From for i32 { - fn from(x: PollTimeout) -> Self { - x.0 - } -} -impl TryFrom for i16 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} -impl TryFrom for i8 { - type Error = >::Error; - fn try_from(x: PollTimeout) -> std::result::Result { - Self::try_from(x.0) - } -} - /// `poll` waits for one of a set of file descriptors to become ready to perform I/O. /// ([`poll(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/poll.html)) /// diff --git a/src/poll_timeout.rs b/src/poll_timeout.rs new file mode 100644 index 0000000000..3f2dc4c4a1 --- /dev/null +++ b/src/poll_timeout.rs @@ -0,0 +1,224 @@ +use std::time::Duration; + +/// PollTimeout argument for polling. +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub struct PollTimeout(i32); + +impl PollTimeout { + /// Blocks indefinitely. + /// + /// > Specifying a negative value in timeout means an infinite timeout. + pub const NONE: Self = Self(-1); + /// Returns immediately. + /// + /// > Specifying a timeout of zero causes poll() to return immediately, even if no file + /// > descriptors are ready. + pub const ZERO: Self = Self(0); + /// Blocks for at most [`std::i32::MAX`] milliseconds. + pub const MAX: Self = Self(i32::MAX); + /// Returns if `self` equals [`PollTimeout::NONE`]. + pub fn is_none(&self) -> bool { + // > Specifying a negative value in timeout means an infinite timeout. + *self <= Self::NONE + } + /// Returns if `self` does not equal [`PollTimeout::NONE`]. + pub fn is_some(&self) -> bool { + !self.is_none() + } + /// Returns the timeout in milliseconds if there is some, otherwise returns `None`. + pub fn as_millis(&self) -> Option { + self.is_some().then_some(u32::try_from(self.0).unwrap()) + } + /// Returns the timeout as a `Duration` if there is some, otherwise returns `None`. + pub fn duration(&self) -> Option { + self.as_millis() + .map(|x| Duration::from_millis(u64::from(x))) + } +} + +/// Error type for integer conversions into `PollTimeout`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PollTimeoutTryFromError { + /// Passing a value less than -1 is invalid on some systems, see + /// . + TooNegative, + /// Passing a value greater than `i32::MAX` is invalid. + TooPositive, +} + +impl std::fmt::Display for PollTimeoutTryFromError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::TooNegative => write!(f, "Passed a negative timeout less than -1."), + Self::TooPositive => write!(f, "Passed a positive timeout greater than `i32::MAX` milliseconds.") + } + } +} + +impl std::error::Error for PollTimeoutTryFromError {} + +impl> From> for PollTimeout { + fn from(x: Option) -> Self { + x.map_or(Self::NONE, |x| x.into()) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: Duration) -> std::result::Result { + Ok(Self( + i32::try_from(x.as_millis()) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: u128) -> std::result::Result { + Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: u64) -> std::result::Result { + Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: u32) -> std::result::Result { + Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )) + } +} +impl From for PollTimeout { + fn from(x: u16) -> Self { + Self(i32::from(x)) + } +} +impl From for PollTimeout { + fn from(x: u8) -> Self { + Self(i32::from(x)) + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i128) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i64) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self( + i32::try_from(x) + .map_err(|_| PollTimeoutTryFromError::TooPositive)?, + )), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i32) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self(x)), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i16) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self(i32::from(x))), + } + } +} +impl TryFrom for PollTimeout { + type Error = PollTimeoutTryFromError; + fn try_from(x: i8) -> std::result::Result { + match x { + ..=-2 => Err(PollTimeoutTryFromError::TooNegative), + -1.. => Ok(Self(i32::from(x))), + } + } +} +impl TryFrom for Duration { + type Error = (); + fn try_from(x: PollTimeout) -> std::result::Result { + x.duration().ok_or(()) + } +} +impl TryFrom for u128 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u64 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u32 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u16 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for u8 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl From for i128 { + fn from(x: PollTimeout) -> Self { + Self::from(x.0) + } +} +impl From for i64 { + fn from(x: PollTimeout) -> Self { + Self::from(x.0) + } +} +impl From for i32 { + fn from(x: PollTimeout) -> Self { + x.0 + } +} +impl TryFrom for i16 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} +impl TryFrom for i8 { + type Error = >::Error; + fn try_from(x: PollTimeout) -> std::result::Result { + Self::try_from(x.0) + } +} diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index 679f9c47d1..32b068e88b 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -1,5 +1,6 @@ use crate::errno::Errno; use crate::Result; +pub use crate::poll_timeout::PollTimeout as EpollTimeout; use libc::{self, c_int}; use std::mem; use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd}; @@ -71,13 +72,13 @@ impl EpollEvent { /// A safe wrapper around [`epoll`](https://man7.org/linux/man-pages/man7/epoll.7.html). /// ``` -/// # use nix::sys::{epoll::{Epoll, EpollEvent, EpollFlags, EpollCreateFlags}, eventfd::{eventfd, EfdFlags}}; +/// # use nix::sys::{epoll::{EpollTimeout, Epoll, EpollEvent, EpollFlags, EpollCreateFlags}, eventfd::{eventfd, EfdFlags}}; /// # use nix::unistd::write; /// # use std::os::unix::io::{OwnedFd, FromRawFd, AsFd}; /// # use std::time::{Instant, Duration}; /// # fn main() -> nix::Result<()> { /// const DATA: u64 = 17; -/// const MILLIS: u64 = 100; +/// const MILLIS: u8 = 100; /// /// // Create epoll /// let epoll = Epoll::new(EpollCreateFlags::empty())?; @@ -92,11 +93,11 @@ impl EpollEvent { /// /// // Wait on event /// let mut events = [EpollEvent::empty()]; -/// epoll.wait(&mut events, MILLIS as isize)?; +/// epoll.wait(&mut events, MILLIS)?; /// /// // Assert data correct & timeout didn't occur /// assert_eq!(events[0].data(), DATA); -/// assert!(now.elapsed() < Duration::from_millis(MILLIS)); +/// assert!(now.elapsed().as_millis() < MILLIS.into()); /// # Ok(()) /// # } /// ``` @@ -140,17 +141,17 @@ impl Epoll { /// (This can be thought of as fetching items from the ready list of the epoll instance.) /// /// [`epoll_wait`](https://man7.org/linux/man-pages/man2/epoll_wait.2.html) - pub fn wait( + pub fn wait>( &self, events: &mut [EpollEvent], - timeout: isize, + timeout: T, ) -> Result { let res = unsafe { libc::epoll_wait( self.0.as_raw_fd(), events.as_mut_ptr().cast(), events.len() as c_int, - timeout as c_int, + timeout.into().into(), ) }; From 2afff8194c75f0550e0d311e88b7e62929ad9d82 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Fri, 24 Nov 2023 23:32:06 -0700 Subject: [PATCH 051/140] Add more cfg aliases (#2205) * Add more cfg aliases Add cfg aliases for linux_android, bsd, and freebsdlike. Use them in many places, though not everywhere they could theoretically be used. Fixes #2188 * Use apple_targets in build.rs Co-authored-by: SteveLauC * whitespace Co-authored-by: SteveLauC * Define a "solarish" target alias. * Describe cfg aliases in CONVENTIONS.md * solarish in line 803 * solarish in line 845 * fix fmt --------- Co-authored-by: SteveLauC --- CONVENTIONS.md | 6 + build.rs | 12 ++ src/errno.rs | 183 ++++------------------ src/fcntl.rs | 62 +++----- src/features.rs | 2 +- src/lib.rs | 10 +- src/macros.rs | 8 +- src/mount/bsd.rs | 8 +- src/mount/mod.rs | 4 +- src/net/if_.rs | 82 ++++------ src/poll.rs | 2 +- src/pty.rs | 2 +- src/sched.rs | 4 +- src/sys/event.rs | 8 +- src/sys/ioctl/mod.rs | 34 ++--- src/sys/mman.rs | 54 +++---- src/sys/mod.rs | 24 +-- src/sys/ptrace/bsd.rs | 2 +- src/sys/ptrace/mod.rs | 4 +- src/sys/resource.rs | 24 +-- src/sys/signal.rs | 6 +- src/sys/socket/addr.rs | 312 +++++++++++--------------------------- src/sys/socket/mod.rs | 130 ++++++++-------- src/sys/socket/sockopt.rs | 52 +++---- src/sys/stat.rs | 12 +- src/sys/statfs.rs | 106 ++++++------- src/sys/statvfs.rs | 12 +- src/sys/termios.rs | 148 +++--------------- src/sys/time.rs | 2 +- src/sys/uio.rs | 2 +- src/sys/utsname.rs | 2 +- src/sys/wait.rs | 16 +- src/time.rs | 20 +-- src/unistd.rs | 222 +++++---------------------- test/common/mod.rs | 2 +- test/sys/mod.rs | 6 +- test/sys/test_ioctl.rs | 14 +- test/sys/test_ptrace.rs | 12 +- test/sys/test_signal.rs | 4 +- test/sys/test_socket.rs | 42 ++--- test/sys/test_sockopt.rs | 10 +- test/sys/test_wait.rs | 2 +- test/test.rs | 2 +- test/test_fcntl.rs | 2 +- test/test_net.rs | 2 +- test/test_pty.rs | 8 +- test/test_sendfile.rs | 2 +- test/test_unistd.rs | 14 +- 48 files changed, 547 insertions(+), 1152 deletions(-) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 695d3d9aa8..eac629c334 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -37,6 +37,12 @@ impl SigSet { When creating newtypes, we use Rust's `CamelCase` type naming convention. +## cfg gates + +When creating operating-system-specific functionality, we gate it by +`#[cfg(target_os = ...)]`. If more than one operating system is affected, we +prefer to use the cfg aliases defined in build.rs, like `#[cfg(bsd)]`. + ## Bitflags Many C functions have flags parameters that are combined from constants using diff --git a/build.rs b/build.rs index 15847184f2..0fc908e6dd 100644 --- a/build.rs +++ b/build.rs @@ -2,10 +2,22 @@ use cfg_aliases::cfg_aliases; fn main() { cfg_aliases! { + android: { target_os = "android" }, + dragonfly: { target_os = "dragonfly" }, ios: { target_os = "ios" }, + freebsd: { target_os = "freebsd" }, + illumos: { target_os = "illumos" }, + linux: { target_os = "linux" }, macos: { target_os = "macos" }, + netbsd: { target_os = "netbsd" }, + openbsd: { target_os = "openbsd" }, + solarish: { target_os = "solaris" }, watchos: { target_os = "watchos" }, tvos: { target_os = "tvos" }, apple_targets: { any(ios, macos, watchos, tvos) }, + bsd: { any(freebsd, dragonfly, netbsd, openbsd, apple_targets) }, + linux_android: { any(android, linux) }, + freebsdlike: { any(dragonfly, freebsd) }, + solarish: { any(illumos, solaris) }, } } diff --git a/src/errno.rs b/src/errno.rs index 869413eaf5..f4f982e23d 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -25,7 +25,7 @@ cfg_if! { unsafe fn errno_location() -> *mut c_int { unsafe { libc::__errno_location() } } - } else if #[cfg(any(target_os = "illumos", target_os = "solaris"))] { + } else if #[cfg(solarish)] { unsafe fn errno_location() -> *mut c_int { unsafe { libc::___errno() } } @@ -501,7 +501,7 @@ fn desc(errno: Errno) -> &'static str { ))] EBADMSG => "Not a data message", - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] EBADMSG => "Trying to read unreadable message", #[cfg(any( @@ -745,7 +745,7 @@ fn desc(errno: Errno) -> &'static str { ))] EOWNERDEAD => "Owner died", - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] EOWNERDEAD => "Process died with lock", #[cfg(any( @@ -756,7 +756,7 @@ fn desc(errno: Errno) -> &'static str { ))] ENOTRECOVERABLE => "State not recoverable", - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] ENOTRECOVERABLE => "Lock is not recoverable", #[cfg(any( @@ -794,25 +794,10 @@ fn desc(errno: Errno) -> &'static str { #[cfg(target_os = "freebsd")] ECAPMODE => "Not permitted in capability mode", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] ENEEDAUTH => "Need authenticator", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", - target_os = "redox", - target_os = "illumos", - target_os = "solaris" - ))] + #[cfg(any(bsd, target_os = "redox", solarish))] EOVERFLOW => "Value too large to be stored in data type", #[cfg(any( @@ -825,36 +810,13 @@ fn desc(errno: Errno) -> &'static str { ))] EILSEQ => "Illegal byte sequence", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", - target_os = "haiku" - ))] + #[cfg(any(bsd, target_os = "haiku"))] ENOATTR => "Attribute not found", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", - target_os = "redox", - target_os = "haiku" - ))] + #[cfg(any(bsd, target_os = "redox", target_os = "haiku"))] EBADMSG => "Bad message", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", - target_os = "redox", - target_os = "haiku" - ))] + #[cfg(any(bsd, target_os = "redox", target_os = "haiku"))] EPROTO => "Protocol error", #[cfg(any( @@ -873,46 +835,17 @@ fn desc(errno: Errno) -> &'static str { ))] EOWNERDEAD => "Previous owner died", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", - target_os = "aix", - target_os = "illumos", - target_os = "solaris", - target_os = "haiku" - ))] + #[cfg(any(bsd, target_os = "aix", solarish, target_os = "haiku"))] ENOTSUP => "Operation not supported", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "aix", - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(any(bsd, target_os = "aix"))] EPROCLIM => "Too many processes", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "aix", - target_os = "openbsd", - target_os = "netbsd", - target_os = "redox" - ))] + #[cfg(any(bsd, target_os = "aix", target_os = "redox"))] EUSERS => "Too many users", #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", + bsd, target_os = "redox", target_os = "aix", target_os = "illumos", @@ -922,11 +855,7 @@ fn desc(errno: Errno) -> &'static str { EDQUOT => "Disc quota exceeded", #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd", + bsd, target_os = "redox", target_os = "aix", target_os = "illumos", @@ -935,89 +864,31 @@ fn desc(errno: Errno) -> &'static str { ))] ESTALE => "Stale NFS file handle", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "aix", - target_os = "openbsd", - target_os = "netbsd", - target_os = "redox" - ))] + #[cfg(any(bsd, target_os = "aix", target_os = "redox"))] EREMOTE => "Too many levels of remote in path", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] EBADRPC => "RPC struct is bad", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] ERPCMISMATCH => "RPC version wrong", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] EPROGUNAVAIL => "RPC prog. not avail", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] EPROGMISMATCH => "Program version wrong", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] EPROCUNAVAIL => "Bad procedure for program", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] EFTYPE => "Inappropriate file type or format", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(bsd)] EAUTH => "Authentication error", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "aix", - target_os = "openbsd", - target_os = "netbsd", - target_os = "redox" - ))] + #[cfg(any(bsd, target_os = "aix", target_os = "redox"))] ECANCELED => "Operation canceled", #[cfg(apple_targets)] @@ -1099,13 +970,13 @@ fn desc(errno: Errno) -> &'static str { #[cfg(target_os = "dragonfly")] EASYNC => "Async", - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] EDEADLOCK => "Resource deadlock would occur", - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] ELOCKUNMAPPED => "Locked lock was unmapped", - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] ENOTACTIVE => "Facility is not active", } } @@ -2688,7 +2559,7 @@ mod consts { } } -#[cfg(any(target_os = "illumos", target_os = "solaris"))] +#[cfg(solarish)] mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] diff --git a/src/fcntl.rs b/src/fcntl.rs index d327c4b22a..331ee2e38d 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -55,9 +55,9 @@ libc_bitflags! { AT_REMOVEDIR; AT_SYMLINK_FOLLOW; AT_SYMLINK_NOFOLLOW; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] AT_NO_AUTOMOUNT; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] AT_EMPTY_PATH; #[cfg(not(target_os = "android"))] AT_EACCESS; @@ -100,7 +100,7 @@ libc_bitflags!( target_os = "netbsd"))] O_DIRECT; /// If the specified path isn't a directory, fail. - #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] + #[cfg(not(solarish))] O_DIRECTORY; /// Implicitly follow each `write()` with an `fdatasync()`. #[cfg(any(target_os = "android", @@ -115,27 +115,18 @@ libc_bitflags!( #[cfg(target_os = "freebsd")] O_EXEC; /// Open with an exclusive file lock. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - target_os = "redox"))] + #[cfg(any(bsd, target_os = "redox"))] O_EXLOCK; /// Same as `O_SYNC`. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + #[cfg(any(bsd, all(target_os = "linux", not(target_env = "musl")), - target_os = "netbsd", - target_os = "openbsd", target_os = "redox"))] O_FSYNC; /// Allow files whose sizes can't be represented in an `off_t` to be opened. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] O_LARGEFILE; /// Do not update the file last access time during `read(2)`s. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] O_NOATIME; /// Don't attach the device as the process' controlling terminal. #[cfg(not(target_os = "redox"))] @@ -170,18 +161,13 @@ libc_bitflags!( #[cfg(target_os = "netbsd")] O_SEARCH; /// Open with a shared file lock. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - target_os = "redox"))] + #[cfg(any(bsd, target_os = "redox"))] O_SHLOCK; /// Implicitly follow each `write()` with an `fsync()`. #[cfg(not(target_os = "redox"))] O_SYNC; /// Create an unnamed temporary file. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] O_TMPFILE; /// Truncate an existing regular file to 0 length if it allows writing. O_TRUNC; @@ -346,7 +332,7 @@ fn inner_readlink( let reported_size = match dirfd { #[cfg(target_os = "redox")] Some(_) => unreachable!(), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Some(dirfd) => { let flags = if path.is_empty() { AtFlags::AT_EMPTY_PATH @@ -463,11 +449,11 @@ pub enum FcntlArg<'a> { F_SETLK(&'a libc::flock), F_SETLKW(&'a libc::flock), F_GETLK(&'a mut libc::flock), - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_OFD_SETLK(&'a libc::flock), - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_OFD_SETLKW(&'a libc::flock), - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_OFD_GETLK(&'a mut libc::flock), #[cfg(any( target_os = "android", @@ -485,9 +471,9 @@ pub enum FcntlArg<'a> { F_FULLFSYNC, #[cfg(apple_targets)] F_BARRIERFSYNC, - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_GETPIPE_SZ, - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_SETPIPE_SZ(c_int), #[cfg(any( target_os = "netbsd", @@ -533,11 +519,11 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { F_SETLKW(flock) => libc::fcntl(fd, libc::F_SETLKW, flock), #[cfg(not(target_os = "redox"))] F_GETLK(flock) => libc::fcntl(fd, libc::F_GETLK, flock), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] F_OFD_SETLK(flock) => libc::fcntl(fd, libc::F_OFD_SETLK, flock), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] F_OFD_SETLKW(flock) => libc::fcntl(fd, libc::F_OFD_SETLKW, flock), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] F_OFD_GETLK(flock) => libc::fcntl(fd, libc::F_OFD_GETLK, flock), #[cfg(any( target_os = "android", @@ -557,9 +543,9 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { F_FULLFSYNC => libc::fcntl(fd, libc::F_FULLFSYNC), #[cfg(apple_targets)] F_BARRIERFSYNC => libc::fcntl(fd, libc::F_BARRIERFSYNC), - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_GETPIPE_SZ => libc::fcntl(fd, libc::F_GETPIPE_SZ), - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] F_SETPIPE_SZ(size) => libc::fcntl(fd, libc::F_SETPIPE_SZ, size), #[cfg(any( target_os = "dragonfly", @@ -636,7 +622,7 @@ pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[cfg(feature = "zerocopy")] libc_bitflags! { /// Additional flags to `splice` and friends. @@ -728,7 +714,7 @@ pub fn copy_file_range( Errno::result(ret).map(|r| r as usize) } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] pub fn splice( fd_in: RawFd, off_in: Option<&mut libc::loff_t>, @@ -750,7 +736,7 @@ pub fn splice( Errno::result(ret).map(|r| r as usize) } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] pub fn tee( fd_in: RawFd, fd_out: RawFd, @@ -761,7 +747,7 @@ pub fn tee( Errno::result(ret).map(|r| r as usize) } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] pub fn vmsplice( fd: RawFd, iov: &[std::io::IoSlice<'_>], diff --git a/src/features.rs b/src/features.rs index 8aac9ede1e..a623d2d533 100644 --- a/src/features.rs +++ b/src/features.rs @@ -1,7 +1,7 @@ //! Feature tests for OS functionality pub use self::os::*; -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] mod os { use crate::sys::utsname::uname; use crate::Result; diff --git a/src/lib.rs b/src/lib.rs index b8beaa56ec..ed9d67b7fe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -124,20 +124,16 @@ feature! { #![feature = "net"] #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "linux", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd"))] + target_os = "illumos"))] #[deny(missing_docs)] pub mod ifaddrs; #[cfg(not(target_os = "redox"))] #[deny(missing_docs)] pub mod net; } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] feature! { #![feature = "kmod"] #[allow(missing_docs)] diff --git a/src/macros.rs b/src/macros.rs index adff2bc6be..3010a1a053 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -27,9 +27,9 @@ macro_rules! feature { /// /// PROT_WRITE enables write protect /// PROT_WRITE; /// PROT_EXEC; -/// #[cfg(any(target_os = "linux", target_os = "android"))] +/// #[cfg(linux_android)] /// PROT_GROWSDOWN; -/// #[cfg(any(target_os = "linux", target_os = "android"))] +/// #[cfg(linux_android)] /// PROT_GROWSUP; /// } /// } @@ -89,9 +89,9 @@ macro_rules! libc_bitflags { /// PROT_READ, /// PROT_WRITE, /// PROT_EXEC, -/// #[cfg(any(target_os = "linux", target_os = "android"))] +/// #[cfg(linux_android)] /// PROT_GROWSDOWN, -/// #[cfg(any(target_os = "linux", target_os = "android"))] +/// #[cfg(linux_android)] /// PROT_GROWSUP, /// } /// } diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index daaf594871..dc0324dda8 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -33,10 +33,10 @@ libc_bitflags!( #[cfg(any(target_os = "macos", target_os = "freebsd"))] MNT_MULTILABEL; /// Disable read clustering. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MNT_NOCLUSTERR; /// Disable write clustering. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MNT_NOCLUSTERW; /// Enable NFS version 4 ACLs. #[cfg(target_os = "freebsd")] @@ -48,7 +48,7 @@ libc_bitflags!( /// Do not honor setuid or setgid bits on files when executing them. MNT_NOSUID; /// Do not follow symlinks. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MNT_NOSYMFOLLOW; /// Mount read-only. MNT_RDONLY; @@ -70,7 +70,7 @@ libc_bitflags!( MNT_SOFTDEP; /// Directories with the SUID bit set chown new files to their own /// owner. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MNT_SUIDDIR; /// All I/O to the file system should be done synchronously. MNT_SYNCHRONOUS; diff --git a/src/mount/mod.rs b/src/mount/mod.rs index 6f00876fc2..73ce0bac52 100644 --- a/src/mount/mod.rs +++ b/src/mount/mod.rs @@ -1,8 +1,8 @@ //! Mount file systems -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod linux; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub use self::linux::*; #[cfg(any( diff --git a/src/net/if_.rs b/src/net/if_.rs index 1497e9d3c8..fff5faea2f 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -53,14 +53,10 @@ libc_bitflags!( /// Resources allocated. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "fuchsia", target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris"))] IFF_RUNNING; /// No arp protocol, L2 destination address not set. (see @@ -83,7 +79,7 @@ libc_bitflags!( target_os = "openbsd"))] IFF_OACTIVE; /// Protocol code on board. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_INTELLIGENT; /// Slave of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) @@ -100,39 +96,27 @@ libc_bitflags!( /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) IFF_MULTICAST; /// Per link layer defined bit. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] IFF_LINK0; /// Multicast using broadcast. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_MULTI_BCAST; /// Is able to select media type via ifmap. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] IFF_PORTSEL; /// Per link layer defined bit. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] IFF_LINK1; /// Non-unique address. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_UNNUMBERED; /// Auto media selection active. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] IFF_AUTOMEDIA; /// Per link layer defined bit. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] IFF_LINK2; /// Use alternate physical connection. #[cfg(any(target_os = "dragonfly", @@ -140,14 +124,14 @@ libc_bitflags!( apple_targets,))] IFF_ALTPHYS; /// DHCP controls interface. - #[cfg(any(target_os = "solaris", target_os = "illumos"))] + #[cfg(solarish)] IFF_DHCPRUNNING; /// The addresses are lost when the interface goes down. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] IFF_DYNAMIC; /// Do not advertise. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_PRIVATE; /// Driver signals L1 up. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] @@ -159,37 +143,37 @@ libc_bitflags!( #[cfg(any(target_os = "freebsd"))] IFF_CANTCONFIG; /// Do not transmit packets. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_NOXMIT; /// Driver signals dormant. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] IFF_DORMANT; /// User-requested promisc mode. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] IFF_PPROMISC; /// Just on-link subnet. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_NOLOCAL; /// Echo sent packets. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] IFF_ECHO; /// User-requested monitor mode. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] IFF_MONITOR; /// Address is deprecated. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_DEPRECATED; /// Static ARP. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] IFF_STATICARP; /// Address from stateless addrconf. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_ADDRCONF; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] IFF_NPOLLING; /// Router on interface. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_ROUTER; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] @@ -198,16 +182,16 @@ libc_bitflags!( #[cfg(any(target_os = "freebsd"))] IFF_DYING; /// No NUD on interface. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_NONUD; /// Interface is being renamed #[cfg(any(target_os = "freebsd"))] IFF_RENAMING; /// Anycast address. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_ANYCAST; /// Don't exchange routing info. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_NORTEXCH; /// Do not provide packet information #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] @@ -219,25 +203,25 @@ libc_bitflags!( #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] IFF_TAP as libc::c_int; /// IPv4 interface. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_IPV4; /// IPv6 interface. - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_IPV6; /// in.mpathd test address - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_NOFAILOVER; /// Interface has failed - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_FAILED; /// Interface is a hot-spare - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_STANDBY; /// Functioning but not used - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_INACTIVE; /// Interface is offline - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] IFF_OFFLINE; #[cfg(target_os = "solaris")] IFF_COS_ENABLED; @@ -263,13 +247,9 @@ libc_bitflags!( ); #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "fuchsia", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "illumos", ))] mod if_nameindex { @@ -394,13 +374,9 @@ mod if_nameindex { } } #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "fuchsia", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "illumos", ))] pub use if_nameindex::*; diff --git a/src/poll.rs b/src/poll.rs index 0144adbf0e..46ee26ae09 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -224,7 +224,7 @@ feature! { /// so in that case `ppoll` differs from `poll` only in the precision of the /// timeout argument. /// -#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(target_os = "android", freebsdlike, target_os = "linux"))] pub fn ppoll( fds: &mut [PollFd], timeout: Option, diff --git a/src/pty.rs b/src/pty.rs index 0b5f3e1085..74f8ecf0df 100644 --- a/src/pty.rs +++ b/src/pty.rs @@ -187,7 +187,7 @@ pub unsafe fn ptsname(fd: &PtyMaster) -> Result { /// /// This value is useful for opening the slave ptty once the master has already been opened with /// `posix_openpt()`. -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[inline] pub fn ptsname_r(fd: &PtyMaster) -> Result { let mut name_buf = Vec::::with_capacity(64); diff --git a/src/sched.rs b/src/sched.rs index f11d600545..bafbfa0bd8 100644 --- a/src/sched.rs +++ b/src/sched.rs @@ -4,10 +4,10 @@ //! [sched.h](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sched.h.html) use crate::{Errno, Result}; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub use self::sched_linux_like::*; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod sched_linux_like { use crate::errno::Errno; use crate::unistd::Pid; diff --git a/src/sys/event.rs b/src/sys/event.rs index 4372508499..f53e0dfdad 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -183,9 +183,7 @@ libc_bitflags! { EV_DELETE; #[allow(missing_docs)] EV_DISABLE; - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - apple_targets, - target_os = "netbsd", target_os = "openbsd"))] + #[cfg(bsd)] #[allow(missing_docs)] EV_DISPATCH; #[cfg(target_os = "freebsd")] @@ -213,9 +211,7 @@ libc_bitflags! { #[cfg(apple_targets)] #[allow(missing_docs)] EV_POLL; - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - apple_targets, - target_os = "netbsd", target_os = "openbsd"))] + #[cfg(bsd)] #[allow(missing_docs)] EV_RECEIPT; } diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index 9694f204f6..200c94d861 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -121,11 +121,11 @@ //! //! ``` //! # #[macro_use] extern crate nix; -//! # #[cfg(any(target_os = "android", target_os = "linux"))] +//! # #[cfg(linux_android)] //! # use nix::libc::TCGETS as TCGETS; -//! # #[cfg(any(target_os = "android", target_os = "linux"))] +//! # #[cfg(linux_android)] //! # use nix::libc::termios as termios; -//! # #[cfg(any(target_os = "android", target_os = "linux"))] +//! # #[cfg(linux_android)] //! ioctl_read_bad!(tcgets, TCGETS, termios); //! # fn main() {} //! ``` @@ -238,27 +238,11 @@ mod linux; ))] pub use self::linux::*; -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - apple_targets, - target_os = "netbsd", - target_os = "haiku", - target_os = "openbsd" -))] +#[cfg(any(bsd, target_os = "illumos", target_os = "haiku",))] #[macro_use] mod bsd; -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - apple_targets, - target_os = "netbsd", - target_os = "haiku", - target_os = "openbsd" -))] +#[cfg(any(bsd, target_os = "illumos", target_os = "haiku",))] pub use self::bsd::*; /// Convert raw ioctl return value to a Nix result @@ -416,7 +400,7 @@ macro_rules! ioctl_read { /// /// ``` /// # #[macro_use] extern crate nix; -/// # #[cfg(any(target_os = "android", target_os = "linux"))] +/// # #[cfg(linux_android)] /// ioctl_read_bad!(tcgets, libc::TCGETS, libc::termios); /// # fn main() {} /// ``` @@ -493,7 +477,7 @@ macro_rules! ioctl_write_ptr { /// /// ``` /// # #[macro_use] extern crate nix; -/// # #[cfg(any(target_os = "android", target_os = "linux"))] +/// # #[cfg(linux_android)] /// ioctl_write_ptr_bad!(tcsets, libc::TCSETS, libc::termios); /// # fn main() {} /// ``` @@ -512,7 +496,7 @@ macro_rules! ioctl_write_ptr_bad { } cfg_if! { - if #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] { + if #[cfg(freebsdlike)] { /// Generates a wrapper function for a ioctl that writes an integer to the kernel. /// /// The arguments to this macro are: @@ -618,7 +602,7 @@ cfg_if! { /// /// ``` /// # #[macro_use] extern crate nix; -/// # #[cfg(any(target_os = "android", target_os = "linux"))] +/// # #[cfg(linux_android)] /// ioctl_write_int_bad!(tcsbrk, libc::TCSBRK); /// # fn main() {} /// ``` diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 289bdda942..199587f557 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -26,10 +26,10 @@ libc_bitflags! { /// Pages can be executed PROT_EXEC; /// Apply protection up to the end of a mapping that grows upwards. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] PROT_GROWSDOWN; /// Apply protection down to the beginning of a mapping that grows downwards. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] PROT_GROWSUP; } } @@ -63,30 +63,30 @@ libc_bitflags! { all(target_os = "freebsd", target_pointer_width = "64")))] MAP_32BIT; /// Used for stacks; indicates to the kernel that the mapping should extend downward in memory. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_GROWSDOWN; /// Compatibility flag. Ignored. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_DENYWRITE; /// Compatibility flag. Ignored. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_EXECUTABLE; /// Mark the mmaped region to be locked in the same way as `mlock(2)`. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_LOCKED; /// Do not reserve swap space for this mapping. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. - #[cfg(not(any(target_os = "dragonfly", target_os = "freebsd", target_os = "aix")))] + #[cfg(not(any(freebsdlike, target_os = "aix")))] MAP_NORESERVE; /// Populate page tables for a mapping. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_POPULATE; /// Only meaningful when used with `MAP_POPULATE`. Don't perform read-ahead. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_NONBLOCK; /// Allocate the mapping using "huge pages." - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MAP_HUGETLB; /// Make use of 64KB huge page (must be supported by the system) #[cfg(target_os = "linux")] @@ -129,7 +129,7 @@ libc_bitflags! { #[cfg(target_os = "netbsd")] MAP_WIRED; /// Causes dirtied data in the specified range to be flushed to disk only when necessary. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MAP_NOSYNC; /// Rename private pages to a file. /// @@ -137,10 +137,10 @@ libc_bitflags! { #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] MAP_RENAME; /// Region may contain semaphores. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] MAP_HASSEMAPHORE; /// Region grows down, like a stack. - #[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux", target_os = "openbsd"))] + #[cfg(any(target_os = "android", freebsdlike, target_os = "linux", target_os = "openbsd"))] MAP_STACK; /// Pages in this mapping are not retained in the kernel's memory cache. #[cfg(apple_targets)] @@ -223,24 +223,24 @@ libc_enum! { /// Do not expect access in the near future. MADV_DONTNEED, /// Free up a given range of pages and its associated backing store. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_REMOVE, /// Do not make pages in this range available to the child after a `fork(2)`. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_DONTFORK, /// Undo the effect of `MADV_DONTFORK`. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_DOFORK, /// Poison the given pages. /// /// Subsequent references to those pages are treated like hardware memory corruption. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_HWPOISON, /// Enable Kernel Samepage Merging (KSM) for the given pages. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_MERGEABLE, /// Undo the effect of `MADV_MERGEABLE` - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_UNMERGEABLE, /// Preserve the memory of each page but offline the original page. #[cfg(any(target_os = "android", @@ -255,31 +255,31 @@ libc_enum! { target_arch = "sparc64"))))] MADV_SOFT_OFFLINE, /// Enable Transparent Huge Pages (THP) for pages in the given range. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_HUGEPAGE, /// Undo the effect of `MADV_HUGEPAGE`. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_NOHUGEPAGE, /// Exclude the given range from a core dump. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_DONTDUMP, /// Undo the effect of an earlier `MADV_DONTDUMP`. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MADV_DODUMP, /// Specify that the application no longer needs the pages in the given range. #[cfg(not(target_os = "aix"))] MADV_FREE, /// Request that the system not flush the current range to disk unless it needs to. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MADV_NOSYNC, /// Undoes the effects of `MADV_NOSYNC` for any future pages dirtied within the given range. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MADV_AUTOSYNC, /// Region is not included in a core file. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MADV_NOCORE, /// Include region in a core file - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] MADV_CORE, /// This process should not be killed when swap space is exhausted. #[cfg(any(target_os = "freebsd"))] diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 7157f3a79a..28ccd1ba2d 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -14,18 +14,14 @@ feature! { feature! { #![feature = "event"] - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[allow(missing_docs)] pub mod epoll; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] pub mod event; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[allow(missing_docs)] pub mod eventfd; } @@ -37,15 +33,11 @@ feature! { } #[cfg(any( + bsd, target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, target_os = "linux", target_os = "redox", - target_os = "netbsd", target_os = "illumos", - target_os = "openbsd" ))] #[cfg(feature = "ioctl")] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] @@ -140,7 +132,7 @@ feature! { pub mod signal; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] feature! { #![feature = "signal"] #[allow(missing_docs)] @@ -177,7 +169,7 @@ feature! { pub mod statvfs; } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub mod sysinfo; @@ -205,13 +197,13 @@ feature! { pub mod wait; } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] feature! { #![feature = "inotify"] pub mod inotify; } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] feature! { #![feature = "time"] pub mod timerfd; diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index 2945d5cdd1..69de590ace 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -154,7 +154,7 @@ pub fn kill(pid: Pid) -> Result<()> { /// } /// ``` #[cfg(any( - any(target_os = "dragonfly", target_os = "freebsd", target_os = "macos"), + any(freebsdlike, target_os = "macos"), all(target_os = "openbsd", target_arch = "x86_64"), all( target_os = "netbsd", diff --git a/src/sys/ptrace/mod.rs b/src/sys/ptrace/mod.rs index 88648acabc..90176e6a77 100644 --- a/src/sys/ptrace/mod.rs +++ b/src/sys/ptrace/mod.rs @@ -1,9 +1,9 @@ //! Provides helpers for making ptrace system calls -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod linux; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub use self::linux::*; #[cfg(any( diff --git a/src/sys/resource.rs b/src/sys/resource.rs index da9e3000e9..6b518b7af5 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -13,12 +13,8 @@ cfg_if! { if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{ use libc::{__rlimit_resource_t, rlimit}; } else if #[cfg(any( - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - apple_targets, + bsd, target_os = "android", - target_os = "dragonfly", target_os = "aix", all(target_os = "linux", not(target_env = "gnu")) ))]{ @@ -44,12 +40,8 @@ libc_enum! { // https://github.com/rust-lang/libc/blob/master/src/unix/linux_like/linux/gnu/mod.rs #[cfg_attr(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")), repr(u32))] #[cfg_attr(any( - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - apple_targets, + bsd, target_os = "android", - target_os = "dragonfly", target_os = "aix", all(target_os = "linux", not(any(target_env = "gnu", target_env = "uclibc"))) ), repr(i32))] @@ -77,7 +69,7 @@ libc_enum! { /// The maximum number of kqueues this user id is allowed to create. RLIMIT_KQUEUES, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] /// A limit on the combined number of flock locks and fcntl leases that /// this process may establish. RLIMIT_LOCKS, @@ -93,12 +85,12 @@ libc_enum! { /// using the mlock(2) system call. RLIMIT_MEMLOCK, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] /// A limit on the number of bytes that can be allocated for POSIX /// message queues for the real user ID of the calling process. RLIMIT_MSGQUEUE, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] /// A ceiling to which the process's nice value can be raised using /// setpriority or nice. RLIMIT_NICE, @@ -130,7 +122,7 @@ libc_enum! { /// eviction of a process' resident pages beyond this amount (in bytes). RLIMIT_RSS, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] /// A ceiling on the real-time priority that may be set for this process /// using sched_setscheduler and sched_set‐ param. RLIMIT_RTPRIO, @@ -141,12 +133,12 @@ libc_enum! { /// making a blocking system call. RLIMIT_RTTIME, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] /// A limit on the number of signals that may be queued for the real /// user ID of the calling process. RLIMIT_SIGPENDING, - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] /// The maximum size (in bytes) of socket buffer usage for this user. RLIMIT_SBSIZE, diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 3250539969..8ef2b95243 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -10,7 +10,7 @@ use std::fmt; use std::hash::{Hash, Hasher}; use std::mem; use std::ops::BitOr; -#[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] +#[cfg(freebsdlike)] use std::os::unix::io::RawFd; use std::ptr; use std::str::FromStr; @@ -1111,7 +1111,7 @@ pub enum SigevNotify { }, // Note: SIGEV_THREAD is not implemented, but could be if desired. /// Notify by delivering an event to a kqueue. - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] SigevKevent { /// File descriptor of the kqueue to notify. kq: RawFd, @@ -1317,7 +1317,7 @@ mod sigevent { sev.sigev_signo = signal as libc::c_int; sev.sigev_value.sival_ptr = si_value as *mut libc::c_void }, - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] SigevNotify::SigevKevent{kq, udata} => { sev.sigev_notify = libc::SIGEV_KEVENT; sev.sigev_signo = kq; diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index eb39d97f88..319876f4c2 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -1,12 +1,8 @@ #[cfg(any( + bsd, target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, target_os = "linux", target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd", target_os = "haiku", target_os = "fuchsia", target_os = "aix", @@ -21,9 +17,9 @@ pub use self::datalink::LinkAddr; pub use self::vsock::VsockAddr; use super::sa_family_t; use crate::errno::Errno; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] use crate::sys::socket::addr::alg::AlgAddr; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] use crate::sys::socket::addr::netlink::NetlinkAddr; #[cfg(all(feature = "ioctl", apple_targets))] use crate::sys::socket::addr::sys_control::SysControlAddr; @@ -72,7 +68,7 @@ pub enum AddressFamily { /// IPv6 Internet protocols (see [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html)) Inet6 = libc::AF_INET6, /// Kernel user interface device (see [`netlink(7)`](https://man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Netlink = libc::AF_NETLINK, /// Kernel interface for interacting with the routing table #[cfg(not(any( @@ -94,7 +90,7 @@ pub enum AddressFamily { #[cfg(apple_targets)] System = libc::AF_SYSTEM, /// Amateur radio AX.25 protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Ax25 = libc::AF_AX25, /// IPX - Novell protocols #[cfg(not(any(target_os = "aix", target_os = "redox")))] @@ -104,65 +100,65 @@ pub enum AddressFamily { AppleTalk = libc::AF_APPLETALK, /// AX.25 packet layer protocol. /// (see [netrom(4)](https://www.unix.com/man-page/linux/4/netrom/)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetRom = libc::AF_NETROM, /// Can't be used for creating sockets; mostly used for bridge /// links in /// [rtnetlink(7)](https://man7.org/linux/man-pages/man7/rtnetlink.7.html) /// protocol commands. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Bridge = libc::AF_BRIDGE, /// Access to raw ATM PVCs - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] AtmPvc = libc::AF_ATMPVC, /// ITU-T X.25 / ISO-8208 protocol (see [`x25(7)`](https://man7.org/linux/man-pages/man7/x25.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] X25 = libc::AF_X25, /// RATS (Radio Amateur Telecommunications Society) Open /// Systems environment (ROSE) AX.25 packet layer protocol. /// (see [netrom(4)](https://www.unix.com/man-page/linux/4/netrom/)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Rose = libc::AF_ROSE, /// DECet protocol sockets. #[cfg(not(any(target_os = "haiku", target_os = "redox")))] Decnet = libc::AF_DECnet, /// Reserved for "802.2LLC project"; never used. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetBeui = libc::AF_NETBEUI, /// This was a short-lived (between Linux 2.1.30 and /// 2.1.99pre2) protocol family for firewall upcalls. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Security = libc::AF_SECURITY, /// Key management protocol. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Key = libc::AF_KEY, #[allow(missing_docs)] // Not documented anywhere that I can find - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Ash = libc::AF_ASH, /// Acorn Econet protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Econet = libc::AF_ECONET, /// Access to ATM Switched Virtual Circuits - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] AtmSvc = libc::AF_ATMSVC, /// Reliable Datagram Sockets (RDS) protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Rds = libc::AF_RDS, /// IBM SNA #[cfg(not(any(target_os = "haiku", target_os = "redox")))] Sna = libc::AF_SNA, /// Socket interface over IrDA - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Irda = libc::AF_IRDA, /// Generic PPP transport layer, for setting up L2 tunnels (L2TP and PPPoE) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Pppox = libc::AF_PPPOX, /// Legacy protocol for wide area network (WAN) connectivity that was used /// by Sangoma WAN cards - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Wanpipe = libc::AF_WANPIPE, /// Logical link control (IEEE 802.2 LLC) protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Llc = libc::AF_LLC, /// InfiniBand native addressing #[cfg(all(target_os = "linux", not(target_env = "uclibc")))] @@ -171,10 +167,10 @@ pub enum AddressFamily { #[cfg(all(target_os = "linux", not(target_env = "uclibc")))] Mpls = libc::AF_MPLS, /// Controller Area Network automotive bus protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Can = libc::AF_CAN, /// TIPC, "cluster domain sockets" protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Tipc = libc::AF_TIPC, /// Bluetooth low-level socket protocol #[cfg(not(any( @@ -187,10 +183,10 @@ pub enum AddressFamily { Bluetooth = libc::AF_BLUETOOTH, /// IUCV (inter-user communication vehicle) z/VM protocol for /// hypervisor-guest interaction - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Iucv = libc::AF_IUCV, /// Rx, Andrew File System remote procedure call protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] RxRpc = libc::AF_RXRPC, /// New "modular ISDN" driver interface protocol #[cfg(not(any( @@ -202,17 +198,17 @@ pub enum AddressFamily { )))] Isdn = libc::AF_ISDN, /// Nokia cellular modem IPC/RPC interface - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Phonet = libc::AF_PHONET, /// IEEE 802.15.4 WPAN (wireless personal area network) raw packet protocol - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Ieee802154 = libc::AF_IEEE802154, /// Ericsson's Communication CPU to Application CPU interface (CAIF) /// protocol. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Caif = libc::AF_CAIF, /// Interface to kernel crypto API - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Alg = libc::AF_ALG, /// Near field communication #[cfg(target_os = "linux")] @@ -225,128 +221,52 @@ pub enum AddressFamily { ))] Vsock = libc::AF_VSOCK, /// ARPANet IMP addresses - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] ImpLink = libc::AF_IMPLINK, /// PUP protocols, e.g. BSP - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Pup = libc::AF_PUP, /// MIT CHAOS protocols - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Chaos = libc::AF_CHAOS, /// Novell and Xerox protocol #[cfg(any(apple_targets, target_os = "netbsd", target_os = "openbsd"))] Ns = libc::AF_NS, #[allow(missing_docs)] // Not documented anywhere that I can find - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Iso = libc::AF_ISO, /// Bell Labs virtual circuit switch ? - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Datakit = libc::AF_DATAKIT, /// CCITT protocols, X.25 etc - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Ccitt = libc::AF_CCITT, /// DEC Direct data link interface - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Dli = libc::AF_DLI, #[allow(missing_docs)] // Not documented anywhere that I can find - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Lat = libc::AF_LAT, /// NSC Hyperchannel - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Hylink = libc::AF_HYLINK, /// Link layer interface #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd" ))] Link = libc::AF_LINK, /// connection-oriented IP, aka ST II - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Coip = libc::AF_COIP, /// Computer Network Technology - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Cnt = libc::AF_CNT, /// Native ATM access - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] Natm = libc::AF_NATM, /// Unspecified address family, (see [`getaddrinfo(3)`](https://man7.org/linux/man-pages/man3/getaddrinfo.3.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Unspec = libc::AF_UNSPEC, } @@ -361,7 +281,7 @@ impl AddressFamily { libc::AF_UNIX => Some(AddressFamily::Unix), libc::AF_INET => Some(AddressFamily::Inet), libc::AF_INET6 => Some(AddressFamily::Inet6), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_NETLINK => Some(AddressFamily::Netlink), #[cfg(any(target_os = "macos", target_os = "macos"))] libc::AF_SYSTEM => Some(AddressFamily::System), @@ -371,15 +291,11 @@ impl AddressFamily { target_os = "android" )))] libc::PF_ROUTE => Some(AddressFamily::Route), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_PACKET => Some(AddressFamily::Packet), #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", + bsd, target_os = "illumos", - target_os = "openbsd" ))] libc::AF_LINK => Some(AddressFamily::Link), #[cfg(any( @@ -422,7 +338,7 @@ pub struct UnixAddr { enum UnixAddrKind<'a> { Pathname(&'a Path), Unnamed, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Abstract(&'a [u8]), } impl<'a> UnixAddrKind<'a> { @@ -435,7 +351,7 @@ impl<'a> UnixAddrKind<'a> { if path_len == 0 { return Self::Unnamed; } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] if sun.sun_path[0] == 0 { let name = unsafe { slice::from_raw_parts( @@ -486,13 +402,7 @@ impl UnixAddr { .try_into() .unwrap(); - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] { ret.sun_len = sun_len; } @@ -512,7 +422,7 @@ impl UnixAddr { /// thus the input `path` is expected to be the bare name, not NUL-prefixed. /// This is a Linux-specific extension, primarily used to allow chrooted /// processes to communicate with processes having a different filesystem view. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[allow(clippy::unnecessary_cast)] // Not unnecessary on all platforms pub fn new_abstract(path: &[u8]) -> Result { unsafe { @@ -542,7 +452,7 @@ impl UnixAddr { } /// Create a new `sockaddr_un` representing an "unnamed" unix socket address. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] pub fn new_unnamed() -> UnixAddr { let ret = libc::sockaddr_un { sun_family: AddressFamily::Unix as sa_family_t, @@ -603,7 +513,7 @@ impl UnixAddr { /// /// For abstract sockets only the bare name is returned, without the /// leading NUL byte. `None` is returned for unnamed or path-backed sockets. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] pub fn as_abstract(&self) -> Option<&[u8]> { match self.kind() { UnixAddrKind::Abstract(name) => Some(name), @@ -612,7 +522,7 @@ impl UnixAddr { } /// Check if this address is an "unnamed" unix socket address. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[inline] pub fn is_unnamed(&self) -> bool { matches!(self.kind(), UnixAddrKind::Unnamed) @@ -733,7 +643,7 @@ impl AsRef for UnixAddr { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn fmt_abstract(abs: &[u8], f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; f.write_str("@\"")?; @@ -750,7 +660,7 @@ impl fmt::Display for UnixAddr { match self.kind() { UnixAddrKind::Pathname(path) => path.display().fmt(f), UnixAddrKind::Unnamed => f.pad(""), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] UnixAddrKind::Abstract(name) => fmt_abstract(name, f), } } @@ -834,11 +744,7 @@ pub trait SockaddrLike: private::SockaddrLikePriv { } cfg_if! { - if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] { + if #[cfg(bsd)] { /// Return the length of valid data in the sockaddr structure. /// /// For fixed-size sockaddrs, this should be the size of the @@ -958,13 +864,9 @@ impl SockaddrIn { pub fn new(a: u8, b: u8, c: u8, d: u8, port: u16) -> Self { Self(libc::sockaddr_in { #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", + bsd, target_os = "aix", target_os = "haiku", - target_os = "openbsd" ))] sin_len: Self::size() as u8, sin_family: AddressFamily::Inet as sa_family_t, @@ -1035,13 +937,9 @@ impl From for SockaddrIn { fn from(addr: net::SocketAddrV4) -> Self { Self(libc::sockaddr_in { #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "haiku", target_os = "hermit", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" ))] sin_len: mem::size_of::() as u8, sin_family: AddressFamily::Inet as sa_family_t, @@ -1163,13 +1061,9 @@ impl From for SockaddrIn6 { #[allow(clippy::needless_update)] // It isn't needless on Illumos Self(libc::sockaddr_in6 { #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "haiku", target_os = "hermit", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" ))] sin6_len: mem::size_of::() as u8, sin6_family: AddressFamily::Inet6 as sa_family_t, @@ -1225,12 +1119,12 @@ impl std::str::FromStr for SockaddrIn6 { #[derive(Clone, Copy, Eq)] #[repr(C)] pub union SockaddrStorage { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] alg: AlgAddr, #[cfg(all(feature = "net", not(target_os = "redox")))] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] dl: LinkAddr, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] nl: NetlinkAddr, #[cfg(all(feature = "ioctl", apple_targets))] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] @@ -1292,7 +1186,7 @@ impl SockaddrLike for SockaddrStorage { // copy it. If addr is of a variable length type and len is not // available, then there's nothing we can do. match unsafe { (*addr).sa_family as i32 } { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_ALG => unsafe { AlgAddr::from_raw(addr, l).map(|alg| Self { alg }) }, @@ -1305,19 +1199,15 @@ impl SockaddrLike for SockaddrStorage { SockaddrIn6::from_raw(addr, l).map(|sin6| Self { sin6 }) }, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", target_os = "haiku", - target_os = "openbsd" ))] #[cfg(feature = "net")] libc::AF_LINK => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_NETLINK => unsafe { NetlinkAddr::from_raw(addr, l).map(|nl| Self { nl }) }, @@ -1464,7 +1354,7 @@ impl SockaddrStorage { } } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] accessors! {as_alg_addr, as_alg_addr_mut, AlgAddr, AddressFamily::Alg, libc::sockaddr_alg, alg} @@ -1479,12 +1369,8 @@ impl SockaddrStorage { AddressFamily::Packet, libc::sockaddr_ll, dl} #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd" ))] #[cfg(feature = "net")] accessors! { @@ -1501,7 +1387,7 @@ impl SockaddrStorage { as_sockaddr_in6, as_sockaddr_in6_mut, SockaddrIn6, AddressFamily::Inet6, libc::sockaddr_in6, sin6} - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] accessors! {as_netlink_addr, as_netlink_addr_mut, NetlinkAddr, AddressFamily::Netlink, libc::sockaddr_nl, nl} @@ -1533,23 +1419,19 @@ impl fmt::Display for SockaddrStorage { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { match self.ss.ss_family as i32 { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_ALG => self.alg.fmt(f), #[cfg(feature = "net")] libc::AF_INET => self.sin.fmt(f), #[cfg(feature = "net")] libc::AF_INET6 => self.sin6.fmt(f), #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd" ))] #[cfg(feature = "net")] libc::AF_LINK => self.dl.fmt(f), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_NETLINK => self.nl.fmt(f), #[cfg(any( target_os = "android", @@ -1610,23 +1492,19 @@ impl Hash for SockaddrStorage { fn hash(&self, s: &mut H) { unsafe { match self.ss.ss_family as i32 { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_ALG => self.alg.hash(s), #[cfg(feature = "net")] libc::AF_INET => self.sin.hash(s), #[cfg(feature = "net")] libc::AF_INET6 => self.sin6.hash(s), #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd" ))] #[cfg(feature = "net")] libc::AF_LINK => self.dl.hash(s), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::AF_NETLINK => self.nl.hash(s), #[cfg(any( target_os = "android", @@ -1655,23 +1533,19 @@ impl PartialEq for SockaddrStorage { fn eq(&self, other: &Self) -> bool { unsafe { match (self.ss.ss_family as i32, other.ss.ss_family as i32) { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] (libc::AF_ALG, libc::AF_ALG) => self.alg == other.alg, #[cfg(feature = "net")] (libc::AF_INET, libc::AF_INET) => self.sin == other.sin, #[cfg(feature = "net")] (libc::AF_INET6, libc::AF_INET6) => self.sin6 == other.sin6, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd" ))] #[cfg(feature = "net")] (libc::AF_LINK, libc::AF_LINK) => self.dl == other.dl, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] (libc::AF_NETLINK, libc::AF_NETLINK) => self.nl == other.nl, #[cfg(any( target_os = "android", @@ -1712,7 +1586,7 @@ pub(super) mod private { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub mod netlink { use super::*; use crate::sys::socket::addr::AddressFamily; @@ -1785,7 +1659,7 @@ pub mod netlink { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub mod alg { use super::*; use libc::{sockaddr_alg, AF_ALG}; @@ -2107,14 +1981,10 @@ mod datalink { } #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "illumos", - target_os = "netbsd", target_os = "haiku", target_os = "aix", - target_os = "openbsd" ))] mod datalink { feature! { @@ -2273,7 +2143,7 @@ pub mod vsock { } impl PartialEq for VsockAddr { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); (inner.svm_family, inner.svm_cid, inner.svm_port) @@ -2299,7 +2169,7 @@ pub mod vsock { impl Eq for VsockAddr {} impl Hash for VsockAddr { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] fn hash(&self, s: &mut H) { let inner = self.0; (inner.svm_family, inner.svm_cid, inner.svm_port).hash(s); @@ -2394,13 +2264,7 @@ mod tests { use super::*; /// Don't panic when trying to display an empty datalink address - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(bsd)] #[test] fn test_datalink_display() { use super::super::LinkAddr; @@ -2510,13 +2374,9 @@ mod tests { #[test] fn size() { #[cfg(any( + bsd, target_os = "aix", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", target_os = "illumos", - target_os = "openbsd", target_os = "haiku" ))] let l = mem::size_of::(); @@ -2608,7 +2468,7 @@ mod tests { assert_eq!(ss.len(), ua.len()); } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[test] fn from_sockaddr_un_abstract_named() { let name = String::from("nix\0abstract\0test"); @@ -2619,7 +2479,7 @@ mod tests { assert_eq!(ss.len(), ua.len()); } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[test] fn from_sockaddr_un_abstract_unnamed() { let ua = UnixAddr::new_unnamed(); @@ -2633,7 +2493,7 @@ mod tests { mod unixaddr { use super::*; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[test] fn abstract_sun_path() { let name = String::from("nix\0abstract\0test"); diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index ccfbe5835e..1e34ef456d 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1,11 +1,7 @@ //! Socket interface functions //! //! [Further reading](https://man7.org/linux/man-pages/man7/socket.7.html) -#[cfg(any( - target_os = "android", - target_os = "freebsd", - target_os = "linux" -))] +#[cfg(any(target_os = "freebsd", linux_android))] #[cfg(feature = "uio")] use crate::sys::time::TimeSpec; #[cfg(not(target_os = "redox"))] @@ -38,9 +34,9 @@ pub mod sockopt; pub use self::addr::{SockaddrLike, SockaddrStorage}; -#[cfg(any(target_os = "illumos", target_os = "solaris"))] +#[cfg(solarish)] pub use self::addr::{AddressFamily, UnixAddr}; -#[cfg(not(any(target_os = "illumos", target_os = "solaris")))] +#[cfg(not(solarish))] pub use self::addr::{AddressFamily, UnixAddr}; #[cfg(not(any( target_os = "illumos", @@ -59,9 +55,9 @@ pub use self::addr::{LinkAddr, SockaddrIn, SockaddrIn6}; #[cfg(feature = "net")] pub use self::addr::{SockaddrIn, SockaddrIn6}; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub use crate::sys::socket::addr::alg::AlgAddr; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] pub use crate::sys::socket::addr::netlink::NetlinkAddr; #[cfg(apple_targets)] #[cfg(feature = "ioctl")] @@ -147,74 +143,74 @@ pub enum SockProtocol { /// Receives routing and link updates and may be used to modify the routing tables (both IPv4 and IPv6), IP addresses, link // parameters, neighbor setups, queueing disciplines, traffic classes and packet classifiers /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkRoute = libc::NETLINK_ROUTE, /// Reserved for user-mode socket protocols /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkUserSock = libc::NETLINK_USERSOCK, /// Query information about sockets of various protocol families from the kernel /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkSockDiag = libc::NETLINK_SOCK_DIAG, /// Netfilter/iptables ULOG. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkNFLOG = libc::NETLINK_NFLOG, /// SELinux event notifications. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkSELinux = libc::NETLINK_SELINUX, /// Open-iSCSI /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkISCSI = libc::NETLINK_ISCSI, /// Auditing /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkAudit = libc::NETLINK_AUDIT, /// Access to FIB lookup from user space /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkFIBLookup = libc::NETLINK_FIB_LOOKUP, /// Netfilter subsystem /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkNetFilter = libc::NETLINK_NETFILTER, /// SCSI Transports /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkSCSITransport = libc::NETLINK_SCSITRANSPORT, /// Infiniband RDMA /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkRDMA = libc::NETLINK_RDMA, /// Transport IPv6 packets from netfilter to user space. Used by ip6_queue kernel module. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkIPv6Firewall = libc::NETLINK_IP6_FW, /// DECnet routing messages /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkDECNetRoutingMessage = libc::NETLINK_DNRTMSG, /// Kernel messages to user space /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkKObjectUEvent = libc::NETLINK_KOBJECT_UEVENT, /// Generic netlink family for simplified netlink usage. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkGeneric = libc::NETLINK_GENERIC, /// Netlink interface to request information about ciphers registered with the kernel crypto API as well as allow /// configuration of the kernel crypto API. /// ([ref](https://www.man7.org/linux/man-pages/man7/netlink.7.html)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] NetlinkCrypto = libc::NETLINK_CRYPTO, /// Non-DIX type protocol number defined for the Ethernet IEEE 802.3 interface that allows packets of all protocols /// defined in the interface to be received. /// ([ref](https://man7.org/linux/man-pages/man7/packet.7.html)) // The protocol number is fed into the socket syscall in network byte order. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] EthAll = (libc::ETH_P_ALL as u16).to_be() as i32, /// ICMP protocol ([icmp(7)](https://man7.org/linux/man-pages/man7/icmp.7.html)) Icmp = libc::IPPROTO_ICMP, @@ -241,7 +237,7 @@ impl SockProtocol { #[allow(non_upper_case_globals)] pub const KextEvent: SockProtocol = SockProtocol::Icmp; // Matches libc::SYSPROTO_EVENT } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] libc_bitflags! { /// Configuration flags for `SO_TIMESTAMPING` interface /// @@ -342,7 +338,7 @@ libc_bitflags! { /// This flag specifies that queued errors should be received from /// the socket error queue. (For more details, see /// [recvfrom(2)](https://linux.die.net/man/2/recvfrom)) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] MSG_ERRQUEUE; /// Set the `close-on-exec` flag for the file descriptor received via a UNIX domain /// file descriptor using the `SCM_RIGHTS` operation (described in @@ -404,7 +400,7 @@ libc_enum! { } cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { /// Unix credentials of the sending process. /// /// This struct is used with the `SO_PEERCRED` ancillary message @@ -459,7 +455,7 @@ cfg_if! { uc.0 } } - } else if #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] { + } else if #[cfg(freebsdlike)] { /// Unix credentials of the sending process. /// /// This struct is used with the `SCM_CREDS` ancillary message for UNIX sockets. @@ -696,10 +692,10 @@ pub enum ControlMessageOwned { /// Received version of [`ControlMessage::ScmRights`] ScmRights(Vec), /// Received version of [`ControlMessage::ScmCredentials`] - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ScmCredentials(UnixCredentials), /// Received version of [`ControlMessage::ScmCreds`] - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ScmCreds(UnixCredentials), /// A message of type `SCM_TIMESTAMP`, containing the time the /// packet was received by the kernel. @@ -762,12 +758,12 @@ pub enum ControlMessageOwned { /// A set of nanosecond resolution timestamps /// /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ScmTimestampsns(Timestamps), /// Nanoseconds resolution timestamp /// /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ScmTimestampns(TimeSpec), /// Realtime clock timestamp /// @@ -790,12 +786,8 @@ pub enum ControlMessageOwned { Ipv4PacketInfo(libc::in_pktinfo), #[cfg(any( target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, + bsd, target_os = "linux", - target_os = "openbsd", - target_os = "netbsd", ))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -852,12 +844,12 @@ pub enum ControlMessageOwned { RxqOvfl(u32), /// Socket error queue control messages read with the `MSG_ERRQUEUE` flag. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvErr(libc::sock_extended_err, Option), /// Socket error queue control messages read with the `MSG_ERRQUEUE` flag. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6RecvErr(libc::sock_extended_err, Option), @@ -872,7 +864,7 @@ pub enum ControlMessageOwned { } /// For representing packet timestamps via `SO_TIMESTAMPING` interface -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct Timestamps { /// software based timestamp, usually one containing data @@ -939,12 +931,12 @@ impl ControlMessageOwned { } ControlMessageOwned::ScmRights(fds) }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] (libc::SOL_SOCKET, libc::SCM_CREDENTIALS) => { let cred: libc::ucred = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmCredentials(cred.into()) } - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] (libc::SOL_SOCKET, libc::SCM_CREDS) => { let cred: libc::cmsgcred = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmCreds(cred.into()) @@ -954,7 +946,7 @@ impl ControlMessageOwned { let tv: libc::timeval = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmTimestamp(TimeVal::from(tv)) }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] (libc::SOL_SOCKET, libc::SCM_TIMESTAMPNS) => { let ts: libc::timespec = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmTimestampns(TimeSpec::from(ts)) @@ -969,7 +961,7 @@ impl ControlMessageOwned { let ts: libc::timespec = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::ScmMonotonic(TimeSpec::from(ts)) } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] (libc::SOL_SOCKET, libc::SCM_TIMESTAMPING) => { let tp = p as *const libc::timespec; let ts: libc::timespec = unsafe { ptr::read_unaligned(tp) }; @@ -1042,13 +1034,13 @@ impl ControlMessageOwned { let drop_counter = unsafe { ptr::read_unaligned(p as *const u32) }; ControlMessageOwned::RxqOvfl(drop_counter) }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVERR) => { let (err, addr) = unsafe { Self::recv_err_helper::(p, len) }; ControlMessageOwned::Ipv4RecvErr(err, addr) }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_RECVERR) => { let (err, addr) = unsafe { Self::recv_err_helper::(p, len) }; @@ -1073,7 +1065,7 @@ impl ControlMessageOwned { } } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[cfg(feature = "net")] #[allow(clippy::cast_ptr_alignment)] // False positive unsafe fn recv_err_helper(p: *mut libc::c_uchar, len: usize) -> (libc::sock_extended_err, Option) { @@ -1124,7 +1116,7 @@ pub enum ControlMessage<'a> { /// /// For further information, please refer to the /// [`unix(7)`](https://man7.org/linux/man-pages/man7/unix.7.html) man page. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ScmCredentials(&'a UnixCredentials), /// A message of type `SCM_CREDS`, containing the pid, uid, euid, gid and groups of /// a process connected to the socket. @@ -1138,7 +1130,7 @@ pub enum ControlMessage<'a> { /// /// For further information, please refer to the /// [`unix(4)`](https://www.freebsd.org/cgi/man.cgi?query=unix) man page. - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ScmCreds, /// Set IV for `AF_ALG` crypto API. @@ -1284,18 +1276,18 @@ impl<'a> ControlMessage<'a> { ControlMessage::ScmRights(fds) => { fds as *const _ as *const u8 }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::ScmCredentials(creds) => { &creds.0 as *const libc::ucred as *const u8 } - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ControlMessage::ScmCreds => { // The kernel overwrites the data, we just zero it // to make sure it's not uninitialized memory unsafe { ptr::write_bytes(cmsg_data, 0, self.len()) }; return } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetIv(iv) => { #[allow(deprecated)] // https://github.com/rust-lang/libc/issues/1501 let af_alg_iv = libc::af_alg_iv { @@ -1320,11 +1312,11 @@ impl<'a> ControlMessage<'a> { return }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetOp(op) => { op as *const _ as *const u8 }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetAeadAssoclen(len) => { len as *const _ as *const u8 }, @@ -1375,23 +1367,23 @@ impl<'a> ControlMessage<'a> { ControlMessage::ScmRights(fds) => { mem::size_of_val(fds) }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::ScmCredentials(creds) => { mem::size_of_val(creds) } - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ControlMessage::ScmCreds => { mem::size_of::() } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetIv(iv) => { mem::size_of::<&[u8]>() + iv.len() }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetOp(op) => { mem::size_of_val(op) }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetAeadAssoclen(len) => { mem::size_of_val(len) }, @@ -1435,11 +1427,11 @@ impl<'a> ControlMessage<'a> { fn cmsg_level(&self) -> libc::c_int { match *self { ControlMessage::ScmRights(_) => libc::SOL_SOCKET, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::ScmCredentials(_) => libc::SOL_SOCKET, - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ControlMessage::ScmCreds => libc::SOL_SOCKET, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetIv(_) | ControlMessage::AlgSetOp(_) | ControlMessage::AlgSetAeadAssoclen(_) => libc::SOL_ALG, #[cfg(target_os = "linux")] @@ -1474,19 +1466,19 @@ impl<'a> ControlMessage<'a> { fn cmsg_type(&self) -> libc::c_int { match *self { ControlMessage::ScmRights(_) => libc::SCM_RIGHTS, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::ScmCredentials(_) => libc::SCM_CREDENTIALS, - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ControlMessage::ScmCreds => libc::SCM_CREDS, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetIv(_) => { libc::ALG_SET_IV }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetOp(_) => { libc::ALG_SET_OP }, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessage::AlgSetAeadAssoclen(_) => { libc::ALG_SET_AEAD_ASSOCLEN }, diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index e2f8a5a860..520d2351c7 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -261,7 +261,7 @@ sockopt_impl!( libc::SO_REUSEADDR, bool ); -#[cfg(not(any(target_os = "illumos", target_os = "solaris")))] +#[cfg(not(solarish))] sockopt_impl!( /// Permits multiple AF_INET or AF_INET6 sockets to be bound to an /// identical socket address. @@ -318,7 +318,7 @@ sockopt_impl!( super::IpMembershipRequest ); cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -329,12 +329,8 @@ cfg_if! { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Leave an IPv6 multicast group. Ipv6DropMembership, SetOnly, libc::IPPROTO_IPV6, libc::IPV6_DROP_MEMBERSHIP, super::Ipv6MembershipRequest); - } else if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + } else if #[cfg(any(bsd, target_os = "illumos", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris"))] { #[cfg(feature = "net")] sockopt_impl!( @@ -476,7 +472,7 @@ sockopt_impl!( libc::SO_KEEPALIVE, bool ); -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", apple_targets))] +#[cfg(any(freebsdlike, apple_targets))] sockopt_impl!( /// Get the credentials of the peer process of a connected unix domain /// socket. @@ -495,7 +491,7 @@ sockopt_impl!( libc::LOCAL_PEERPID, libc::c_int ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Return the credentials of the foreign process connected to this socket. PeerCredentials, @@ -534,7 +530,7 @@ sockopt_impl!( u32 ); cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { sockopt_impl!( /// The maximum segment size for outgoing TCP packets. TcpMaxSeg, Both, libc::IPPROTO_TCP, libc::TCP_MAXSEG, u32); @@ -614,7 +610,7 @@ sockopt_impl!( libc::SO_SNDBUF, usize ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Using this socket option, a privileged (`CAP_NET_ADMIN`) process can /// perform the same task as `SO_RCVBUF`, but the `rmem_max limit` can be @@ -625,7 +621,7 @@ sockopt_impl!( libc::SO_RCVBUFFORCE, usize ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Using this socket option, a privileged (`CAP_NET_ADMIN`) process can /// perform the same task as `SO_SNDBUF`, but the `wmem_max` limit can be @@ -654,7 +650,7 @@ sockopt_impl!( libc::SO_ACCEPTCONN, bool ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Bind this socket to a particular device like “eth0”. BindToDevice, @@ -663,7 +659,7 @@ sockopt_impl!( libc::SO_BINDTODEVICE, OsString<[u8; libc::IFNAMSIZ]> ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -675,7 +671,7 @@ sockopt_impl!( libc::SO_ORIGINAL_DST, libc::sockaddr_in ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( #[allow(missing_docs)] // Not documented by Linux! @@ -685,7 +681,7 @@ sockopt_impl!( libc::IP6T_SO_ORIGINAL_DST, libc::sockaddr_in6 ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Specifies exact type of timestamping information collected by the kernel /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) @@ -704,7 +700,7 @@ sockopt_impl!( libc::SO_TIMESTAMP, bool ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Enable or disable the receiving of the `SO_TIMESTAMPNS` control message. ReceiveTimestampns, @@ -723,7 +719,7 @@ sockopt_impl!( libc::SO_TS_CLOCK, super::SocketTimestamp ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -808,7 +804,7 @@ sockopt_impl!( libc::SO_MARK, u32 ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Enable or disable the receiving of the `SCM_CREDENTIALS` control /// message. @@ -967,7 +963,7 @@ sockopt_impl!( libc::IPV6_V6ONLY, bool ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Enable extended reliable error message passing. Ipv4RecvErr, @@ -976,7 +972,7 @@ sockopt_impl!( libc::IP_RECVERR, bool ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Control receiving of asynchronous error options. Ipv6RecvErr, @@ -985,7 +981,7 @@ sockopt_impl!( libc::IPV6_RECVERR, bool ); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] sockopt_impl!( /// Fetch the current system-estimated Path MTU. IpMtu, @@ -1046,13 +1042,13 @@ sockopt_impl!( #[allow(missing_docs)] // Not documented by Linux! -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[derive(Copy, Clone, Debug)] pub struct AlgSetAeadAuthSize; // ALG_SET_AEAD_AUTH_SIZE read the length from passed `option_len` // See https://elixir.bootlin.com/linux/v4.4/source/crypto/af_alg.c#L222 -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] impl SetSockOpt for AlgSetAeadAuthSize { type Val = usize; @@ -1072,18 +1068,18 @@ impl SetSockOpt for AlgSetAeadAuthSize { #[allow(missing_docs)] // Not documented by Linux! -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[derive(Clone, Debug)] pub struct AlgSetKey(::std::marker::PhantomData); -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] impl Default for AlgSetKey { fn default() -> Self { AlgSetKey(Default::default()) } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] impl SetSockOpt for AlgSetKey where T: AsRef<[u8]> + Clone, @@ -1394,7 +1390,7 @@ impl<'a> Set<'a, OsString> for SetOsString<'a> { #[cfg(test)] mod test { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] #[test] fn can_get_peercred_on_unix_socket() { use super::super::*; diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 84a14f53d3..dc40907f47 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -74,13 +74,7 @@ pub type type_of_file_flag = c_uint; ))] pub type type_of_file_flag = c_ulong; -#[cfg(any( - target_os = "openbsd", - target_os = "netbsd", - target_os = "freebsd", - target_os = "dragonfly", - apple_targets -))] +#[cfg(bsd)] libc_bitflags! { /// File flags. pub struct FileFlag: type_of_file_flag { @@ -99,7 +93,7 @@ libc_bitflags! { #[cfg(any(target_os = "dragonfly"))] SF_NOHISTORY; /// The file may not be renamed or deleted. - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] SF_NOUNLINK; /// Mask of superuser changeable flags SF_SETTABLE; @@ -135,7 +129,7 @@ libc_bitflags! { #[cfg(any(target_os = "dragonfly"))] UF_NOHISTORY; /// The file may not be renamed or deleted. - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] UF_NOUNLINK; /// The file is offline, or has the Windows and CIFS /// `FILE_ATTRIBUTE_OFFLINE` attribute. diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index a98909b61e..22e9a26ce0 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -92,200 +92,200 @@ pub struct FsType(pub fs_type_t); // These constants are defined without documentation in the Linux headers, so we // can't very well document them here. -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const ADFS_SUPER_MAGIC: FsType = FsType(libc::ADFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const AFFS_SUPER_MAGIC: FsType = FsType(libc::AFFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const AFS_SUPER_MAGIC: FsType = FsType(libc::AFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const AUTOFS_SUPER_MAGIC: FsType = FsType(libc::AUTOFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const BPF_FS_MAGIC: FsType = FsType(libc::BPF_FS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const BTRFS_SUPER_MAGIC: FsType = FsType(libc::BTRFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const CGROUP2_SUPER_MAGIC: FsType = FsType(libc::CGROUP2_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const CGROUP_SUPER_MAGIC: FsType = FsType(libc::CGROUP_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const CODA_SUPER_MAGIC: FsType = FsType(libc::CODA_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const CRAMFS_MAGIC: FsType = FsType(libc::CRAMFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const DEBUGFS_MAGIC: FsType = FsType(libc::DEBUGFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const DEVPTS_SUPER_MAGIC: FsType = FsType(libc::DEVPTS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const ECRYPTFS_SUPER_MAGIC: FsType = FsType(libc::ECRYPTFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const EFS_SUPER_MAGIC: FsType = FsType(libc::EFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const EXT2_SUPER_MAGIC: FsType = FsType(libc::EXT2_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const EXT3_SUPER_MAGIC: FsType = FsType(libc::EXT3_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const EXT4_SUPER_MAGIC: FsType = FsType(libc::EXT4_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const F2FS_SUPER_MAGIC: FsType = FsType(libc::F2FS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const FUSE_SUPER_MAGIC: FsType = FsType(libc::FUSE_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const FUTEXFS_SUPER_MAGIC: FsType = FsType(libc::FUTEXFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const HOSTFS_SUPER_MAGIC: FsType = FsType(libc::HOSTFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const HPFS_SUPER_MAGIC: FsType = FsType(libc::HPFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const HUGETLBFS_MAGIC: FsType = FsType(libc::HUGETLBFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const ISOFS_SUPER_MAGIC: FsType = FsType(libc::ISOFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const JFFS2_SUPER_MAGIC: FsType = FsType(libc::JFFS2_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const MINIX2_SUPER_MAGIC2: FsType = FsType(libc::MINIX2_SUPER_MAGIC2 as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const MINIX2_SUPER_MAGIC: FsType = FsType(libc::MINIX2_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const MINIX3_SUPER_MAGIC: FsType = FsType(libc::MINIX3_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const MINIX_SUPER_MAGIC2: FsType = FsType(libc::MINIX_SUPER_MAGIC2 as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const MINIX_SUPER_MAGIC: FsType = FsType(libc::MINIX_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const MSDOS_SUPER_MAGIC: FsType = FsType(libc::MSDOS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const NCP_SUPER_MAGIC: FsType = FsType(libc::NCP_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const NFS_SUPER_MAGIC: FsType = FsType(libc::NFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const NILFS_SUPER_MAGIC: FsType = FsType(libc::NILFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const OCFS2_SUPER_MAGIC: FsType = FsType(libc::OCFS2_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const OPENPROM_SUPER_MAGIC: FsType = FsType(libc::OPENPROM_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const OVERLAYFS_SUPER_MAGIC: FsType = FsType(libc::OVERLAYFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const PROC_SUPER_MAGIC: FsType = FsType(libc::PROC_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const QNX4_SUPER_MAGIC: FsType = FsType(libc::QNX4_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const QNX6_SUPER_MAGIC: FsType = FsType(libc::QNX6_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const RDTGROUP_SUPER_MAGIC: FsType = FsType(libc::RDTGROUP_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const REISERFS_SUPER_MAGIC: FsType = FsType(libc::REISERFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const SECURITYFS_MAGIC: FsType = FsType(libc::SECURITYFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const SELINUX_MAGIC: FsType = FsType(libc::SELINUX_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const SMACK_MAGIC: FsType = FsType(libc::SMACK_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const SMB_SUPER_MAGIC: FsType = FsType(libc::SMB_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const SYSFS_MAGIC: FsType = FsType(libc::SYSFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const TMPFS_MAGIC: FsType = FsType(libc::TMPFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const TRACEFS_MAGIC: FsType = FsType(libc::TRACEFS_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const UDF_SUPER_MAGIC: FsType = FsType(libc::UDF_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const USBDEVICE_SUPER_MAGIC: FsType = FsType(libc::USBDEVICE_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const XENFS_SUPER_MAGIC: FsType = FsType(libc::XENFS_SUPER_MAGIC as fs_type_t); -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[allow(missing_docs)] pub const NSFS_MAGIC: FsType = FsType(libc::NSFS_MAGIC as fs_type_t); #[cfg(all( diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 88fb2cd4ec..1b2cb5ea50 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -21,16 +21,16 @@ libc_bitflags!( #[cfg(not(target_os = "haiku"))] ST_NOSUID; /// Do not interpret character or block-special devices - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ST_NODEV; /// Do not allow execution of binaries on the filesystem - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ST_NOEXEC; /// All IO should be done synchronously - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ST_SYNCHRONOUS; /// Allow mandatory locks on the filesystem - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ST_MANDLOCK; /// Write on file/directory/symlink #[cfg(target_os = "linux")] @@ -42,10 +42,10 @@ libc_bitflags!( #[cfg(target_os = "linux")] ST_IMMUTABLE; /// Do not update access times on files - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ST_NOATIME; /// Do not update access times on files - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ST_NODIRATIME; /// Update access time relative to modify/change time #[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"))))] diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 6620cd6a14..0a88ca697b 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -85,26 +85,8 @@ //! //! On non-BSDs, `cfgetispeed()` and `cfgetospeed()` both return a `BaudRate`: //! -#![cfg_attr( - any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ), - doc = " ```rust,ignore" -)] -#![cfg_attr( - not(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - )), - doc = " ```rust" -)] +#![cfg_attr(bsd, doc = " ```rust,ignore")] +#![cfg_attr(not(bsd), doc = " ```rust")] //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfgetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -116,26 +98,8 @@ //! //! But on the BSDs, `cfgetispeed()` and `cfgetospeed()` both return `u32`s: //! -#![cfg_attr( - any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ), - doc = " ```rust" -)] -#![cfg_attr( - not(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - )), - doc = " ```rust,ignore" -)] +#![cfg_attr(bsd, doc = " ```rust")] +#![cfg_attr(not(bsd), doc = " ```rust,ignore")] //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfgetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -147,26 +111,8 @@ //! //! It's trivial to convert from a `BaudRate` to a `u32` on BSDs: //! -#![cfg_attr( - any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ), - doc = " ```rust" -)] -#![cfg_attr( - not(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - )), - doc = " ```rust,ignore" -)] +#![cfg_attr(bsd, doc = " ```rust")] +#![cfg_attr(not(bsd), doc = " ```rust,ignore")] //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -179,26 +125,8 @@ //! And on BSDs you can specify arbitrary baud rates (**note** this depends on hardware support) //! by specifying baud rates directly using `u32`s: //! -#![cfg_attr( - any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - ), - doc = " ```rust" -)] -#![cfg_attr( - not(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" - )), - doc = " ```rust,ignore" -)] +#![cfg_attr(bsd, doc = " ```rust")] +#![cfg_attr(not(bsd), doc = " ```rust,ignore")] //! # use nix::sys::termios::{cfsetispeed, cfsetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -396,11 +324,11 @@ libc_enum! { B76800, #[cfg(not(target_os = "aix"))] B115200, - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] B153600, #[cfg(not(target_os = "aix"))] B230400, - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] B307200, #[cfg(any(target_os = "android", target_os = "freebsd", @@ -409,9 +337,9 @@ libc_enum! { target_os = "netbsd", target_os = "solaris"))] B460800, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] B500000, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] B576000, #[cfg(any(target_os = "android", target_os = "freebsd", @@ -420,13 +348,13 @@ libc_enum! { target_os = "netbsd", target_os = "solaris"))] B921600, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] B1000000, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] B1152000, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] B1500000, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] B2000000, #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "sparc64"))))] B2500000, @@ -440,13 +368,7 @@ libc_enum! { impl TryFrom } -#[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(bsd)] impl From for u32 { fn from(b: BaudRate) -> u32 { b as u32 @@ -690,7 +612,7 @@ libc_bitflags! { target_os = "linux", apple_targets))] TAB3 as tcflag_t; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] XTABS; #[cfg(any(target_os = "android", target_os = "haiku", @@ -722,11 +644,7 @@ libc_bitflags! { target_os = "linux", apple_targets))] FF1 as tcflag_t; - #[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] OXTABS; #[cfg(any(target_os = "freebsd", target_os = "dragonfly", @@ -776,11 +694,7 @@ libc_bitflags! { libc_bitflags! { /// Flags for setting the control mode of a terminal pub struct ControlFlags: tcflag_t { - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] CIGNORE; CS5; CS6; @@ -794,7 +708,7 @@ libc_bitflags! { CLOCAL; #[cfg(not(any(target_os = "redox", target_os = "aix")))] CRTSCTS; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] CBAUD; #[cfg(any(target_os = "android", all(target_os = "linux", not(target_arch = "mips"))))] CMSPAR; @@ -802,7 +716,7 @@ libc_bitflags! { all(target_os = "linux", not(any(target_arch = "powerpc", target_arch = "powerpc64")))))] CIBAUD; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] CBAUDEX; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", @@ -855,11 +769,7 @@ libc_bitflags! { ECHOCTL; ISIG; ICANON; - #[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] ALTWERASE; IEXTEN; #[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "aix")))] @@ -867,11 +777,7 @@ libc_bitflags! { TOSTOP; #[cfg(not(target_os = "redox"))] FLUSHO; - #[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(bsd)] NOKERNINFO; #[cfg(not(target_os = "redox"))] PENDIN; @@ -880,11 +786,7 @@ libc_bitflags! { } cfg_if! { - if #[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] { + if #[cfg(bsd)] { /// Get input baud rate (see /// [cfgetispeed(3p)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/cfgetispeed.html)). /// diff --git a/src/sys/time.rs b/src/sys/time.rs index a0160e21ff..86cf000295 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -88,7 +88,7 @@ pub(crate) mod timer { Interval(TimeSpec), } - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] bitflags! { /// Flags that are used for arming the timer. #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] diff --git a/src/sys/uio.rs b/src/sys/uio.rs index 7b9d844256..e893cb42f7 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -149,7 +149,7 @@ pub fn pread(fd: Fd, buf: &mut [u8], offset: off_t) -> Result { /// therefore not represented in Rust by an actual slice as `IoSlice` is. It /// is used with [`process_vm_readv`](fn.process_vm_readv.html) /// and [`process_vm_writev`](fn.process_vm_writev.html). -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[repr(C)] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct RemoteIoVec { diff --git a/src/sys/utsname.rs b/src/sys/utsname.rs index a6d128bcd7..f07067b5b1 100644 --- a/src/sys/utsname.rs +++ b/src/sys/utsname.rs @@ -37,7 +37,7 @@ impl UtsName { } /// NIS or YP domain name of this machine. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] pub fn domainname(&self) -> &OsStr { cast_and_trim(&self.0.domainname) } diff --git a/src/sys/wait.rs b/src/sys/wait.rs index 65940713c3..299ea1bec9 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -98,14 +98,14 @@ pub enum WaitStatus { /// /// [`nix::sys::ptrace`]: ../ptrace/index.html /// [`ptrace`(2)]: https://man7.org/linux/man-pages/man2/ptrace.2.html - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] PtraceEvent(Pid, Signal, c_int), /// The traced process was stopped by execution of a system call, /// and `PTRACE_O_TRACESYSGOOD` is in effect. See [`ptrace`(2)] for /// more information. /// /// [`ptrace`(2)]: https://man7.org/linux/man-pages/man2/ptrace.2.html - #[cfg(any(target_os = "linux", target_os = "android"))] + #[cfg(linux_android)] PtraceSyscall(Pid), /// The process was previously stopped but has resumed execution /// after receiving a `SIGCONT` signal. This is only reported if @@ -128,7 +128,7 @@ impl WaitStatus { Some(p) } StillAlive => None, - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] PtraceEvent(p, _, _) | PtraceSyscall(p) => Some(p), } } @@ -162,7 +162,7 @@ fn stop_signal(status: i32) -> Result { Signal::try_from(libc::WSTOPSIG(status)) } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn syscall_stop(status: i32) -> bool { // From ptrace(2), setting PTRACE_O_TRACESYSGOOD has the effect // of delivering SIGTRAP | 0x80 as the signal number for syscall @@ -171,7 +171,7 @@ fn syscall_stop(status: i32) -> bool { libc::WSTOPSIG(status) == libc::SIGTRAP | 0x80 } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn stop_additional(status: i32) -> c_int { (status >> 16) as c_int } @@ -269,7 +269,7 @@ impl WaitStatus { WaitStatus::Stopped(pid, Signal::try_from(si_status)?) } libc::CLD_CONTINUED => WaitStatus::Continued(pid), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] libc::CLD_TRAPPED => { if si_status == libc::SIGTRAP | 0x80 { WaitStatus::PtraceSyscall(pid) @@ -343,7 +343,7 @@ pub enum Id<'fd> { /// If the PID is zero, the caller's process group is used since Linux 5.4. PGid(Pid), /// Wait for the child referred to by the given PID file descriptor - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] PIDFd(BorrowedFd<'fd>), /// A helper variant to resolve the unused parameter (`'fd`) problem on platforms /// other than Linux and Android. @@ -365,7 +365,7 @@ pub fn waitid(id: Id, flags: WaitPidFlag) -> Result { Id::All => (libc::P_ALL, 0), Id::Pid(pid) => (libc::P_PID, pid.as_raw() as libc::id_t), Id::PGid(pid) => (libc::P_PGID, pid.as_raw() as libc::id_t), - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] Id::PIDFd(fd) => (libc::P_PIDFD, fd.as_raw_fd() as libc::id_t), Id::_Unreachable(_) => { unreachable!("This variant could never be constructed") diff --git a/src/time.rs b/src/time.rs index ba7fc9f586..cdcad0977d 100644 --- a/src/time.rs +++ b/src/time.rs @@ -86,10 +86,10 @@ impl ClockId { ))] pub const CLOCK_MONOTONIC_COARSE: ClockId = ClockId(libc::CLOCK_MONOTONIC_COARSE); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_MONOTONIC_FAST: ClockId = ClockId(libc::CLOCK_MONOTONIC_FAST); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_MONOTONIC_PRECISE: ClockId = ClockId(libc::CLOCK_MONOTONIC_PRECISE); #[cfg(any( @@ -111,7 +111,7 @@ impl ClockId { ))] pub const CLOCK_PROCESS_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_PROCESS_CPUTIME_ID); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_PROF: ClockId = ClockId(libc::CLOCK_PROF); pub const CLOCK_REALTIME: ClockId = ClockId(libc::CLOCK_REALTIME); #[cfg(any( @@ -130,12 +130,12 @@ impl ClockId { ))] pub const CLOCK_REALTIME_COARSE: ClockId = ClockId(libc::CLOCK_REALTIME_COARSE); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_REALTIME_FAST: ClockId = ClockId(libc::CLOCK_REALTIME_FAST); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_REALTIME_PRECISE: ClockId = ClockId(libc::CLOCK_REALTIME_PRECISE); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_SECOND: ClockId = ClockId(libc::CLOCK_SECOND); #[cfg(any( target_os = "emscripten", @@ -161,14 +161,14 @@ impl ClockId { ))] pub const CLOCK_THREAD_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_THREAD_CPUTIME_ID); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_UPTIME: ClockId = ClockId(libc::CLOCK_UPTIME); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_UPTIME_FAST: ClockId = ClockId(libc::CLOCK_UPTIME_FAST); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_UPTIME_PRECISE: ClockId = ClockId(libc::CLOCK_UPTIME_PRECISE); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] pub const CLOCK_VIRTUAL: ClockId = ClockId(libc::CLOCK_VIRTUAL); } diff --git a/src/unistd.rs b/src/unistd.rs index 1148eeb977..6320d3c1b7 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -13,16 +13,7 @@ use crate::fcntl::AtFlags; #[cfg(feature = "fs")] use crate::fcntl::{fcntl, FcntlArg::F_SETFD, FdFlag, OFlag}; -#[cfg(all( - feature = "fs", - any( - target_os = "openbsd", - target_os = "netbsd", - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - ) -))] +#[cfg(all(feature = "fs", bsd))] use crate::sys::stat::FileFlag; #[cfg(feature = "fs")] use crate::sys::stat::Mode; @@ -44,7 +35,7 @@ use std::{fmt, mem, ptr}; feature! { #![feature = "fs"] - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] pub use self::pivot_root::*; } @@ -407,7 +398,7 @@ pub fn getpgrp() -> Pid { /// /// No error handling is required as a thread id should always exist for any /// process, even if threads are not being used. -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[inline] pub fn gettid() -> Pid { Pid(unsafe { libc::syscall(libc::SYS_gettid) as pid_t }) @@ -941,7 +932,7 @@ pub fn fexecve, SE: AsRef>( /// /// This function is similar to `execve`, except that the program to be executed /// is referenced as a file descriptor to the base directory plus a path. -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[inline] pub fn execveat, SE: AsRef>( dirfd: Option, @@ -1179,7 +1170,7 @@ pub fn lseek(fd: RawFd, offset: off_t, whence: Whence) -> Result { Errno::result(res).map(|r| r as off_t) } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] pub fn lseek64( fd: RawFd, offset: libc::off64_t, @@ -1534,7 +1525,7 @@ feature! { /// ID of the caller. /// /// See also [setfsuid(2)](https://man7.org/linux/man-pages/man2/setfsuid.2.html) -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] pub fn setfsuid(uid: Uid) -> Uid { let prev_fsuid = unsafe { libc::setfsuid(uid.into()) }; Uid::from_raw(prev_fsuid as uid_t) @@ -1545,7 +1536,7 @@ pub fn setfsuid(uid: Uid) -> Uid { /// ID of the caller. /// /// See also [setfsgid(2)](https://man7.org/linux/man-pages/man2/setfsgid.2.html) -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] pub fn setfsgid(gid: Gid) -> Gid { let prev_fsgid = unsafe { libc::setfsgid(gid.into()) }; Gid::from_raw(prev_fsgid as gid_t) @@ -1653,13 +1644,9 @@ pub fn getgroups() -> Result> { )))] pub fn setgroups(groups: &[Gid]) -> Result<()> { cfg_if! { - if #[cfg(any(target_os = "aix", - target_os = "dragonfly", - target_os = "freebsd", + if #[cfg(any(bsd, + target_os = "aix", target_os = "illumos", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris"))] { type setgroups_ngroups_t = c_int; } else { @@ -2315,13 +2302,9 @@ pub enum SysconfVar { #[cfg(not(any(target_os = "redox", target_os = "haiku")))] EXPR_NEST_MAX = libc::_SC_EXPR_NEST_MAX, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris" ))] /// Maximum length of a host name (not including the terminating null) as @@ -2367,13 +2350,9 @@ pub enum SysconfVar { /// The implementation supports the Advisory Information option. _POSIX_ADVISORY_INFO = libc::_SC_ADVISORY_INFO, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris" ))] /// The implementation supports barriers. @@ -2382,25 +2361,17 @@ pub enum SysconfVar { #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX_ASYNCHRONOUS_IO = libc::_SC_ASYNCHRONOUS_IO, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris" ))] /// The implementation supports clock selection. _POSIX_CLOCK_SELECTION = libc::_SC_CLOCK_SELECTION, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris" ))] /// The implementation supports the Process CPU-Time Clocks option. @@ -2467,13 +2438,9 @@ pub enum SysconfVar { /// The implementation supports the Raw Sockets option. _POSIX_RAW_SOCKETS = libc::_SC_RAW_SOCKETS, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris" ))] /// The implementation supports read-write locks. @@ -2489,13 +2456,9 @@ pub enum SysconfVar { /// The implementation supports realtime signals. _POSIX_REALTIME_SIGNALS = libc::_SC_REALTIME_SIGNALS, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + bsd, target_os = "illumos", - apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "solaris" ))] /// The implementation supports the Regular Expression Handling option. @@ -2509,34 +2472,13 @@ pub enum SysconfVar { /// The implementation supports the Shared Memory Objects option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX_SHARED_MEMORY_OBJECTS = libc::_SC_SHARED_MEMORY_OBJECTS, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux",))] /// The implementation supports the POSIX shell. _POSIX_SHELL = libc::_SC_SHELL, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux",))] /// The implementation supports the Spawn option. _POSIX_SPAWN = libc::_SC_SPAWN, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux",))] /// The implementation supports spin locks. _POSIX_SPIN_LOCKS = libc::_SC_SPIN_LOCKS, #[cfg(any( @@ -2581,14 +2523,7 @@ pub enum SysconfVar { /// The implementation supports the Thread Execution Scheduling option. #[cfg(not(target_os = "redox"))] _POSIX_THREAD_PRIORITY_SCHEDULING = libc::_SC_THREAD_PRIORITY_SCHEDULING, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Thread Process-Shared Synchronization /// option. _POSIX_THREAD_PROCESS_SHARED = libc::_SC_THREAD_PROCESS_SHARED, @@ -2706,48 +2641,20 @@ pub enum SysconfVar { /// to which the implementation conforms. For implementations conforming to /// POSIX.1-2008, the value shall be 200809L. _POSIX_VERSION = libc::_SC_VERSION, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation provides a C-language compilation environment with /// 32-bit `int`, `long`, `pointer`, and `off_t` types. _POSIX_V6_ILP32_OFF32 = libc::_SC_V6_ILP32_OFF32, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation provides a C-language compilation environment with /// 32-bit `int`, `long`, and pointer types and an `off_t` type using at /// least 64 bits. _POSIX_V6_ILP32_OFFBIG = libc::_SC_V6_ILP32_OFFBIG, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation provides a C-language compilation environment with /// 32-bit `int` and 64-bit `long`, `pointer`, and `off_t` types. _POSIX_V6_LP64_OFF64 = libc::_SC_V6_LP64_OFF64, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation provides a C-language compilation environment with an /// `int` type using at least 32 bits and `long`, pointer, and `off_t` types /// using at least 64 bits. @@ -2771,65 +2678,23 @@ pub enum SysconfVar { /// utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX2_LOCALEDEF = libc::_SC_2_LOCALEDEF, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Batch Environment Services and Utilities /// option. _POSIX2_PBS = libc::_SC_2_PBS, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Batch Accounting option. _POSIX2_PBS_ACCOUNTING = libc::_SC_2_PBS_ACCOUNTING, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Batch Checkpoint/Restart option. _POSIX2_PBS_CHECKPOINT = libc::_SC_2_PBS_CHECKPOINT, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Locate Batch Job Request option. _POSIX2_PBS_LOCATE = libc::_SC_2_PBS_LOCATE, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Batch Job Message Request option. _POSIX2_PBS_MESSAGE = libc::_SC_2_PBS_MESSAGE, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] /// The implementation supports the Track Batch Job Request option. _POSIX2_PBS_TRACK = libc::_SC_2_PBS_TRACK, /// The implementation supports the Software Development Utilities option. @@ -2887,14 +2752,7 @@ pub enum SysconfVar { ))] SIGQUEUE_MAX = libc::_SC_SIGQUEUE_MAX, STREAM_MAX = libc::_SC_STREAM_MAX, - #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(bsd, target_os = "linux"))] SYMLOOP_MAX = libc::_SC_SYMLOOP_MAX, #[cfg(not(target_os = "redox"))] TIMER_MAX = libc::_SC_TIMER_MAX, @@ -2986,16 +2844,16 @@ pub enum SysconfVar { _XOPEN_VERSION = libc::_SC_XOPEN_VERSION, /// The number of pages of physical memory. Note that it is possible for /// the product of this value to overflow. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] _PHYS_PAGES = libc::_SC_PHYS_PAGES, /// The number of currently available pages of physical memory. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] _AVPHYS_PAGES = libc::_SC_AVPHYS_PAGES, /// The number of processors configured. - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] _NPROCESSORS_CONF = libc::_SC_NPROCESSORS_CONF, /// The number of processors currently online (available). - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] _NPROCESSORS_ONLN = libc::_SC_NPROCESSORS_ONLN, } @@ -3032,7 +2890,7 @@ pub fn sysconf(var: SysconfVar) -> Result> { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[cfg(feature = "fs")] mod pivot_root { use crate::errno::Errno; @@ -3463,7 +3321,7 @@ impl From for libc::passwd { pw_age: CString::new("").unwrap().into_raw(), #[cfg(target_os = "illumos")] pw_comment: CString::new("").unwrap().into_raw(), - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] pw_fields: 0, } } @@ -3763,13 +3621,7 @@ feature! { /// Get the effective user ID and group ID associated with a Unix domain socket. /// /// See also [getpeereid(3)](https://www.freebsd.org/cgi/man.cgi?query=getpeereid) -#[cfg(any( - apple_targets, - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly", -))] +#[cfg(bsd)] pub fn getpeereid(fd: F) -> Result<(Uid, Gid)> { let mut uid = 1; let mut gid = 1; diff --git a/test/common/mod.rs b/test/common/mod.rs index bb056aab87..7a9cc23e56 100644 --- a/test/common/mod.rs +++ b/test/common/mod.rs @@ -51,7 +51,7 @@ macro_rules! require_mount { }; } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[macro_export] macro_rules! skip_if_cirrus { ($reason:expr) => { diff --git a/test/sys/mod.rs b/test/sys/mod.rs index 43bb0bfaae..55dfa00023 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -29,7 +29,7 @@ mod test_socket; #[cfg(not(any(target_os = "redox")))] mod test_sockopt; mod test_stat; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod test_sysinfo; #[cfg(not(any( target_os = "redox", @@ -40,7 +40,7 @@ mod test_termios; mod test_uio; mod test_wait; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod test_epoll; #[cfg(target_os = "linux")] mod test_fanotify; @@ -57,5 +57,5 @@ mod test_pthread; target_os = "openbsd" ))] mod test_ptrace; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod test_timerfd; diff --git a/test/sys/test_ioctl.rs b/test/sys/test_ioctl.rs index 2062b25fb3..08843bf61c 100644 --- a/test/sys/test_ioctl.rs +++ b/test/sys/test_ioctl.rs @@ -28,7 +28,7 @@ ioctl_readwrite_buf!(readwritebuf_test, 0, 0, u32); // TODO: Need a way to compute these constants at test time. Using precomputed // values is fragile and needs to be maintained. -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] mod linux { // The cast is not unnecessary on all platforms. #[allow(clippy::unnecessary_cast)] @@ -148,13 +148,7 @@ mod linux { } } -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(bsd)] mod bsd { #[test] fn test_op_none() { @@ -162,7 +156,7 @@ mod bsd { assert_eq!(request_code_none!(b'a', 255), 0x2000_61FF); } - #[cfg(any(target_os = "dragonfly", target_os = "freebsd"))] + #[cfg(freebsdlike)] #[test] fn test_op_write_int() { assert_eq!(request_code_write_int!(b'v', 4), 0x2004_7604); @@ -206,7 +200,7 @@ mod bsd { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod linux_ioctls { use std::mem; use std::os::unix::io::AsRawFd; diff --git a/test/sys/test_ptrace.rs b/test/sys/test_ptrace.rs index 530560fe17..246b35445d 100644 --- a/test/sys/test_ptrace.rs +++ b/test/sys/test_ptrace.rs @@ -6,11 +6,11 @@ use memoffset::offset_of; use nix::errno::Errno; use nix::sys::ptrace; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] use nix::sys::ptrace::Options; use nix::unistd::getpid; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] use std::mem; use crate::*; @@ -28,7 +28,7 @@ fn test_ptrace() { // Just make sure ptrace_setoptions can be called at all, for now. #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptrace_setoptions() { require_capability!("test_ptrace_setoptions", CAP_SYS_PTRACE); let err = ptrace::setoptions(getpid(), Options::PTRACE_O_TRACESYSGOOD) @@ -38,7 +38,7 @@ fn test_ptrace_setoptions() { // Just make sure ptrace_getevent can be called at all, for now. #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptrace_getevent() { require_capability!("test_ptrace_getevent", CAP_SYS_PTRACE); let err = ptrace::getevent(getpid()).unwrap_err(); @@ -47,7 +47,7 @@ fn test_ptrace_getevent() { // Just make sure ptrace_getsiginfo can be called at all, for now. #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptrace_getsiginfo() { require_capability!("test_ptrace_getsiginfo", CAP_SYS_PTRACE); if let Err(Errno::EOPNOTSUPP) = ptrace::getsiginfo(getpid()) { @@ -57,7 +57,7 @@ fn test_ptrace_getsiginfo() { // Just make sure ptrace_setsiginfo can be called at all, for now. #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptrace_setsiginfo() { require_capability!("test_ptrace_setsiginfo", CAP_SYS_PTRACE); let siginfo = unsafe { mem::zeroed() }; diff --git a/test/sys/test_signal.rs b/test/sys/test_signal.rs index ca25ff9ab0..bf201ab800 100644 --- a/test/sys/test_signal.rs +++ b/test/sys/test_signal.rs @@ -124,7 +124,7 @@ fn test_signal() { raise(Signal::SIGINT).unwrap(); assert!(SIGNALED.load(Ordering::Relaxed)); - #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] + #[cfg(not(solarish))] assert_eq!( unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), handler @@ -132,7 +132,7 @@ fn test_signal() { // System V based OSes (e.g. illumos and Solaris) always resets the // disposition to SIG_DFL prior to calling the signal handler - #[cfg(any(target_os = "illumos", target_os = "solaris"))] + #[cfg(solarish)] assert_eq!( unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(), SigHandler::SigDfl diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 3959f3facf..1a9cdb465f 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1,4 +1,4 @@ -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] use crate::*; use libc::c_char; use nix::sys::socket::{getsockname, AddressFamily, UnixAddr}; @@ -224,7 +224,7 @@ pub fn test_addr_equality_path() { assert_eq!(calculate_hash(&addr1), calculate_hash(&addr2)); } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_abstract_sun_path_too_long() { let name = String::from("nix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0tesnix\0abstract\0testttttnix\0abstract\0test\0make\0sure\0this\0is\0long\0enough"); @@ -232,7 +232,7 @@ pub fn test_abstract_sun_path_too_long() { addr.expect_err("assertion failed"); } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_addr_equality_abstract() { let name = String::from("nix\0abstract\0test"); @@ -248,7 +248,7 @@ pub fn test_addr_equality_abstract() { } // Test getting/setting abstract addresses (without unix socket creation) -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_abstract_uds_addr() { let empty = String::new(); @@ -270,7 +270,7 @@ pub fn test_abstract_uds_addr() { } // Test getting an unnamed address (without unix socket creation) -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_unnamed_uds_addr() { use crate::nix::sys::socket::SockaddrLike; @@ -929,7 +929,7 @@ pub fn test_scm_rights() { } // Disable the test on emulated platforms due to not enabled support of AF_ALG in QEMU from rust cross -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[cfg_attr(qemu, ignore)] #[test] pub fn test_af_alg_cipher() { @@ -1022,7 +1022,7 @@ pub fn test_af_alg_cipher() { // Disable the test on emulated platforms due to not enabled support of AF_ALG // in QEMU from rust cross -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[cfg_attr(qemu, ignore)] #[test] pub fn test_af_alg_aead() { @@ -1441,7 +1441,7 @@ fn test_scm_credentials() { recvmsg, sendmsg, socketpair, AddressFamily, ControlMessage, ControlMessageOwned, MsgFlags, SockFlag, SockType, UnixCredentials, }; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] use nix::sys::socket::{setsockopt, sockopt::PassCred}; use nix::unistd::{getgid, getpid, getuid}; use std::io::{IoSlice, IoSliceMut}; @@ -1453,16 +1453,16 @@ fn test_scm_credentials() { SockFlag::empty(), ) .unwrap(); - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] setsockopt(&recv, PassCred, &true).unwrap(); { let iov = [IoSlice::new(b"hello")]; - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] let cred = UnixCredentials::new(); - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] let cmsg = ControlMessage::ScmCredentials(&cred); - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] let cmsg = ControlMessage::ScmCreds; assert_eq!( sendmsg::<()>( @@ -1493,9 +1493,9 @@ fn test_scm_credentials() { for cmsg in msg.cmsgs() { let cred = match cmsg { - #[cfg(any(target_os = "android", target_os = "linux"))] + #[cfg(linux_android)] ControlMessageOwned::ScmCredentials(cred) => cred, - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] ControlMessageOwned::ScmCreds(cred) => cred, other => panic!("unexpected cmsg {other:?}"), }; @@ -1515,7 +1515,7 @@ fn test_scm_credentials() { /// Ensure that we can send `SCM_CREDENTIALS` and `SCM_RIGHTS` with a single /// `sendmsg` call. -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] // qemu's handling of multiple cmsgs is bugged, ignore tests under emulation // see https://bugs.launchpad.net/qemu/+bug/1781280 #[cfg_attr(qemu, ignore)] @@ -1527,7 +1527,7 @@ fn test_scm_credentials_and_rights() { /// Ensure that passing a an oversized control message buffer to recvmsg /// still works. -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] // qemu's handling of multiple cmsgs is bugged, ignore tests under emulation // see https://bugs.launchpad.net/qemu/+bug/1781280 #[cfg_attr(qemu, ignore)] @@ -1537,7 +1537,7 @@ fn test_too_large_cmsgspace() { test_impl_scm_credentials_and_rights(space); } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_impl_scm_credentials_and_rights(mut space: Vec) { use libc::ucred; use nix::sys::socket::sockopt::PassCred; @@ -1676,7 +1676,7 @@ pub fn test_named_unixdomain() { } // Test using unnamed unix domain addresses -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_unnamed_unixdomain() { use nix::sys::socket::{getsockname, socketpair}; @@ -1696,7 +1696,7 @@ pub fn test_unnamed_unixdomain() { } // Test creating and using unnamed unix domain addresses for autobinding sockets -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_unnamed_unixdomain_autobind() { use nix::sys::socket::{bind, getsockname, socket}; @@ -2269,7 +2269,7 @@ pub fn test_recv_ipv6pktinfo() { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] pub fn test_vsock() { use nix::sys::socket::SockaddrLike; @@ -2809,7 +2809,7 @@ pub fn test_txtime() { } // cfg needed for capability check. -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] fn test_icmp_protocol() { use nix::sys::socket::{ diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 0107deec36..6f9e3f0447 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -1,4 +1,4 @@ -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] use crate::*; use nix::sys::socket::{ getsockopt, setsockopt, socket, sockopt, AddressFamily, SockFlag, @@ -8,7 +8,7 @@ use rand::{thread_rng, Rng}; use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd}; // NB: FreeBSD supports LOCAL_PEERCRED for SOCK_SEQPACKET, but OSX does not. -#[cfg(any(target_os = "dragonfly", target_os = "freebsd",))] +#[cfg(freebsdlike)] #[test] pub fn test_local_peercred_seqpacket() { use nix::{ @@ -29,7 +29,7 @@ pub fn test_local_peercred_seqpacket() { assert_eq!(Gid::from_raw(xucred.groups()[0]), Gid::current()); } -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", apple_targets))] +#[cfg(any(freebsdlike, apple_targets))] #[test] pub fn test_local_peercred_stream() { use nix::{ @@ -224,7 +224,7 @@ fn test_tcp_congestion() { } #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_bindtodevice() { skip_if_not_root!("test_bindtodevice"); @@ -276,7 +276,7 @@ fn test_so_tcp_keepalive() { } #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[cfg_attr(qemu, ignore)] fn test_get_mtu() { use nix::sys::socket::{bind, connect, SockaddrIn}; diff --git a/test/sys/test_wait.rs b/test/sys/test_wait.rs index 43fa05dbbf..365b0165f8 100644 --- a/test/sys/test_wait.rs +++ b/test/sys/test_wait.rs @@ -150,7 +150,7 @@ fn test_waitid_pid() { } } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] // FIXME: qemu-user doesn't implement ptrace on most arches #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] mod ptrace { diff --git a/test/test.rs b/test/test.rs index c8c9bf1aa7..41c3dce8e6 100644 --- a/test/test.rs +++ b/test/test.rs @@ -8,7 +8,7 @@ mod sys; #[cfg(not(target_os = "redox"))] mod test_dir; mod test_fcntl; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] mod test_kmod; #[cfg(any( target_os = "dragonfly", diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 112d03a38a..788b7a8a0d 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -272,7 +272,7 @@ fn test_copy_file_range() { assert_eq!(from_offset, 6); } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] mod linux_android { use libc::loff_t; use std::io::prelude::*; diff --git a/test/test_net.rs b/test/test_net.rs index c44655a4c9..00708ace38 100644 --- a/test/test_net.rs +++ b/test/test_net.rs @@ -1,6 +1,6 @@ use nix::net::if_::*; -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] const LOOPBACK: &[u8] = b"lo"; #[cfg(not(any( diff --git a/test/test_pty.rs b/test/test_pty.rs index 9b5c500e45..ae4127e481 100644 --- a/test/test_pty.rs +++ b/test/test_pty.rs @@ -12,7 +12,7 @@ use nix::unistd::{pause, write}; /// Test equivalence of `ptsname` and `ptsname_r` #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptsname_equivalence() { let _m = crate::PTSNAME_MTX.lock(); @@ -29,7 +29,7 @@ fn test_ptsname_equivalence() { /// Test data copying of `ptsname` // TODO need to run in a subprocess, since ptsname is non-reentrant #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptsname_copy() { let _m = crate::PTSNAME_MTX.lock(); @@ -47,7 +47,7 @@ fn test_ptsname_copy() { /// Test data copying of `ptsname_r` #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptsname_r_copy() { // Open a new PTTY master let master_fd = posix_openpt(OFlag::O_RDWR).unwrap(); @@ -61,7 +61,7 @@ fn test_ptsname_r_copy() { /// Test that `ptsname` returns different names for different devices #[test] -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] fn test_ptsname_unique() { let _m = crate::PTSNAME_MTX.lock(); diff --git a/test/test_sendfile.rs b/test/test_sendfile.rs index 99493f0a60..e6152c5dee 100644 --- a/test/test_sendfile.rs +++ b/test/test_sendfile.rs @@ -18,7 +18,7 @@ cfg_if! { } } -#[cfg(any(target_os = "android", target_os = "linux"))] +#[cfg(linux_android)] #[test] fn test_sendfile_linux() { const CONTENTS: &[u8] = b"abcdef123456"; diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 44cf460253..5a58585e7d 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -217,7 +217,7 @@ fn test_getsid() { assert_eq!(none_sid, pid_sid); } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] mod linux_android { use nix::unistd::gettid; @@ -558,7 +558,7 @@ fn test_lseek() { assert_eq!(b"f123456", &buf); } -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[test] fn test_lseek64() { const CONTENTS: &[u8] = b"abcdef123456"; @@ -1170,7 +1170,7 @@ fn test_user_into_passwd() { } /// Tests setting the filesystem UID with `setfsuid`. -#[cfg(any(target_os = "linux", target_os = "android"))] +#[cfg(linux_android)] #[test] fn test_setfsuid() { use std::os::unix::fs::PermissionsExt; @@ -1241,13 +1241,7 @@ fn test_ttyname_not_pty() { } #[test] -#[cfg(any( - apple_targets, - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd", - target_os = "dragonfly", -))] +#[cfg(bsd)] fn test_getpeereid() { use std::os::unix::net::UnixStream; let (sock_a, sock_b) = UnixStream::pair().unwrap(); From 57f90c7737833e12a928daecc31c0cd41c2e780d Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sat, 25 Nov 2023 16:21:20 +0800 Subject: [PATCH 052/140] fix: fix wrong solaris alias (#2208) --- build.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/build.rs b/build.rs index 0fc908e6dd..c5ccd8b6dc 100644 --- a/build.rs +++ b/build.rs @@ -11,9 +11,10 @@ fn main() { macos: { target_os = "macos" }, netbsd: { target_os = "netbsd" }, openbsd: { target_os = "openbsd" }, - solarish: { target_os = "solaris" }, + solaris: { target_os = "solaris" }, watchos: { target_os = "watchos" }, tvos: { target_os = "tvos" }, + apple_targets: { any(ios, macos, watchos, tvos) }, bsd: { any(freebsd, dragonfly, netbsd, openbsd, apple_targets) }, linux_android: { any(android, linux) }, From d4a35b207c9bf7b7b7f3925cce6fc3c17d1ae0f5 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 01:07:17 +0800 Subject: [PATCH 053/140] docs: document how to remove/deprecate an interface (#2209) --- CONVENTIONS.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CONVENTIONS.md b/CONVENTIONS.md index eac629c334..e461b13b24 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -100,3 +100,20 @@ type or mutability that way. [`cast()`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast [`cast_mut()`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast_mut [`cast_const()`]: https://doc.rust-lang.org/std/primitive.pointer.html#method.cast_const + +## Remove/deprecate an interface + +In Nix, if we want to remove something, we don't do it immediately, instead, we +deprecate it for at least one release before removing it. + +To deprecate an interface, put the following attribute on the top of it: + +``` +#[deprecated(since = "", note = "")] +``` + +`` is the version where this interface will be deprecated, in most +cases, it will be the version of the next release. And a user-friendly note +should be added. Normally, there should be a new interface that will replace +the old one, so a note should be something like: " should be +used instead". From bcbf0e7dbed62734fd0c9246ac7cfd251116ae25 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sat, 25 Nov 2023 17:09:31 -0700 Subject: [PATCH 054/140] impl Display for InterfaceFlags (#2206) And add a full example for getifaddrs. --- changelog/2206.added.md | 1 + examples/getifaddrs.rs | 57 +++++++++++++++++++++++++++++++++++++++++ src/net/if_.rs | 8 ++++++ 3 files changed, 66 insertions(+) create mode 100644 changelog/2206.added.md create mode 100644 examples/getifaddrs.rs diff --git a/changelog/2206.added.md b/changelog/2206.added.md new file mode 100644 index 0000000000..68f16b6cad --- /dev/null +++ b/changelog/2206.added.md @@ -0,0 +1 @@ +impl Display for InterfaceFlags diff --git a/examples/getifaddrs.rs b/examples/getifaddrs.rs new file mode 100644 index 0000000000..602c9e829f --- /dev/null +++ b/examples/getifaddrs.rs @@ -0,0 +1,57 @@ +//! Print all interfaces and interface addresses on the system, in a format +//! similar to ifconfig(8). +#![cfg(feature = "net")] +#[cfg(any(bsd, linux_android, target_os = "illumos"))] +fn main() { + use nix::ifaddrs::getifaddrs; + use nix::sys::socket::{SockaddrLike, SockaddrStorage}; + + let addrs = getifaddrs().unwrap(); + let mut ifname = None; + for addr in addrs { + if ifname.as_ref() != Some(&addr.interface_name) { + if ifname.is_some() { + println!(); + } + ifname = Some(addr.interface_name.clone()); + println!( + "{}: flags={:x}<{}>", + addr.interface_name, + addr.flags.bits(), + addr.flags + ); + } + if let Some(dl) = addr.address.as_ref().unwrap().as_link_addr() { + if dl.addr().is_none() { + continue; + } + } + let family = addr + .address + .as_ref() + .and_then(SockaddrStorage::family) + .map(|af| format!("{:?}", af)) + .unwrap_or("".to_owned()); + match ( + &addr.address, + &addr.netmask, + &addr.broadcast, + &addr.destination, + ) { + (Some(a), Some(nm), Some(b), None) => { + println!("\t{} {} netmask {} broadcast {}", family, a, nm, b) + } + (Some(a), Some(nm), None, None) => { + println!("\t{} {} netmask {}", family, a, nm) + } + (Some(a), None, None, None) => println!("\t{} {}", family, a), + (Some(a), None, None, Some(d)) => { + println!("\t{} {} -> {}", family, a, d) + } + x => todo!("{:?}", x), + } + } +} + +#[cfg(not(any(bsd, linux_android, target_os = "illumos")))] +fn main() {} diff --git a/src/net/if_.rs b/src/net/if_.rs index fff5faea2f..c4a761839e 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -3,6 +3,7 @@ //! Uses Linux and/or POSIX functions to resolve interface names like "eth0" //! or "socan1" into device numbers. +use std::fmt; use crate::{Error, NixPath, Result}; use libc::c_uint; @@ -246,6 +247,13 @@ libc_bitflags!( } ); +impl fmt::Display for InterfaceFlags { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + bitflags::parser::to_writer(self, f) + } +} + + #[cfg(any( bsd, target_os = "fuchsia", From 0ee21e7b1467ced871f696ad1865934dd2d23808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ad=C3=A4?= Date: Sun, 26 Nov 2023 01:16:01 +0100 Subject: [PATCH 055/140] fmt (#2211) --- src/sys/epoll.rs | 2 +- src/sys/fanotify.rs | 34 +++++++++++--------- src/sys/ptrace/bsd.rs | 2 +- src/sys/sendfile.rs | 7 +++- src/sys/socket/addr.rs | 73 +++++++++++------------------------------- 5 files changed, 46 insertions(+), 72 deletions(-) diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index 32b068e88b..88314ef926 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -1,6 +1,6 @@ use crate::errno::Errno; -use crate::Result; pub use crate::poll_timeout::PollTimeout as EpollTimeout; +use crate::Result; use libc::{self, c_int}; use std::mem; use std::os::unix::io::{AsFd, AsRawFd, FromRawFd, OwnedFd, RawFd}; diff --git a/src/sys/fanotify.rs b/src/sys/fanotify.rs index a089d78df8..e217406e02 100644 --- a/src/sys/fanotify.rs +++ b/src/sys/fanotify.rs @@ -10,12 +10,12 @@ //! For more documentation, please read //! [fanotify(7)](https://man7.org/linux/man-pages/man7/fanotify.7.html). -use crate::{NixPath, Result}; use crate::errno::Errno; -use crate::fcntl::{OFlag, at_rawfd}; +use crate::fcntl::{at_rawfd, OFlag}; use crate::unistd::{close, read, write}; +use crate::{NixPath, Result}; use std::marker::PhantomData; -use std::mem::{MaybeUninit, size_of}; +use std::mem::{size_of, MaybeUninit}; use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd, RawFd}; use std::ptr; @@ -288,11 +288,16 @@ impl Fanotify { /// Returns a Result containing a Fanotify instance. /// /// For more information, see [fanotify_init(2)](https://man7.org/linux/man-pages/man7/fanotify_init.2.html). - pub fn init(flags: InitFlags, event_f_flags: EventFFlags) -> Result { + pub fn init( + flags: InitFlags, + event_f_flags: EventFFlags, + ) -> Result { let res = Errno::result(unsafe { libc::fanotify_init(flags.bits(), event_f_flags.bits()) }); - res.map(|fd| Fanotify { fd: unsafe { OwnedFd::from_raw_fd(fd) }}) + res.map(|fd| Fanotify { + fd: unsafe { OwnedFd::from_raw_fd(fd) }, + }) } /// Add, remove, or modify an fanotify mark on a filesystem object. @@ -386,22 +391,21 @@ impl Fanotify { /// available on a group that has been initialized with the flag /// `InitFlags::FAN_NONBLOCK`, thus making this method nonblocking. pub fn write_response(&self, response: FanotifyResponse) -> Result<()> { - write( - self.fd.as_fd(), - unsafe { - std::slice::from_raw_parts( - (&response.inner as *const libc::fanotify_response).cast(), - size_of::(), - ) - }, - )?; + write(self.fd.as_fd(), unsafe { + std::slice::from_raw_parts( + (&response.inner as *const libc::fanotify_response).cast(), + size_of::(), + ) + })?; Ok(()) } } impl FromRawFd for Fanotify { unsafe fn from_raw_fd(fd: RawFd) -> Self { - Fanotify { fd: unsafe { OwnedFd::from_raw_fd(fd) }} + Fanotify { + fd: unsafe { OwnedFd::from_raw_fd(fd) }, + } } } diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index 69de590ace..086e32dcaf 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -68,7 +68,7 @@ unsafe fn ptrace_other( addr, data, )) - .map(|_| 0) + .map(|_| 0) } } diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 6e2e0ace90..546664cf2e 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -22,7 +22,12 @@ use crate::Result; /// /// For more information, see [the sendfile(2) man page.](https://man7.org/linux/man-pages/man2/sendfile.2.html) for Linux, /// see [the sendfile(2) man page.](https://docs.oracle.com/cd/E88353_01/html/E37843/sendfile-3c.html) for Solaris. -#[cfg(any(target_os = "android", target_os = "linux", target_os = "solaris", target_os = "illumos"))] +#[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "solaris", + target_os = "illumos", +))] pub fn sendfile( out_fd: F1, in_fd: F2, diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 319876f4c2..5c4bb9bf06 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -251,10 +251,7 @@ pub enum AddressFamily { #[cfg(bsd)] Hylink = libc::AF_HYLINK, /// Link layer interface - #[cfg(any( - bsd, - target_os = "illumos", - ))] + #[cfg(any(bsd, target_os = "illumos"))] Link = libc::AF_LINK, /// connection-oriented IP, aka ST II #[cfg(bsd)] @@ -293,10 +290,7 @@ impl AddressFamily { libc::PF_ROUTE => Some(AddressFamily::Route), #[cfg(linux_android)] libc::AF_PACKET => Some(AddressFamily::Packet), - #[cfg(any( - bsd, - target_os = "illumos", - ))] + #[cfg(any(bsd, target_os = "illumos"))] libc::AF_LINK => Some(AddressFamily::Link), #[cfg(any( target_os = "android", @@ -863,11 +857,7 @@ impl SockaddrIn { /// Creates a new socket address from IPv4 octets and a port number. pub fn new(a: u8, b: u8, c: u8, d: u8, port: u16) -> Self { Self(libc::sockaddr_in { - #[cfg(any( - bsd, - target_os = "aix", - target_os = "haiku", - ))] + #[cfg(any(bsd, target_os = "aix", target_os = "haiku"))] sin_len: Self::size() as u8, sin_family: AddressFamily::Inet as sa_family_t, sin_port: u16::to_be(port), @@ -936,11 +926,7 @@ impl fmt::Display for SockaddrIn { impl From for SockaddrIn { fn from(addr: net::SocketAddrV4) -> Self { Self(libc::sockaddr_in { - #[cfg(any( - bsd, - target_os = "haiku", - target_os = "hermit", - ))] + #[cfg(any(bsd, target_os = "haiku", target_os = "hermit"))] sin_len: mem::size_of::() as u8, sin_family: AddressFamily::Inet as sa_family_t, sin_port: addr.port().to_be(), // network byte order @@ -1060,11 +1046,7 @@ impl From for SockaddrIn6 { fn from(addr: net::SocketAddrV6) -> Self { #[allow(clippy::needless_update)] // It isn't needless on Illumos Self(libc::sockaddr_in6 { - #[cfg(any( - bsd, - target_os = "haiku", - target_os = "hermit", - ))] + #[cfg(any(bsd, target_os = "haiku", target_os = "hermit"))] sin6_len: mem::size_of::() as u8, sin6_family: AddressFamily::Inet6 as sa_family_t, sin6_port: addr.port().to_be(), // network byte order @@ -1198,15 +1180,11 @@ impl SockaddrLike for SockaddrStorage { libc::AF_INET6 => unsafe { SockaddrIn6::from_raw(addr, l).map(|sin6| Self { sin6 }) }, - #[cfg(any( - bsd, - target_os = "illumos", - target_os = "haiku", - ))] + #[cfg(any(bsd, target_os = "illumos", target_os = "haiku"))] #[cfg(feature = "net")] libc::AF_LINK => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) - } + }, #[cfg(linux_android)] libc::AF_NETLINK => unsafe { NetlinkAddr::from_raw(addr, l).map(|nl| Self { nl }) @@ -1219,12 +1197,16 @@ impl SockaddrLike for SockaddrStorage { #[cfg(feature = "net")] libc::AF_PACKET => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) - } + }, #[cfg(all(feature = "ioctl", apple_targets))] libc::AF_SYSTEM => unsafe { SysControlAddr::from_raw(addr, l).map(|sctl| Self { sctl }) - } - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos" ))] + }, + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "macos", + ))] libc::AF_VSOCK => unsafe { VsockAddr::from_raw(addr, l).map(|vsock| Self { vsock }) }, @@ -1368,10 +1350,7 @@ impl SockaddrStorage { as_link_addr, as_link_addr_mut, LinkAddr, AddressFamily::Packet, libc::sockaddr_ll, dl} - #[cfg(any( - bsd, - target_os = "illumos", - ))] + #[cfg(any(bsd, target_os = "illumos"))] #[cfg(feature = "net")] accessors! { as_link_addr, as_link_addr_mut, LinkAddr, @@ -1425,10 +1404,7 @@ impl fmt::Display for SockaddrStorage { libc::AF_INET => self.sin.fmt(f), #[cfg(feature = "net")] libc::AF_INET6 => self.sin6.fmt(f), - #[cfg(any( - bsd, - target_os = "illumos", - ))] + #[cfg(any(bsd, target_os = "illumos"))] #[cfg(feature = "net")] libc::AF_LINK => self.dl.fmt(f), #[cfg(linux_android)] @@ -1498,10 +1474,7 @@ impl Hash for SockaddrStorage { libc::AF_INET => self.sin.hash(s), #[cfg(feature = "net")] libc::AF_INET6 => self.sin6.hash(s), - #[cfg(any( - bsd, - target_os = "illumos", - ))] + #[cfg(any(bsd, target_os = "illumos"))] #[cfg(feature = "net")] libc::AF_LINK => self.dl.hash(s), #[cfg(linux_android)] @@ -1539,10 +1512,7 @@ impl PartialEq for SockaddrStorage { (libc::AF_INET, libc::AF_INET) => self.sin == other.sin, #[cfg(feature = "net")] (libc::AF_INET6, libc::AF_INET6) => self.sin6 == other.sin6, - #[cfg(any( - bsd, - target_os = "illumos", - ))] + #[cfg(any(bsd, target_os = "illumos"))] #[cfg(feature = "net")] (libc::AF_LINK, libc::AF_LINK) => self.dl == other.dl, #[cfg(linux_android)] @@ -1980,12 +1950,7 @@ mod datalink { } } -#[cfg(any( - bsd, - target_os = "illumos", - target_os = "haiku", - target_os = "aix", -))] +#[cfg(any(bsd, target_os = "illumos", target_os = "haiku", target_os = "aix"))] mod datalink { feature! { #![feature = "net"] From 54ded47c6e6cd9765706c9f140e9af0415f841a7 Mon Sep 17 00:00:00 2001 From: Tom Dryer Date: Sat, 25 Nov 2023 19:27:22 -0800 Subject: [PATCH 056/140] Add `fctrl::SealFlag::F_SEAL_FUTURE_WRITE` (#2213) * Add `fctrl::SealFlag::F_SEAL_FUTURE_WRITE` Add `fctrl::SealFlag::F_SEAL_FUTURE_WRITE`, a file sealing flag available since Linux 5.1 which prevents modification except via shared writable mappings that were created prior to the seal being set. * Add changelog entry * Use `linux_android` alias Co-authored-by: SteveLauC --------- Co-authored-by: SteveLauC --- changelog/2213.added.md | 1 + src/fcntl.rs | 4 ++++ 2 files changed, 5 insertions(+) create mode 100644 changelog/2213.added.md diff --git a/changelog/2213.added.md b/changelog/2213.added.md new file mode 100644 index 0000000000..7635067eaa --- /dev/null +++ b/changelog/2213.added.md @@ -0,0 +1 @@ +Added `fctrl::SealFlag::F_SEAL_FUTURE_WRITE` diff --git a/src/fcntl.rs b/src/fcntl.rs index 331ee2e38d..e4f0417b7a 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -420,6 +420,10 @@ libc_bitflags!( F_SEAL_GROW; /// The file contents cannot be modified. F_SEAL_WRITE; + /// The file contents cannot be modified, except via shared writable mappings that were + /// created prior to the seal being set. Since Linux 5.1. + #[cfg(linux_android)] + F_SEAL_FUTURE_WRITE; } ); From 0c8da48785c378bf89cd09b9b37a4c0fd45950c2 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:22:35 +0800 Subject: [PATCH 057/140] refactor: cfg for aio/epoll/event/mman/mod/resource/sendfile/signal (#2218) --- src/sys/event.rs | 57 +++++++++--------------------------------- src/sys/mman.rs | 4 +-- src/sys/mod.rs | 38 ++++++---------------------- src/sys/resource.rs | 9 +++---- src/sys/sendfile.rs | 11 ++------ src/sys/signal.rs | 61 +++++++++++++++------------------------------ 6 files changed, 46 insertions(+), 134 deletions(-) diff --git a/src/sys/event.rs b/src/sys/event.rs index f53e0dfdad..28f1e1a1e4 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -78,12 +78,7 @@ impl Kqueue { } } -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] type type_of_udata = *mut libc::c_void; #[cfg(target_os = "netbsd")] type type_of_udata = intptr_t; @@ -108,9 +103,7 @@ libc_enum! { /// Takes a descriptor as the identifier, and returns whenever one of /// the specified exceptional conditions has occurred on the descriptor. EVFILT_EXCEPT, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets))] + #[cfg(any(freebsdlike, apple_targets))] /// Establishes a file system monitor. EVFILT_FS, #[cfg(target_os = "freebsd")] @@ -142,9 +135,7 @@ libc_enum! { EVFILT_SIGNAL, /// Establishes a timer and notifies when the timer expires. EVFILT_TIMER, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets))] + #[cfg(any(freebsdlike, apple_targets))] /// Notifies only when explicitly requested by the user. EVFILT_USER, #[cfg(apple_targets)] @@ -159,12 +150,7 @@ libc_enum! { impl TryFrom } -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] #[doc(hidden)] pub type type_of_event_flag = u16; #[cfg(target_os = "netbsd")] @@ -244,34 +230,22 @@ libc_bitflags!( NOTE_EXITSTATUS; #[allow(missing_docs)] NOTE_EXTEND; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_FFAND; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_FFCOPY; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_FFCTRLMASK; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_FFLAGSMASK; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_FFNOP; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_FFOR; #[allow(missing_docs)] @@ -314,9 +288,7 @@ libc_bitflags!( NOTE_TRACK; #[allow(missing_docs)] NOTE_TRACKERR; - #[cfg(any(apple_targets, - target_os = "freebsd", - target_os = "dragonfly"))] + #[cfg(any(apple_targets, freebsdlike))] #[allow(missing_docs)] NOTE_TRIGGER; #[cfg(target_os = "openbsd")] @@ -434,12 +406,7 @@ pub fn kevent( kq.kevent(changelist, eventlist, Some(timeout)) } -#[cfg(any( - apple_targets, - target_os = "freebsd", - target_os = "dragonfly", - target_os = "openbsd" -))] +#[cfg(any(apple_targets, freebsdlike, target_os = "openbsd"))] type type_of_nchanges = c_int; #[cfg(target_os = "netbsd")] type type_of_nchanges = size_t; diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 199587f557..6247ea4e17 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -57,7 +57,7 @@ libc_bitflags! { /// The mapping is not backed by any file. MAP_ANONYMOUS; /// Put the mapping into the first 2GB of the process address space. - #[cfg(any(all(any(target_os = "android", target_os = "linux"), + #[cfg(any(all(linux_android, any(target_arch = "x86", target_arch = "x86_64")), all(target_os = "linux", target_env = "musl", any(target_arch = "x86", target_arch = "x86_64")), all(target_os = "freebsd", target_pointer_width = "64")))] @@ -140,7 +140,7 @@ libc_bitflags! { #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] MAP_HASSEMAPHORE; /// Region grows down, like a stack. - #[cfg(any(target_os = "android", freebsdlike, target_os = "linux", target_os = "openbsd"))] + #[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))] MAP_STACK; /// Pages in this mapping are not retained in the kernel's memory cache. #[cfg(apple_targets)] diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 28ccd1ba2d..c29d5ce376 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -1,7 +1,6 @@ //! Mostly platform-specific functionality #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, all(target_os = "linux", not(target_env = "uclibc")), apple_targets, target_os = "netbsd" @@ -32,19 +31,13 @@ feature! { pub mod fanotify; } -#[cfg(any( - bsd, - target_os = "android", - target_os = "linux", - target_os = "redox", - target_os = "illumos", -))] +#[cfg(any(bsd, linux_android, target_os = "redox", target_os = "illumos"))] #[cfg(feature = "ioctl")] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] #[macro_use] pub mod ioctl; -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] feature! { #![feature = "fs"] pub mod memfd; @@ -74,10 +67,8 @@ feature! { } #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + linux_android, + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" @@ -116,15 +107,7 @@ feature! { pub mod select; } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "solaris", - target_os = "illumos", -))] +#[cfg(any(linux_android, freebsdlike, apple_targets, solarish))] feature! { #![feature = "zerocopy"] pub mod sendfile; @@ -151,14 +134,7 @@ feature! { pub mod stat; } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "openbsd"))] feature! { #![feature = "fs"] pub mod statfs; diff --git a/src/sys/resource.rs b/src/sys/resource.rs index 6b518b7af5..14f3e14c21 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -75,10 +75,9 @@ libc_enum! { RLIMIT_LOCKS, #[cfg(any( - target_os = "android", + linux_android, target_os = "freebsd", target_os = "openbsd", - target_os = "linux", target_os = "netbsd" ))] /// The maximum size (in bytes) which a process may lock into memory @@ -96,11 +95,10 @@ libc_enum! { RLIMIT_NICE, #[cfg(any( - target_os = "android", + linux_android, target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", - target_os = "linux", target_os = "aix", ))] /// The maximum number of simultaneous processes for this user id. @@ -111,11 +109,10 @@ libc_enum! { /// create. RLIMIT_NPTS, - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd", target_os = "openbsd", - target_os = "linux", target_os = "aix", ))] /// When there is memory pressure and swap is available, prioritize diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 546664cf2e..ced85d48e8 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -22,12 +22,7 @@ use crate::Result; /// /// For more information, see [the sendfile(2) man page.](https://man7.org/linux/man-pages/man2/sendfile.2.html) for Linux, /// see [the sendfile(2) man page.](https://docs.oracle.com/cd/E88353_01/html/E37843/sendfile-3c.html) for Solaris. -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "solaris", - target_os = "illumos", -))] +#[cfg(any(linux_android, solarish))] pub fn sendfile( out_fd: F1, in_fd: F2, @@ -82,9 +77,7 @@ pub fn sendfile64( } cfg_if! { - if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets,))] { + if #[cfg(any(freebsdlike, apple_targets))] { use std::io::IoSlice; #[derive(Clone, Debug)] diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 8ef2b95243..3156848c48 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -65,8 +65,8 @@ libc_enum! { /// Software termination signal from kill SIGTERM, /// Stack fault (obsolete) - #[cfg(all(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux"), + #[cfg(all(any(linux_android, target_os = "emscripten", + target_os = "fuchsia"), not(any(target_arch = "mips", target_arch = "mips32r6", target_arch = "mips64", @@ -100,22 +100,20 @@ libc_enum! { /// Input/output possible signal #[cfg(not(target_os = "haiku"))] SIGIO, - #[cfg(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", - target_os = "aix"))] + #[cfg(any(linux_android, target_os = "emscripten", + target_os = "fuchsia", target_os = "aix"))] /// Power failure imminent. SIGPWR, /// Bad system call SIGSYS, - #[cfg(not(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", + #[cfg(not(any(linux_android, target_os = "emscripten", + target_os = "fuchsia", target_os = "redox", target_os = "haiku")))] /// Emulator trap SIGEMT, - #[cfg(not(any(target_os = "android", target_os = "emscripten", - target_os = "fuchsia", target_os = "linux", - target_os = "redox", target_os = "haiku", - target_os = "aix")))] + #[cfg(not(any(linux_android, target_os = "emscripten", + target_os = "fuchsia", target_os = "redox", + target_os = "haiku", target_os = "aix")))] /// Information request SIGINFO, } @@ -144,10 +142,9 @@ impl FromStr for Signal { "SIGTERM" => Signal::SIGTERM, #[cfg(all( any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux" ), not(any( target_arch = "mips", @@ -173,27 +170,24 @@ impl FromStr for Signal { #[cfg(not(target_os = "haiku"))] "SIGIO" => Signal::SIGIO, #[cfg(any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux" ))] "SIGPWR" => Signal::SIGPWR, "SIGSYS" => Signal::SIGSYS, #[cfg(not(any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux", target_os = "redox", target_os = "haiku" )))] "SIGEMT" => Signal::SIGEMT, #[cfg(not(any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux", target_os = "redox", target_os = "aix", target_os = "haiku" @@ -230,10 +224,9 @@ impl Signal { Signal::SIGTERM => "SIGTERM", #[cfg(all( any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux" ), not(any( target_arch = "mips", @@ -259,28 +252,25 @@ impl Signal { #[cfg(not(target_os = "haiku"))] Signal::SIGIO => "SIGIO", #[cfg(any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", target_os = "aix", - target_os = "linux" ))] Signal::SIGPWR => "SIGPWR", Signal::SIGSYS => "SIGSYS", #[cfg(not(any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux", target_os = "redox", target_os = "haiku" )))] Signal::SIGEMT => "SIGEMT", #[cfg(not(any( - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", - target_os = "linux", target_os = "redox", target_os = "aix", target_os = "haiku" @@ -324,12 +314,7 @@ const SIGNALS: [Signal; 28] = [ SIGPROF, SIGWINCH, SIGSYS, ]; #[cfg(all( - any( - target_os = "linux", - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia" - ), + any(linux_android, target_os = "emscripten", target_os = "fuchsia"), not(any( target_arch = "mips", target_arch = "mips32r6", @@ -346,12 +331,7 @@ const SIGNALS: [Signal; 31] = [ SIGVTALRM, SIGPROF, SIGWINCH, SIGIO, SIGPWR, SIGSYS, ]; #[cfg(all( - any( - target_os = "linux", - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia" - ), + any(linux_android, target_os = "emscripten", target_os = "fuchsia"), any( target_arch = "mips", target_arch = "mips32r6", @@ -376,8 +356,7 @@ const SIGNALS: [Signal; 30] = [ SIGVTALRM, SIGPROF, SIGXCPU, SIGXFSZ, SIGTRAP, ]; #[cfg(not(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "emscripten", target_os = "aix", From 50c1ec16ec3012f73c5dc0990905718868971f5e Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:23:46 +0800 Subject: [PATCH 058/140] refactor: cfg for stat/statfs (#2219) --- src/sys/stat.rs | 12 ++---------- src/sys/statfs.rs | 39 ++++++++++++--------------------------- 2 files changed, 14 insertions(+), 37 deletions(-) diff --git a/src/sys/stat.rs b/src/sys/stat.rs index dc40907f47..20b5294b31 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -1,10 +1,6 @@ #[cfg(any(apple_targets, target_os = "openbsd"))] pub use libc::c_uint; -#[cfg(any( - target_os = "netbsd", - target_os = "freebsd", - target_os = "dragonfly" -))] +#[cfg(any(target_os = "netbsd", freebsdlike))] pub use libc::c_ulong; pub use libc::stat as FileStat; pub use libc::{dev_t, mode_t}; @@ -67,11 +63,7 @@ libc_bitflags! { #[cfg(any(apple_targets, target_os = "openbsd"))] pub type type_of_file_flag = c_uint; -#[cfg(any( - target_os = "netbsd", - target_os = "freebsd", - target_os = "dragonfly" -))] +#[cfg(any(freebsdlike, target_os = "netbsd"))] pub type type_of_file_flag = c_ulong; #[cfg(bsd)] diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index 22e9a26ce0..d6ec2a8501 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -1,7 +1,7 @@ //! Get filesystem statistics, non-portably //! //! See [`statvfs`](crate::sys::statvfs) for a portable alternative. -#[cfg(not(any(target_os = "linux", target_os = "android")))] +#[cfg(not(linux_android))] use std::ffi::CStr; use std::fmt::{self, Debug}; use std::mem; @@ -12,8 +12,7 @@ use cfg_if::cfg_if; #[cfg(all( feature = "mount", any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" @@ -32,7 +31,7 @@ pub type fsid_t = libc::__fsid_t; pub type fsid_t = libc::fsid_t; cfg_if! { - if #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] { + if #[cfg(any(linux_android, target_os = "fuchsia"))] { type type_of_statfs = libc::statfs64; const LIBC_FSTATFS: unsafe extern fn (fd: libc::c_int, buf: *mut type_of_statfs) -> libc::c_int @@ -288,10 +287,7 @@ pub const XENFS_SUPER_MAGIC: FsType = #[cfg(linux_android)] #[allow(missing_docs)] pub const NSFS_MAGIC: FsType = FsType(libc::NSFS_MAGIC as fs_type_t); -#[cfg(all( - any(target_os = "linux", target_os = "android"), - not(target_env = "musl") -))] +#[cfg(all(linux_android, not(target_env = "musl")))] #[allow(missing_docs)] pub const XFS_SUPER_MAGIC: FsType = FsType(libc::XFS_SUPER_MAGIC as fs_type_t); @@ -307,7 +303,7 @@ impl Statfs { } /// Magic code defining system type - #[cfg(not(any(target_os = "linux", target_os = "android")))] + #[cfg(not(linux_android))] pub fn filesystem_type_name(&self) -> &str { let c_str = unsafe { CStr::from_ptr(self.0.f_fstypename.as_ptr()) }; c_str.to_str().unwrap() @@ -434,8 +430,7 @@ impl Statfs { #[cfg(all( feature = "mount", any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" @@ -500,11 +495,10 @@ impl Statfs { /// Total data blocks in filesystem #[cfg(any( apple_targets, - target_os = "android", + linux_android, target_os = "freebsd", target_os = "fuchsia", target_os = "openbsd", - target_os = "linux", ))] pub fn blocks(&self) -> u64 { self.0.f_blocks @@ -525,11 +519,10 @@ impl Statfs { /// Free blocks in filesystem #[cfg(any( apple_targets, - target_os = "android", + linux_android, target_os = "freebsd", target_os = "fuchsia", target_os = "openbsd", - target_os = "linux", ))] pub fn blocks_free(&self) -> u64 { self.0.f_bfree @@ -548,12 +541,7 @@ impl Statfs { } /// Free blocks available to unprivileged user - #[cfg(any( - apple_targets, - target_os = "android", - target_os = "fuchsia", - target_os = "linux", - ))] + #[cfg(any(apple_targets, linux_android, target_os = "fuchsia"))] pub fn blocks_available(&self) -> u64 { self.0.f_bavail } @@ -579,11 +567,10 @@ impl Statfs { /// Total file nodes in filesystem #[cfg(any( apple_targets, - target_os = "android", + linux_android, target_os = "freebsd", target_os = "fuchsia", target_os = "openbsd", - target_os = "linux", ))] pub fn files(&self) -> u64 { self.0.f_files @@ -604,10 +591,9 @@ impl Statfs { /// Free file nodes in filesystem #[cfg(any( apple_targets, - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "openbsd", - target_os = "linux", ))] pub fn files_free(&self) -> u64 { self.0.f_ffree @@ -651,8 +637,7 @@ impl Debug for Statfs { #[cfg(all( feature = "mount", any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" From ab1d1beb31f15f407eda69b077f44fb7081dadd5 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:26:05 +0800 Subject: [PATCH 059/140] refactor: cfg for time/uio/wait (#2221) --- src/sys/uio.rs | 4 +-- src/sys/wait.rs | 23 ++++++------- src/time.rs | 87 ++++++++++--------------------------------------- 3 files changed, 29 insertions(+), 85 deletions(-) diff --git a/src/sys/uio.rs b/src/sys/uio.rs index e893cb42f7..29e3647b35 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -182,7 +182,7 @@ feature! { /// [ptrace]: ../ptrace/index.html /// [`IoSlice`]: https://doc.rust-lang.org/std/io/struct.IoSlice.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html -#[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))] +#[cfg(all(linux_android, not(target_env = "uclibc")))] pub fn process_vm_writev( pid: crate::unistd::Pid, local_iov: &[IoSlice<'_>], @@ -217,7 +217,7 @@ pub fn process_vm_writev( /// [`ptrace`]: ../ptrace/index.html /// [`IoSliceMut`]: https://doc.rust-lang.org/std/io/struct.IoSliceMut.html /// [`RemoteIoVec`]: struct.RemoteIoVec.html -#[cfg(all(any(target_os = "linux", target_os = "android"), not(target_env = "uclibc")))] +#[cfg(all(linux_android, not(target_env = "uclibc")))] pub fn process_vm_readv( pid: crate::unistd::Pid, local_iov: &mut [IoSliceMut<'_>], diff --git a/src/sys/wait.rs b/src/sys/wait.rs index 299ea1bec9..844e165c18 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -24,11 +24,10 @@ libc_bitflags!( /// [`SIGSTOP`](crate::sys::signal::Signal::SIGSTOP) signal. WUNTRACED; /// Report the status of selected processes which have terminated. - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, + apple_targets, target_os = "freebsd", target_os = "haiku", - apple_targets, - target_os = "linux", target_os = "redox", target_os = "netbsd"))] WEXITED; @@ -37,31 +36,29 @@ libc_bitflags!( /// [`SIGCONT`](crate::sys::signal::Signal::SIGCONT) signal. WCONTINUED; /// An alias for WUNTRACED. - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, + apple_targets, target_os = "freebsd", target_os = "haiku", - apple_targets, - target_os = "linux", target_os = "redox", target_os = "netbsd"))] WSTOPPED; /// Don't reap, just poll status. - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, + apple_targets, target_os = "freebsd", target_os = "haiku", - apple_targets, - target_os = "linux", target_os = "redox", target_os = "netbsd"))] WNOWAIT; /// Don't wait on children of other threads in this group - #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] + #[cfg(any(linux_android, target_os = "redox"))] __WNOTHREAD; /// Wait on all children, regardless of type - #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] + #[cfg(any(linux_android, target_os = "redox"))] __WALL; /// Wait for "clone" children only. - #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] + #[cfg(any(linux_android, target_os = "redox"))] __WCLONE; } ); @@ -205,7 +202,7 @@ impl WaitStatus { WaitStatus::Signaled(pid, term_signal(status)?, dumped_core(status)) } else if stopped(status) { cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { fn decode_stopped(pid: Pid, status: i32) -> Result { let status_additional = stop_additional(status); Ok(if syscall_stop(status) { diff --git a/src/time.rs b/src/time.rs index cdcad0977d..6e8aac6ac1 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,11 +1,5 @@ use crate::sys::time::TimeSpec; -#[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux", - target_os = "android", - target_os = "emscripten", -))] +#[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] #[cfg(feature = "process")] use crate::unistd::Pid; use crate::{Errno, Result}; @@ -29,10 +23,8 @@ impl ClockId { #![feature = "process"] /// Returns `ClockId` of a `pid` CPU-time clock #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux", - target_os = "android", + freebsdlike, + linux_android, target_os = "emscripten", ))] pub fn pid_cpu_clock_id(pid: Pid) -> Result { @@ -62,28 +54,13 @@ impl ClockId { self.0 } - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_BOOTTIME: ClockId = ClockId(libc::CLOCK_BOOTTIME); - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_BOOTTIME_ALARM: ClockId = ClockId(libc::CLOCK_BOOTTIME_ALARM); pub const CLOCK_MONOTONIC: ClockId = ClockId(libc::CLOCK_MONOTONIC); - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_MONOTONIC_COARSE: ClockId = ClockId(libc::CLOCK_MONOTONIC_COARSE); #[cfg(freebsdlike)] @@ -92,42 +69,25 @@ impl ClockId { #[cfg(freebsdlike)] pub const CLOCK_MONOTONIC_PRECISE: ClockId = ClockId(libc::CLOCK_MONOTONIC_PRECISE); - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_MONOTONIC_RAW: ClockId = ClockId(libc::CLOCK_MONOTONIC_RAW); #[cfg(any( - target_os = "android", + linux_android, + apple_targets, + freebsdlike, target_os = "emscripten", target_os = "fuchsia", - apple_targets, - target_os = "freebsd", - target_os = "dragonfly", target_os = "redox", - target_os = "linux" ))] pub const CLOCK_PROCESS_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_PROCESS_CPUTIME_ID); #[cfg(freebsdlike)] pub const CLOCK_PROF: ClockId = ClockId(libc::CLOCK_PROF); pub const CLOCK_REALTIME: ClockId = ClockId(libc::CLOCK_REALTIME); - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_REALTIME_ALARM: ClockId = ClockId(libc::CLOCK_REALTIME_ALARM); - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_REALTIME_COARSE: ClockId = ClockId(libc::CLOCK_REALTIME_COARSE); #[cfg(freebsdlike)] @@ -143,21 +103,14 @@ impl ClockId { all(target_os = "linux", target_env = "musl") ))] pub const CLOCK_SGI_CYCLE: ClockId = ClockId(libc::CLOCK_SGI_CYCLE); - #[cfg(any( - target_os = "android", - target_os = "emscripten", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_TAI: ClockId = ClockId(libc::CLOCK_TAI); #[cfg(any( - target_os = "android", + linux_android, + apple_targets, + freebsdlike, target_os = "emscripten", target_os = "fuchsia", - apple_targets, - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux" ))] pub const CLOCK_THREAD_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_THREAD_CPUTIME_ID); @@ -224,13 +177,7 @@ pub fn clock_settime(clock_id: ClockId, timespec: TimeSpec) -> Result<()> { /// Get the clock id of the specified process id, (see /// [clock_getcpuclockid(3)](https://pubs.opengroup.org/onlinepubs/009695399/functions/clock_getcpuclockid.html)). -#[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux", - target_os = "android", - target_os = "emscripten", -))] +#[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] #[cfg(feature = "process")] #[cfg_attr(docsrs, doc(cfg(feature = "process")))] pub fn clock_getcpuclockid(pid: Pid) -> Result { From 2563d24f3e6aba963e03a30e47ceab661fddcfb3 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:29:36 +0800 Subject: [PATCH 060/140] refactor: cfg for termios.rs (#2220) --- src/sys/termios.rs | 185 +++++++++++++++------------------------------ 1 file changed, 60 insertions(+), 125 deletions(-) diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 0a88ca697b..9333adc752 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -166,7 +166,7 @@ pub struct Termios { /// Control characters (see `termios.c_cc` documentation) pub control_chars: [libc::cc_t; NCCS], /// Line discipline (see `termios.c_line` documentation) - #[cfg(any(target_os = "linux", target_os = "android",))] + #[cfg(linux_android)] pub line_discipline: libc::cc_t, /// Line discipline (see `termios.c_line` documentation) #[cfg(target_os = "haiku")] @@ -186,11 +186,7 @@ impl Termios { termios.c_cflag = self.control_flags.bits(); termios.c_lflag = self.local_flags.bits(); termios.c_cc = self.control_chars; - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "haiku", - ))] + #[cfg(any(linux_android, target_os = "haiku"))] { termios.c_line = self.line_discipline; } @@ -212,11 +208,7 @@ impl Termios { termios.c_cflag = self.control_flags.bits(); termios.c_lflag = self.local_flags.bits(); termios.c_cc = self.control_chars; - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "haiku", - ))] + #[cfg(any(linux_android, target_os = "haiku"))] { termios.c_line = self.line_discipline; } @@ -232,11 +224,7 @@ impl Termios { self.control_flags = ControlFlags::from_bits_retain(termios.c_cflag); self.local_flags = LocalFlags::from_bits_truncate(termios.c_lflag); self.control_chars = termios.c_cc; - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "haiku", - ))] + #[cfg(any(linux_android, target_os = "haiku"))] { self.line_discipline = termios.c_line; } @@ -252,11 +240,7 @@ impl From for Termios { control_flags: ControlFlags::from_bits_truncate(termios.c_cflag), local_flags: LocalFlags::from_bits_truncate(termios.c_lflag), control_chars: termios.c_cc, - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "haiku", - ))] + #[cfg(any(linux_android, target_os = "haiku"))] line_discipline: termios.c_line, } } @@ -293,22 +277,19 @@ libc_enum! { B1800, B2400, B4800, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] B7200, B9600, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] B14400, B19200, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] @@ -316,8 +297,7 @@ libc_enum! { B38400, #[cfg(not(target_os = "aix"))] B57600, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] @@ -330,23 +310,19 @@ libc_enum! { B230400, #[cfg(solarish)] B307200, - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, + solarish, target_os = "freebsd", - target_os = "illumos", - target_os = "linux", - target_os = "netbsd", - target_os = "solaris"))] + target_os = "netbsd"))] B460800, #[cfg(linux_android)] B500000, #[cfg(linux_android)] B576000, - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, + solarish, target_os = "freebsd", - target_os = "illumos", - target_os = "linux", - target_os = "netbsd", - target_os = "solaris"))] + target_os = "netbsd"))] B921600, #[cfg(linux_android)] B1000000, @@ -441,51 +417,44 @@ libc_enum! { pub enum SpecialCharacterIndices { #[cfg(not(any(target_os = "aix", target_os = "haiku")))] VDISCARD, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + #[cfg(any(freebsdlike, + solarish, target_os = "macos", target_os = "netbsd", target_os = "openbsd", - target_os = "aix", - target_os = "solaris"))] + target_os = "aix"))] VDSUSP, VEOF, VEOL, VEOL2, VERASE, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "solaris"))] + #[cfg(any(freebsdlike, solarish))] VERASE2, VINTR, VKILL, #[cfg(not(target_os = "haiku"))] VLNEXT, #[cfg(not(any(all(target_os = "linux", target_arch = "sparc64"), - target_os = "illumos", target_os = "solaris", target_os = "aix", target_os = "haiku")))] + solarish, target_os = "aix", target_os = "haiku")))] VMIN, VQUIT, #[cfg(not(target_os = "haiku"))] VREPRINT, VSTART, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + #[cfg(any(freebsdlike, + solarish, target_os = "macos", target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris"))] + target_os = "openbsd"))] VSTATUS, VSTOP, VSUSP, #[cfg(target_os = "linux")] VSWTC, - #[cfg(any(target_os = "haiku", target_os = "illumos", target_os = "solaris"))] + #[cfg(any(solarish, target_os = "haiku"))] VSWTCH, #[cfg(not(any(all(target_os = "linux", target_arch = "sparc64"), - target_os = "illumos", target_os = "solaris", target_os = "aix", target_os = "haiku")))] + solarish, target_os = "aix", target_os = "haiku")))] VTIME, #[cfg(not(any(target_os = "aix", target_os = "haiku")))] VWERASE, @@ -496,8 +465,7 @@ libc_enum! { #[cfg(any( all(target_os = "linux", target_arch = "sparc64"), - target_os = "illumos", - target_os = "solaris", + solarish, target_os = "aix", target_os = "haiku", ))] @@ -508,10 +476,8 @@ impl SpecialCharacterIndices { pub use libc::NCCS; #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + linux_android, + freebsdlike, target_os = "aix", target_os = "macos", target_os = "netbsd", @@ -537,7 +503,7 @@ libc_bitflags! { IXANY; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] IMAXBEL; - #[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] + #[cfg(any(linux_android, target_os = "macos"))] IUTF8; } } @@ -546,108 +512,89 @@ libc_bitflags! { /// Flags for configuring the output mode of a terminal pub struct OutputFlags: tcflag_t { OPOST; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", target_os = "openbsd"))] OLCUC; ONLCR; OCRNL as tcflag_t; ONOCR as tcflag_t; ONLRET as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] OFDEL as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] NL0 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] NL1 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] CR0 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] CR1 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] CR2 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] CR3 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "freebsd", target_os = "haiku", - target_os = "linux", apple_targets))] TAB0 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] TAB1 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] TAB2 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "freebsd", target_os = "haiku", - target_os = "linux", apple_targets))] TAB3 as tcflag_t; #[cfg(linux_android)] XTABS; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] BS0 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] BS1 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] VT0 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] VT1 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] FF0 as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] FF1 as tcflag_t; #[cfg(bsd)] OXTABS; - #[cfg(any(target_os = "freebsd", - target_os = "dragonfly", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] @@ -657,35 +604,29 @@ libc_bitflags! { // These should be moved to be a mask once https://github.com/rust-lang-nursery/bitflags/issues/110 // is resolved. - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] NLDLY as tcflag_t; // FIXME: Datatype needs to be corrected in libc for mac - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] CRDLY as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "freebsd", target_os = "haiku", - target_os = "linux", apple_targets))] TABDLY as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] BSDLY as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] VTDLY as tcflag_t; - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "haiku", - target_os = "linux", apple_targets))] FFDLY as tcflag_t; } @@ -718,32 +659,26 @@ libc_bitflags! { CIBAUD; #[cfg(linux_android)] CBAUDEX; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] MDMBUF; #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] CHWFLOW; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] CCTS_OFLOW; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] CRTS_IFLOW; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd"))] + #[cfg(freebsdlike)] CDTR_IFLOW; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd"))] + #[cfg(freebsdlike)] CDSR_OFLOW; - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd"))] + #[cfg(freebsdlike)] CCAR_OFLOW; // Bitmasks for use with ControlFlags to select specific settings From 8cc58e7655eb324fe89defdebe767ec9f9b54cb7 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:38:02 +0800 Subject: [PATCH 061/140] refactor: cfg for dir/env/errno (#2214) --- src/dir.rs | 22 +-- src/env.rs | 5 +- src/errno.rs | 451 ++++++++++----------------------------------------- 3 files changed, 91 insertions(+), 387 deletions(-) diff --git a/src/dir.rs b/src/dir.rs index 6dec1525d5..b42321f1f8 100644 --- a/src/dir.rs +++ b/src/dir.rs @@ -225,15 +225,13 @@ impl Entry { pub fn ino(&self) -> u64 { cfg_if! { if #[cfg(any(target_os = "aix", - target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", + solarish, + linux_android, apple_targets, - target_os = "l4re", - target_os = "linux", - target_os = "solaris"))] { + target_os = "l4re"))] { self.0.d_ino as u64 } else { u64::from(self.0.d_fileno) @@ -252,12 +250,7 @@ impl Entry { /// notably, some Linux filesystems don't implement this. The caller should use `stat` or /// `fstat` if this returns `None`. pub fn file_type(&self) -> Option { - #[cfg(not(any( - target_os = "aix", - target_os = "illumos", - target_os = "solaris", - target_os = "haiku" - )))] + #[cfg(not(any(solarish, target_os = "aix", target_os = "haiku")))] match self.0.d_type { libc::DT_FIFO => Some(Type::Fifo), libc::DT_CHR => Some(Type::CharacterDevice), @@ -270,12 +263,7 @@ impl Entry { } // illumos, Solaris, and Haiku systems do not have the d_type member at all: - #[cfg(any( - target_os = "aix", - target_os = "illumos", - target_os = "solaris", - target_os = "haiku" - ))] + #[cfg(any(solarish, target_os = "aix", target_os = "haiku"))] None } } diff --git a/src/env.rs b/src/env.rs index e4ad0a628a..510bbb0924 100644 --- a/src/env.rs +++ b/src/env.rs @@ -40,11 +40,10 @@ impl std::error::Error for ClearEnvError {} /// thread safety must still be upheld. pub unsafe fn clearenv() -> std::result::Result<(), ClearEnvError> { cfg_if! { - if #[cfg(any(target_os = "fuchsia", + if #[cfg(any(linux_android, + target_os = "fuchsia", target_os = "wasi", target_env = "uclibc", - target_os = "linux", - target_os = "android", target_os = "emscripten"))] { let ret = unsafe { libc::clearenv() }; } else { diff --git a/src/errno.rs b/src/errno.rs index f4f982e23d..555c07bacd 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -224,467 +224,239 @@ fn desc(errno: Errno) -> &'static str { EHOSTUNREACH => "No route to host", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] ECHRNG => "Channel number out of range", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EL2NSYNC => "Level 2 not synchronized", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EL3HLT => "Level 3 halted", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EL3RST => "Level 3 reset", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] ELNRNG => "Link number out of range", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EUNATCH => "Protocol driver not attached", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] ENOCSI => "No CSI structure available", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EL2HLT => "Level 2 halted", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBADE => "Invalid exchange", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBADR => "Invalid request descriptor", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EXFULL => "Exchange full", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENOANO => "No anode", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBADRQC => "Invalid request code", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBADSLT => "Invalid slot", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBFONT => "Bad font file format", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENOSTR => "Device not a stream", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENODATA => "No data available", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ETIME => "Timer expired", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENOSR => "Out of streams resources", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENONET => "Machine is not on the network", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENOPKG => "Package not installed", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EREMOTE => "Object is remote", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] ENOLINK => "Link has been severed", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EADV => "Advertise error", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ESRMNT => "Srmount error", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ECOMM => "Communication error on send", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EPROTO => "Protocol error", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] EMULTIHOP => "Multihop attempted", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EDOTDOT => "RFS specific error", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "aix", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "aix", target_os = "fuchsia"))] EBADMSG => "Not a data message", #[cfg(solarish)] EBADMSG => "Trying to read unreadable message", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "aix", target_os = "fuchsia", target_os = "haiku" ))] EOVERFLOW => "Value too large for defined data type", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENOTUNIQ => "Name not unique on network", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBADFD => "File descriptor in bad state", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EREMCHG => "Remote address changed", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ELIBACC => "Can not access a needed shared library", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ELIBBAD => "Accessing a corrupted shared library", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ELIBSCN => ".lib section in a.out corrupted", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ELIBMAX => "Attempting to link in too many shared libraries", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ELIBEXEC => "Cannot exec a shared library directly", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia", target_os = "openbsd" ))] EILSEQ => "Illegal byte sequence", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, + solarish, target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "fuchsia" ))] ERESTART => "Interrupted system call should be restarted", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ESTRPIPE => "Streams pipe error", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EUSERS => "Too many users", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "netbsd", target_os = "redox" ))] EOPNOTSUPP => "Operation not supported on transport endpoint", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ESTALE => "Stale file handle", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EUCLEAN => "Structure needs cleaning", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ENOTNAM => "Not a XENIX named type file", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ENAVAIL => "No XENIX semaphores available", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EISNAM => "Is a named type file", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EREMOTEIO => "Remote I/O error", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EDQUOT => "Quota exceeded", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "openbsd", target_os = "dragonfly" @@ -692,68 +464,39 @@ fn desc(errno: Errno) -> &'static str { ENOMEDIUM => "No medium found", #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "openbsd" ))] EMEDIUMTYPE => "Wrong medium type", #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "illumos", - target_os = "solaris", + linux_android, + solarish, target_os = "fuchsia", target_os = "haiku" ))] ECANCELED => "Operation canceled", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ENOKEY => "Required key not available", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EKEYEXPIRED => "Key has expired", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EKEYREVOKED => "Key has been revoked", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] EKEYREJECTED => "Key was rejected by service", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "aix", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "aix", target_os = "fuchsia"))] EOWNERDEAD => "Owner died", #[cfg(solarish)] EOWNERDEAD => "Process died with lock", - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "aix", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "aix", target_os = "fuchsia"))] ENOTRECOVERABLE => "State not recoverable", #[cfg(solarish)] @@ -771,21 +514,13 @@ fn desc(errno: Errno) -> &'static str { ))] EHWPOISON => "Memory page has hardware error", - #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] + #[cfg(freebsdlike)] EDOOFUS => "Programming error", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "redox" - ))] + #[cfg(any(freebsdlike, target_os = "redox"))] EMULTIHOP => "Multihop attempted", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "redox" - ))] + #[cfg(any(freebsdlike, target_os = "redox"))] ENOLINK => "Link has been severed", #[cfg(target_os = "freebsd")] @@ -801,8 +536,7 @@ fn desc(errno: Errno) -> &'static str { EOVERFLOW => "Value too large to be stored in data type", #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", + freebsdlike, apple_targets, target_os = "netbsd", target_os = "redox", @@ -819,20 +553,10 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any(bsd, target_os = "redox", target_os = "haiku"))] EPROTO => "Protocol error", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd" - ))] + #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] ENOTRECOVERABLE => "State not recoverable", - #[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - apple_targets, - target_os = "openbsd" - ))] + #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] EOWNERDEAD => "Previous owner died", #[cfg(any(bsd, target_os = "aix", solarish, target_os = "haiku"))] @@ -846,20 +570,18 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any( bsd, + solarish, target_os = "redox", target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "haiku" ))] EDQUOT => "Disc quota exceeded", #[cfg(any( bsd, + solarish, target_os = "redox", target_os = "aix", - target_os = "illumos", - target_os = "solaris", target_os = "haiku" ))] ESTALE => "Stale NFS file handle", @@ -947,12 +669,7 @@ fn desc(errno: Errno) -> &'static str { ))] ETIME => "STREAM ioctl timeout", - #[cfg(any( - apple_targets, - target_os = "aix", - target_os = "illumos", - target_os = "solaris" - ))] + #[cfg(any(apple_targets, solarish, target_os = "aix"))] EOPNOTSUPP => "Operation not supported on socket", #[cfg(apple_targets)] @@ -981,7 +698,7 @@ fn desc(errno: Errno) -> &'static str { } } -#[cfg(any(target_os = "linux", target_os = "android", target_os = "fuchsia"))] +#[cfg(any(linux_android, target_os = "fuchsia"))] mod consts { #[derive(Clone, Copy, Debug, Eq, PartialEq)] #[repr(i32)] From 39dfa2bb58832bbd16ad4fa19313f71e0f4f5fa5 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:39:26 +0800 Subject: [PATCH 062/140] refactor: cfg for mount/* & if_.rs (#2217) --- src/mount/bsd.rs | 3 +-- src/mount/mod.rs | 6 ++---- src/net/if_.rs | 43 +++++++++++++++++++------------------------ 3 files changed, 22 insertions(+), 30 deletions(-) diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index dc0324dda8..0e92cd0241 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -62,8 +62,7 @@ libc_bitflags!( MNT_SNAPSHOT; /// Using soft updates. #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "netbsd", target_os = "openbsd" ))] diff --git a/src/mount/mod.rs b/src/mount/mod.rs index 73ce0bac52..56e9c9a9b2 100644 --- a/src/mount/mod.rs +++ b/src/mount/mod.rs @@ -6,8 +6,7 @@ mod linux; pub use self::linux::*; #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" @@ -15,8 +14,7 @@ pub use self::linux::*; mod bsd; #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" diff --git a/src/net/if_.rs b/src/net/if_.rs index c4a761839e..49a3b2abcc 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -40,25 +40,23 @@ libc_bitflags!( IFF_POINTOPOINT; /// Avoid use of trailers. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", - target_os = "fuchsia", + #[cfg(any( + linux_android, + solarish, apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "illumos", - target_os = "solaris"))] + target_os = "fuchsia", + target_os = "netbsd"))] IFF_NOTRAILERS; /// Interface manages own routes. #[cfg(any(target_os = "dragonfly"))] IFF_SMART; /// Resources allocated. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", + #[cfg(any( + linux_android, bsd, - target_os = "fuchsia", - target_os = "illumos", - target_os = "linux", - target_os = "solaris"))] + solarish, + target_os = "fuchsia"))] IFF_RUNNING; /// No arp protocol, L2 destination address not set. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) @@ -71,7 +69,7 @@ libc_bitflags!( IFF_ALLMULTI; /// Master of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_MASTER; /// transmission in progress, tx hardware queue is full #[cfg(any(target_os = "freebsd", @@ -84,11 +82,10 @@ libc_bitflags!( IFF_INTELLIGENT; /// Slave of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_SLAVE; /// Can't hear own transmissions. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd"))] @@ -104,7 +101,7 @@ libc_bitflags!( IFF_MULTI_BCAST; /// Is able to select media type via ifmap. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_PORTSEL; /// Per link layer defined bit. #[cfg(bsd)] @@ -114,22 +111,20 @@ libc_bitflags!( IFF_UNNUMBERED; /// Auto media selection active. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_AUTOMEDIA; /// Per link layer defined bit. #[cfg(bsd)] IFF_LINK2; /// Use alternate physical connection. - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - apple_targets,))] + #[cfg(any(freebsdlike, apple_targets))] IFF_ALTPHYS; /// DHCP controls interface. #[cfg(solarish)] IFF_DHCPRUNNING; /// The addresses are lost when the interface goes down. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_DYNAMIC; /// Do not advertise. #[cfg(solarish)] @@ -195,13 +190,13 @@ libc_bitflags!( #[cfg(solarish)] IFF_NORTEXCH; /// Do not provide packet information - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_NO_PI as libc::c_int; /// TUN device (no Ethernet headers) - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_TUN as libc::c_int; /// TAP device - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_TAP as libc::c_int; /// IPv4 interface. #[cfg(solarish)] From fefed8eab47052a93423c70deb2afc1c5daeba6c Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:48:26 +0800 Subject: [PATCH 063/140] refactor: cfg for unistd.rs (#2216) --- src/unistd.rs | 396 +++++++++++++++----------------------------------- 1 file changed, 119 insertions(+), 277 deletions(-) diff --git a/src/unistd.rs b/src/unistd.rs index 6320d3c1b7..7c3a33f809 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -4,7 +4,7 @@ use crate::errno::{self, Errno}; #[cfg(any( all(feature = "fs", not(target_os = "redox")), - all(feature = "process", any(target_os = "android", target_os = "linux")) + all(feature = "process", linux_android) ))] use crate::fcntl::at_rawfd; #[cfg(not(target_os = "redox"))] @@ -39,22 +39,10 @@ feature! { pub use self::pivot_root::*; } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, linux_android, target_os = "openbsd"))] pub use self::setres::*; -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, linux_android, target_os = "openbsd"))] pub use self::getres::*; feature! { @@ -902,12 +890,7 @@ pub fn execvpe, SE: AsRef>( /// /// This function is similar to `execve`, except that the program to be executed /// is referenced as a file descriptor instead of a path. -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "dragonfly", - target_os = "freebsd" -))] +#[cfg(any(linux_android, freebsdlike))] #[inline] pub fn fexecve, SE: AsRef>( fd: RawFd, @@ -985,14 +968,11 @@ pub fn execveat, SE: AsRef>( /// * `noclose = false`: The process' stdin, stdout, and stderr will point to /// `/dev/null` after daemonizing. #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris" + linux_android, + freebsdlike, + solarish, + target_os = "netbsd", + target_os = "openbsd", ))] pub fn daemon(nochdir: bool, noclose: bool) -> Result<()> { let res = unsafe { libc::daemon(nochdir as c_int, noclose as c_int) }; @@ -1014,12 +994,10 @@ feature! { pub fn sethostname>(name: S) -> Result<()> { // Handle some differences in type of the len arg across platforms. cfg_if! { - if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + if #[cfg(any(freebsdlike, + solarish, apple_targets, - target_os = "aix", - target_os = "solaris", ))] { + target_os = "aix"))] { type sethostname_len_t = c_int; } else { type sethostname_len_t = size_t; @@ -1139,11 +1117,9 @@ pub enum Whence { /// equal to offset that contains some data. If offset points to /// some data, then the file offset is set to offset. #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + freebsdlike, + solarish, target_os = "linux", - target_os = "solaris" ))] SeekData = libc::SEEK_DATA, /// Specify an offset relative to the next hole in the file greater than @@ -1152,11 +1128,9 @@ pub enum Whence { /// then the file offset should be adjusted to the end of the file (i.e., there /// is an implicit hole at the end of any file). #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + freebsdlike, + solarish, target_os = "linux", - target_os = "solaris" ))] SeekHole = libc::SEEK_HOLE, } @@ -1216,16 +1190,13 @@ feature! { /// /// See also [pipe(2)](https://man7.org/linux/man-pages/man2/pipe.2.html) #[cfg(any( - target_os = "android", - target_os = "dragonfly", + linux_android, + freebsdlike, + solarish, target_os = "emscripten", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", target_os = "redox", target_os = "netbsd", target_os = "openbsd", - target_os = "solaris" ))] pub fn pipe2(flags: OFlag) -> Result<(OwnedFd, OwnedFd)> { let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit(); @@ -1380,8 +1351,7 @@ pub fn chroot(path: &P) -> Result<()> { /// /// See also [sync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sync.html) #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "linux", target_os = "netbsd", target_os = "openbsd" @@ -1416,15 +1386,13 @@ pub fn fsync(fd: RawFd) -> Result<()> { /// See also /// [fdatasync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fdatasync.html) #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "emscripten", + linux_android, + solarish, target_os = "freebsd", + target_os = "emscripten", target_os = "fuchsia", target_os = "netbsd", target_os = "openbsd", - target_os = "illumos", - target_os = "solaris" ))] #[inline] pub fn fdatasync(fd: RawFd) -> Result<()> { @@ -1645,9 +1613,8 @@ pub fn getgroups() -> Result> { pub fn setgroups(groups: &[Gid]) -> Result<()> { cfg_if! { if #[cfg(any(bsd, - target_os = "aix", - target_os = "illumos", - target_os = "solaris"))] { + solarish, + target_os = "aix"))] { type setgroups_ngroups_t = c_int; } else { type setgroups_ngroups_t = size_t; @@ -1994,8 +1961,7 @@ feature! { #[non_exhaustive] pub enum PathconfVar { #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "linux", target_os = "netbsd", target_os = "openbsd", @@ -2024,22 +1990,18 @@ pub enum PathconfVar { /// a pipe. PIPE_BUF = libc::_PC_PIPE_BUF, #[cfg(any( - target_os = "android", + linux_android, + solarish, target_os = "dragonfly", - target_os = "illumos", - target_os = "linux", target_os = "netbsd", target_os = "openbsd", target_os = "redox", - target_os = "solaris" ))] /// Symbolic links can be created. POSIX2_SYMLINKS = libc::_PC_2_SYMLINKS, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + linux_android, + freebsdlike, target_os = "openbsd", target_os = "redox" ))] @@ -2047,55 +2009,44 @@ pub enum PathconfVar { /// a file. POSIX_ALLOC_SIZE_MIN = libc::_PC_ALLOC_SIZE_MIN, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + freebsdlike, + linux_android, target_os = "openbsd" ))] /// Recommended increment for file transfer sizes between the /// `POSIX_REC_MIN_XFER_SIZE` and `POSIX_REC_MAX_XFER_SIZE` values. POSIX_REC_INCR_XFER_SIZE = libc::_PC_REC_INCR_XFER_SIZE, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + linux_android, + freebsdlike, target_os = "openbsd", target_os = "redox" ))] /// Maximum recommended file transfer size. POSIX_REC_MAX_XFER_SIZE = libc::_PC_REC_MAX_XFER_SIZE, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + linux_android, + freebsdlike, target_os = "openbsd", target_os = "redox" ))] /// Minimum recommended file transfer size. POSIX_REC_MIN_XFER_SIZE = libc::_PC_REC_MIN_XFER_SIZE, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + linux_android, + freebsdlike, target_os = "openbsd", target_os = "redox" ))] /// Recommended file transfer buffer alignment. POSIX_REC_XFER_ALIGN = libc::_PC_REC_XFER_ALIGN, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", + linux_android, + freebsdlike, + solarish, target_os = "netbsd", target_os = "openbsd", target_os = "redox", - target_os = "solaris" ))] /// Maximum number of bytes in a symbolic link. SYMLINK_MAX = libc::_PC_SYMLINK_MAX, @@ -2110,41 +2061,32 @@ pub enum PathconfVar { /// disable terminal special character handling. _POSIX_VDISABLE = libc::_PC_VDISABLE, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", + linux_android, + freebsdlike, + solarish, target_os = "openbsd", target_os = "redox", - target_os = "solaris" ))] /// Asynchronous input or output operations may be performed for the /// associated file. _POSIX_ASYNC_IO = libc::_PC_ASYNC_IO, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", + linux_android, + freebsdlike, + solarish, target_os = "openbsd", target_os = "redox", - target_os = "solaris" ))] /// Prioritized input or output operations may be performed for the /// associated file. _POSIX_PRIO_IO = libc::_PC_PRIO_IO, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", - target_os = "linux", + linux_android, + freebsdlike, + solarish, target_os = "netbsd", target_os = "openbsd", target_os = "redox", - target_os = "solaris" ))] /// Synchronized input or output operations may be performed for the /// associated file. @@ -2259,11 +2201,9 @@ pub enum SysconfVar { #[cfg(not(any(target_os = "redox", target_os = "haiku")))] AIO_MAX = libc::_SC_AIO_MAX, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The maximum amount by which a process can decrease its asynchronous I/O @@ -2301,12 +2241,7 @@ pub enum SysconfVar { /// the expr utility. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] EXPR_NEST_MAX = libc::_SC_EXPR_NEST_MAX, - #[cfg(any( - bsd, - target_os = "illumos", - target_os = "linux", - target_os = "solaris" - ))] + #[cfg(any(bsd, solarish, target_os = "linux"))] /// Maximum length of a host name (not including the terminating null) as /// returned from the `gethostname` function HOST_NAME_MAX = libc::_SC_HOST_NAME_MAX, @@ -2341,52 +2276,34 @@ pub enum SysconfVar { /// a newly-created file descriptor. OPEN_MAX = libc::_SC_OPEN_MAX, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" ))] /// The implementation supports the Advisory Information option. _POSIX_ADVISORY_INFO = libc::_SC_ADVISORY_INFO, - #[cfg(any( - bsd, - target_os = "illumos", - target_os = "linux", - target_os = "solaris" - ))] + #[cfg(any(bsd, solarish, target_os = "linux"))] /// The implementation supports barriers. _POSIX_BARRIERS = libc::_SC_BARRIERS, /// The implementation supports asynchronous input and output. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX_ASYNCHRONOUS_IO = libc::_SC_ASYNCHRONOUS_IO, - #[cfg(any( - bsd, - target_os = "illumos", - target_os = "linux", - target_os = "solaris" - ))] + #[cfg(any(bsd, solarish, target_os = "linux"))] /// The implementation supports clock selection. _POSIX_CLOCK_SELECTION = libc::_SC_CLOCK_SELECTION, - #[cfg(any( - bsd, - target_os = "illumos", - target_os = "linux", - target_os = "solaris" - ))] + #[cfg(any(bsd, solarish, target_os = "linux"))] /// The implementation supports the Process CPU-Time Clocks option. _POSIX_CPUTIME = libc::_SC_CPUTIME, /// The implementation supports the File Synchronization option. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX_FSYNC = libc::_SC_FSYNC, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + freebsdlike, apple_targets, + solarish, target_os = "linux", target_os = "openbsd", - target_os = "solaris" ))] /// The implementation supports the IPv6 option. _POSIX_IPV6 = libc::_SC_IPV6, @@ -2412,14 +2329,11 @@ pub enum SysconfVar { #[cfg(not(target_os = "redox"))] _POSIX_MONOTONIC_CLOCK = libc::_SC_MONOTONIC_CLOCK, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + linux_android, + freebsdlike, + solarish, apple_targets, - target_os = "linux", target_os = "openbsd", - target_os = "solaris" ))] /// The implementation supports the Prioritized Input and Output option. _POSIX_PRIORITIZED_IO = libc::_SC_PRIORITIZED_IO, @@ -2427,39 +2341,33 @@ pub enum SysconfVar { #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX_PRIORITY_SCHEDULING = libc::_SC_PRIORITY_SCHEDULING, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "illumos", + freebsdlike, + solarish, apple_targets, target_os = "linux", target_os = "openbsd", - target_os = "solaris" ))] /// The implementation supports the Raw Sockets option. _POSIX_RAW_SOCKETS = libc::_SC_RAW_SOCKETS, #[cfg(any( bsd, - target_os = "illumos", + solarish, target_os = "linux", - target_os = "solaris" ))] /// The implementation supports read-write locks. _POSIX_READER_WRITER_LOCKS = libc::_SC_READER_WRITER_LOCKS, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The implementation supports realtime signals. _POSIX_REALTIME_SIGNALS = libc::_SC_REALTIME_SIGNALS, #[cfg(any( bsd, - target_os = "illumos", + solarish, target_os = "linux", - target_os = "solaris" ))] /// The implementation supports the Regular Expression Handling option. _POSIX_REGEXP = libc::_SC_REGEXP, @@ -2482,8 +2390,7 @@ pub enum SysconfVar { /// The implementation supports spin locks. _POSIX_SPIN_LOCKS = libc::_SC_SPIN_LOCKS, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2545,8 +2452,7 @@ pub enum SysconfVar { #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _POSIX_THREAD_SAFE_FUNCTIONS = libc::_SC_THREAD_SAFE_FUNCTIONS, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2557,8 +2463,7 @@ pub enum SysconfVar { #[cfg(not(target_os = "redox"))] _POSIX_THREADS = libc::_SC_THREADS, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2569,8 +2474,7 @@ pub enum SysconfVar { #[cfg(not(target_os = "redox"))] _POSIX_TIMERS = libc::_SC_TIMERS, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2578,8 +2482,7 @@ pub enum SysconfVar { /// The implementation supports the Trace option. _POSIX_TRACE = libc::_SC_TRACE, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2593,8 +2496,7 @@ pub enum SysconfVar { ))] _POSIX_TRACE_EVENT_NAME_MAX = libc::_SC_TRACE_EVENT_NAME_MAX, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2602,8 +2504,7 @@ pub enum SysconfVar { /// The implementation supports the Trace Inherit option. _POSIX_TRACE_INHERIT = libc::_SC_TRACE_INHERIT, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2629,8 +2530,7 @@ pub enum SysconfVar { ))] _POSIX_TRACE_USER_EVENT_MAX = libc::_SC_TRACE_USER_EVENT_MAX, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2723,31 +2623,25 @@ pub enum SysconfVar { #[cfg(not(target_os = "haiku"))] RE_DUP_MAX = libc::_SC_RE_DUP_MAX, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] RTSIG_MAX = libc::_SC_RTSIG_MAX, #[cfg(not(target_os = "redox"))] SEM_NSEMS_MAX = libc::_SC_SEM_NSEMS_MAX, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] SEM_VALUE_MAX = libc::_SC_SEM_VALUE_MAX, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] SIGQUEUE_MAX = libc::_SC_SIGQUEUE_MAX, @@ -2759,51 +2653,41 @@ pub enum SysconfVar { TTY_NAME_MAX = libc::_SC_TTY_NAME_MAX, TZNAME_MAX = libc::_SC_TZNAME_MAX, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The implementation supports the X/Open Encryption Option Group. _XOPEN_CRYPT = libc::_SC_XOPEN_CRYPT, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The implementation supports the Issue 4, Version 2 Enhanced /// Internationalization Option Group. _XOPEN_ENH_I18N = libc::_SC_XOPEN_ENH_I18N, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] _XOPEN_LEGACY = libc::_SC_XOPEN_LEGACY, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The implementation supports the X/Open Realtime Option Group. _XOPEN_REALTIME = libc::_SC_XOPEN_REALTIME, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The implementation supports the X/Open Realtime Threads Option Group. @@ -2813,8 +2697,7 @@ pub enum SysconfVar { #[cfg(not(any(target_os = "redox", target_os = "haiku")))] _XOPEN_SHM = libc::_SC_XOPEN_SHM, #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "linux", target_os = "openbsd" @@ -2822,21 +2705,17 @@ pub enum SysconfVar { /// The implementation supports the XSI STREAMS Option Group. _XOPEN_STREAMS = libc::_SC_XOPEN_STREAMS, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// The implementation supports the XSI option _XOPEN_UNIX = libc::_SC_XOPEN_UNIX, #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + linux_android, + freebsdlike, apple_targets, - target_os = "linux", target_os = "openbsd" ))] /// Integer value indicating version of the X/Open Portability Guide to @@ -2914,13 +2793,7 @@ mod pivot_root { } } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))] mod setres { feature! { #![feature = "user"] @@ -2965,13 +2838,7 @@ mod setres { } } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))] mod getres { feature! { #![feature = "user"] @@ -3108,9 +2975,8 @@ pub fn faccessat( /// * [FreeBSD man page](https://www.freebsd.org/cgi/man.cgi?query=eaccess&sektion=2&n=1) /// * [Linux man page](https://man7.org/linux/man-pages/man3/euidaccess.3.html) #[cfg(any( + freebsdlike, all(target_os = "linux", not(target_env = "uclibc")), - target_os = "freebsd", - target_os = "dragonfly" ))] pub fn eaccess(path: &P, mode: AccessFlags) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { @@ -3149,35 +3015,29 @@ pub struct User { pub shell: PathBuf, /// Login class #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] pub class: CString, /// Last password change #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] pub change: libc::time_t, /// Expiration time of account #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] pub expire: libc::time_t, } @@ -3225,34 +3085,28 @@ impl From<&libc::passwd> for User { uid: Uid::from_raw(pw.pw_uid), gid: Gid::from_raw(pw.pw_gid), #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] class: CString::new(CStr::from_ptr(pw.pw_class).to_bytes()) .unwrap(), #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] change: pw.pw_change, #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] expire: pw.pw_expire, } @@ -3288,33 +3142,27 @@ impl From for libc::passwd { pw_uid: u.uid.0, pw_gid: u.gid.0, #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] pw_class: u.class.into_raw(), #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] pw_change: u.change, #[cfg(not(any( + linux_android, + solarish, target_os = "aix", - target_os = "android", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", - target_os = "solaris" )))] pw_expire: u.expire, #[cfg(target_os = "illumos")] @@ -3638,13 +3486,7 @@ feature! { /// Set the file flags. /// /// See also [chflags(2)](https://www.freebsd.org/cgi/man.cgi?query=chflags&sektion=2) -#[cfg(any( - target_os = "openbsd", - target_os = "netbsd", - target_os = "freebsd", - target_os = "dragonfly", - apple_targets -))] +#[cfg(bsd)] pub fn chflags(path: &P, flags: FileFlag) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { libc::chflags(cstr.as_ptr(), flags.bits()) From 89aa05e0867135c38d492104c56f25fd277533e8 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:49:18 +0800 Subject: [PATCH 064/140] refactor: cfg for ioctl/* & ptrace/* (#2222) --- src/sys/ioctl/mod.rs | 8 ++------ src/sys/ptrace/bsd.rs | 9 ++------- src/sys/ptrace/mod.rs | 6 ++---- 3 files changed, 6 insertions(+), 17 deletions(-) diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index 200c94d861..df222ec86c 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -227,15 +227,11 @@ //! ``` use cfg_if::cfg_if; -#[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] +#[cfg(any(linux_android, target_os = "redox"))] #[macro_use] mod linux; -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "redox" -))] +#[cfg(any(linux_android, target_os = "redox"))] pub use self::linux::*; #[cfg(any(bsd, target_os = "illumos", target_os = "haiku",))] diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index 086e32dcaf..32a53085af 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -9,10 +9,7 @@ use std::ptr; pub type RequestType = c_int; cfg_if! { - if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "openbsd"))] { + if #[cfg(any(freebsdlike, target_os = "macos", target_os = "openbsd"))] { #[doc(hidden)] pub type AddressType = *mut ::libc::c_char; } else { @@ -37,9 +34,7 @@ libc_enum! { PT_WRITE_U, PT_CONTINUE, PT_KILL, - #[cfg(any(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos"), + #[cfg(any(any(freebsdlike, target_os = "macos"), all(target_os = "openbsd", target_arch = "x86_64"), all(target_os = "netbsd", any(target_arch = "x86_64", target_arch = "powerpc"))))] diff --git a/src/sys/ptrace/mod.rs b/src/sys/ptrace/mod.rs index 90176e6a77..f87073fef2 100644 --- a/src/sys/ptrace/mod.rs +++ b/src/sys/ptrace/mod.rs @@ -7,8 +7,7 @@ mod linux; pub use self::linux::*; #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" @@ -16,8 +15,7 @@ pub use self::linux::*; mod bsd; #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "macos", target_os = "netbsd", target_os = "openbsd" From 974740f16c5642d82f350ed274411deb8b2dfc89 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 26 Nov 2023 23:57:45 +0800 Subject: [PATCH 065/140] refactor: cfg for socket/addr.rs (#2223) --- src/sys/socket/addr.rs | 169 +++++++++-------------------------------- 1 file changed, 35 insertions(+), 134 deletions(-) diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 5c4bb9bf06..41d30b03a0 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -1,7 +1,6 @@ #[cfg(any( bsd, - target_os = "android", - target_os = "linux", + linux_android, target_os = "illumos", target_os = "haiku", target_os = "fuchsia", @@ -9,11 +8,7 @@ ))] #[cfg(feature = "net")] pub use self::datalink::LinkAddr; -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" -))] +#[cfg(any(linux_android, target_os = "macos"))] pub use self::vsock::VsockAddr; use super::sa_family_t; use crate::errno::Errno; @@ -71,20 +66,10 @@ pub enum AddressFamily { #[cfg(linux_android)] Netlink = libc::AF_NETLINK, /// Kernel interface for interacting with the routing table - #[cfg(not(any( - target_os = "redox", - target_os = "linux", - target_os = "android" - )))] + #[cfg(not(any(linux_android, target_os = "redox")))] Route = libc::PF_ROUTE, /// Low level packet interface (see [`packet(7)`](https://man7.org/linux/man-pages/man7/packet.7.html)) - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "illumos", - target_os = "fuchsia", - target_os = "solaris" - ))] + #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] Packet = libc::AF_PACKET, /// KEXT Controls and Notifications #[cfg(apple_targets)] @@ -175,9 +160,8 @@ pub enum AddressFamily { /// Bluetooth low-level socket protocol #[cfg(not(any( target_os = "aix", - target_os = "illumos", + solarish, apple_targets, - target_os = "solaris", target_os = "redox", )))] Bluetooth = libc::AF_BLUETOOTH, @@ -191,8 +175,7 @@ pub enum AddressFamily { /// New "modular ISDN" driver interface protocol #[cfg(not(any( target_os = "aix", - target_os = "illumos", - target_os = "solaris", + solarish, target_os = "haiku", target_os = "redox", )))] @@ -214,11 +197,7 @@ pub enum AddressFamily { #[cfg(target_os = "linux")] Nfc = libc::AF_NFC, /// VMWare VSockets protocol for hypervisor-guest interaction. - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] Vsock = libc::AF_VSOCK, /// ARPANet IMP addresses #[cfg(bsd)] @@ -280,23 +259,15 @@ impl AddressFamily { libc::AF_INET6 => Some(AddressFamily::Inet6), #[cfg(linux_android)] libc::AF_NETLINK => Some(AddressFamily::Netlink), - #[cfg(any(target_os = "macos", target_os = "macos"))] + #[cfg(target_os = "macos")] libc::AF_SYSTEM => Some(AddressFamily::System), - #[cfg(not(any( - target_os = "redox", - target_os = "linux", - target_os = "android" - )))] + #[cfg(not(any(linux_android, target_os = "redox")))] libc::PF_ROUTE => Some(AddressFamily::Route), #[cfg(linux_android)] libc::AF_PACKET => Some(AddressFamily::Packet), #[cfg(any(bsd, target_os = "illumos"))] libc::AF_LINK => Some(AddressFamily::Link), - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] libc::AF_VSOCK => Some(AddressFamily::Vsock), _ => None, } @@ -313,10 +284,9 @@ pub struct UnixAddr { /// but excluding any trailing nul. // On the BSDs, this field is built into sun #[cfg(any( - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux", target_os = "redox", ))] sun_len: u8, @@ -475,10 +445,9 @@ impl UnixAddr { sun_len: u8, ) -> UnixAddr { cfg_if! { - if #[cfg(any(target_os = "android", + if #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux", target_os = "redox", ))] { @@ -540,10 +509,9 @@ impl UnixAddr { fn sun_len(&self) -> u8 { cfg_if! { - if #[cfg(any(target_os = "android", + if #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux", target_os = "redox", ))] { @@ -557,12 +525,7 @@ impl UnixAddr { impl private::SockaddrLikePriv for UnixAddr {} impl SockaddrLike for UnixAddr { - #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "illumos", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos"))] fn len(&self) -> libc::socklen_t { self.sun_len.into() } @@ -587,10 +550,9 @@ impl SockaddrLike for UnixAddr { let mut su: libc::sockaddr_un = unsafe { mem::zeroed() }; let sup = &mut su as *mut libc::sockaddr_un as *mut u8; cfg_if! { - if #[cfg(any(target_os = "android", + if #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux", target_os = "redox", ))] { let su_len = len.unwrap_or( @@ -618,10 +580,9 @@ impl SockaddrLike for UnixAddr { // `new_length` is only used on some platforms, so it must be provided even when not used #![allow(unused_variables)] cfg_if! { - if #[cfg(any(target_os = "android", + if #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux", target_os = "redox", ))] { self.sun_len = new_length as u8; @@ -1117,11 +1078,7 @@ pub union SockaddrStorage { sin6: SockaddrIn6, ss: libc::sockaddr_storage, su: UnixAddr, - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] vsock: VsockAddr, } impl private::SockaddrLikePriv for SockaddrStorage {} @@ -1147,10 +1104,9 @@ impl SockaddrLike for SockaddrStorage { let ssp = &mut ss as *mut libc::sockaddr_storage as *mut u8; unsafe { ptr::copy(addr as *const u8, ssp, len as usize) }; #[cfg(any( - target_os = "android", + linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux" ))] if i32::from(ss.ss_family) == libc::AF_UNIX { // Safe because we UnixAddr is strictly smaller than @@ -1189,11 +1145,7 @@ impl SockaddrLike for SockaddrStorage { libc::AF_NETLINK => unsafe { NetlinkAddr::from_raw(addr, l).map(|nl| Self { nl }) }, - #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] #[cfg(feature = "net")] libc::AF_PACKET => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) @@ -1202,11 +1154,7 @@ impl SockaddrLike for SockaddrStorage { libc::AF_SYSTEM => unsafe { SysControlAddr::from_raw(addr, l).map(|sctl| Self { sctl }) }, - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos", - ))] + #[cfg(any(linux_android, target_os = "macos"))] libc::AF_VSOCK => unsafe { VsockAddr::from_raw(addr, l).map(|vsock| Self { vsock }) }, @@ -1215,12 +1163,7 @@ impl SockaddrLike for SockaddrStorage { } } - #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "illumos", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos"))] fn len(&self) -> libc::socklen_t { match self.as_unix_addr() { // The UnixAddr type knows its own length @@ -1279,10 +1222,9 @@ impl SockaddrStorage { /// Downcast to an immutable `[UnixAddr]` reference. pub fn as_unix_addr(&self) -> Option<&UnixAddr> { cfg_if! { - if #[cfg(any(target_os = "android", + if #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux" ))] { let p = unsafe{ &self.ss as *const libc::sockaddr_storage }; @@ -1309,10 +1251,9 @@ impl SockaddrStorage { /// Downcast to a mutable `[UnixAddr]` reference. pub fn as_unix_addr_mut(&mut self) -> Option<&mut UnixAddr> { cfg_if! { - if #[cfg(any(target_os = "android", + if #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos", - target_os = "linux" ))] { let p = unsafe{ &self.ss as *const libc::sockaddr_storage }; @@ -1340,11 +1281,7 @@ impl SockaddrStorage { accessors! {as_alg_addr, as_alg_addr_mut, AlgAddr, AddressFamily::Alg, libc::sockaddr_alg, alg} - #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] #[cfg(feature = "net")] accessors! { as_link_addr, as_link_addr_mut, LinkAddr, @@ -1375,11 +1312,7 @@ impl SockaddrStorage { accessors! {as_sys_control_addr, as_sys_control_addr_mut, SysControlAddr, AddressFamily::System, libc::sockaddr_ctl, sctl} - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] accessors! {as_vsock_addr, as_vsock_addr_mut, VsockAddr, AddressFamily::Vsock, libc::sockaddr_vm, vsock} } @@ -1409,22 +1342,14 @@ impl fmt::Display for SockaddrStorage { libc::AF_LINK => self.dl.fmt(f), #[cfg(linux_android)] libc::AF_NETLINK => self.nl.fmt(f), - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] #[cfg(feature = "net")] libc::AF_PACKET => self.dl.fmt(f), #[cfg(apple_targets)] #[cfg(feature = "ioctl")] libc::AF_SYSTEM => self.sctl.fmt(f), libc::AF_UNIX => self.su.fmt(f), - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] libc::AF_VSOCK => self.vsock.fmt(f), _ => "
".fmt(f), } @@ -1479,22 +1404,14 @@ impl Hash for SockaddrStorage { libc::AF_LINK => self.dl.hash(s), #[cfg(linux_android)] libc::AF_NETLINK => self.nl.hash(s), - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "fuchsia" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] #[cfg(feature = "net")] libc::AF_PACKET => self.dl.hash(s), #[cfg(apple_targets)] #[cfg(feature = "ioctl")] libc::AF_SYSTEM => self.sctl.hash(s), libc::AF_UNIX => self.su.hash(s), - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] libc::AF_VSOCK => self.vsock.hash(s), _ => self.ss.hash(s), } @@ -1517,22 +1434,14 @@ impl PartialEq for SockaddrStorage { (libc::AF_LINK, libc::AF_LINK) => self.dl == other.dl, #[cfg(linux_android)] (libc::AF_NETLINK, libc::AF_NETLINK) => self.nl == other.nl, - #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] #[cfg(feature = "net")] (libc::AF_PACKET, libc::AF_PACKET) => self.dl == other.dl, #[cfg(apple_targets)] #[cfg(feature = "ioctl")] (libc::AF_SYSTEM, libc::AF_SYSTEM) => self.sctl == other.sctl, (libc::AF_UNIX, libc::AF_UNIX) => self.su == other.su, - #[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" - ))] + #[cfg(any(linux_android, target_os = "macos"))] (libc::AF_VSOCK, libc::AF_VSOCK) => self.vsock == other.vsock, _ => false, } @@ -1857,7 +1766,7 @@ pub mod sys_control { } } -#[cfg(any(target_os = "android", target_os = "linux", target_os = "fuchsia"))] +#[cfg(any(linux_android, target_os = "fuchsia"))] mod datalink { feature! { #![feature = "net"] @@ -2063,7 +1972,7 @@ mod datalink { } } -#[cfg(any(target_os = "android", target_os = "linux", target_os = "macos"))] +#[cfg(any(linux_android, target_os = "macos"))] pub mod vsock { use super::*; use crate::sys::socket::addr::AddressFamily; @@ -2249,11 +2158,7 @@ mod tests { } #[cfg(all( - any( - target_os = "android", - target_os = "fuchsia", - target_os = "linux" - ), + any(linux_android, target_os = "fuchsia"), target_endian = "little" ))] #[test] @@ -2345,11 +2250,7 @@ mod tests { target_os = "haiku" ))] let l = mem::size_of::(); - #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "linux" - ))] + #[cfg(any(linux_android, target_os = "fuchsia"))] let l = mem::size_of::(); assert_eq!(LinkAddr::size() as usize, l); } From 51adb3023ce33dc9117d68679586921538ee48e2 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 27 Nov 2023 00:03:06 +0800 Subject: [PATCH 066/140] refactor: cfg for socket/mod.rs (#2224) --- src/sys/socket/mod.rs | 247 +++++++++++------------------------------- 1 file changed, 64 insertions(+), 183 deletions(-) diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 1e34ef456d..a145444fa2 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -38,20 +38,10 @@ pub use self::addr::{SockaddrLike, SockaddrStorage}; pub use self::addr::{AddressFamily, UnixAddr}; #[cfg(not(solarish))] pub use self::addr::{AddressFamily, UnixAddr}; -#[cfg(not(any( - target_os = "illumos", - target_os = "solaris", - target_os = "haiku", - target_os = "redox", -)))] +#[cfg(not(any(solarish, target_os = "haiku", target_os = "redox")))] #[cfg(feature = "net")] pub use self::addr::{LinkAddr, SockaddrIn, SockaddrIn6}; -#[cfg(any( - target_os = "illumos", - target_os = "solaris", - target_os = "haiku", - target_os = "redox", -))] +#[cfg(any(solarish, target_os = "haiku", target_os = "redox"))] #[cfg(feature = "net")] pub use self::addr::{SockaddrIn, SockaddrIn6}; @@ -62,11 +52,7 @@ pub use crate::sys::socket::addr::netlink::NetlinkAddr; #[cfg(apple_targets)] #[cfg(feature = "ioctl")] pub use crate::sys::socket::addr::sys_control::SysControlAddr; -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "macos" -))] +#[cfg(any(linux_android, target_os = "macos"))] pub use crate::sys::socket::addr::vsock::VsockAddr; #[cfg(all(feature = "uio", not(target_os = "redox")))] @@ -267,20 +253,16 @@ libc_bitflags! { /// Additional socket options pub struct SockFlag: c_int { /// Set non-blocking mode on the new socket - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(linux_android, + freebsdlike, target_os = "illumos", - target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] SOCK_NONBLOCK; /// Set close-on-exec on the new descriptor - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(linux_android, + freebsdlike, target_os = "illumos", - target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] SOCK_CLOEXEC; @@ -347,31 +329,25 @@ libc_bitflags! { /// [open(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html). /// /// Only used in [`recvmsg`](fn.recvmsg.html) function. - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", + #[cfg(any(linux_android, + freebsdlike, target_os = "netbsd", target_os = "openbsd"))] MSG_CMSG_CLOEXEC; /// Requests not to send `SIGPIPE` errors when the other end breaks the connection. /// (For more details, see [send(2)](https://linux.die.net/man/2/send)). - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", + #[cfg(any(linux_android, + freebsdlike, + solarish, target_os = "fuchsia", target_os = "haiku", - target_os = "illumos", - target_os = "linux", target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris"))] + target_os = "openbsd"))] MSG_NOSIGNAL; /// Turns on [`MSG_DONTWAIT`] after the first message has been received (only for /// `recvmmsg()`). - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "linux", target_os = "netbsd", target_os = "freebsd", target_os = "openbsd", @@ -504,11 +480,7 @@ cfg_if! { } cfg_if! { - if #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets - ))] { + if #[cfg(any(freebsdlike, apple_targets))] { /// Return type of [`LocalPeerCred`](crate::sys::socket::sockopt::LocalPeerCred) #[repr(transparent)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -775,20 +747,11 @@ pub enum ControlMessageOwned { /// [Further reading](https://man.freebsd.org/cgi/man.cgi?setsockopt) #[cfg(target_os = "freebsd")] ScmMonotonic(TimeSpec), - #[cfg(any( - target_os = "android", - apple_targets, - target_os = "linux", - target_os = "netbsd", - ))] + #[cfg(any(linux_android, apple_targets, target_os = "netbsd"))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4PacketInfo(libc::in_pktinfo), - #[cfg(any( - target_os = "android", - bsd, - target_os = "linux", - ))] + #[cfg(any(linux_android, bsd))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6PacketInfo(libc::in6_pktinfo), @@ -810,11 +773,11 @@ pub enum ControlMessageOwned { #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvDstAddr(libc::in_addr), - #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4OrigDstAddr(libc::sockaddr_in), - #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6OrigDstAddr(libc::sockaddr_in6), @@ -840,7 +803,7 @@ pub enum ControlMessageOwned { /// /// `RxqOvfl` socket option should be enabled on a socket /// to allow receiving the drop counter. - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] RxqOvfl(u32), /// Socket error queue control messages read with the `MSG_ERRQUEUE` flag. @@ -973,23 +936,13 @@ impl ControlMessageOwned { let timestamping = Timestamps { system, hw_trans, hw_raw }; ControlMessageOwned::ScmTimestampsns(timestamping) } - #[cfg(any( - target_os = "android", - target_os = "freebsd", - apple_targets, - target_os = "linux" - ))] + #[cfg(any(target_os = "freebsd", linux_android, apple_targets))] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_PKTINFO) => { let info = unsafe { ptr::read_unaligned(p as *const libc::in6_pktinfo) }; ControlMessageOwned::Ipv6PacketInfo(info) } - #[cfg(any( - target_os = "android", - apple_targets, - target_os = "linux", - target_os = "netbsd", - ))] + #[cfg(any(linux_android, apple_targets, target_os = "netbsd"))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_PKTINFO) => { let info = unsafe { ptr::read_unaligned(p as *const libc::in_pktinfo) }; @@ -1017,7 +970,7 @@ impl ControlMessageOwned { let dl = unsafe { ptr::read_unaligned(p as *const libc::in_addr) }; ControlMessageOwned::Ipv4RecvDstAddr(dl) }, - #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_ORIGDSTADDR) => { let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_in) }; @@ -1029,7 +982,7 @@ impl ControlMessageOwned { let gso_size: u16 = unsafe { ptr::read_unaligned(p as *const _) }; ControlMessageOwned::UdpGroSegments(gso_size) }, - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] (libc::SOL_SOCKET, libc::SO_RXQ_OVFL) => { let drop_counter = unsafe { ptr::read_unaligned(p as *const u32) }; ControlMessageOwned::RxqOvfl(drop_counter) @@ -1046,7 +999,7 @@ impl ControlMessageOwned { let (err, addr) = unsafe { Self::recv_err_helper::(p, len) }; ControlMessageOwned::Ipv6RecvErr(err, addr) }, - #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "net")] (libc::IPPROTO_IPV6, libc::IPV6_ORIGDSTADDR) => { let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_in6) }; @@ -1137,30 +1090,21 @@ pub enum ControlMessage<'a> { /// /// For further information, please refer to the /// [`documentation`](https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html) - #[cfg(any( - target_os = "android", - target_os = "linux", - ))] + #[cfg(linux_android)] AlgSetIv(&'a [u8]), /// Set crypto operation for `AF_ALG` crypto API. It may be one of /// `ALG_OP_ENCRYPT` or `ALG_OP_DECRYPT` /// /// For further information, please refer to the /// [`documentation`](https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html) - #[cfg(any( - target_os = "android", - target_os = "linux", - ))] + #[cfg(linux_android)] AlgSetOp(&'a libc::c_int), /// Set the length of associated authentication data (AAD) (applicable only to AEAD algorithms) /// for `AF_ALG` crypto API. /// /// For further information, please refer to the /// [`documentation`](https://kernel.readthedocs.io/en/sphinx-samples/crypto-API.html) - #[cfg(any( - target_os = "android", - target_os = "linux", - ))] + #[cfg(linux_android)] AlgSetAeadAssoclen(&'a u32), /// UDP GSO makes it possible for applications to generate network packets @@ -1192,22 +1136,16 @@ pub enum ControlMessage<'a> { /// /// For further information, please refer to the /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. - #[cfg(any(target_os = "linux", + #[cfg(any(linux_android, target_os = "netbsd", target_os = "freebsd", - target_os = "android", apple_targets))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6PacketInfo(&'a libc::in6_pktinfo), /// Configure the IPv4 source address with `IP_SENDSRCADDR`. - #[cfg(any( - target_os = "netbsd", - target_os = "freebsd", - target_os = "openbsd", - target_os = "dragonfly", - ))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4SendSrcAddr(&'a libc::in_addr), @@ -1220,9 +1158,7 @@ pub enum ControlMessage<'a> { /// with sendmsg have a hop limit of 1 and will not leave the local network. /// For further information, please refer to the /// [`ipv6(7)`](https://man7.org/linux/man-pages/man7/ipv6.7.html) man page. - #[cfg(any(target_os = "linux", target_os = "freebsd", - target_os = "dragonfly", target_os = "android", - apple_targets, target_os = "haiku"))] + #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6HopLimit(&'a libc::c_int), @@ -1232,7 +1168,7 @@ pub enum ControlMessage<'a> { /// skbs indicating the number of packets dropped by the /// socket between the last recieved packet and this /// received packet. - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] RxqOvfl(&'a u32), /// Configure the transmission time of packets. @@ -1325,25 +1261,20 @@ impl<'a> ControlMessage<'a> { ControlMessage::UdpGsoSegments(gso_size) => { gso_size as *const _ as *const u8 }, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "android", apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(info) => info as *const _ as *const u8, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "freebsd", target_os = "android", - apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", + target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => info as *const _ as *const u8, - #[cfg(any(target_os = "netbsd", target_os = "freebsd", - target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => addr as *const _ as *const u8, - #[cfg(any(target_os = "linux", target_os = "freebsd", - target_os = "dragonfly", target_os = "android", - apple_targets, target_os = "haiku"))] + #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(limit) => limit as *const _ as *const u8, - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ControlMessage::RxqOvfl(drop_count) => { drop_count as *const _ as *const u8 }, @@ -1392,27 +1323,22 @@ impl<'a> ControlMessage<'a> { ControlMessage::UdpGsoSegments(gso_size) => { mem::size_of_val(gso_size) }, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "android", apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(info) => mem::size_of_val(info), - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "freebsd", target_os = "android", - apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", + target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => mem::size_of_val(info), - #[cfg(any(target_os = "netbsd", target_os = "freebsd", - target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => mem::size_of_val(addr), - #[cfg(any(target_os = "linux", target_os = "freebsd", - target_os = "dragonfly", target_os = "android", - apple_targets, target_os = "haiku"))] + #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(limit) => { mem::size_of_val(limit) }, - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ControlMessage::RxqOvfl(drop_count) => { mem::size_of_val(drop_count) }, @@ -1437,25 +1363,20 @@ impl<'a> ControlMessage<'a> { #[cfg(target_os = "linux")] #[cfg(feature = "net")] ControlMessage::UdpGsoSegments(_) => libc::SOL_UDP, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "android", apple_targets,))] + #[cfg(any(linux_android, target_os = "netbsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(_) => libc::IPPROTO_IP, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "freebsd", target_os = "android", - apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", + target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPPROTO_IPV6, - #[cfg(any(target_os = "netbsd", target_os = "freebsd", - target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IPPROTO_IP, - #[cfg(any(target_os = "linux", target_os = "freebsd", - target_os = "dragonfly", target_os = "android", - apple_targets, target_os = "haiku"))] + #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(_) => libc::IPPROTO_IPV6, - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ControlMessage::RxqOvfl(_) => libc::SOL_SOCKET, #[cfg(target_os = "linux")] ControlMessage::TxTime(_) => libc::SOL_SOCKET, @@ -1487,25 +1408,20 @@ impl<'a> ControlMessage<'a> { ControlMessage::UdpGsoSegments(_) => { libc::UDP_SEGMENT }, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "android", apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv4PacketInfo(_) => libc::IP_PKTINFO, - #[cfg(any(target_os = "linux", target_os = "netbsd", - target_os = "freebsd", target_os = "android", - apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", + target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPV6_PKTINFO, - #[cfg(any(target_os = "netbsd", target_os = "freebsd", - target_os = "openbsd", target_os = "dragonfly"))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IP_SENDSRCADDR, - #[cfg(any(target_os = "linux", target_os = "freebsd", - target_os = "dragonfly", target_os = "android", - apple_targets, target_os = "haiku"))] + #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] #[cfg(feature = "net")] ControlMessage::Ipv6HopLimit(_) => libc::IPV6_HOPLIMIT, - #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] + #[cfg(any(linux_android, target_os = "fuchsia"))] ControlMessage::RxqOvfl(_) => { libc::SO_RXQ_OVFL }, @@ -1604,12 +1520,7 @@ pub fn sendmsg(fd: RawFd, iov: &[IoSlice<'_>], cmsgs: &[ControlMessage], /// /// # References /// [`sendmsg`](fn.sendmsg.html) -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] pub fn sendmmsg<'a, XS, AS, C, I, S>( fd: RawFd, data: &'a mut MultiHeaders, @@ -1680,12 +1591,7 @@ pub fn sendmmsg<'a, XS, AS, C, I, S>( } -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] #[derive(Debug)] /// Preallocated structures needed for [`recvmmsg`] and [`sendmmsg`] functions pub struct MultiHeaders { @@ -1698,12 +1604,7 @@ pub struct MultiHeaders { msg_controllen: usize, } -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] impl MultiHeaders { /// Preallocate structure used by [`recvmmsg`] and [`sendmmsg`] takes number of headers to preallocate /// @@ -1773,12 +1674,7 @@ impl MultiHeaders { // always produce the desired results - see https://github.com/nix-rust/nix/pull/1744 for more // details -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] pub fn recvmmsg<'a, XS, S, I>( fd: RawFd, data: &'a mut MultiHeaders, @@ -1827,12 +1723,7 @@ where } /// Iterator over results of [`recvmmsg`]/[`sendmmsg`] -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] #[derive(Debug)] pub struct MultiResults<'a, S> { // preallocated structures @@ -1841,12 +1732,7 @@ pub struct MultiResults<'a, S> { received: usize, } -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] impl<'a, S> Iterator for MultiResults<'a, S> where S: Copy + SockaddrLike, @@ -2296,9 +2182,8 @@ pub fn accept(sockfd: RawFd) -> Result { target_arch = "x86_64" ) ), - target_os = "dragonfly", + freebsdlike, target_os = "emscripten", - target_os = "freebsd", target_os = "fuchsia", target_os = "illumos", target_os = "linux", @@ -2519,11 +2404,7 @@ mod tests { let _ = cmsg_space!(u8); } - #[cfg(not(any( - target_os = "redox", - target_os = "linux", - target_os = "android" - )))] + #[cfg(not(any(linux_android, target_os = "redox")))] #[test] fn can_open_routing_socket() { let _ = super::socket( From 4e5f08972d62b3d73b8800f566e9c0f60d72398a Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 27 Nov 2023 00:11:09 +0800 Subject: [PATCH 067/140] refactor: cfg for socket/sockopt.rs (#2225) --- src/sys/socket/sockopt.rs | 38 ++++++++++++-------------------------- 1 file changed, 12 insertions(+), 26 deletions(-) diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 520d2351c7..6776e15627 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -7,7 +7,6 @@ use cfg_if::cfg_if; use libc::{self, c_int, c_void, socklen_t}; use std::ffi::{OsStr, OsString}; use std::mem::{self, MaybeUninit}; -#[cfg(target_family = "unix")] use std::os::unix::ffi::OsStrExt; use std::os::unix::io::{AsFd, AsRawFd}; @@ -329,9 +328,7 @@ cfg_if! { #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Leave an IPv6 multicast group. Ipv6DropMembership, SetOnly, libc::IPPROTO_IPV6, libc::IPV6_DROP_MEMBERSHIP, super::Ipv6MembershipRequest); - } else if #[cfg(any(bsd, - target_os = "illumos", - target_os = "solaris"))] { + } else if #[cfg(any(bsd, solarish))] { #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -403,7 +400,7 @@ sockopt_impl!( libc::IPV6_TCLASS, libc::c_int ); -#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "fuchsia"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -512,12 +509,7 @@ sockopt_impl!( libc::TCP_KEEPALIVE, u32 ); -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux" -))] +#[cfg(any(freebsdlike, linux_android))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -556,7 +548,7 @@ sockopt_impl!( libc::TCP_KEEPCNT, u32 ); -#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "fuchsia"))] sockopt_impl!( #[allow(missing_docs)] // Not documented by Linux! @@ -826,12 +818,7 @@ sockopt_impl!( libc::TCP_CONGESTION, OsString<[u8; TCP_CA_NAME_MAX]> ); -#[cfg(any( - target_os = "android", - apple_targets, - target_os = "linux", - target_os = "netbsd", -))] +#[cfg(any(linux_android, apple_targets, target_os = "netbsd"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -844,10 +831,9 @@ sockopt_impl!( bool ); #[cfg(any( - target_os = "android", + linux_android, target_os = "freebsd", apple_targets, - target_os = "linux", target_os = "netbsd", target_os = "openbsd", ))] @@ -896,7 +882,7 @@ sockopt_impl!( libc::IP_RECVDSTADDR, bool ); -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -942,7 +928,7 @@ sockopt_impl!( libc::SO_TXTIME, libc::sock_txtime ); -#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "fuchsia"))] sockopt_impl!( /// Indicates that an unsigned 32-bit value ancillary message (cmsg) should /// be attached to received skbs indicating the number of packets dropped by @@ -990,7 +976,7 @@ sockopt_impl!( libc::IP_MTU, libc::c_int ); -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] sockopt_impl!( /// Set or retrieve the current time-to-live field that is used in every /// packet sent from this socket. @@ -1000,7 +986,7 @@ sockopt_impl!( libc::IP_TTL, libc::c_int ); -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] sockopt_impl!( /// Set the unicast hop limit for the socket. Ipv6Ttl, @@ -1009,7 +995,7 @@ sockopt_impl!( libc::IPV6_UNICAST_HOPS, libc::c_int ); -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -1030,7 +1016,7 @@ sockopt_impl!( libc::IP_DONTFRAG, bool ); -#[cfg(any(target_os = "android", apple_targets, target_os = "linux",))] +#[cfg(any(linux_android, apple_targets))] sockopt_impl!( /// Set "don't fragment packet" flag on the IPv6 packet. Ipv6DontFrag, From e411540aeb164064473deb763f8d135247351994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ad=C3=A4?= Date: Mon, 27 Nov 2023 00:32:57 +0100 Subject: [PATCH 068/140] netbsdlike (#2226) --- build.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/build.rs b/build.rs index c5ccd8b6dc..4535af1f04 100644 --- a/build.rs +++ b/build.rs @@ -19,6 +19,7 @@ fn main() { bsd: { any(freebsd, dragonfly, netbsd, openbsd, apple_targets) }, linux_android: { any(android, linux) }, freebsdlike: { any(dragonfly, freebsd) }, + netbsdlike: { any(netbsd, openbsd) }, solarish: { any(illumos, solaris) }, } } From 2f810decd28c587242ffa517f712f0c3da6cba1b Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 27 Nov 2023 08:15:06 +0800 Subject: [PATCH 069/140] refactor: cfg for fcntl/fetures/ifaddrs/lib/poll/sched/time (#2215) * refactor: cfg for fcntl/fetures/ifaddrs/lib/poll/sched/time * revert the wrong change --- src/fcntl.rs | 63 ++++++++++++++++++++----------------------------- src/features.rs | 3 +-- src/ifaddrs.rs | 2 +- src/lib.rs | 10 ++------ src/poll.rs | 2 +- src/sched.rs | 14 ++--------- src/time.rs | 6 +---- 7 files changed, 33 insertions(+), 67 deletions(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index e4f0417b7a..5853b62f12 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -22,11 +22,7 @@ use std::os::unix::io::RawFd; all(target_os = "freebsd", target_arch = "x86_64"), ))] use std::path::PathBuf; -#[cfg(any( - target_os = "android", - target_os = "freebsd", - target_os = "linux" -))] +#[cfg(any(linux_android, target_os = "freebsd"))] use std::{ os::unix::io::{AsFd, AsRawFd}, ptr, @@ -36,8 +32,7 @@ use std::{ use crate::{sys::stat::Mode, NixPath, Result}; #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", target_os = "wasi", @@ -81,10 +76,11 @@ libc_bitflags!( /// Open the file in append-only mode. O_APPEND; /// Generate a signal when input or output becomes possible. - #[cfg(not(any(target_os = "aix", - target_os = "illumos", - target_os = "solaris", - target_os = "haiku")))] + #[cfg(not(any( + solarish, + target_os = "aix", + target_os = "haiku" + )))] O_ASYNC; /// Closes the file descriptor once an `execve` call is made. /// @@ -93,19 +89,18 @@ libc_bitflags!( /// Create the file if it does not exist. O_CREAT; /// Try to minimize cache effects of the I/O for this file. - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd"))] + #[cfg(any( + freebsdlike, + linux_android, + target_os = "netbsd" + ))] O_DIRECT; /// If the specified path isn't a directory, fail. #[cfg(not(solarish))] O_DIRECTORY; /// Implicitly follow each `write()` with an `fdatasync()`. - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, apple_targets, - target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] O_DSYNC; @@ -144,7 +139,7 @@ libc_bitflags!( /// Obtain a file descriptor for low-level access. /// /// The file itself is not opened and other file operations will fail. - #[cfg(any(target_os = "android", target_os = "linux", target_os = "redox"))] + #[cfg(any(linux_android, target_os = "redox"))] O_PATH; /// Only allow reading. /// @@ -184,7 +179,7 @@ libc_bitflags!( /// Computes the raw fd consumed by a function of the form `*at`. #[cfg(any( all(feature = "fs", not(target_os = "redox")), - all(feature = "process", any(target_os = "android", target_os = "linux")), + all(feature = "process", linux_android), all(feature = "fanotify", target_os = "linux") ))] pub(crate) fn at_rawfd(fd: Option) -> raw::c_int { @@ -346,8 +341,7 @@ fn inner_readlink( ) } #[cfg(not(any( - target_os = "android", - target_os = "linux", + linux_android, target_os = "redox" )))] Some(dirfd) => super::sys::stat::fstatat( @@ -406,7 +400,7 @@ pub fn readlinkat( } } -#[cfg(any(target_os = "android", target_os = "linux", target_os = "freebsd"))] +#[cfg(any(linux_android, target_os = "freebsd"))] #[cfg(feature = "fs")] libc_bitflags!( /// Additional flags for file sealing, which allows for limiting operations on a file. @@ -460,14 +454,12 @@ pub enum FcntlArg<'a> { #[cfg(linux_android)] F_OFD_GETLK(&'a mut libc::flock), #[cfg(any( - target_os = "android", - target_os = "linux", + linux_android, target_os = "freebsd" ))] F_ADD_SEALS(SealFlag), #[cfg(any( - target_os = "android", - target_os = "linux", + linux_android, target_os = "freebsd" ))] F_GET_SEALS, @@ -530,16 +522,14 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { #[cfg(linux_android)] F_OFD_GETLK(flock) => libc::fcntl(fd, libc::F_OFD_GETLK, flock), #[cfg(any( - target_os = "android", - target_os = "linux", + linux_android, target_os = "freebsd" ))] F_ADD_SEALS(flag) => { libc::fcntl(fd, libc::F_ADD_SEALS, flag.bits()) } #[cfg(any( - target_os = "android", - target_os = "linux", + linux_android, target_os = "freebsd" ))] F_GET_SEALS => libc::fcntl(fd, libc::F_GET_SEALS), @@ -672,7 +662,7 @@ feature! { // Note: FreeBSD defines the offset argument as "off_t". Linux and Android // define it as "loff_t". But on both OSes, on all supported platforms, those // are 64 bits. So Nix uses i64 to make the docs simple and consistent. -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] pub fn copy_file_range( fd_in: Fd1, off_in: Option<&mut i64>, @@ -960,8 +950,7 @@ pub fn fspacectl_all( } #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", target_os = "wasi", @@ -1008,13 +997,11 @@ mod posix_fadvise { } #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "dragonfly", + linux_android, + freebsdlike, target_os = "emscripten", target_os = "fuchsia", target_os = "wasi", - target_os = "freebsd" ))] pub fn posix_fallocate( fd: RawFd, diff --git a/src/features.rs b/src/features.rs index a623d2d533..b528773d10 100644 --- a/src/features.rs +++ b/src/features.rs @@ -98,8 +98,7 @@ mod os { } #[cfg(any( - target_os = "dragonfly", // Since ??? - target_os = "freebsd", // Since 10.0 + freebsdlike, // FreeBSD since 10.0 DragonFlyBSD since ??? target_os = "illumos", // Since ??? target_os = "netbsd", // Since 6.0 target_os = "openbsd", // Since 5.7 diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index e90b26d012..58cbfec9eb 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -33,7 +33,7 @@ pub struct InterfaceAddress { } cfg_if! { - if #[cfg(any(target_os = "android", target_os = "emscripten", target_os = "fuchsia", target_os = "linux"))] { + if #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] { fn get_ifu_from_sockaddr(info: &libc::ifaddrs) -> *const libc::sockaddr { info.ifa_ifu } diff --git a/src/lib.rs b/src/lib.rs index ed9d67b7fe..0d4416926f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -123,9 +123,8 @@ pub mod fcntl; feature! { #![feature = "net"] - #[cfg(any(target_os = "android", + #[cfg(any(linux_android, bsd, - target_os = "linux", target_os = "illumos"))] #[deny(missing_docs)] pub mod ifaddrs; @@ -143,12 +142,7 @@ feature! { #![feature = "mount"] pub mod mount; } -#[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "netbsd" -))] +#[cfg(any(freebsdlike, target_os = "linux", target_os = "netbsd"))] feature! { #![feature = "mqueue"] pub mod mqueue; diff --git a/src/poll.rs b/src/poll.rs index 46ee26ae09..0ad9f40d3b 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -224,7 +224,7 @@ feature! { /// so in that case `ppoll` differs from `poll` only in the precision of the /// timeout argument. /// -#[cfg(any(target_os = "android", freebsdlike, target_os = "linux"))] +#[cfg(any(linux_android, freebsdlike))] pub fn ppoll( fds: &mut [PollFd], timeout: Option, diff --git a/src/sched.rs b/src/sched.rs index bafbfa0bd8..d76d5581d1 100644 --- a/src/sched.rs +++ b/src/sched.rs @@ -152,20 +152,10 @@ mod sched_linux_like { } } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux" -))] +#[cfg(any(linux_android, freebsdlike))] pub use self::sched_affinity::*; -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux" -))] +#[cfg(any(linux_android, freebsdlike))] mod sched_affinity { use crate::errno::Errno; use crate::unistd::Pid; diff --git a/src/time.rs b/src/time.rs index 6e8aac6ac1..b4b0f07eb7 100644 --- a/src/time.rs +++ b/src/time.rs @@ -22,11 +22,7 @@ impl ClockId { feature! { #![feature = "process"] /// Returns `ClockId` of a `pid` CPU-time clock - #[cfg(any( - freebsdlike, - linux_android, - target_os = "emscripten", - ))] + #[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] pub fn pid_cpu_clock_id(pid: Pid) -> Result { clock_getcpuclockid(pid) } From 1bd6b90fd25edb3bb91d04bb6cbb987f28c4ff12 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 27 Nov 2023 08:15:39 +0800 Subject: [PATCH 070/140] refactor: cfg for sys/time.rs (#2229) * refactor: cfg for sys/time.rs * fmt --- src/sys/time.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/sys/time.rs b/src/sys/time.rs index 86cf000295..d5e9f3a6b2 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -97,12 +97,7 @@ pub(crate) mod timer { const TFD_TIMER_CANCEL_ON_SET = libc::TFD_TIMER_CANCEL_ON_SET; } } - #[cfg(any( - target_os = "freebsd", - target_os = "netbsd", - target_os = "dragonfly", - target_os = "illumos" - ))] + #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "illumos"))] bitflags! { /// Flags that are used for arming the timer. #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] From 39ad47bc80af68fb9ad67d37ab699684bea0e2a9 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 27 Nov 2023 08:51:38 +0800 Subject: [PATCH 071/140] refactor: remove the l4re target (#2228) --- src/dir.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/dir.rs b/src/dir.rs index b42321f1f8..1579b65683 100644 --- a/src/dir.rs +++ b/src/dir.rs @@ -230,8 +230,7 @@ impl Entry { target_os = "haiku", solarish, linux_android, - apple_targets, - target_os = "l4re"))] { + apple_targets))] { self.0.d_ino as u64 } else { u64::from(self.0.d_fileno) From e13a18275e02110ab98953956ab05df74e58cb99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ad=C3=A4?= Date: Thu, 30 Nov 2023 07:49:56 +0100 Subject: [PATCH 072/140] more cfg alias targets (#2236) --- build.rs | 3 +++ src/lib.rs | 1 + 2 files changed, 4 insertions(+) diff --git a/build.rs b/build.rs index 4535af1f04..6db634d44f 100644 --- a/build.rs +++ b/build.rs @@ -6,11 +6,14 @@ fn main() { dragonfly: { target_os = "dragonfly" }, ios: { target_os = "ios" }, freebsd: { target_os = "freebsd" }, + fuchsia: { target_os = "fuchsia" }, + haiku: { target_os = "haiku" }, illumos: { target_os = "illumos" }, linux: { target_os = "linux" }, macos: { target_os = "macos" }, netbsd: { target_os = "netbsd" }, openbsd: { target_os = "openbsd" }, + redox: { target_os = "redox" }, solaris: { target_os = "solaris" }, watchos: { target_os = "watchos" }, tvos: { target_os = "tvos" }, diff --git a/src/lib.rs b/src/lib.rs index 0d4416926f..fdcd092378 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,6 +92,7 @@ #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(clippy::cast_ptr_alignment)] #![deny(unsafe_op_in_unsafe_fn)] +#![allow(clippy::mismatched_target_os)] // Re-exported external crates pub use libc; From 0bb23ca24ddbaa1bb34387eb507553b053c7de34 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 1 Dec 2023 08:00:41 +0800 Subject: [PATCH 073/140] Revert "more cfg alias targets (#2236)" (#2237) This reverts commit e13a18275e02110ab98953956ab05df74e58cb99. --- build.rs | 3 --- src/lib.rs | 1 - 2 files changed, 4 deletions(-) diff --git a/build.rs b/build.rs index 6db634d44f..4535af1f04 100644 --- a/build.rs +++ b/build.rs @@ -6,14 +6,11 @@ fn main() { dragonfly: { target_os = "dragonfly" }, ios: { target_os = "ios" }, freebsd: { target_os = "freebsd" }, - fuchsia: { target_os = "fuchsia" }, - haiku: { target_os = "haiku" }, illumos: { target_os = "illumos" }, linux: { target_os = "linux" }, macos: { target_os = "macos" }, netbsd: { target_os = "netbsd" }, openbsd: { target_os = "openbsd" }, - redox: { target_os = "redox" }, solaris: { target_os = "solaris" }, watchos: { target_os = "watchos" }, tvos: { target_os = "tvos" }, diff --git a/src/lib.rs b/src/lib.rs index fdcd092378..0d4416926f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,7 +92,6 @@ #![cfg_attr(docsrs, feature(doc_cfg))] #![deny(clippy::cast_ptr_alignment)] #![deny(unsafe_op_in_unsafe_fn)] -#![allow(clippy::mismatched_target_os)] // Re-exported external crates pub use libc; From 83dfd90741756041977ad91ae123d2ab1b27c13f Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 1 Dec 2023 08:04:01 +0800 Subject: [PATCH 074/140] refactor: apply the netbsdlike alias for src/* (#2231) * refactor: apply the netbsdlike alias for src/* * remove openbsd --- src/errno.rs | 4 +-- src/fcntl.rs | 7 ++-- src/features.rs | 3 +- src/mount/bsd.rs | 6 +--- src/mount/mod.rs | 14 ++------ src/net/if_.rs | 10 ++---- src/sys/aio.rs | 3 +- src/sys/mman.rs | 4 +-- src/sys/mod.rs | 8 +---- src/sys/ptrace/mod.rs | 14 ++------ src/sys/resource.rs | 15 +++------ src/sys/socket/addr.rs | 2 +- src/sys/socket/mod.rs | 69 +++++++++++---------------------------- src/sys/socket/sockopt.rs | 22 ++----------- src/sys/statfs.rs | 21 ++---------- src/sys/termios.rs | 49 +++++++-------------------- src/unistd.rs | 31 +++++------------- 17 files changed, 66 insertions(+), 216 deletions(-) diff --git a/src/errno.rs b/src/errno.rs index 555c07bacd..c7a182b6c0 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -12,9 +12,7 @@ cfg_if! { unsafe fn errno_location() -> *mut c_int { unsafe { libc::__error() } } - } else if #[cfg(any(target_os = "android", - target_os = "netbsd", - target_os = "openbsd"))] { + } else if #[cfg(any(target_os = "android", netbsdlike))] { unsafe fn errno_location() -> *mut c_int { unsafe { libc::__errno() } } diff --git a/src/fcntl.rs b/src/fcntl.rs index 5853b62f12..6bda0c09e2 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -99,10 +99,7 @@ libc_bitflags!( #[cfg(not(solarish))] O_DIRECTORY; /// Implicitly follow each `write()` with an `fdatasync()`. - #[cfg(any(linux_android, - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(linux_android, apple_targets, netbsdlike))] O_DSYNC; /// Error out if a file was not created. O_EXCL; @@ -150,7 +147,7 @@ libc_bitflags!( /// This should not be combined with `O_WRONLY` or `O_RDONLY`. O_RDWR; /// Similar to `O_DSYNC` but applies to `read`s instead. - #[cfg(any(target_os = "linux", target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(target_os = "linux", netbsdlike))] O_RSYNC; /// Skip search permission checks. #[cfg(target_os = "netbsd")] diff --git a/src/features.rs b/src/features.rs index b528773d10..d75f6a408a 100644 --- a/src/features.rs +++ b/src/features.rs @@ -99,9 +99,8 @@ mod os { #[cfg(any( freebsdlike, // FreeBSD since 10.0 DragonFlyBSD since ??? + netbsdlike, // NetBSD since 6.0 OpenBSD since 5.7 target_os = "illumos", // Since ??? - target_os = "netbsd", // Since 6.0 - target_os = "openbsd", // Since 5.7 target_os = "redox", // Since 1-july-2020 ))] mod os { diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index 0e92cd0241..e3fabf21d5 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -61,11 +61,7 @@ libc_bitflags!( #[cfg(any(target_os = "macos", target_os = "freebsd"))] MNT_SNAPSHOT; /// Using soft updates. - #[cfg(any( - freebsdlike, - target_os = "netbsd", - target_os = "openbsd" - ))] + #[cfg(any(freebsdlike, netbsdlike))] MNT_SOFTDEP; /// Directories with the SUID bit set chown new files to their own /// owner. diff --git a/src/mount/mod.rs b/src/mount/mod.rs index 56e9c9a9b2..4d062b0921 100644 --- a/src/mount/mod.rs +++ b/src/mount/mod.rs @@ -5,18 +5,8 @@ mod linux; #[cfg(linux_android)] pub use self::linux::*; -#[cfg(any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] mod bsd; -#[cfg(any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] pub use self::bsd::*; diff --git a/src/net/if_.rs b/src/net/if_.rs index 49a3b2abcc..a61b719ca3 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -72,10 +72,7 @@ libc_bitflags!( #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_MASTER; /// transmission in progress, tx hardware queue is full - #[cfg(any(target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] IFF_OACTIVE; /// Protocol code on board. #[cfg(solarish)] @@ -85,10 +82,7 @@ libc_bitflags!( #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_SLAVE; /// Can't hear own transmissions. - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] IFF_SIMPLEX; /// Supports multicast. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 636611cf8b..fbf5b27695 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -55,8 +55,7 @@ libc_enum! { /// on supported operating systems only, do it like `fdatasync` #[cfg(any(apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd"))] + netbsdlike))] O_DSYNC } impl TryFrom diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 6247ea4e17..5e968f052b 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -134,10 +134,10 @@ libc_bitflags! { /// Rename private pages to a file. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. - #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] + #[cfg(netbsdlike)] MAP_RENAME; /// Region may contain semaphores. - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] MAP_HASSEMAPHORE; /// Region grows down, like a stack. #[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))] diff --git a/src/sys/mod.rs b/src/sys/mod.rs index c29d5ce376..48e7f4e21c 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -66,13 +66,7 @@ feature! { pub mod pthread; } -#[cfg(any( - linux_android, - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(any(linux_android, freebsdlike, target_os = "macos", netbsdlike))] feature! { #![feature = "ptrace"] #[allow(missing_docs)] diff --git a/src/sys/ptrace/mod.rs b/src/sys/ptrace/mod.rs index f87073fef2..d1dd84b4a9 100644 --- a/src/sys/ptrace/mod.rs +++ b/src/sys/ptrace/mod.rs @@ -6,18 +6,8 @@ mod linux; #[cfg(linux_android)] pub use self::linux::*; -#[cfg(any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] mod bsd; -#[cfg(any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] pub use self::bsd::*; diff --git a/src/sys/resource.rs b/src/sys/resource.rs index 14f3e14c21..c0116f080b 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -47,7 +47,7 @@ libc_enum! { ), repr(i32))] #[non_exhaustive] pub enum Resource { - #[cfg(not(any(target_os = "freebsd", target_os = "netbsd", target_os = "openbsd")))] + #[cfg(not(any(target_os = "freebsd", netbsdlike)))] /// The maximum amount (in bytes) of virtual memory the process is /// allowed to map. RLIMIT_AS, @@ -74,12 +74,7 @@ libc_enum! { /// this process may establish. RLIMIT_LOCKS, - #[cfg(any( - linux_android, - target_os = "freebsd", - target_os = "openbsd", - target_os = "netbsd" - ))] + #[cfg(any(linux_android, target_os = "freebsd", netbsdlike))] /// The maximum size (in bytes) which a process may lock into memory /// using the mlock(2) system call. RLIMIT_MEMLOCK, @@ -97,8 +92,7 @@ libc_enum! { #[cfg(any( linux_android, target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, target_os = "aix", ))] /// The maximum number of simultaneous processes for this user id. @@ -111,8 +105,7 @@ libc_enum! { #[cfg(any(linux_android, target_os = "freebsd", - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, target_os = "aix", ))] /// When there is memory pressure and swap is available, prioritize diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 41d30b03a0..09c1e91d39 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -209,7 +209,7 @@ pub enum AddressFamily { #[cfg(bsd)] Chaos = libc::AF_CHAOS, /// Novell and Xerox protocol - #[cfg(any(apple_targets, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(apple_targets, netbsdlike))] Ns = libc::AF_NS, #[allow(missing_docs)] // Not documented anywhere that I can find #[cfg(bsd)] diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index a145444fa2..1e081dd2ea 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -255,16 +255,14 @@ libc_bitflags! { /// Set non-blocking mode on the new socket #[cfg(any(linux_android, freebsdlike, - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + netbsdlike, + target_os = "illumos"))] SOCK_NONBLOCK; /// Set close-on-exec on the new descriptor #[cfg(any(linux_android, freebsdlike, - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + netbsdlike, + target_os = "illumos"))] SOCK_CLOEXEC; /// Return `EPIPE` instead of raising `SIGPIPE` #[cfg(target_os = "netbsd")] @@ -329,28 +327,23 @@ libc_bitflags! { /// [open(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html). /// /// Only used in [`recvmsg`](fn.recvmsg.html) function. - #[cfg(any(linux_android, - freebsdlike, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(linux_android, freebsdlike, netbsdlike))] MSG_CMSG_CLOEXEC; /// Requests not to send `SIGPIPE` errors when the other end breaks the connection. /// (For more details, see [send(2)](https://linux.die.net/man/2/send)). #[cfg(any(linux_android, freebsdlike, solarish, + netbsdlike, target_os = "fuchsia", - target_os = "haiku", - target_os = "netbsd", - target_os = "openbsd"))] + target_os = "haiku"))] MSG_NOSIGNAL; /// Turns on [`MSG_DONTWAIT`] after the first message has been received (only for /// `recvmmsg()`). #[cfg(any(linux_android, + netbsdlike, target_os = "fuchsia", - target_os = "netbsd", target_os = "freebsd", - target_os = "openbsd", target_os = "solaris"))] MSG_WAITFORONE; } @@ -755,21 +748,11 @@ pub enum ControlMessageOwned { #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6PacketInfo(libc::in6_pktinfo), - #[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - ))] + #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvIf(libc::sockaddr_dl), - #[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - ))] + #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvDstAddr(libc::in_addr), @@ -948,23 +931,13 @@ impl ControlMessageOwned { let info = unsafe { ptr::read_unaligned(p as *const libc::in_pktinfo) }; ControlMessageOwned::Ipv4PacketInfo(info) } - #[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - ))] + #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVIF) => { let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_dl) }; ControlMessageOwned::Ipv4RecvIf(dl) }, - #[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - ))] + #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVDSTADDR) => { let dl = unsafe { ptr::read_unaligned(p as *const libc::in_addr) }; @@ -1124,10 +1097,7 @@ pub enum ControlMessage<'a> { /// /// For further information, please refer to the /// [`ip(7)`](https://man7.org/linux/man-pages/man7/ip.7.html) man page. - #[cfg(any(target_os = "linux", - target_os = "netbsd", - target_os = "android", - apple_targets))] + #[cfg(any(linux_android, target_os = "netbsd", apple_targets))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4PacketInfo(&'a libc::in_pktinfo), @@ -1145,7 +1115,7 @@ pub enum ControlMessage<'a> { Ipv6PacketInfo(&'a libc::in6_pktinfo), /// Configure the IPv4 source address with `IP_SENDSRCADDR`. - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4SendSrcAddr(&'a libc::in_addr), @@ -1268,7 +1238,7 @@ impl<'a> ControlMessage<'a> { target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => info as *const _ as *const u8, - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => addr as *const _ as *const u8, #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] @@ -1330,7 +1300,7 @@ impl<'a> ControlMessage<'a> { target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(info) => mem::size_of_val(info), - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(addr) => mem::size_of_val(addr), #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] @@ -1370,7 +1340,7 @@ impl<'a> ControlMessage<'a> { target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPPROTO_IPV6, - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IPPROTO_IP, #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] @@ -1415,7 +1385,7 @@ impl<'a> ControlMessage<'a> { target_os = "freebsd", apple_targets))] #[cfg(feature = "net")] ControlMessage::Ipv6PacketInfo(_) => libc::IPV6_PKTINFO, - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] #[cfg(feature = "net")] ControlMessage::Ipv4SendSrcAddr(_) => libc::IP_SENDSRCADDR, #[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "haiku"))] @@ -2183,12 +2153,11 @@ pub fn accept(sockfd: RawFd) -> Result { ) ), freebsdlike, + netbsdlike, target_os = "emscripten", target_os = "fuchsia", target_os = "illumos", target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" ))] pub fn accept4(sockfd: RawFd, flags: SockFlag) -> Result { let res = unsafe { diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 6776e15627..cad2cce180 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -830,13 +830,7 @@ sockopt_impl!( libc::IP_PKTINFO, bool ); -#[cfg(any( - linux_android, - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -848,12 +842,7 @@ sockopt_impl!( libc::IPV6_RECVPKTINFO, bool ); -#[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", -))] +#[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -865,12 +854,7 @@ sockopt_impl!( libc::IP_RECVIF, bool ); -#[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", -))] +#[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index d6ec2a8501..fd754f7a4f 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -11,12 +11,7 @@ use cfg_if::cfg_if; #[cfg(all( feature = "mount", - any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" - ) + any(freebsdlike, target_os = "macos", netbsdlike) ))] use crate::mount::MntFlags; #[cfg(target_os = "linux")] @@ -429,12 +424,7 @@ impl Statfs { /// Get the mount flags #[cfg(all( feature = "mount", - any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" - ) + any(freebsdlike, target_os = "macos", netbsdlike) ))] #[allow(clippy::unnecessary_cast)] // Not unnecessary on all arches pub fn flags(&self) -> MntFlags { @@ -636,12 +626,7 @@ impl Debug for Statfs { ds.field("filesystem_id", &self.filesystem_id()); #[cfg(all( feature = "mount", - any( - freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" - ) + any(freebsdlike, target_os = "macos", netbsdlike) ))] ds.field("flags", &self.flags()); ds.finish() diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 9333adc752..f63c390f1e 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -277,30 +277,18 @@ libc_enum! { B1800, B2400, B4800, - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] B7200, B9600, - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] B14400, B19200, - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] B28800, B38400, #[cfg(not(target_os = "aix"))] B57600, - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] B76800, #[cfg(not(target_os = "aix"))] B115200, @@ -420,8 +408,7 @@ libc_enum! { #[cfg(any(freebsdlike, solarish, target_os = "macos", - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, target_os = "aix"))] VDSUSP, VEOF, @@ -444,8 +431,7 @@ libc_enum! { #[cfg(any(freebsdlike, solarish, target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + netbsdlike))] VSTATUS, VSTOP, VSUSP, @@ -480,8 +466,7 @@ pub use libc::NCCS; freebsdlike, target_os = "aix", target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" + netbsdlike ))] pub use libc::_POSIX_VDISABLE; @@ -594,10 +579,7 @@ libc_bitflags! { FF1 as tcflag_t; #[cfg(bsd)] OXTABS; - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] ONOEOT as tcflag_t; // Bitmasks for use with OutputFlags to select specific settings @@ -659,20 +641,13 @@ libc_bitflags! { CIBAUD; #[cfg(linux_android)] CBAUDEX; - #[cfg(any(freebsdlike, - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] MDMBUF; - #[cfg(any(target_os = "netbsd", target_os = "openbsd"))] + #[cfg(netbsdlike)] CHWFLOW; - #[cfg(any(freebsdlike, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] CCTS_OFLOW; - #[cfg(any(freebsdlike, - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any(freebsdlike, netbsdlike))] CRTS_IFLOW; #[cfg(freebsdlike)] CDTR_IFLOW; diff --git a/src/unistd.rs b/src/unistd.rs index 7c3a33f809..abdc9bdbaf 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -971,8 +971,7 @@ pub fn execveat, SE: AsRef>( linux_android, freebsdlike, solarish, - target_os = "netbsd", - target_os = "openbsd", + netbsdlike ))] pub fn daemon(nochdir: bool, noclose: bool) -> Result<()> { let res = unsafe { libc::daemon(nochdir as c_int, noclose as c_int) }; @@ -1195,8 +1194,7 @@ feature! { solarish, target_os = "emscripten", target_os = "redox", - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, ))] pub fn pipe2(flags: OFlag) -> Result<(OwnedFd, OwnedFd)> { let mut fds = mem::MaybeUninit::<[OwnedFd; 2]>::uninit(); @@ -1350,12 +1348,7 @@ pub fn chroot(path: &P) -> Result<()> { /// Commit filesystem caches to disk /// /// See also [sync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sync.html) -#[cfg(any( - freebsdlike, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" -))] +#[cfg(any(freebsdlike, target_os = "linux", netbsdlike))] pub fn sync() { unsafe { libc::sync() }; } @@ -1388,11 +1381,10 @@ pub fn fsync(fd: RawFd) -> Result<()> { #[cfg(any( linux_android, solarish, + netbsdlike, target_os = "freebsd", target_os = "emscripten", target_os = "fuchsia", - target_os = "netbsd", - target_os = "openbsd", ))] #[inline] pub fn fdatasync(fd: RawFd) -> Result<()> { @@ -1962,9 +1954,8 @@ feature! { pub enum PathconfVar { #[cfg(any( freebsdlike, + netbsdlike, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", target_os = "redox" ))] /// Minimum number of bits needed to represent, as a signed integer value, @@ -1992,9 +1983,8 @@ pub enum PathconfVar { #[cfg(any( linux_android, solarish, + netbsdlike, target_os = "dragonfly", - target_os = "netbsd", - target_os = "openbsd", target_os = "redox", ))] /// Symbolic links can be created. @@ -2044,8 +2034,7 @@ pub enum PathconfVar { linux_android, freebsdlike, solarish, - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, target_os = "redox", ))] /// Maximum number of bytes in a symbolic link. @@ -2084,8 +2073,7 @@ pub enum PathconfVar { linux_android, freebsdlike, solarish, - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, target_os = "redox", ))] /// Synchronized input or output operations may be performed for the @@ -2415,8 +2403,7 @@ pub enum SysconfVar { #[cfg(any( apple_targets, target_os = "linux", - target_os = "netbsd", - target_os = "openbsd" + netbsdlike, ))] /// The implementation supports the Thread CPU-Time Clocks option. _POSIX_THREAD_CPUTIME = libc::_SC_THREAD_CPUTIME, From e95162f28898f0b522b2b926750a32f4026d3ee2 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 3 Dec 2023 01:10:04 +0800 Subject: [PATCH 075/140] refactor: enable most macOS funcs for apple_targets (#2241) * refactor: enable most macOS funcs for apple_targets * respond to review * respond to review --- changelog/2241.added.md | 1 + src/mount/bsd.rs | 6 +++--- src/mount/mod.rs | 4 ++-- src/net/if_.rs | 2 +- src/sys/event.rs | 2 +- src/sys/mod.rs | 2 +- src/sys/ptrace/bsd.rs | 16 ++++++++-------- src/sys/ptrace/mod.rs | 4 ++-- src/sys/socket/addr.rs | 28 ++++++++++++++-------------- src/sys/socket/mod.rs | 2 +- src/sys/statfs.rs | 15 +++------------ src/sys/termios.rs | 31 ++++++++++--------------------- src/time.rs | 16 ++++++++++++++-- test/sys/mod.rs | 2 +- test/sys/test_aio.rs | 8 ++++---- test/sys/test_socket.rs | 6 +++--- 16 files changed, 69 insertions(+), 76 deletions(-) create mode 100644 changelog/2241.added.md diff --git a/changelog/2241.added.md b/changelog/2241.added.md new file mode 100644 index 0000000000..2323b9153f --- /dev/null +++ b/changelog/2241.added.md @@ -0,0 +1 @@ +`ClockId::set_time()` and `time::clock_settime()` are now enabled on macOS diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index e3fabf21d5..248e0ab1d2 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -30,7 +30,7 @@ libc_bitflags!( #[cfg(target_os = "freebsd")] MNT_GJOURNAL; /// MAC support for objects. - #[cfg(any(target_os = "macos", target_os = "freebsd"))] + #[cfg(any(apple_targets, target_os = "freebsd"))] MNT_MULTILABEL; /// Disable read clustering. #[cfg(freebsdlike)] @@ -58,7 +58,7 @@ libc_bitflags!( /// Create a snapshot of the file system. /// /// See [mksnap_ffs(8)](https://www.freebsd.org/cgi/man.cgi?query=mksnap_ffs) - #[cfg(any(target_os = "macos", target_os = "freebsd"))] + #[cfg(any(apple_targets, target_os = "freebsd"))] MNT_SNAPSHOT; /// Using soft updates. #[cfg(any(freebsdlike, netbsdlike))] @@ -71,7 +71,7 @@ libc_bitflags!( MNT_SYNCHRONOUS; /// Union with underlying fs. #[cfg(any( - target_os = "macos", + apple_targets, target_os = "freebsd", target_os = "netbsd" ))] diff --git a/src/mount/mod.rs b/src/mount/mod.rs index 4d062b0921..8caf27f7df 100644 --- a/src/mount/mod.rs +++ b/src/mount/mod.rs @@ -5,8 +5,8 @@ mod linux; #[cfg(linux_android)] pub use self::linux::*; -#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] +#[cfg(bsd)] mod bsd; -#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] +#[cfg(bsd)] pub use self::bsd::*; diff --git a/src/net/if_.rs b/src/net/if_.rs index a61b719ca3..4e59fc15da 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -82,7 +82,7 @@ libc_bitflags!( #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_SLAVE; /// Can't hear own transmissions. - #[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] + #[cfg(bsd)] IFF_SIMPLEX; /// Supports multicast. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) diff --git a/src/sys/event.rs b/src/sys/event.rs index 28f1e1a1e4..d30896aaeb 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -191,7 +191,7 @@ libc_bitflags! { EV_NODATA; #[allow(missing_docs)] EV_ONESHOT; - #[cfg(any(target_os = "macos", target_os = "tvos"))] + #[cfg(apple_targets)] #[allow(missing_docs)] EV_OOBAND; #[cfg(apple_targets)] diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 48e7f4e21c..94302484fb 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -66,7 +66,7 @@ feature! { pub mod pthread; } -#[cfg(any(linux_android, freebsdlike, target_os = "macos", netbsdlike))] +#[cfg(any(linux_android, bsd))] feature! { #![feature = "ptrace"] #[allow(missing_docs)] diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index 32a53085af..3dd486210c 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -9,7 +9,7 @@ use std::ptr; pub type RequestType = c_int; cfg_if! { - if #[cfg(any(freebsdlike, target_os = "macos", target_os = "openbsd"))] { + if #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] { #[doc(hidden)] pub type AddressType = *mut ::libc::c_char; } else { @@ -26,26 +26,26 @@ libc_enum! { PT_TRACE_ME, PT_READ_I, PT_READ_D, - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] PT_READ_U, PT_WRITE_I, PT_WRITE_D, - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] PT_WRITE_U, PT_CONTINUE, PT_KILL, - #[cfg(any(any(freebsdlike, target_os = "macos"), + #[cfg(any(any(freebsdlike, apple_targets), all(target_os = "openbsd", target_arch = "x86_64"), all(target_os = "netbsd", any(target_arch = "x86_64", target_arch = "powerpc"))))] PT_STEP, PT_ATTACH, PT_DETACH, - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] PT_SIGEXC, - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] PT_THUPDATE, - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] PT_ATTACHEXC } } @@ -149,7 +149,7 @@ pub fn kill(pid: Pid) -> Result<()> { /// } /// ``` #[cfg(any( - any(freebsdlike, target_os = "macos"), + any(freebsdlike, apple_targets), all(target_os = "openbsd", target_arch = "x86_64"), all( target_os = "netbsd", diff --git a/src/sys/ptrace/mod.rs b/src/sys/ptrace/mod.rs index d1dd84b4a9..c059797df9 100644 --- a/src/sys/ptrace/mod.rs +++ b/src/sys/ptrace/mod.rs @@ -6,8 +6,8 @@ mod linux; #[cfg(linux_android)] pub use self::linux::*; -#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] +#[cfg(bsd)] mod bsd; -#[cfg(any(freebsdlike, netbsdlike, target_os = "macos"))] +#[cfg(bsd)] pub use self::bsd::*; diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 09c1e91d39..2c2058b24d 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -8,7 +8,7 @@ ))] #[cfg(feature = "net")] pub use self::datalink::LinkAddr; -#[cfg(any(linux_android, target_os = "macos"))] +#[cfg(any(linux_android, apple_targets))] pub use self::vsock::VsockAddr; use super::sa_family_t; use crate::errno::Errno; @@ -197,7 +197,7 @@ pub enum AddressFamily { #[cfg(target_os = "linux")] Nfc = libc::AF_NFC, /// VMWare VSockets protocol for hypervisor-guest interaction. - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] Vsock = libc::AF_VSOCK, /// ARPANet IMP addresses #[cfg(bsd)] @@ -259,7 +259,7 @@ impl AddressFamily { libc::AF_INET6 => Some(AddressFamily::Inet6), #[cfg(linux_android)] libc::AF_NETLINK => Some(AddressFamily::Netlink), - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] libc::AF_SYSTEM => Some(AddressFamily::System), #[cfg(not(any(linux_android, target_os = "redox")))] libc::PF_ROUTE => Some(AddressFamily::Route), @@ -267,7 +267,7 @@ impl AddressFamily { libc::AF_PACKET => Some(AddressFamily::Packet), #[cfg(any(bsd, target_os = "illumos"))] libc::AF_LINK => Some(AddressFamily::Link), - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] libc::AF_VSOCK => Some(AddressFamily::Vsock), _ => None, } @@ -1078,7 +1078,7 @@ pub union SockaddrStorage { sin6: SockaddrIn6, ss: libc::sockaddr_storage, su: UnixAddr, - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] vsock: VsockAddr, } impl private::SockaddrLikePriv for SockaddrStorage {} @@ -1154,7 +1154,7 @@ impl SockaddrLike for SockaddrStorage { libc::AF_SYSTEM => unsafe { SysControlAddr::from_raw(addr, l).map(|sctl| Self { sctl }) }, - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] libc::AF_VSOCK => unsafe { VsockAddr::from_raw(addr, l).map(|vsock| Self { vsock }) }, @@ -1312,7 +1312,7 @@ impl SockaddrStorage { accessors! {as_sys_control_addr, as_sys_control_addr_mut, SysControlAddr, AddressFamily::System, libc::sockaddr_ctl, sctl} - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] accessors! {as_vsock_addr, as_vsock_addr_mut, VsockAddr, AddressFamily::Vsock, libc::sockaddr_vm, vsock} } @@ -1349,7 +1349,7 @@ impl fmt::Display for SockaddrStorage { #[cfg(feature = "ioctl")] libc::AF_SYSTEM => self.sctl.fmt(f), libc::AF_UNIX => self.su.fmt(f), - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] libc::AF_VSOCK => self.vsock.fmt(f), _ => "
".fmt(f), } @@ -1411,7 +1411,7 @@ impl Hash for SockaddrStorage { #[cfg(feature = "ioctl")] libc::AF_SYSTEM => self.sctl.hash(s), libc::AF_UNIX => self.su.hash(s), - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] libc::AF_VSOCK => self.vsock.hash(s), _ => self.ss.hash(s), } @@ -1441,7 +1441,7 @@ impl PartialEq for SockaddrStorage { #[cfg(feature = "ioctl")] (libc::AF_SYSTEM, libc::AF_SYSTEM) => self.sctl == other.sctl, (libc::AF_UNIX, libc::AF_UNIX) => self.su == other.su, - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] (libc::AF_VSOCK, libc::AF_VSOCK) => self.vsock == other.vsock, _ => false, } @@ -1972,7 +1972,7 @@ mod datalink { } } -#[cfg(any(linux_android, target_os = "macos"))] +#[cfg(any(linux_android, apple_targets))] pub mod vsock { use super::*; use crate::sys::socket::addr::AddressFamily; @@ -2023,7 +2023,7 @@ pub mod vsock { (inner.svm_family, inner.svm_cid, inner.svm_port) == (other.svm_family, other.svm_cid, other.svm_port) } - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); ( @@ -2048,7 +2048,7 @@ pub mod vsock { let inner = self.0; (inner.svm_family, inner.svm_cid, inner.svm_port).hash(s); } - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] fn hash(&self, s: &mut H) { let inner = self.0; ( @@ -2073,7 +2073,7 @@ pub mod vsock { addr.svm_cid = cid; addr.svm_port = port; - #[cfg(target_os = "macos")] + #[cfg(apple_targets)] { addr.svm_len = std::mem::size_of::() as u8; } diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 1e081dd2ea..093e37dc5f 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -52,7 +52,7 @@ pub use crate::sys::socket::addr::netlink::NetlinkAddr; #[cfg(apple_targets)] #[cfg(feature = "ioctl")] pub use crate::sys::socket::addr::sys_control::SysControlAddr; -#[cfg(any(linux_android, target_os = "macos"))] +#[cfg(any(linux_android, apple_targets))] pub use crate::sys::socket::addr::vsock::VsockAddr; #[cfg(all(feature = "uio", not(target_os = "redox")))] diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index fd754f7a4f..377e303e99 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -9,10 +9,7 @@ use std::os::unix::io::{AsFd, AsRawFd}; use cfg_if::cfg_if; -#[cfg(all( - feature = "mount", - any(freebsdlike, target_os = "macos", netbsdlike) -))] +#[cfg(all(feature = "mount", bsd))] use crate::mount::MntFlags; #[cfg(target_os = "linux")] use crate::sys::statvfs::FsFlags; @@ -422,10 +419,7 @@ impl Statfs { } /// Get the mount flags - #[cfg(all( - feature = "mount", - any(freebsdlike, target_os = "macos", netbsdlike) - ))] + #[cfg(all(feature = "mount", bsd))] #[allow(clippy::unnecessary_cast)] // Not unnecessary on all arches pub fn flags(&self) -> MntFlags { MntFlags::from_bits_truncate(self.0.f_flags as i32) @@ -624,10 +618,7 @@ impl Debug for Statfs { ds.field("files", &self.files()); ds.field("files_free", &self.files_free()); ds.field("filesystem_id", &self.filesystem_id()); - #[cfg(all( - feature = "mount", - any(freebsdlike, target_os = "macos", netbsdlike) - ))] + #[cfg(all(feature = "mount", bsd))] ds.field("flags", &self.flags()); ds.finish() } diff --git a/src/sys/termios.rs b/src/sys/termios.rs index f63c390f1e..bdddc0c735 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -277,18 +277,18 @@ libc_enum! { B1800, B2400, B4800, - #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] + #[cfg(bsd)] B7200, B9600, - #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] + #[cfg(bsd)] B14400, B19200, - #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] + #[cfg(bsd)] B28800, B38400, #[cfg(not(target_os = "aix"))] B57600, - #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] + #[cfg(bsd)] B76800, #[cfg(not(target_os = "aix"))] B115200, @@ -405,10 +405,8 @@ libc_enum! { pub enum SpecialCharacterIndices { #[cfg(not(any(target_os = "aix", target_os = "haiku")))] VDISCARD, - #[cfg(any(freebsdlike, + #[cfg(any(bsd, solarish, - target_os = "macos", - netbsdlike, target_os = "aix"))] VDSUSP, VEOF, @@ -428,10 +426,7 @@ libc_enum! { #[cfg(not(target_os = "haiku"))] VREPRINT, VSTART, - #[cfg(any(freebsdlike, - solarish, - target_os = "macos", - netbsdlike))] + #[cfg(any(bsd, solarish))] VSTATUS, VSTOP, VSUSP, @@ -461,13 +456,7 @@ impl SpecialCharacterIndices { } pub use libc::NCCS; -#[cfg(any( - linux_android, - freebsdlike, - target_os = "aix", - target_os = "macos", - netbsdlike -))] +#[cfg(any(linux_android, target_os = "aix", bsd))] pub use libc::_POSIX_VDISABLE; libc_bitflags! { @@ -488,7 +477,7 @@ libc_bitflags! { IXANY; #[cfg(not(any(target_os = "redox", target_os = "haiku")))] IMAXBEL; - #[cfg(any(linux_android, target_os = "macos"))] + #[cfg(any(linux_android, apple_targets))] IUTF8; } } @@ -579,7 +568,7 @@ libc_bitflags! { FF1 as tcflag_t; #[cfg(bsd)] OXTABS; - #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] + #[cfg(bsd)] ONOEOT as tcflag_t; // Bitmasks for use with OutputFlags to select specific settings @@ -641,7 +630,7 @@ libc_bitflags! { CIBAUD; #[cfg(linux_android)] CBAUDEX; - #[cfg(any(freebsdlike, target_os = "macos", netbsdlike))] + #[cfg(bsd)] MDMBUF; #[cfg(netbsdlike)] CHWFLOW; diff --git a/src/time.rs b/src/time.rs index b4b0f07eb7..96e84900dd 100644 --- a/src/time.rs +++ b/src/time.rs @@ -40,7 +40,13 @@ impl ClockId { } /// Sets time to `timespec` on the clock id - #[cfg(not(any(apple_targets, target_os = "redox", target_os = "hermit",)))] + #[cfg(not(any( + target_os = "ios", + target_os = "tvos", + target_os = "watchos", + target_os = "redox", + target_os = "hermit" + )))] pub fn set_time(self, timespec: TimeSpec) -> Result<()> { clock_settime(self, timespec) } @@ -164,7 +170,13 @@ pub fn clock_gettime(clock_id: ClockId) -> Result { /// Set the time of the specified clock, (see /// [clock_settime(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_settime.html)). -#[cfg(not(any(apple_targets, target_os = "redox", target_os = "hermit",)))] +#[cfg(not(any( + target_os = "ios", + target_os = "tvos", + target_os = "watchos", + target_os = "redox", + target_os = "hermit" +)))] pub fn clock_settime(clock_id: ClockId, timespec: TimeSpec) -> Result<()> { let ret = unsafe { libc::clock_settime(clock_id.as_raw(), timespec.as_ref()) }; diff --git a/test/sys/mod.rs b/test/sys/mod.rs index 55dfa00023..a62e6cb376 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -52,7 +52,7 @@ mod test_pthread; target_os = "dragonfly", target_os = "freebsd", target_os = "linux", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "openbsd" ))] diff --git a/test/sys/test_aio.rs b/test/sys/test_aio.rs index 1939ac767b..e8eb818024 100644 --- a/test/sys/test_aio.rs +++ b/test/sys/test_aio.rs @@ -67,7 +67,7 @@ mod aio_fsync { // Skip on Linux, because Linux's AIO implementation can't detect errors // synchronously #[test] - #[cfg(any(target_os = "freebsd", target_os = "macos"))] + #[cfg(any(target_os = "freebsd", apple_targets))] fn error() { use std::mem; @@ -157,7 +157,7 @@ mod aio_read { // Skip on Linux, because Linux's AIO implementation can't detect errors // synchronously #[test] - #[cfg(any(target_os = "freebsd", target_os = "macos"))] + #[cfg(any(target_os = "freebsd", apple_targets))] fn error() { const INITIAL: &[u8] = b"abcdef123456"; let mut rbuf = vec![0; 4]; @@ -411,7 +411,7 @@ mod aio_write { // Skip on Linux, because Linux's AIO implementation can't detect errors // synchronously #[test] - #[cfg(any(target_os = "freebsd", target_os = "macos"))] + #[cfg(any(target_os = "freebsd", apple_targets))] fn error() { let wbuf = "CDEF".to_string().into_bytes(); let mut aiow = Box::pin(AioWrite::new( @@ -574,7 +574,7 @@ fn test_aio_cancel_all() { #[cfg_attr(target_os = "linux", ignore)] // On Cirrus, aio_suspend is failing with EINVAL // https://github.com/nix-rust/nix/issues/1361 -#[cfg_attr(target_os = "macos", ignore)] +#[cfg_attr(apple_targets, ignore)] fn test_aio_suspend() { const INITIAL: &[u8] = b"abcdef123456"; const WBUF: &[u8] = b"CDEFG"; diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 1a9cdb465f..4ba66cbbb2 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1156,7 +1156,7 @@ pub fn test_af_alg_aead() { // This would be a more interesting test if we could assume that the test host // has more than one IP address (since we could select a different address to // test from). -#[cfg(any(target_os = "linux", target_os = "macos", target_os = "netbsd"))] +#[cfg(any(target_os = "linux", apple_targets, target_os = "netbsd"))] #[test] pub fn test_sendmsg_ipv4packetinfo() { use cfg_if::cfg_if; @@ -1218,7 +1218,7 @@ pub fn test_sendmsg_ipv4packetinfo() { // test from). #[cfg(any( target_os = "linux", - target_os = "macos", + apple_targets, target_os = "netbsd", target_os = "freebsd" ))] @@ -2309,7 +2309,7 @@ pub fn test_vsock() { assert_eq!(addr3.as_ref().svm_port, addr1.port()); } -#[cfg(target_os = "macos")] +#[cfg(apple_targets)] #[test] pub fn test_vsock() { use nix::sys::socket::SockaddrLike; From a4e0c9544cbc7ec092fbda8a7c69afa7b65438b2 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 3 Dec 2023 01:10:19 +0800 Subject: [PATCH 076/140] feat: ControlMessageOwned::{Ipv4RecvIf,Ipv4RecvDstAddr} for DragonFlyBSD (#2240) * feat: Enable ControlMessageOwned::{Ipv4RecvIf,Ipv4RecvDstAddr} for DragonFlyBSD * fix DrafonFlyBSD * fix Linux * fix cfg --- changelog/2240.added.md | 1 + src/sys/socket/mod.rs | 8 ++++---- src/sys/socket/sockopt.rs | 4 ++-- test/sys/test_socket.rs | 16 ++-------------- 4 files changed, 9 insertions(+), 20 deletions(-) create mode 100644 changelog/2240.added.md diff --git a/changelog/2240.added.md b/changelog/2240.added.md new file mode 100644 index 0000000000..315c67554c --- /dev/null +++ b/changelog/2240.added.md @@ -0,0 +1 @@ +Enable `ControlMessageOwned::Ipv4RecvIf` and `ControlMessageOwned::Ipv4RecvDstAddr` for DragonFlyBSD diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 093e37dc5f..50b87fbf98 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -748,11 +748,11 @@ pub enum ControlMessageOwned { #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv6PacketInfo(libc::in6_pktinfo), - #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] + #[cfg(bsd)] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvIf(libc::sockaddr_dl), - #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] + #[cfg(bsd)] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Ipv4RecvDstAddr(libc::in_addr), @@ -931,13 +931,13 @@ impl ControlMessageOwned { let info = unsafe { ptr::read_unaligned(p as *const libc::in_pktinfo) }; ControlMessageOwned::Ipv4PacketInfo(info) } - #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] + #[cfg(bsd)] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVIF) => { let dl = unsafe { ptr::read_unaligned(p as *const libc::sockaddr_dl) }; ControlMessageOwned::Ipv4RecvIf(dl) }, - #[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] + #[cfg(bsd)] #[cfg(feature = "net")] (libc::IPPROTO_IP, libc::IP_RECVDSTADDR) => { let dl = unsafe { ptr::read_unaligned(p as *const libc::in_addr) }; diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index cad2cce180..5ebb885293 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -842,7 +842,7 @@ sockopt_impl!( libc::IPV6_RECVPKTINFO, bool ); -#[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] +#[cfg(bsd)] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -854,7 +854,7 @@ sockopt_impl!( libc::IP_RECVIF, bool ); -#[cfg(any(target_os = "freebsd", apple_targets, netbsdlike))] +#[cfg(bsd)] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 4ba66cbbb2..12729b23a4 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1750,14 +1750,7 @@ pub fn test_syscontrol() { // connect(fd.as_raw_fd(), &sockaddr).expect("connect failed"); } -#[cfg(any( - target_os = "android", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", -))] +#[cfg(any(bsd, linux_android))] fn loopback_address( family: AddressFamily, ) -> Option { @@ -1880,12 +1873,7 @@ pub fn test_recv_ipv4pktinfo() { } } -#[cfg(any( - target_os = "freebsd", - apple_targets, - target_os = "netbsd", - target_os = "openbsd", -))] +#[cfg(bsd)] // qemu doesn't seem to be emulating this correctly in these architectures #[cfg_attr( all( From 3b1ae36c263f2e3888dfc43c890c373e63226b5e Mon Sep 17 00:00:00 2001 From: Daniil Bondarev Date: Sat, 2 Dec 2023 14:01:43 -0800 Subject: [PATCH 077/140] Added IpBindAddressNoPort sockopt (#2244) From [man page](https://man7.org/linux/man-pages/man7/ip.7.html): ``` IP_BIND_ADDRESS_NO_PORT (since Linux 4.2) Inform the kernel to not reserve an ephemeral port when using bind(2) with a port number of 0. The port will later be automatically chosen at connect(2) time, in a way that allows sharing a source port as long as the 4-tuple is unique. ``` --- changelog/2244.added.md | 1 + src/sys/socket/sockopt.rs | 14 ++++++++++++++ test/sys/test_sockopt.rs | 27 +++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 changelog/2244.added.md diff --git a/changelog/2244.added.md b/changelog/2244.added.md new file mode 100644 index 0000000000..c5d9465c76 --- /dev/null +++ b/changelog/2244.added.md @@ -0,0 +1 @@ +Added `IpBindAddressNoPort` sockopt to support `IP_BIND_ADDRESS_NO_PORT` available on linux. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 5ebb885293..17d3f9b77f 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -412,6 +412,20 @@ sockopt_impl!( libc::IP_FREEBIND, bool ); +#[cfg(linux_android)] +#[cfg(feature = "net")] +sockopt_impl!( + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + /// If enabled, the kernel will not reserve an ephemeral port when binding + /// socket with a port number of 0. The port will later be automatically + /// chosen at connect time, in a way that allows sharing a source port as + /// long as the 4-tuple is unique. + IpBindAddressNoPort, + Both, + libc::IPPROTO_IP, + libc::IP_BIND_ADDRESS_NO_PORT, + bool +); sockopt_impl!( /// Specify the receiving timeout until reporting an error. ReceiveTimeout, diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 6f9e3f0447..e4e4f493c6 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -549,3 +549,30 @@ fn test_ts_clock_monotonic() { SocketTimestamp::SO_TS_MONOTONIC ); } + +#[test] +#[cfg(linux_android)] +// Disable the test under emulation because it failsi with ENOPROTOOPT in CI +// on cross target. Lack of QEMU support is suspected. +#[cfg_attr(qemu, ignore)] +fn test_ip_bind_address_no_port() { + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + setsockopt(&fd, sockopt::IpBindAddressNoPort, &true).expect( + "setting IP_BIND_ADDRESS_NO_PORT on an inet stream socket should succeed", + ); + assert!(getsockopt(&fd, sockopt::IpBindAddressNoPort).expect( + "getting IP_BIND_ADDRESS_NO_PORT on an inet stream socket should succeed", + )); + setsockopt(&fd, sockopt::IpBindAddressNoPort, &false).expect( + "unsetting IP_BIND_ADDRESS_NO_PORT on an inet stream socket should succeed", + ); + assert!(!getsockopt(&fd, sockopt::IpBindAddressNoPort).expect( + "getting IP_BIND_ADDRESS_NO_PORT on an inet stream socket should succeed", + )); +} From 2ad5573b9ea1d70739403d7b0023c1c3d0a08dba Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Sat, 2 Dec 2023 22:05:29 +0000 Subject: [PATCH 078/140] sys::socket fixes for haiku, illumos's cfg to solarish compound. (#2242) --- changelog/2242.fixed.md | 2 ++ src/sys/socket/addr.rs | 15 +++++---------- src/sys/socket/mod.rs | 2 +- 3 files changed, 8 insertions(+), 11 deletions(-) create mode 100644 changelog/2242.fixed.md diff --git a/changelog/2242.fixed.md b/changelog/2242.fixed.md new file mode 100644 index 0000000000..c5194db5fa --- /dev/null +++ b/changelog/2242.fixed.md @@ -0,0 +1,2 @@ +Fixed UnixAddr::new for haiku, it did not record the `sun_len` value as needed. +Fixed `sys::socket::addr::from_raw_parts` and `sys::socket::Sockaddrlike::len` build for solaris. diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index 2c2058b24d..a446f7454b 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -283,12 +283,7 @@ pub struct UnixAddr { /// The length of the valid part of `sun`, including the sun_family field /// but excluding any trailing nul. // On the BSDs, this field is built into sun - #[cfg(any( - linux_android, - target_os = "fuchsia", - target_os = "illumos", - target_os = "redox", - ))] + #[cfg(not(any(bsd, target_os = "haiku")))] sun_len: u8, } @@ -366,7 +361,7 @@ impl UnixAddr { .try_into() .unwrap(); - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "haiku"))] { ret.sun_len = sun_len; } @@ -447,7 +442,7 @@ impl UnixAddr { cfg_if! { if #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "redox", ))] { @@ -525,7 +520,7 @@ impl UnixAddr { impl private::SockaddrLikePriv for UnixAddr {} impl SockaddrLike for UnixAddr { - #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos"))] + #[cfg(any(linux_android, target_os = "fuchsia", solarish, target_os = "redox"))] fn len(&self) -> libc::socklen_t { self.sun_len.into() } @@ -2246,7 +2241,7 @@ mod tests { #[cfg(any( bsd, target_os = "aix", - target_os = "illumos", + solarish, target_os = "haiku" ))] let l = mem::size_of::(); diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 50b87fbf98..a37e123616 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -2373,7 +2373,7 @@ mod tests { let _ = cmsg_space!(u8); } - #[cfg(not(any(linux_android, target_os = "redox")))] + #[cfg(not(any(linux_android, target_os = "redox", target_os = "haiku")))] #[test] fn can_open_routing_socket() { let _ = super::socket( From 9b39cf9f0e584cb6cc0ab5b4b58d0ad91cbcc23f Mon Sep 17 00:00:00 2001 From: Chris Date: Sun, 3 Dec 2023 03:06:23 +0000 Subject: [PATCH 079/140] Added `Flock` object for automatic unlock on drop. (#2170) * Added object for automatic unlock on drop. * Added appropriate changelog file. * Fixed doc error on `Flock`. * Requested changes to make `fcntl::flock` private and OwnedFd instead of RawFd. * Indent fix. * Removed doc links to private item, updated imports. * More import fixes. * Format changes. * Remove unused import for redox. * Added `Flockable` trait per discussions, added tests for `Flock`. * Simplified flock error conditionals. * Added missing cfg flags for `Flockable`. * Added missing cfg flags for impl of `Flockable` on `File`. * Update src/fcntl.rs Co-authored-by: SteveLauC * Updated `Flockable` comment per suggestion. * Finalized `FlockArg` as enum and removed TODO accordingly, removed flock wrapper entirely. * Implemented `Flockable` for `OwnedFd` as well. * Fixed linting error. * Updated changelog accordingly. * Corrected errno logic in `Flock::lock`. * Properly dropped inner type for `Flock`. * Replaced `ManuallyDrop` with `Option` as inner `Flock` type to avoid double-free. * Fixed linting errors. * Removed unnecessary cfg condition, updated documentation. * Modified Flock behavior for drop() and unlock(). * Reverted changes to original `flock()` and `FlockArg` for deprecation period, added EINVAL case if the unlock operation is given to `Flock::lock()`. * Refactored `Flock` to wrap T directly and avoid a double-free after `unlock()` is used. * Fixed linting errors. * More linting fixes. * Fixed example code for `Flock::unlock()`. * Made requested changes. * Removed duplicate import. * Format change. --------- Co-authored-by: SteveLauC --- changelog/2170.added.md | 2 + src/fcntl.rs | 128 ++++++++++++++++++++++++++++++++++++++-- test/test_fcntl.rs | 54 +++++++++++++++++ 3 files changed, 178 insertions(+), 6 deletions(-) create mode 100644 changelog/2170.added.md diff --git a/changelog/2170.added.md b/changelog/2170.added.md new file mode 100644 index 0000000000..6d089a120a --- /dev/null +++ b/changelog/2170.added.md @@ -0,0 +1,2 @@ +Added newtype `Flock` to automatically unlock a held flock upon drop. +Added `Flockable` trait to represent valid types for `Flock`. diff --git a/src/fcntl.rs b/src/fcntl.rs index 6bda0c09e2..8f68b498e7 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -10,11 +10,14 @@ use libc::{self, c_int, c_uint, size_t, ssize_t}; ))] use std::ffi::CStr; use std::ffi::OsString; +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +use std::ops::{Deref, DerefMut}; #[cfg(not(target_os = "redox"))] use std::os::raw; use std::os::unix::ffi::OsStringExt; use std::os::unix::io::RawFd; -// For splice and copy_file_range +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +use std::os::unix::io::{AsRawFd, OwnedFd}; #[cfg(any( target_os = "netbsd", apple_targets, @@ -23,10 +26,7 @@ use std::os::unix::io::RawFd; ))] use std::path::PathBuf; #[cfg(any(linux_android, target_os = "freebsd"))] -use std::{ - os::unix::io::{AsFd, AsRawFd}, - ptr, -}; +use std::{os::unix::io::AsFd, ptr}; #[cfg(feature = "fs")] use crate::{sys::stat::Mode, NixPath, Result}; @@ -578,7 +578,6 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { Errno::result(res) } -// TODO: convert to libc_enum #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum FlockArg { @@ -591,6 +590,7 @@ pub enum FlockArg { } #[cfg(not(any(target_os = "redox", target_os = "solaris")))] +#[deprecated(since = "0.28.0", note = "`fcntl::Flock` should be used instead.")] pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> { use self::FlockArg::*; @@ -611,6 +611,122 @@ pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> { Errno::result(res).map(drop) } + +/// Represents valid types for flock. +/// +/// # Safety +/// Types implementing this must not be `Clone`. +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +pub unsafe trait Flockable: AsRawFd {} + +/// Represents an owned flock, which unlocks on drop. +/// +/// See [flock(2)](https://linux.die.net/man/2/flock) for details on locking semantics. +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +#[derive(Debug)] +pub struct Flock(T); + +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +impl Drop for Flock { + fn drop(&mut self) { + let res = Errno::result(unsafe { libc::flock(self.0.as_raw_fd(), libc::LOCK_UN) }); + if res.is_err() && !std::thread::panicking() { + panic!("Failed to remove flock: {}", res.unwrap_err()); + } + } +} + +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +impl Deref for Flock { + type Target = T; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +impl DerefMut for Flock { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +impl Flock { + /// Obtain a/an flock. + /// + /// # Example + /// ``` + /// # use std::io::Write; + /// # use std::fs::File; + /// # use nix::fcntl::{Flock, FlockArg}; + /// # fn do_stuff(file: File) { + /// let mut file = match Flock::lock(file, FlockArg::LockExclusive) { + /// Ok(l) => l, + /// Err(_) => return, + /// }; + /// + /// // Do stuff + /// let data = "Foo bar"; + /// _ = file.write(data.as_bytes()); + /// _ = file.sync_data(); + /// # } + pub fn lock(t: T, args: FlockArg) -> std::result::Result { + let flags = match args { + FlockArg::LockShared => libc::LOCK_SH, + FlockArg::LockExclusive => libc::LOCK_EX, + FlockArg::LockSharedNonblock => libc::LOCK_SH | libc::LOCK_NB, + FlockArg::LockExclusiveNonblock => libc::LOCK_EX | libc::LOCK_NB, + FlockArg::Unlock | FlockArg::UnlockNonblock => return Err((t, Errno::EINVAL)), + }; + match Errno::result(unsafe { libc::flock(t.as_raw_fd(), flags) }) { + Ok(_) => Ok(Self(t)), + Err(errno) => Err((t, errno)), + } + } + + /// Remove the lock and return the object wrapped within. + /// + /// # Example + /// ``` + /// # use std::fs::File; + /// # use nix::fcntl::{Flock, FlockArg}; + /// fn do_stuff(file: File) -> nix::Result<()> { + /// let mut lock = match Flock::lock(file, FlockArg::LockExclusive) { + /// Ok(l) => l, + /// Err((_,e)) => return Err(e), + /// }; + /// + /// // Do critical section + /// + /// // Unlock + /// let file = match lock.unlock() { + /// Ok(f) => f, + /// Err((_, e)) => return Err(e), + /// }; + /// + /// // Do anything else + /// + /// Ok(()) + /// } + pub fn unlock(self) -> std::result::Result { + let inner = unsafe { match Errno::result(libc::flock(self.0.as_raw_fd(), libc::LOCK_UN)) { + Ok(_) => std::ptr::read(&self.0), + Err(errno) => return Err((self, errno)), + }}; + + std::mem::forget(self); + Ok(inner) + } +} + +// Safety: `File` is not [std::clone::Clone]. +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +unsafe impl Flockable for std::fs::File {} + +// Safety: `OwnedFd` is not [std::clone::Clone]. +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +unsafe impl Flockable for OwnedFd {} } #[cfg(linux_android)] diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index 788b7a8a0d..df323c4394 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -630,3 +630,57 @@ fn test_f_kinfo() { assert_ne!(res, -1); assert_eq!(path, tmp.path()); } + +/// Test `Flock` and associated functions. +/// +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] +mod test_flock { + use nix::fcntl::*; + use tempfile::NamedTempFile; + + /// Verify that `Flock::lock()` correctly obtains a lock, and subsequently unlocks upon drop. + #[test] + fn verify_lock_and_drop() { + // Get 2 `File` handles to same underlying file. + let file1 = NamedTempFile::new().unwrap(); + let file2 = file1.reopen().unwrap(); + let file1 = file1.into_file(); + + // Lock first handle + let lock1 = Flock::lock(file1, FlockArg::LockExclusive).unwrap(); + + // Attempt to lock second handle + let file2 = match Flock::lock(file2, FlockArg::LockExclusiveNonblock) { + Ok(_) => panic!("Expected second exclusive lock to fail."), + Err((f, _)) => f, + }; + + // Drop first lock + std::mem::drop(lock1); + + // Attempt to lock second handle again (but successfully) + if Flock::lock(file2, FlockArg::LockExclusiveNonblock).is_err() { + panic!("Expected locking to be successful."); + } + } + + /// Verify that `Flock::unlock()` correctly obtains unlocks. + #[test] + fn verify_unlock() { + // Get 2 `File` handles to same underlying file. + let file1 = NamedTempFile::new().unwrap(); + let file2 = file1.reopen().unwrap(); + let file1 = file1.into_file(); + + // Lock first handle + let lock1 = Flock::lock(file1, FlockArg::LockExclusive).unwrap(); + + // Unlock and retain file so any erroneous flocks also remain present. + let _file1 = lock1.unlock().unwrap(); + + // Attempt to lock second handle. + if Flock::lock(file2, FlockArg::LockExclusiveNonblock).is_err() { + panic!("Expected locking to be successful."); + } + } +} From db5353cae02f0b8dca63274516e131a3d7b5e591 Mon Sep 17 00:00:00 2001 From: Daniil Bondarev Date: Sun, 3 Dec 2023 15:01:28 -0800 Subject: [PATCH 080/140] Added TcpFastOpenConnect sockopt (#2247) From [tcp](https://man7.org/linux/man-pages/man7/tcp.7.html) man page: ``` TCP_FASTOPEN_CONNECT (since Linux 4.11) This option enables an alternative way to perform Fast Open on the active side (client). When this option is enabled, connect(2) would behave differently depending on if a Fast Open cookie is available for the destination. If a cookie is not available (i.e. first contact to the destination), connect(2) behaves as usual by sending a SYN immediately, except the SYN would include an empty Fast Open cookie option to solicit a cookie. If a cookie is available, connect(2) would return 0 immediately but the SYN transmission is deferred. A subsequent write(2) or sendmsg(2) would trigger a SYN with data plus cookie in the Fast Open option. In other words, the actual connect operation is deferred until data is supplied. Note: While this option is designed for convenience, enabling it does change the behaviors and certain system calls might set different errno values. With cookie present, write(2) or sendmsg(2) must be called right after connect(2) in order to send out SYN+data to complete 3WHS and establish connection. Calling read(2) right after connect(2) without write(2) will cause the blocking socket to be blocked forever. The application should either set TCP_FASTOPEN_CONNECT socket option before write(2) or sendmsg(2), or call write(2) or sendmsg(2) with MSG_FASTOPEN flag directly, instead of both on the same connection. Here is the typical call flow with this new option: s = socket(); setsockopt(s, IPPROTO_TCP, TCP_FASTOPEN_CONNECT, 1, ...); connect(s); write(s); /* write() should always follow connect() * in order to trigger SYN to go out. */ read(s)/write(s); /* ... */ close(s); ``` --- changelog/2247.added.md | 1 + src/sys/socket/sockopt.rs | 20 ++++++++++++++++++++ test/sys/test_sockopt.rs | 24 ++++++++++++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 changelog/2247.added.md diff --git a/changelog/2247.added.md b/changelog/2247.added.md new file mode 100644 index 0000000000..f79f35495f --- /dev/null +++ b/changelog/2247.added.md @@ -0,0 +1 @@ +Added `TcpFastOpenConnect` sockopt to support `TCP_FASTOPEN_CONNECT` available on linux. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 17d3f9b77f..ac5827b572 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -600,6 +600,26 @@ sockopt_impl!( libc::TCP_USER_TIMEOUT, u32 ); +#[cfg(linux_android)] +#[cfg(feature = "net")] +sockopt_impl!( + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + /// Enables TCP Fast Open (RFC 7413) on a connecting socket. If a fast open + /// cookie is not available (first attempt to connect), `connect` syscall + /// will behave as usual, except for internally trying to solicit a cookie + /// from remote peer. When cookie is available, the next `connect` syscall + /// will immediately succeed without actually establishing TCP connection. + /// The connection establishment will be defered till the next `write` or + /// `sendmsg` syscalls on the socket, allowing TCP prtocol to establish + /// connection and send data in the same packets. Note: calling `read` right + /// after `connect` without `write` on the socket will cause the blocking + /// socket to be blocked forever. + TcpFastOpenConnect, + Both, + libc::IPPROTO_TCP, + libc::TCP_FASTOPEN_CONNECT, + bool +); sockopt_impl!( /// Sets or gets the maximum socket receive buffer in bytes. RcvBuf, diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index e4e4f493c6..60b57fb5f2 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -576,3 +576,27 @@ fn test_ip_bind_address_no_port() { "getting IP_BIND_ADDRESS_NO_PORT on an inet stream socket should succeed", )); } + +#[test] +#[cfg(linux_android)] +fn test_tcp_fast_open_connect() { + let fd = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + setsockopt(&fd, sockopt::TcpFastOpenConnect, &true).expect( + "setting TCP_FASTOPEN_CONNECT on an inet stream socket should succeed", + ); + assert!(getsockopt(&fd, sockopt::TcpFastOpenConnect).expect( + "getting TCP_FASTOPEN_CONNECT on an inet stream socket should succeed", + )); + setsockopt(&fd, sockopt::TcpFastOpenConnect, &false).expect( + "unsetting TCP_FASTOPEN_CONNECT on an inet stream socket should succeed", + ); + assert!(!getsockopt(&fd, sockopt::TcpFastOpenConnect).expect( + "getting TCP_FASTOPEN_CONNECT on an inet stream socket should succeed", + )); +} From cb56e89aab6745bd708975c6910e33fa13191e23 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 3 Dec 2023 16:02:26 -0700 Subject: [PATCH 081/140] Ensure all tests use unique IP ports (#2196) --- src/sys/socket/addr.rs | 2 +- test/sys/test_socket.rs | 8 ++++---- test/sys/test_sockopt.rs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index a446f7454b..eb1944bb99 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -2272,7 +2272,7 @@ mod tests { #[test] fn ip() { - let s = "127.0.0.1:8080"; + let s = "127.0.0.1:8082"; let ip = SockaddrIn::from_str(s).unwrap().ip(); assert_eq!("127.0.0.1", format!("{ip}")); } diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 12729b23a4..ffa54a98c2 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -21,7 +21,7 @@ pub fn test_timestamping() { }; use std::io::{IoSlice, IoSliceMut}; - let sock_addr = SockaddrIn::from_str("127.0.0.1:6790").unwrap(); + let sock_addr = SockaddrIn::from_str("127.0.0.1:6797").unwrap(); let ssock = socket( AddressFamily::Inet, @@ -434,7 +434,7 @@ mod recvfrom { #[test] pub fn udp() { - let std_sa = SocketAddrV4::from_str("127.0.0.1:6789").unwrap(); + let std_sa = SocketAddrV4::from_str("127.0.0.1:6795").unwrap(); let sock_addr = SockaddrIn::from(std_sa); let rsock = socket( AddressFamily::Inet, @@ -793,10 +793,10 @@ mod recvfrom { #[test] pub fn udp_inet6() { let addr = std::net::Ipv6Addr::from_str("::1").unwrap(); - let rport = 6789; + let rport = 6796; let rstd_sa = SocketAddrV6::new(addr, rport, 0, 0); let raddr = SockaddrIn6::from(rstd_sa); - let sport = 6790; + let sport = 6798; let sstd_sa = SocketAddrV6::new(addr, sport, 0, 0); let saddr = SockaddrIn6::from(sstd_sa); let rsock = socket( diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 60b57fb5f2..bd72e9a7fd 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -110,7 +110,7 @@ fn test_so_tcp_maxseg() { use std::net::SocketAddrV4; use std::str::FromStr; - let std_sa = SocketAddrV4::from_str("127.0.0.1:4001").unwrap(); + let std_sa = SocketAddrV4::from_str("127.0.0.1:4003").unwrap(); let sock_addr = SockaddrIn::from(std_sa); let rsock = socket( From 8d656e32f64b7654ce6dbf7c5f54dcfc86c6b85b Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 4 Dec 2023 08:11:56 +0800 Subject: [PATCH 082/140] feat: MapFlags::map_hugetlb_with_size_log2 for Android/Fuchsia (#2245) * feat: MapFlags::map_hugetlb_with_size_log2 for Android/Fuchsia * fmt Cargo.toml * changelog --- Cargo.toml | 2 +- changelog/2245.added.md | 1 + src/sys/mman.rs | 5 +---- 3 files changed, 3 insertions(+), 5 deletions(-) create mode 100644 changelog/2245.added.md diff --git a/Cargo.toml b/Cargo.toml index f36c819723..06302aac6d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { version = "0.2.148", features = ["extra_traits"] } +libc = { git = "https://github.com/rust-lang/libc", rev = "497ac428bc010b5db9682ecf94cd567b31d53e5c", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } diff --git a/changelog/2245.added.md b/changelog/2245.added.md new file mode 100644 index 0000000000..6ea7e0dec7 --- /dev/null +++ b/changelog/2245.added.md @@ -0,0 +1 @@ +Enable `MapFlags::map_hugetlb_with_size_log2` method for Android/Fuchsia diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 5e968f052b..9f4c40acaf 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -169,10 +169,7 @@ impl MapFlags { /// let f = MapFlags::map_hugetlb_with_size_log2(30).unwrap(); /// assert_eq!(f, MapFlags::MAP_HUGETLB | MapFlags::MAP_HUGE_1GB); /// ``` - // TODO: support Andorid and Fuchsia when https://github.com/rust-lang/libc/pull/3444 - // will be released - #[cfg(target_os = "linux")] - #[cfg_attr(docsrs, doc(cfg(all())))] + #[cfg(any(linux_android, target_os = "fuchsia"))] pub fn map_hugetlb_with_size_log2( huge_page_size_log2: u32, ) -> Option { From 75bddf255a7ba50d1efbedf8f9dc41ad8226987c Mon Sep 17 00:00:00 2001 From: sgasse <47532708+sgasse@users.noreply.github.com> Date: Mon, 4 Dec 2023 03:43:07 +0100 Subject: [PATCH 083/140] Add `Ipv6MulticastHops` as socket option (#2234) (#2234) Co-authored-by: Simon B. Gasse --- changelog/2234.added.md | 1 + src/sys/socket/sockopt.rs | 11 +++++++++++ test/sys/test_sockopt.rs | 13 +++++++++++++ 3 files changed, 25 insertions(+) create mode 100644 changelog/2234.added.md diff --git a/changelog/2234.added.md b/changelog/2234.added.md new file mode 100644 index 0000000000..138ac3ed3a --- /dev/null +++ b/changelog/2234.added.md @@ -0,0 +1 @@ +Added `Ipv6MulticastHops` as socket option to set and read. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index ac5827b572..f5fef2e9f0 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -355,6 +355,17 @@ sockopt_impl!( u8 ); #[cfg(feature = "net")] +sockopt_impl!( + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + /// Set or read the hop limit value of outgoing IPv6 multicast packets for + /// this socket. + Ipv6MulticastHops, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_MULTICAST_HOPS, + libc::c_int +); +#[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Set or read a boolean integer argument that determines whether sent diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index bd72e9a7fd..ec25a7e93b 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -325,6 +325,19 @@ fn test_ttl_opts() { .expect("setting ipv6ttl on an inet6 socket should succeed"); } +#[test] +fn test_ipv6_multicast_hops() { + let fd6 = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(&fd6, sockopt::Ipv6MulticastHops, &7) + .expect("setting ipv6multicasthops on an inet6 socket should succeed"); +} + #[test] #[cfg(apple_targets)] fn test_dontfrag_opts() { From 3a20eef318eba8d652c0c9e8dde304869f04d14c Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Mon, 4 Dec 2023 06:24:21 +0000 Subject: [PATCH 084/140] FreeBSD's rfork wrapper proposal (#2121) --- changelog/2121.added.md | 1 + src/unistd.rs | 48 +++++++++++++++++++++++++++++++++++++++++ test/test_unistd.rs | 31 ++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 changelog/2121.added.md diff --git a/changelog/2121.added.md b/changelog/2121.added.md new file mode 100644 index 0000000000..687c373947 --- /dev/null +++ b/changelog/2121.added.md @@ -0,0 +1 @@ +Added rfork support for FreeBSD in `unistd` diff --git a/src/unistd.rs b/src/unistd.rs index abdc9bdbaf..a9d8b0aaf2 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -2898,6 +2898,54 @@ mod getres { } } +#[cfg(feature = "process")] +#[cfg(target_os = "freebsd")] +libc_bitflags! { + /// Flags for [`rfork`] + /// + /// subset of flags supported by FreeBSD 12.x and onwards + /// with a safe outcome, thus as `RFMEM` can possibly lead to undefined behavior, + /// it is not in the list. And `rfork_thread` is deprecated. + pub struct RforkFlags: libc::c_int { + /// creates a new process. + RFPROC; + /// the child process will detach from the parent. + /// however, no status will be emitted at child's exit. + RFNOWAIT; + /// the file descriptor's table will be copied + RFFDG; + /// a new file descriptor's table will be created + RFCFDG; + /// force sharing the sigacts structure between + /// the child and the parent. + RFSIGSHARE; + /// enables kernel thread support. + RFTHREAD; + /// sets a status to emit at child's exit. + RFTSIGZMB; + /// linux's behavior compatibility setting. + /// emits SIGUSR1 as opposed to SIGCHLD upon child's exit. + RFLINUXTHPN; + } +} + +feature! { +#![feature = "process"] +#[cfg(target_os = "freebsd")] +/// rfork can be used to have a tigher control about which resources child +/// and parent process will be sharing, file descriptors, address spaces +/// and child exit's behavior. +pub unsafe fn rfork(flags: RforkFlags) -> Result { + use ForkResult::*; + let res = unsafe { libc::rfork(flags.bits()) }; + + Errno::result(res).map(|res| match res { + 0 => Child, + res => Parent { child: Pid(res) }, + }) +} +} + #[cfg(feature = "fs")] libc_bitflags! { /// Options for access() diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 5a58585e7d..0a841df060 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -66,6 +66,37 @@ fn test_fork_and_waitpid() { } } +#[test] +#[cfg(target_os = "freebsd")] +fn test_rfork_and_waitpid() { + let _m = crate::FORK_MTX.lock(); + + // Safe: Child only calls `_exit`, which is signal-safe + match unsafe { rfork(RforkFlags::RFPROC | RforkFlags::RFTHREAD) } + .expect("Error: Rfork Failed") + { + Child => unsafe { _exit(0) }, + Parent { child } => { + // assert that child was created and pid > 0 + let child_raw: ::libc::pid_t = child.into(); + assert!(child_raw > 0); + let wait_status = waitpid(child, None); + match wait_status { + // assert that waitpid returned correct status and the pid is the one of the child + Ok(WaitStatus::Exited(pid_t, _)) => assert_eq!(pid_t, child), + + // panic, must never happen + s @ Ok(_) => { + panic!("Child exited {s:?}, should never happen") + } + + // panic, waitpid should never fail + Err(s) => panic!("Error: waitpid returned Err({s:?}"), + } + } + } +} + #[test] fn test_wait() { // Grab FORK_MTX so wait doesn't reap a different test's child process From da451400ea538dc56c30eecaf2e36792325d4a42 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Mon, 4 Dec 2023 06:28:48 +0000 Subject: [PATCH 085/140] sys::sendfile adding solaris' sendfilev wrapper proposal. (#2207) --- changelog/2207.added.md | 1 + src/sys/sendfile.rs | 61 +++++++++++++++++++++++++++++++++++++++++ test/test.rs | 1 + test/test_sendfile.rs | 60 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 123 insertions(+) create mode 100644 changelog/2207.added.md diff --git a/changelog/2207.added.md b/changelog/2207.added.md new file mode 100644 index 0000000000..ddaa904221 --- /dev/null +++ b/changelog/2207.added.md @@ -0,0 +1 @@ +Added `sendfilev` in sys::sendfile for solarish diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index ced85d48e8..579013b4b8 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -118,6 +118,42 @@ cfg_if! { ) } } + } else if #[cfg(solarish)] { + use std::os::unix::io::BorrowedFd; + use std::marker::PhantomData; + + #[derive(Debug, Copy, Clone)] + /// Mapping of the raw C sendfilevec_t struct + pub struct SendfileVec<'fd> { + raw: libc::sendfilevec_t, + phantom: PhantomData> + } + + impl<'fd> SendfileVec<'fd> { + /// initialises SendfileVec to send data directly from the process's address space + /// same in C with sfv_fd set to SFV_FD_SELF. + pub fn newself( + off: off_t, + len: usize + ) -> Self { + Self{raw: libc::sendfilevec_t{sfv_fd: libc::SFV_FD_SELF, sfv_flag: 0, sfv_off: off, sfv_len: len}, phantom: PhantomData} + } + + /// initialises SendfileVec to send data from `fd`. + pub fn new( + fd: BorrowedFd<'fd>, + off: off_t, + len: usize + ) -> SendfileVec<'fd> { + Self{raw: libc::sendfilevec_t{sfv_fd: fd.as_raw_fd(), sfv_flag: 0, sfv_off:off, sfv_len: len}, phantom: PhantomData} + } + } + + impl From> for libc::sendfilevec_t { + fn from<'fd>(vec: SendfileVec) -> libc::sendfilevec_t { + vec.raw + } + } } } @@ -285,5 +321,30 @@ cfg_if! { }; (Errno::result(return_code).and(Ok(())), len) } + } else if #[cfg(solarish)] { + /// Write data from the vec arrays to `out_sock` and returns a `Result` and a + /// count of bytes written. + /// + /// Each `SendfileVec` set needs to be instantiated either with `SendfileVec::new` or + /// `SendfileVec::newself`. + /// + /// The former allows to send data from a file descriptor through `fd`, + /// from an offset `off` and for a given amount of data `len`. + /// + /// The latter allows to send data from the process's address space, from an offset `off` + /// and for a given amount of data `len`. + /// + /// For more information, see + /// [the sendfilev(3) man page.](https://illumos.org/man/3EXT/sendfilev) + pub fn sendfilev( + out_sock: F, + vec: &[SendfileVec] + ) -> (Result<()>, usize) { + let mut len = 0usize; + let return_code = unsafe { + libc::sendfilev(out_sock.as_fd().as_raw_fd(), vec.as_ptr() as *const libc::sendfilevec_t, vec.len() as i32, &mut len) + }; + (Errno::result(return_code).and(Ok(())), len) + } } } diff --git a/test/test.rs b/test/test.rs index 41c3dce8e6..eed532c194 100644 --- a/test/test.rs +++ b/test/test.rs @@ -44,6 +44,7 @@ mod test_sched; target_os = "freebsd", apple_targets, target_os = "linux", + solarish ))] mod test_sendfile; mod test_stat; diff --git a/test/test_sendfile.rs b/test/test_sendfile.rs index e6152c5dee..df3445b5c5 100644 --- a/test/test_sendfile.rs +++ b/test/test_sendfile.rs @@ -12,6 +12,7 @@ cfg_if! { target_os = "dragonfly", target_os = "freebsd", apple_targets, + solarish ))] { use std::net::Shutdown; use std::os::unix::net::UnixStream; @@ -204,3 +205,62 @@ fn test_sendfile_darwin() { assert_eq!(bytes_written as usize, bytes_read); assert_eq!(expected_string, read_string); } + +#[cfg(solarish)] +#[test] +fn test_sendfilev() { + use std::os::fd::AsFd; + // Declare the content + let header_strings = + ["HTTP/1.1 200 OK\n", "Content-Type: text/plain\n", "\n"]; + let body = "Xabcdef123456"; + let body_offset = 1usize; + let trailer_strings = ["\n", "Served by Make Believe\n"]; + + // Write data to files + let mut header_data = tempfile().unwrap(); + header_data + .write_all(header_strings.concat().as_bytes()) + .unwrap(); + let mut body_data = tempfile().unwrap(); + body_data.write_all(body.as_bytes()).unwrap(); + let mut trailer_data = tempfile().unwrap(); + trailer_data + .write_all(trailer_strings.concat().as_bytes()) + .unwrap(); + let (mut rd, wr) = UnixStream::pair().unwrap(); + let vec: &[SendfileVec] = &[ + SendfileVec::new( + header_data.as_fd(), + 0, + header_strings.iter().map(|s| s.len()).sum(), + ), + SendfileVec::new( + body_data.as_fd(), + body_offset as off_t, + body.len() - body_offset, + ), + SendfileVec::new( + trailer_data.as_fd(), + 0, + trailer_strings.iter().map(|s| s.len()).sum(), + ), + ]; + + let (res, bytes_written) = sendfilev(&wr, vec); + assert!(res.is_ok()); + wr.shutdown(Shutdown::Both).unwrap(); + + // Prepare the expected result + let expected_string = header_strings.concat() + + &body[body_offset..] + + &trailer_strings.concat(); + + // Verify the message that was sent + assert_eq!(bytes_written, expected_string.as_bytes().len()); + + let mut read_string = String::new(); + let bytes_read = rd.read_to_string(&mut read_string).unwrap(); + assert_eq!(bytes_written, bytes_read); + assert_eq!(expected_string, read_string); +} From b763d7355a726fe48f06e1f7cd1a92b1defa2fa8 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Wed, 6 Dec 2023 08:43:36 +0000 Subject: [PATCH 086/140] sys::memfd additional flags related to the hugetlb filesystem support. (#2252) --- changelog/2252.added.md | 1 + src/sys/memfd.rs | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 changelog/2252.added.md diff --git a/changelog/2252.added.md b/changelog/2252.added.md new file mode 100644 index 0000000000..8737adde79 --- /dev/null +++ b/changelog/2252.added.md @@ -0,0 +1 @@ +Added new `MemFdCreateFlag` constants to `sys::memfd` on Linux and Android related to hugetlbfs support. diff --git a/src/sys/memfd.rs b/src/sys/memfd.rs index 516ffd3262..22ee5fc5b7 100644 --- a/src/sys/memfd.rs +++ b/src/sys/memfd.rs @@ -29,6 +29,49 @@ libc_bitflags!( /// /// [`memfd_create(2)`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html MFD_ALLOW_SEALING; + /// Anonymous file will be created using huge pages. It should be safe now to + /// combine with [`MFD_ALLOW_SEALING`] too. + /// However, despite its presence, on FreeBSD it is unimplemented for now (ENOSYS). + /// + /// See also the hugetlb filesystem in [`memfd_create(2)`]. + /// + /// [`memfd_create(2)`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html + #[cfg(linux_android)] + MFD_HUGETLB; + /// Following are to be used with [`MFD_HUGETLB`], indicating the desired hugetlb size. + /// + /// See also the hugetlb filesystem in [`memfd_create(2)`]. + /// + /// [`memfd_create(2)`]: https://man7.org/linux/man-pages/man2/memfd_create.2.html + #[cfg(linux_android)] + MFD_HUGE_1MB; + /// hugetlb size of 2MB. + #[cfg(linux_android)] + MFD_HUGE_2MB; + /// hugetlb size of 8MB. + #[cfg(linux_android)] + MFD_HUGE_8MB; + /// hugetlb size of 16MB. + #[cfg(linux_android)] + MFD_HUGE_16MB; + /// hugetlb size of 32MB. + #[cfg(linux_android)] + MFD_HUGE_32MB; + /// hugetlb size of 256MB. + #[cfg(linux_android)] + MFD_HUGE_256MB; + /// hugetlb size of 512MB. + #[cfg(linux_android)] + MFD_HUGE_512MB; + /// hugetlb size of 1GB. + #[cfg(linux_android)] + MFD_HUGE_1GB; + /// hugetlb size of 2GB. + #[cfg(linux_android)] + MFD_HUGE_2GB; + /// hugetlb size of 16GB. + #[cfg(linux_android)] + MFD_HUGE_16GB; } ); From a90b4b215fee79449546655a9f75c371ca3e72ba Mon Sep 17 00:00:00 2001 From: Samuel Thibault Date: Fri, 8 Dec 2023 19:51:35 +0100 Subject: [PATCH 087/140] Add GNU/Hurd support (#2131) --- .github/workflows/ci.yml | 1 + src/dir.rs | 1 + src/errno.rs | 375 ++++++++++++++++++++++++++++++++++---- src/fcntl.rs | 8 +- src/features.rs | 1 + src/sys/mman.rs | 5 +- src/sys/resource.rs | 20 +- src/sys/signal.rs | 7 +- src/sys/socket/addr.rs | 48 +++-- src/sys/socket/mod.rs | 4 +- src/sys/socket/sockopt.rs | 2 +- src/sys/statvfs.rs | 6 + src/sys/termios.rs | 7 +- src/unistd.rs | 26 ++- test/sys/mod.rs | 3 +- test/test_unistd.rs | 17 +- 16 files changed, 463 insertions(+), 68 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9338285e94..5b84767897 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -271,6 +271,7 @@ jobs: # https://github.com/nix-rust/nix/issues/2200 #- target: armv7-unknown-linux-uclibceabihf - target: x86_64-unknown-haiku + - target: i686-unknown-hurd-gnu steps: - name: checkout uses: actions/checkout@v4 diff --git a/src/dir.rs b/src/dir.rs index 1579b65683..ab70f064cc 100644 --- a/src/dir.rs +++ b/src/dir.rs @@ -228,6 +228,7 @@ impl Entry { target_os = "emscripten", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", solarish, linux_android, apple_targets))] { diff --git a/src/errno.rs b/src/errno.rs index c7a182b6c0..cde462d958 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -19,7 +19,8 @@ cfg_if! { } else if #[cfg(any(target_os = "linux", target_os = "redox", target_os = "dragonfly", - target_os = "fuchsia"))] { + target_os = "fuchsia", + target_os = "hurd"))] { unsafe fn errno_location() -> *mut c_int { unsafe { libc::__errno_location() } } @@ -306,16 +307,36 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] EBFONT => "Bad font file format", - #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] + #[cfg(any( + linux_android, + solarish, + target_os = "fuchsia", + target_os = "hurd" + ))] ENOSTR => "Device not a stream", - #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] + #[cfg(any( + linux_android, + solarish, + target_os = "fuchsia", + target_os = "hurd" + ))] ENODATA => "No data available", - #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] + #[cfg(any( + linux_android, + solarish, + target_os = "fuchsia", + target_os = "hurd" + ))] ETIME => "Timer expired", - #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] + #[cfg(any( + linux_android, + solarish, + target_os = "fuchsia", + target_os = "hurd" + ))] ENOSR => "Out of streams resources", #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] @@ -324,7 +345,12 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ENOPKG => "Package not installed", - #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] + #[cfg(any( + linux_android, + solarish, + target_os = "fuchsia", + target_os = "hurd" + ))] EREMOTE => "Object is remote", #[cfg(any( @@ -348,7 +374,7 @@ fn desc(errno: Errno) -> &'static str { linux_android, solarish, target_os = "aix", - target_os = "fuchsia" + target_os = "fuchsia", ))] EPROTO => "Protocol error", @@ -373,7 +399,8 @@ fn desc(errno: Errno) -> &'static str { linux_android, target_os = "aix", target_os = "fuchsia", - target_os = "haiku" + target_os = "haiku", + target_os = "hurd" ))] EOVERFLOW => "Value too large for defined data type", @@ -398,7 +425,12 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] ELIBMAX => "Attempting to link in too many shared libraries", - #[cfg(any(linux_android, solarish, target_os = "fuchsia"))] + #[cfg(any( + linux_android, + solarish, + target_os = "fuchsia", + target_os = "hurd" + ))] ELIBEXEC => "Cannot exec a shared library directly", #[cfg(any( @@ -432,7 +464,7 @@ fn desc(errno: Errno) -> &'static str { ))] EOPNOTSUPP => "Operation not supported on transport endpoint", - #[cfg(any(linux_android, target_os = "fuchsia"))] + #[cfg(any(linux_android, target_os = "fuchsia", target_os = "hurd"))] ESTALE => "Stale file handle", #[cfg(any(linux_android, target_os = "fuchsia"))] @@ -488,7 +520,12 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any(linux_android, target_os = "fuchsia"))] EKEYREJECTED => "Key was rejected by service", - #[cfg(any(linux_android, target_os = "aix", target_os = "fuchsia"))] + #[cfg(any( + linux_android, + target_os = "aix", + target_os = "fuchsia", + target_os = "hurd" + ))] EOWNERDEAD => "Owner died", #[cfg(solarish)] @@ -515,10 +552,10 @@ fn desc(errno: Errno) -> &'static str { #[cfg(freebsdlike)] EDOOFUS => "Programming error", - #[cfg(any(freebsdlike, target_os = "redox"))] + #[cfg(any(freebsdlike, target_os = "hurd", target_os = "redox"))] EMULTIHOP => "Multihop attempted", - #[cfg(any(freebsdlike, target_os = "redox"))] + #[cfg(any(freebsdlike, target_os = "hurd", target_os = "redox"))] ENOLINK => "Link has been severed", #[cfg(target_os = "freebsd")] @@ -527,7 +564,7 @@ fn desc(errno: Errno) -> &'static str { #[cfg(target_os = "freebsd")] ECAPMODE => "Not permitted in capability mode", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] ENEEDAUTH => "Need authenticator", #[cfg(any(bsd, target_os = "redox", solarish))] @@ -538,32 +575,59 @@ fn desc(errno: Errno) -> &'static str { apple_targets, target_os = "netbsd", target_os = "redox", - target_os = "haiku" + target_os = "haiku", + target_os = "hurd" ))] EILSEQ => "Illegal byte sequence", #[cfg(any(bsd, target_os = "haiku"))] ENOATTR => "Attribute not found", - #[cfg(any(bsd, target_os = "redox", target_os = "haiku"))] + #[cfg(any( + bsd, + target_os = "redox", + target_os = "haiku", + target_os = "hurd" + ))] EBADMSG => "Bad message", - #[cfg(any(bsd, target_os = "redox", target_os = "haiku"))] + #[cfg(any( + bsd, + target_os = "haiku", + target_os = "hurd", + target_os = "redox" + ))] EPROTO => "Protocol error", - #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] + #[cfg(any( + freebsdlike, + apple_targets, + target_os = "openbsd", + target_os = "hurd" + ))] ENOTRECOVERABLE => "State not recoverable", #[cfg(any(freebsdlike, apple_targets, target_os = "openbsd"))] EOWNERDEAD => "Previous owner died", - #[cfg(any(bsd, target_os = "aix", solarish, target_os = "haiku"))] + #[cfg(any( + bsd, + target_os = "aix", + solarish, + target_os = "haiku", + target_os = "hurd" + ))] ENOTSUP => "Operation not supported", - #[cfg(any(bsd, target_os = "aix"))] + #[cfg(any(bsd, target_os = "aix", target_os = "hurd"))] EPROCLIM => "Too many processes", - #[cfg(any(bsd, target_os = "aix", target_os = "redox"))] + #[cfg(any( + bsd, + target_os = "aix", + target_os = "hurd", + target_os = "redox" + ))] EUSERS => "Too many users", #[cfg(any( @@ -571,7 +635,8 @@ fn desc(errno: Errno) -> &'static str { solarish, target_os = "redox", target_os = "aix", - target_os = "haiku" + target_os = "haiku", + target_os = "hurd" ))] EDQUOT => "Disc quota exceeded", @@ -587,28 +652,33 @@ fn desc(errno: Errno) -> &'static str { #[cfg(any(bsd, target_os = "aix", target_os = "redox"))] EREMOTE => "Too many levels of remote in path", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] EBADRPC => "RPC struct is bad", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] ERPCMISMATCH => "RPC version wrong", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] EPROGUNAVAIL => "RPC prog. not avail", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] EPROGMISMATCH => "Program version wrong", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] EPROCUNAVAIL => "Bad procedure for program", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] EFTYPE => "Inappropriate file type or format", - #[cfg(bsd)] + #[cfg(any(bsd, target_os = "hurd"))] EAUTH => "Authentication error", - #[cfg(any(bsd, target_os = "aix", target_os = "redox"))] + #[cfg(any( + bsd, + target_os = "aix", + target_os = "hurd", + target_os = "redox" + ))] ECANCELED => "Operation canceled", #[cfg(apple_targets)] @@ -676,7 +746,7 @@ fn desc(errno: Errno) -> &'static str { #[cfg(apple_targets)] EQFULL => "Interface output queue is full", - #[cfg(target_os = "openbsd")] + #[cfg(any(target_os = "openbsd", target_os = "hurd"))] EOPNOTSUPP => "Operation not supported", #[cfg(target_os = "openbsd")] @@ -693,6 +763,21 @@ fn desc(errno: Errno) -> &'static str { #[cfg(solarish)] ENOTACTIVE => "Facility is not active", + + #[cfg(target_os = "hurd")] + EBACKGROUND => "Inappropriate operation for background process", + + #[cfg(target_os = "hurd")] + EDIED => "Translator died", + + #[cfg(target_os = "hurd")] + EGREGIOUS => "You really blew it this time", + + #[cfg(target_os = "hurd")] + EIEIO => "Computer bought the farm", + + #[cfg(target_os = "hurd")] + EGRATUITOUS => "Gratuitous error", } } @@ -2926,3 +3011,231 @@ mod consts { } } } + +#[cfg(target_os = "hurd")] +mod consts { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + #[repr(i32)] + #[non_exhaustive] + pub enum Errno { + UnknownErrno = 0, + EPERM = libc::EPERM, + ENOENT = libc::ENOENT, + ESRCH = libc::ESRCH, + EINTR = libc::EINTR, + EIO = libc::EIO, + ENXIO = libc::ENXIO, + E2BIG = libc::E2BIG, + ENOEXEC = libc::ENOEXEC, + EBADF = libc::EBADF, + ECHILD = libc::ECHILD, + EDEADLK = libc::EDEADLK, + ENOMEM = libc::ENOMEM, + EACCES = libc::EACCES, + EFAULT = libc::EFAULT, + ENOTBLK = libc::ENOTBLK, + EBUSY = libc::EBUSY, + EEXIST = libc::EEXIST, + EXDEV = libc::EXDEV, + ENODEV = libc::ENODEV, + ENOTDIR = libc::ENOTDIR, + EISDIR = libc::EISDIR, + EINVAL = libc::EINVAL, + EMFILE = libc::EMFILE, + ENFILE = libc::ENFILE, + ENOTTY = libc::ENOTTY, + ETXTBSY = libc::ETXTBSY, + EFBIG = libc::EFBIG, + ENOSPC = libc::ENOSPC, + ESPIPE = libc::ESPIPE, + EROFS = libc::EROFS, + EMLINK = libc::EMLINK, + EPIPE = libc::EPIPE, + EDOM = libc::EDOM, + ERANGE = libc::ERANGE, + EAGAIN = libc::EAGAIN, + EINPROGRESS = libc::EINPROGRESS, + EALREADY = libc::EALREADY, + ENOTSOCK = libc::ENOTSOCK, + EMSGSIZE = libc::EMSGSIZE, + EPROTOTYPE = libc::EPROTOTYPE, + ENOPROTOOPT = libc::ENOPROTOOPT, + EPROTONOSUPPORT = libc::EPROTONOSUPPORT, + ESOCKTNOSUPPORT = libc::ESOCKTNOSUPPORT, + EOPNOTSUPP = libc::EOPNOTSUPP, + EPFNOSUPPORT = libc::EPFNOSUPPORT, + EAFNOSUPPORT = libc::EAFNOSUPPORT, + EADDRINUSE = libc::EADDRINUSE, + EADDRNOTAVAIL = libc::EADDRNOTAVAIL, + ENETDOWN = libc::ENETDOWN, + ENETUNREACH = libc::ENETUNREACH, + ENETRESET = libc::ENETRESET, + ECONNABORTED = libc::ECONNABORTED, + ECONNRESET = libc::ECONNRESET, + ENOBUFS = libc::ENOBUFS, + EISCONN = libc::EISCONN, + ENOTCONN = libc::ENOTCONN, + EDESTADDRREQ = libc::EDESTADDRREQ, + ESHUTDOWN = libc::ESHUTDOWN, + ETOOMANYREFS = libc::ETOOMANYREFS, + ETIMEDOUT = libc::ETIMEDOUT, + ECONNREFUSED = libc::ECONNREFUSED, + ELOOP = libc::ELOOP, + ENAMETOOLONG = libc::ENAMETOOLONG, + EHOSTDOWN = libc::EHOSTDOWN, + EHOSTUNREACH = libc::EHOSTUNREACH, + ENOTEMPTY = libc::ENOTEMPTY, + EPROCLIM = libc::EPROCLIM, + EUSERS = libc::EUSERS, + EDQUOT = libc::EDQUOT, + ESTALE = libc::ESTALE, + EREMOTE = libc::EREMOTE, + EBADRPC = libc::EBADRPC, + ERPCMISMATCH = libc::ERPCMISMATCH, + EPROGUNAVAIL = libc::EPROGUNAVAIL, + EPROGMISMATCH = libc::EPROGMISMATCH, + EPROCUNAVAIL = libc::EPROCUNAVAIL, + ENOLCK = libc::ENOLCK, + EFTYPE = libc::EFTYPE, + EAUTH = libc::EAUTH, + ENEEDAUTH = libc::ENEEDAUTH, + ENOSYS = libc::ENOSYS, + ELIBEXEC = libc::ELIBEXEC, + ENOTSUP = libc::ENOTSUP, + EILSEQ = libc::EILSEQ, + EBACKGROUND = libc::EBACKGROUND, + EDIED = libc::EDIED, + EGREGIOUS = libc::EGREGIOUS, + EIEIO = libc::EIEIO, + EGRATUITOUS = libc::EGRATUITOUS, + EBADMSG = libc::EBADMSG, + EIDRM = libc::EIDRM, + EMULTIHOP = libc::EMULTIHOP, + ENODATA = libc::ENODATA, + ENOLINK = libc::ENOLINK, + ENOMSG = libc::ENOMSG, + ENOSR = libc::ENOSR, + ENOSTR = libc::ENOSTR, + EOVERFLOW = libc::EOVERFLOW, + EPROTO = libc::EPROTO, + ETIME = libc::ETIME, + ECANCELED = libc::ECANCELED, + EOWNERDEAD = libc::EOWNERDEAD, + ENOTRECOVERABLE = libc::ENOTRECOVERABLE, + } + + impl Errno { + pub const EWOULDBLOCK: Errno = Errno::EAGAIN; + } + + pub const fn from_i32(e: i32) -> Errno { + use self::Errno::*; + + match e { + libc::EPERM => EPERM, + libc::ENOENT => ENOENT, + libc::ESRCH => ESRCH, + libc::EINTR => EINTR, + libc::EIO => EIO, + libc::ENXIO => ENXIO, + libc::E2BIG => E2BIG, + libc::ENOEXEC => ENOEXEC, + libc::EBADF => EBADF, + libc::ECHILD => ECHILD, + libc::EDEADLK => EDEADLK, + libc::ENOMEM => ENOMEM, + libc::EACCES => EACCES, + libc::EFAULT => EFAULT, + libc::ENOTBLK => ENOTBLK, + libc::EBUSY => EBUSY, + libc::EEXIST => EEXIST, + libc::EXDEV => EXDEV, + libc::ENODEV => ENODEV, + libc::ENOTDIR => ENOTDIR, + libc::EISDIR => EISDIR, + libc::EINVAL => EINVAL, + libc::EMFILE => EMFILE, + libc::ENFILE => ENFILE, + libc::ENOTTY => ENOTTY, + libc::ETXTBSY => ETXTBSY, + libc::EFBIG => EFBIG, + libc::ENOSPC => ENOSPC, + libc::ESPIPE => ESPIPE, + libc::EROFS => EROFS, + libc::EMLINK => EMLINK, + libc::EPIPE => EPIPE, + libc::EDOM => EDOM, + libc::ERANGE => ERANGE, + libc::EAGAIN => EAGAIN, + libc::EINPROGRESS => EINPROGRESS, + libc::EALREADY => EALREADY, + libc::ENOTSOCK => ENOTSOCK, + libc::EMSGSIZE => EMSGSIZE, + libc::EPROTOTYPE => EPROTOTYPE, + libc::ENOPROTOOPT => ENOPROTOOPT, + libc::EPROTONOSUPPORT => EPROTONOSUPPORT, + libc::ESOCKTNOSUPPORT => ESOCKTNOSUPPORT, + libc::EOPNOTSUPP => EOPNOTSUPP, + libc::EPFNOSUPPORT => EPFNOSUPPORT, + libc::EAFNOSUPPORT => EAFNOSUPPORT, + libc::EADDRINUSE => EADDRINUSE, + libc::EADDRNOTAVAIL => EADDRNOTAVAIL, + libc::ENETDOWN => ENETDOWN, + libc::ENETUNREACH => ENETUNREACH, + libc::ENETRESET => ENETRESET, + libc::ECONNABORTED => ECONNABORTED, + libc::ECONNRESET => ECONNRESET, + libc::ENOBUFS => ENOBUFS, + libc::EISCONN => EISCONN, + libc::ENOTCONN => ENOTCONN, + libc::EDESTADDRREQ => EDESTADDRREQ, + libc::ESHUTDOWN => ESHUTDOWN, + libc::ETOOMANYREFS => ETOOMANYREFS, + libc::ETIMEDOUT => ETIMEDOUT, + libc::ECONNREFUSED => ECONNREFUSED, + libc::ELOOP => ELOOP, + libc::ENAMETOOLONG => ENAMETOOLONG, + libc::EHOSTDOWN => EHOSTDOWN, + libc::EHOSTUNREACH => EHOSTUNREACH, + libc::ENOTEMPTY => ENOTEMPTY, + libc::EPROCLIM => EPROCLIM, + libc::EUSERS => EUSERS, + libc::EDQUOT => EDQUOT, + libc::ESTALE => ESTALE, + libc::EREMOTE => EREMOTE, + libc::EBADRPC => EBADRPC, + libc::ERPCMISMATCH => ERPCMISMATCH, + libc::EPROGUNAVAIL => EPROGUNAVAIL, + libc::EPROGMISMATCH => EPROGMISMATCH, + libc::EPROCUNAVAIL => EPROCUNAVAIL, + libc::ENOLCK => ENOLCK, + libc::EFTYPE => EFTYPE, + libc::EAUTH => EAUTH, + libc::ENEEDAUTH => ENEEDAUTH, + libc::ENOSYS => ENOSYS, + libc::ELIBEXEC => ELIBEXEC, + libc::ENOTSUP => ENOTSUP, + libc::EILSEQ => EILSEQ, + libc::EBACKGROUND => EBACKGROUND, + libc::EDIED => EDIED, + libc::EGREGIOUS => EGREGIOUS, + libc::EIEIO => EIEIO, + libc::EGRATUITOUS => EGRATUITOUS, + libc::EBADMSG => EBADMSG, + libc::EIDRM => EIDRM, + libc::EMULTIHOP => EMULTIHOP, + libc::ENODATA => ENODATA, + libc::ENOLINK => ENOLINK, + libc::ENOMSG => ENOMSG, + libc::ENOSR => ENOSR, + libc::ENOSTR => ENOSTR, + libc::EOVERFLOW => EOVERFLOW, + libc::EPROTO => EPROTO, + libc::ETIME => ETIME, + libc::ECANCELED => ECANCELED, + libc::EOWNERDEAD => EOWNERDEAD, + libc::ENOTRECOVERABLE => ENOTRECOVERABLE, + _ => UnknownErrno, + } + } +} diff --git a/src/fcntl.rs b/src/fcntl.rs index 8f68b498e7..c89b304554 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -306,7 +306,11 @@ fn inner_readlink( dirfd: Option, path: &P, ) -> Result { - let mut v = Vec::with_capacity(libc::PATH_MAX as usize); + #[cfg(not(target_os = "hurd"))] + const PATH_MAX: usize = libc::PATH_MAX as usize; + #[cfg(target_os = "hurd")] + const PATH_MAX: usize = 1024; // Hurd does not define a hard limit, so try a guess first + let mut v = Vec::with_capacity(PATH_MAX); { // simple case: result is strictly less than `PATH_MAX` @@ -358,7 +362,7 @@ fn inner_readlink( } else { // If lstat doesn't cooperate, or reports an error, be a little less // precise. - (libc::PATH_MAX as usize).max(128) << 1 + PATH_MAX.max(128) << 1 } }; diff --git a/src/features.rs b/src/features.rs index d75f6a408a..0a0c618096 100644 --- a/src/features.rs +++ b/src/features.rs @@ -100,6 +100,7 @@ mod os { #[cfg(any( freebsdlike, // FreeBSD since 10.0 DragonFlyBSD since ??? netbsdlike, // NetBSD since 6.0 OpenBSD since 5.7 + target_os = "hurd", // Since glibc 2.28 target_os = "illumos", // Since ??? target_os = "redox", // Since 1-july-2020 ))] diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 9f4c40acaf..3518662756 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -77,7 +77,7 @@ libc_bitflags! { /// Do not reserve swap space for this mapping. /// /// This was removed in FreeBSD 11 and is unused in DragonFlyBSD. - #[cfg(not(any(freebsdlike, target_os = "aix")))] + #[cfg(not(any(freebsdlike, target_os = "aix", target_os = "hurd")))] MAP_NORESERVE; /// Populate page tables for a mapping. #[cfg(linux_android)] @@ -264,7 +264,7 @@ libc_enum! { #[cfg(linux_android)] MADV_DODUMP, /// Specify that the application no longer needs the pages in the given range. - #[cfg(not(target_os = "aix"))] + #[cfg(not(any(target_os = "aix", target_os = "hurd")))] MADV_FREE, /// Request that the system not flush the current range to disk unless it needs to. #[cfg(freebsdlike)] @@ -513,6 +513,7 @@ pub unsafe fn munmap(addr: NonNull, len: size_t) -> Result<()> { /// [`MmapAdvise::MADV_FREE`]. /// /// [`madvise(2)`]: https://man7.org/linux/man-pages/man2/madvise.2.html +#[allow(rustdoc::broken_intra_doc_links)] // For Hurd as `MADV_FREE` is not available on it pub unsafe fn madvise( addr: NonNull, length: size_t, diff --git a/src/sys/resource.rs b/src/sys/resource.rs index c0116f080b..f57db47944 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -10,7 +10,10 @@ pub use libc::RLIM_INFINITY; use std::mem; cfg_if! { - if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{ + if #[cfg(any( + all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")), + target_os = "hurd" + ))]{ use libc::{__rlimit_resource_t, rlimit}; } else if #[cfg(any( bsd, @@ -38,7 +41,10 @@ libc_enum! { // // https://gcc.gnu.org/legacy-ml/gcc/2015-08/msg00441.html // https://github.com/rust-lang/libc/blob/master/src/unix/linux_like/linux/gnu/mod.rs - #[cfg_attr(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")), repr(u32))] + #[cfg_attr(any( + all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")), + target_os = "hurd" + ), repr(u32))] #[cfg_attr(any( bsd, target_os = "android", @@ -171,7 +177,10 @@ pub fn getrlimit(resource: Resource) -> Result<(rlim_t, rlim_t)> { let mut old_rlim = mem::MaybeUninit::::uninit(); cfg_if! { - if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{ + if #[cfg(any( + all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")), + target_os = "hurd" + ))] { let res = unsafe { libc::getrlimit(resource as __rlimit_resource_t, old_rlim.as_mut_ptr()) }; } else { let res = unsafe { libc::getrlimit(resource as c_int, old_rlim.as_mut_ptr()) }; @@ -224,7 +233,10 @@ pub fn setrlimit( rlim_max: hard_limit, }; cfg_if! { - if #[cfg(all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")))]{ + if #[cfg(any( + all(target_os = "linux", any(target_env = "gnu", target_env = "uclibc")), + target_os = "hurd", + ))]{ let res = unsafe { libc::setrlimit(resource as __rlimit_resource_t, &new_rlim as *const rlimit) }; }else{ let res = unsafe { libc::setrlimit(resource as c_int, &new_rlim as *const rlimit) }; diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 3156848c48..10f1de85b0 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -17,6 +17,7 @@ use std::str::FromStr; #[cfg(not(any( target_os = "fuchsia", + target_os = "hurd", target_os = "openbsd", target_os = "redox" )))] @@ -431,6 +432,7 @@ libc_bitflags! { SA_NOCLDSTOP; /// When catching a [`Signal::SIGCHLD`] signal, the system will not /// create zombie processes when children of the calling process exit. + #[cfg(not(target_os = "hurd"))] SA_NOCLDWAIT; /// Further occurrences of the delivered signal are not masked during /// the execution of the handler. @@ -1068,14 +1070,14 @@ feature! { #[cfg(target_os = "freebsd")] pub type type_of_thread_id = libc::lwpid_t; /// Identifies a thread for [`SigevNotify::SigevThreadId`] -#[cfg(any(target_env = "gnu", target_env = "uclibc"))] +#[cfg(all(not(target_os = "hurd"), any(target_env = "gnu", target_env = "uclibc")))] pub type type_of_thread_id = libc::pid_t; /// Specifies the notification method used by a [`SigEvent`] // sigval is actually a union of a int and a void*. But it's never really used // as a pointer, because neither libc nor the kernel ever dereference it. nix // therefore presents it as an intptr_t, which is how kevent uses it. -#[cfg(not(any(target_os = "fuchsia", target_os = "openbsd", target_os = "redox")))] +#[cfg(not(any(target_os = "fuchsia", target_os = "hurd", target_os = "openbsd", target_os = "redox")))] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum SigevNotify { /// No notification will be delivered @@ -1128,6 +1130,7 @@ pub enum SigevNotify { #[cfg(not(any( target_os = "fuchsia", + target_os = "hurd", target_os = "openbsd", target_os = "redox" )))] diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index eb1944bb99..b8413b6c44 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -162,6 +162,7 @@ pub enum AddressFamily { target_os = "aix", solarish, apple_targets, + target_os = "hurd", target_os = "redox", )))] Bluetooth = libc::AF_BLUETOOTH, @@ -177,6 +178,7 @@ pub enum AddressFamily { target_os = "aix", solarish, target_os = "haiku", + target_os = "hurd", target_os = "redox", )))] Isdn = libc::AF_ISDN, @@ -283,7 +285,7 @@ pub struct UnixAddr { /// The length of the valid part of `sun`, including the sun_family field /// but excluding any trailing nul. // On the BSDs, this field is built into sun - #[cfg(not(any(bsd, target_os = "haiku")))] + #[cfg(not(any(bsd, target_os = "haiku", target_os = "hurd")))] sun_len: u8, } @@ -361,7 +363,7 @@ impl UnixAddr { .try_into() .unwrap(); - #[cfg(any(bsd, target_os = "haiku"))] + #[cfg(any(bsd, target_os = "haiku", target_os = "hurd"))] { ret.sun_len = sun_len; } @@ -520,7 +522,12 @@ impl UnixAddr { impl private::SockaddrLikePriv for UnixAddr {} impl SockaddrLike for UnixAddr { - #[cfg(any(linux_android, target_os = "fuchsia", solarish, target_os = "redox"))] + #[cfg(any( + linux_android, + target_os = "fuchsia", + solarish, + target_os = "redox" + ))] fn len(&self) -> libc::socklen_t { self.sun_len.into() } @@ -813,7 +820,12 @@ impl SockaddrIn { /// Creates a new socket address from IPv4 octets and a port number. pub fn new(a: u8, b: u8, c: u8, d: u8, port: u16) -> Self { Self(libc::sockaddr_in { - #[cfg(any(bsd, target_os = "aix", target_os = "haiku"))] + #[cfg(any( + bsd, + target_os = "aix", + target_os = "haiku", + target_os = "hurd" + ))] sin_len: Self::size() as u8, sin_family: AddressFamily::Inet as sa_family_t, sin_port: u16::to_be(port), @@ -882,7 +894,12 @@ impl fmt::Display for SockaddrIn { impl From for SockaddrIn { fn from(addr: net::SocketAddrV4) -> Self { Self(libc::sockaddr_in { - #[cfg(any(bsd, target_os = "haiku", target_os = "hermit"))] + #[cfg(any( + bsd, + target_os = "haiku", + target_os = "hermit", + target_os = "hurd" + ))] sin_len: mem::size_of::() as u8, sin_family: AddressFamily::Inet as sa_family_t, sin_port: addr.port().to_be(), // network byte order @@ -1002,7 +1019,12 @@ impl From for SockaddrIn6 { fn from(addr: net::SocketAddrV6) -> Self { #[allow(clippy::needless_update)] // It isn't needless on Illumos Self(libc::sockaddr_in6 { - #[cfg(any(bsd, target_os = "haiku", target_os = "hermit"))] + #[cfg(any( + bsd, + target_os = "haiku", + target_os = "hermit", + target_os = "hurd" + ))] sin6_len: mem::size_of::() as u8, sin6_family: AddressFamily::Inet6 as sa_family_t, sin6_port: addr.port().to_be(), // network byte order @@ -1059,7 +1081,10 @@ impl std::str::FromStr for SockaddrIn6 { pub union SockaddrStorage { #[cfg(linux_android)] alg: AlgAddr, - #[cfg(all(feature = "net", not(target_os = "redox")))] + #[cfg(all( + feature = "net", + not(any(target_os = "hurd", target_os = "redox")) + ))] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] dl: LinkAddr, #[cfg(linux_android)] @@ -2124,7 +2149,7 @@ mod tests { } } - #[cfg(not(target_os = "redox"))] + #[cfg(not(any(target_os = "hurd", target_os = "redox")))] mod link { #![allow(clippy::cast_ptr_alignment)] @@ -2238,12 +2263,7 @@ mod tests { #[test] fn size() { - #[cfg(any( - bsd, - target_os = "aix", - solarish, - target_os = "haiku" - ))] + #[cfg(any(bsd, target_os = "aix", solarish, target_os = "haiku"))] let l = mem::size_of::(); #[cfg(any(linux_android, target_os = "fuchsia"))] let l = mem::size_of::(); diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index a37e123616..96d20035e5 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -38,10 +38,10 @@ pub use self::addr::{SockaddrLike, SockaddrStorage}; pub use self::addr::{AddressFamily, UnixAddr}; #[cfg(not(solarish))] pub use self::addr::{AddressFamily, UnixAddr}; -#[cfg(not(any(solarish, target_os = "haiku", target_os = "redox")))] +#[cfg(not(any(solarish, target_os = "haiku", target_os = "hurd", target_os = "redox")))] #[cfg(feature = "net")] pub use self::addr::{LinkAddr, SockaddrIn, SockaddrIn6}; -#[cfg(any(solarish, target_os = "haiku", target_os = "redox"))] +#[cfg(any(solarish, target_os = "haiku", target_os = "hurd", target_os = "redox"))] #[cfg(feature = "net")] pub use self::addr::{SockaddrIn, SockaddrIn6}; diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index f5fef2e9f0..63db9b9e21 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -728,7 +728,7 @@ sockopt_impl!( libc::SO_TIMESTAMPING, super::TimestampingFlag ); -#[cfg(not(any(target_os = "aix", target_os = "haiku", target_os = "redox")))] +#[cfg(not(any(target_os = "aix", target_os = "haiku", target_os = "hurd", target_os = "redox")))] sockopt_impl!( /// Enable or disable the receiving of the `SO_TIMESTAMP` control message. ReceiveTimestamp, diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 1b2cb5ea50..72f38ab7ab 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -104,9 +104,15 @@ impl Statvfs { } /// Get the file system id + #[cfg(not(target_os = "hurd"))] pub fn filesystem_id(&self) -> c_ulong { self.0.f_fsid } + /// Get the file system id + #[cfg(target_os = "hurd")] + pub fn filesystem_id(&self) -> u64 { + self.0.f_fsid + } /// Get the mount flags #[cfg(not(target_os = "redox"))] diff --git a/src/sys/termios.rs b/src/sys/termios.rs index bdddc0c735..57b42254ea 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -260,8 +260,13 @@ libc_enum! { /// /// B0 is special and will disable the port. #[cfg_attr(target_os = "haiku", repr(u8))] + #[cfg_attr(target_os = "hurd", repr(i32))] #[cfg_attr(all(apple_targets, target_pointer_width = "64"), repr(u64))] - #[cfg_attr(all(not(all(apple_targets, target_pointer_width = "64")), not(target_os = "haiku")), repr(u32))] + #[cfg_attr(all( + not(all(apple_targets, target_pointer_width = "64")), + not(target_os = "haiku"), + not(target_os = "hurd") + ), repr(u32))] #[non_exhaustive] pub enum BaudRate { B0, diff --git a/src/unistd.rs b/src/unistd.rs index a9d8b0aaf2..b982178f3b 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -22,7 +22,7 @@ use crate::{Error, NixPath, Result}; use cfg_if::cfg_if; use libc::{ self, c_char, c_int, c_long, c_uint, gid_t, mode_t, off_t, pid_t, size_t, - uid_t, PATH_MAX, + uid_t, }; use std::convert::Infallible; #[cfg(not(target_os = "redox"))] @@ -669,8 +669,13 @@ pub fn getcwd() -> Result { } } + #[cfg(not(target_os = "hurd"))] + const PATH_MAX: usize = libc::PATH_MAX as usize; + #[cfg(target_os = "hurd")] + const PATH_MAX: usize = 1024; // Hurd does not define a hard limit, so try a guess first + // Trigger the internal buffer resizing logic. - reserve_double_buffer_size(&mut buf, PATH_MAX as usize)?; + reserve_double_buffer_size(&mut buf, PATH_MAX)?; } } } @@ -864,7 +869,7 @@ pub fn execvp>( /// This functions like a combination of `execvp(2)` and `execve(2)` to pass an /// environment and have a search path. See these two for additional /// information. -#[cfg(any(target_os = "haiku", target_os = "linux", target_os = "openbsd"))] +#[cfg(any(target_os = "haiku", target_os = "hurd", target_os = "linux", target_os = "openbsd"))] pub fn execvpe, SE: AsRef>( filename: &CStr, args: &[SA], @@ -890,7 +895,7 @@ pub fn execvpe, SE: AsRef>( /// /// This function is similar to `execve`, except that the program to be executed /// is referenced as a file descriptor instead of a path. -#[cfg(any(linux_android, freebsdlike))] +#[cfg(any(linux_android, freebsdlike, target_os = "hurd"))] #[inline] pub fn fexecve, SE: AsRef>( fd: RawFd, @@ -1193,6 +1198,7 @@ feature! { freebsdlike, solarish, target_os = "emscripten", + target_os = "hurd", target_os = "redox", netbsdlike, ))] @@ -3055,6 +3061,7 @@ pub struct User { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] pub class: CString, /// Last password change @@ -3064,6 +3071,7 @@ pub struct User { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] pub change: libc::time_t, /// Expiration time of account @@ -3073,6 +3081,7 @@ pub struct User { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] pub expire: libc::time_t, } @@ -3125,6 +3134,7 @@ impl From<&libc::passwd> for User { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] class: CString::new(CStr::from_ptr(pw.pw_class).to_bytes()) .unwrap(), @@ -3134,6 +3144,7 @@ impl From<&libc::passwd> for User { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] change: pw.pw_change, #[cfg(not(any( @@ -3142,6 +3153,7 @@ impl From<&libc::passwd> for User { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] expire: pw.pw_expire, } @@ -3182,6 +3194,7 @@ impl From for libc::passwd { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] pw_class: u.class.into_raw(), #[cfg(not(any( @@ -3190,6 +3203,7 @@ impl From for libc::passwd { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] pw_change: u.change, #[cfg(not(any( @@ -3198,6 +3212,7 @@ impl From for libc::passwd { target_os = "aix", target_os = "fuchsia", target_os = "haiku", + target_os = "hurd", )))] pw_expire: u.expire, #[cfg(target_os = "illumos")] @@ -3483,7 +3498,10 @@ feature! { /// (see [`ttyname(3)`](https://man7.org/linux/man-pages/man3/ttyname.3.html)). #[cfg(not(target_os = "fuchsia"))] pub fn ttyname(fd: F) -> Result { + #[cfg(not(target_os = "hurd"))] const PATH_MAX: usize = libc::PATH_MAX as usize; + #[cfg(target_os = "hurd")] + const PATH_MAX: usize = 1024; // Hurd does not define a hard limit, so try a guess first let mut buf = vec![0_u8; PATH_MAX]; let c_buf = buf.as_mut_ptr().cast(); diff --git a/test/sys/mod.rs b/test/sys/mod.rs index a62e6cb376..8812cdd6cd 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -15,7 +15,8 @@ mod test_aio; #[cfg(not(any( target_os = "redox", target_os = "fuchsia", - target_os = "haiku" + target_os = "haiku", + target_os = "hurd" )))] mod test_ioctl; #[cfg(not(target_os = "redox"))] diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 0a841df060..3bd130e7ad 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -432,6 +432,7 @@ cfg_if! { execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd()); } else if #[cfg(any(target_os = "dragonfly", target_os = "freebsd", + target_os = "hurd", target_os = "linux"))] { // These tests frequently fail on musl, probably due to // https://github.com/nix-rust/nix/issues/555 @@ -447,7 +448,12 @@ cfg_if! { } } -#[cfg(any(target_os = "haiku", target_os = "linux", target_os = "openbsd"))] +#[cfg(any( + target_os = "haiku", + target_os = "hurd", + target_os = "linux", + target_os = "openbsd" +))] execve_test_factory!(test_execvpe, execvpe, &CString::new("sh").unwrap()); cfg_if! { @@ -656,10 +662,11 @@ fn test_acct() { acct::disable().unwrap(); } +#[cfg_attr(target_os = "hurd", ignore)] #[test] fn test_fpathconf_limited() { let f = tempfile().unwrap(); - // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test + // PATH_MAX is limited on most platforms, so it makes a good test let path_max = fpathconf(f, PathconfVar::PATH_MAX); assert!( path_max @@ -669,9 +676,10 @@ fn test_fpathconf_limited() { ); } +#[cfg_attr(target_os = "hurd", ignore)] #[test] fn test_pathconf_limited() { - // AFAIK, PATH_MAX is limited on all platforms, so it makes a good test + // PATH_MAX is limited on most platforms, so it makes a good test let path_max = pathconf("/", PathconfVar::PATH_MAX); assert!( path_max @@ -681,9 +689,10 @@ fn test_pathconf_limited() { ); } +#[cfg_attr(target_os = "hurd", ignore)] #[test] fn test_sysconf_limited() { - // AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test + // OPEN_MAX is limited on most platforms, so it makes a good test let open_max = sysconf(SysconfVar::OPEN_MAX); assert!( open_max From 8708d5b3b7d5335e4f0acad855132741cf561cb8 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sat, 9 Dec 2023 02:51:50 +0800 Subject: [PATCH 088/140] refactor: some clippy warnings (#2250) --- src/poll_timeout.rs | 2 +- src/sys/socket/mod.rs | 2 +- src/unistd.rs | 16 ++++++++-------- test/test_unistd.rs | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/poll_timeout.rs b/src/poll_timeout.rs index 3f2dc4c4a1..f7d9015f56 100644 --- a/src/poll_timeout.rs +++ b/src/poll_timeout.rs @@ -14,7 +14,7 @@ impl PollTimeout { /// > Specifying a timeout of zero causes poll() to return immediately, even if no file /// > descriptors are ready. pub const ZERO: Self = Self(0); - /// Blocks for at most [`std::i32::MAX`] milliseconds. + /// Blocks for at most [`i32::MAX`] milliseconds. pub const MAX: Self = Self(i32::MAX); /// Returns if `self` equals [`PollTimeout::NONE`]. pub fn is_none(&self) -> bool { diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 96d20035e5..87b56f9169 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1599,7 +1599,7 @@ impl MultiHeaders { .enumerate() .map(|(ix, address)| { let (ptr, cap) = match &mut cmsg_buffers { - Some(v) => ((&mut v[ix * msg_controllen] as *mut u8), msg_controllen), + Some(v) => (&mut v[ix * msg_controllen] as *mut u8, msg_controllen), None => (std::ptr::null_mut(), 0), }; let msg_hdr = unsafe { pack_mhdr_to_receive(std::ptr::null_mut(), 0, ptr, cap, address.as_mut_ptr()) }; diff --git a/src/unistd.rs b/src/unistd.rs index b982178f3b..32fa025bbc 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1526,7 +1526,7 @@ pub fn getgroups() -> Result> { // equal to the value of {NGROUPS_MAX} + 1. let ngroups_max = match sysconf(SysconfVar::NGROUPS_MAX) { Ok(Some(n)) => (n + 1) as usize, - Ok(None) | Err(_) => ::max_value(), + Ok(None) | Err(_) => usize::MAX, }; // Next, get the number of groups so we can size our Vec @@ -1660,7 +1660,7 @@ pub fn setgroups(groups: &[Gid]) -> Result<()> { pub fn getgrouplist(user: &CStr, group: Gid) -> Result> { let ngroups_max = match sysconf(SysconfVar::NGROUPS_MAX) { Ok(Some(n)) => n as c_int, - Ok(None) | Err(_) => ::max_value(), + Ok(None) | Err(_) => c_int::MAX, }; use std::cmp::min; let mut groups = Vec::::with_capacity(min(ngroups_max, 8) as usize); @@ -2867,9 +2867,9 @@ mod getres { /// #[inline] pub fn getresuid() -> Result { - let mut ruid = libc::uid_t::max_value(); - let mut euid = libc::uid_t::max_value(); - let mut suid = libc::uid_t::max_value(); + let mut ruid = libc::uid_t::MAX; + let mut euid = libc::uid_t::MAX; + let mut suid = libc::uid_t::MAX; let res = unsafe { libc::getresuid(&mut ruid, &mut euid, &mut suid) }; Errno::result(res).map(|_| ResUid { @@ -2890,9 +2890,9 @@ mod getres { /// #[inline] pub fn getresgid() -> Result { - let mut rgid = libc::gid_t::max_value(); - let mut egid = libc::gid_t::max_value(); - let mut sgid = libc::gid_t::max_value(); + let mut rgid = libc::gid_t::MAX; + let mut egid = libc::gid_t::MAX; + let mut sgid = libc::gid_t::MAX; let res = unsafe { libc::getresgid(&mut rgid, &mut egid, &mut sgid) }; Errno::result(res).map(|_| ResGid { diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 3bd130e7ad..1e4b013630 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -1103,8 +1103,8 @@ fn test_linkat_follow_symlink() { // Check the file type of the new link assert_eq!( - (stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t) - & SFlag::S_IFMT), + stat::SFlag::from_bits_truncate(newfilestat.st_mode as mode_t) + & SFlag::S_IFMT, SFlag::S_IFREG ); From c9dfad9004a3345f412fb11e25da055cfebc5f0a Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sat, 9 Dec 2023 02:52:05 +0800 Subject: [PATCH 089/140] docs: document that we should use libc from git repo when under dev (#2246) * docs: document that we should use libc from git repo when under dev * try fix diff * try fix diff * respond to review --- CONTRIBUTING.md | 10 +++++----- CONVENTIONS.md | 15 +++++++++++---- RELEASE_PROCEDURE.md | 13 ++++++++++--- 3 files changed, 26 insertions(+), 12 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ef31b36dcc..45c6108213 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,7 +63,7 @@ Please make pull requests against the `master` branch. If you change the API by way of adding, removing or changing something or if you fix a bug, please add an appropriate note, every note should be a new markdown file under the [changelog directory][cl] stating the change made by your pull request, -the filename should be in the following foramt: +the filename should be in the following format: ``` ..md @@ -104,17 +104,17 @@ run once you open a pull request. ### Disabling a test in the CI environment -Sometimes there are features that cannot be tested in the CI environment. To +Sometimes there are features that cannot be tested in the CI environment. To stop a test from running under CI, add `skip_if_cirrus!()` to it. Please describe the reason it shouldn't run under CI, and a link to an issue if -possible! Other tests cannot be run under QEMU, which is used for some -architectures. To skip them, add a `#[cfg_attr(qemu, ignore)]` attribute to +possible! Other tests cannot be run under QEMU, which is used for some +architectures. To skip them, add a `#[cfg_attr(qemu, ignore)]` attribute to the test. ## GitHub Merge Queues We use GitHub merge queues to ensure that subtle merge conflicts won't result -in failing code. If you add or remove a CI job, remember to adjust the +in failing code. If you add or remove a CI job, remember to adjust the required status checks in the repository's branch protection rules! ## API conventions diff --git a/CONVENTIONS.md b/CONVENTIONS.md index e461b13b24..540cdce666 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -17,8 +17,15 @@ We follow the conventions laid out in [Keep A CHANGELOG][kacl]. ## libc constants, functions and structs -We do not define integer constants ourselves, but use or reexport them from the -[libc crate][libc]. +We do not define ffi functions or their associated constants and types ourselves, +but use or reexport them from the [libc crate][libc], if your PR uses something +that does not exist in the libc crate, you should add it to libc first. Once +your libc PR gets merged, you can adjust our `libc` dependency to include that +libc change. Use a git dependency if necessary. + +```toml +libc = { git = "https://github.com/rust-lang/libc", rev = "the commit includes your libc PR", ... } +``` We use the functions exported from [libc][libc] instead of writing our own `extern` declarations. @@ -40,7 +47,7 @@ When creating newtypes, we use Rust's `CamelCase` type naming convention. ## cfg gates When creating operating-system-specific functionality, we gate it by -`#[cfg(target_os = ...)]`. If more than one operating system is affected, we +`#[cfg(target_os = ...)]`. If more than one operating system is affected, we prefer to use the cfg aliases defined in build.rs, like `#[cfg(bsd)]`. ## Bitflags @@ -115,5 +122,5 @@ To deprecate an interface, put the following attribute on the top of it: `` is the version where this interface will be deprecated, in most cases, it will be the version of the next release. And a user-friendly note should be added. Normally, there should be a new interface that will replace -the old one, so a note should be something like: " should be +the old one, so a note should be something like: "`` should be used instead". diff --git a/RELEASE_PROCEDURE.md b/RELEASE_PROCEDURE.md index 1ffd21aa84..b7d1fa3972 100644 --- a/RELEASE_PROCEDURE.md +++ b/RELEASE_PROCEDURE.md @@ -4,15 +4,22 @@ library. # Before Release Nix uses [cargo release](https://github.com/crate-ci/cargo-release) to automate -the release process. Based on changes since the last release, pick a new +the release process. Based on changes since the last release, pick a new version number following semver conventions. For nix, a change that drops support for some Rust versions counts as a breaking change, and requires a major bump. The release is prepared as follows: -- Ask for a new libc version if, necessary. It usually is. Then update the - dependency in Cargo.toml accordingly. +- Ask for a new libc version if, necessary. It usually is. Then update the + dependency in `Cargo.toml` to rely on a release from crates.io. + + ```diff + [dependencies] + -libc = { git = "https://github.com/rust-lang/libc", rev = "", features = ["extra_traits"] } + +libc = { version = "", features = ["extra_traits"] } + ``` + - Update the version number in `Cargo.toml` - Generate `CHANGELOG.md` for this release by `towncrier build --version= --yes` From 2ab5558e08f64eb88fb9a22a6ad21577b305d0ca Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Fri, 8 Dec 2023 19:29:11 +0000 Subject: [PATCH 090/140] fix, mostly, solaris build. (#2248) With few exceptions as newer interfaces like preadv/pwritev unsupported only on solaris. --- changelog/2248.fixed.md | 1 + src/ifaddrs.rs | 4 +- src/lib.rs | 2 +- src/net/if_.rs | 119 +++++++++++++++++++++------------------- src/sys/ioctl/bsd.rs | 4 +- src/sys/ioctl/mod.rs | 4 +- src/sys/mod.rs | 6 +- src/sys/socket/addr.rs | 38 ++++++------- src/sys/socket/mod.rs | 9 ++- src/sys/time.rs | 4 +- src/sys/uio.rs | 4 +- src/unistd.rs | 6 +- test/sys/test_uio.rs | 12 +++- test/test.rs | 2 +- test/test_dir.rs | 4 +- test/test_pty.rs | 2 +- test/test_resource.rs | 4 +- test/test_stat.rs | 2 +- test/test_unistd.rs | 6 +- 19 files changed, 126 insertions(+), 107 deletions(-) create mode 100644 changelog/2248.fixed.md diff --git a/changelog/2248.fixed.md b/changelog/2248.fixed.md new file mode 100644 index 0000000000..3115e7ef90 --- /dev/null +++ b/changelog/2248.fixed.md @@ -0,0 +1 @@ +Fixed solaris build globally. diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index 58cbfec9eb..b3de64b01a 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -94,7 +94,9 @@ impl InterfaceAddress { unsafe { SockaddrStorage::from_raw(info.ifa_netmask, None) }; let mut addr = InterfaceAddress { interface_name: ifname.to_string_lossy().to_string(), - flags: InterfaceFlags::from_bits_truncate(info.ifa_flags as i32), + flags: InterfaceFlags::from_bits_truncate( + info.ifa_flags as IflagsType, + ), address, netmask, broadcast: None, diff --git a/src/lib.rs b/src/lib.rs index 0d4416926f..aaf1c2d4c8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -125,7 +125,7 @@ feature! { #[cfg(any(linux_android, bsd, - target_os = "illumos"))] + solarish))] #[deny(missing_docs)] pub mod ifaddrs; #[cfg(not(target_os = "redox"))] diff --git a/src/net/if_.rs b/src/net/if_.rs index 4e59fc15da..c66b5dc0b3 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -7,6 +7,13 @@ use std::fmt; use crate::{Error, NixPath, Result}; use libc::c_uint; +#[cfg(not(solarish))] +/// type alias for InterfaceFlags +pub type IflagsType = libc::c_int; +#[cfg(solarish)] +/// type alias for InterfaceFlags +pub type IflagsType = libc::c_longlong; + /// Resolve an interface into a interface number. pub fn if_nametoindex(name: &P) -> Result { let if_index = name @@ -21,23 +28,24 @@ pub fn if_nametoindex(name: &P) -> Result { libc_bitflags!( /// Standard interface flags, used by `getifaddrs` - pub struct InterfaceFlags: libc::c_int { + pub struct InterfaceFlags: IflagsType { + /// Interface is running. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_UP; + IFF_UP as IflagsType; /// Valid broadcast address set. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_BROADCAST; + IFF_BROADCAST as IflagsType; /// Internal debugging flag. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(not(target_os = "haiku"))] - IFF_DEBUG; + IFF_DEBUG as IflagsType; /// Interface is a loopback interface. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_LOOPBACK; + IFF_LOOPBACK as IflagsType; /// Interface is a point-to-point link. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_POINTOPOINT; + IFF_POINTOPOINT as IflagsType; /// Avoid use of trailers. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any( @@ -46,10 +54,10 @@ libc_bitflags!( apple_targets, target_os = "fuchsia", target_os = "netbsd"))] - IFF_NOTRAILERS; + IFF_NOTRAILERS as IflagsType; /// Interface manages own routes. #[cfg(any(target_os = "dragonfly"))] - IFF_SMART; + IFF_SMART as IflagsType; /// Resources allocated. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any( @@ -57,16 +65,16 @@ libc_bitflags!( bsd, solarish, target_os = "fuchsia"))] - IFF_RUNNING; + IFF_RUNNING as IflagsType; /// No arp protocol, L2 destination address not set. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_NOARP; + IFF_NOARP as IflagsType; /// Interface is in promiscuous mode. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_PROMISC; + IFF_PROMISC as IflagsType; /// Receive all multicast packets. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_ALLMULTI; + IFF_ALLMULTI as IflagsType; /// Master of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(linux_android, target_os = "fuchsia"))] @@ -76,7 +84,7 @@ libc_bitflags!( IFF_OACTIVE; /// Protocol code on board. #[cfg(solarish)] - IFF_INTELLIGENT; + IFF_INTELLIGENT as IflagsType; /// Slave of a load balancing bundle. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(linux_android, target_os = "fuchsia"))] @@ -86,13 +94,13 @@ libc_bitflags!( IFF_SIMPLEX; /// Supports multicast. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) - IFF_MULTICAST; + IFF_MULTICAST as IflagsType; /// Per link layer defined bit. #[cfg(bsd)] IFF_LINK0; /// Multicast using broadcast. #[cfg(solarish)] - IFF_MULTI_BCAST; + IFF_MULTI_BCAST as IflagsType; /// Is able to select media type via ifmap. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(linux_android, target_os = "fuchsia"))] @@ -102,7 +110,7 @@ libc_bitflags!( IFF_LINK1; /// Non-unique address. #[cfg(solarish)] - IFF_UNNUMBERED; + IFF_UNNUMBERED as IflagsType; /// Auto media selection active. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(linux_android, target_os = "fuchsia"))] @@ -115,14 +123,14 @@ libc_bitflags!( IFF_ALTPHYS; /// DHCP controls interface. #[cfg(solarish)] - IFF_DHCPRUNNING; + IFF_DHCPRUNNING as IflagsType; /// The addresses are lost when the interface goes down. (see /// [`netdevice(7)`](https://man7.org/linux/man-pages/man7/netdevice.7.html)) #[cfg(any(linux_android, target_os = "fuchsia"))] IFF_DYNAMIC; /// Do not advertise. #[cfg(solarish)] - IFF_PRIVATE; + IFF_PRIVATE as IflagsType; /// Driver signals L1 up. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] IFF_LOWER_UP; @@ -134,7 +142,7 @@ libc_bitflags!( IFF_CANTCONFIG; /// Do not transmit packets. #[cfg(solarish)] - IFF_NOXMIT; + IFF_NOXMIT as IflagsType; /// Driver signals dormant. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] IFF_DORMANT; @@ -143,7 +151,7 @@ libc_bitflags!( IFF_PPROMISC; /// Just on-link subnet. #[cfg(solarish)] - IFF_NOLOCAL; + IFF_NOLOCAL as IflagsType; /// Echo sent packets. Volatile. #[cfg(any(target_os = "fuchsia", target_os = "linux"))] IFF_ECHO; @@ -152,19 +160,19 @@ libc_bitflags!( IFF_MONITOR; /// Address is deprecated. #[cfg(solarish)] - IFF_DEPRECATED; + IFF_DEPRECATED as IflagsType; /// Static ARP. #[cfg(freebsdlike)] IFF_STATICARP; /// Address from stateless addrconf. #[cfg(solarish)] - IFF_ADDRCONF; + IFF_ADDRCONF as IflagsType; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] IFF_NPOLLING; /// Router on interface. #[cfg(solarish)] - IFF_ROUTER; + IFF_ROUTER as IflagsType; /// Interface is in polling mode. #[cfg(any(target_os = "dragonfly"))] IFF_IDIRECT; @@ -173,66 +181,67 @@ libc_bitflags!( IFF_DYING; /// No NUD on interface. #[cfg(solarish)] - IFF_NONUD; + IFF_NONUD as IflagsType; /// Interface is being renamed #[cfg(any(target_os = "freebsd"))] IFF_RENAMING; /// Anycast address. #[cfg(solarish)] - IFF_ANYCAST; + IFF_ANYCAST as IflagsType; /// Don't exchange routing info. #[cfg(solarish)] - IFF_NORTEXCH; + IFF_NORTEXCH as IflagsType; /// Do not provide packet information #[cfg(any(linux_android, target_os = "fuchsia"))] - IFF_NO_PI as libc::c_int; + IFF_NO_PI as IflagsType; /// TUN device (no Ethernet headers) #[cfg(any(linux_android, target_os = "fuchsia"))] - IFF_TUN as libc::c_int; + IFF_TUN as IflagsType; /// TAP device #[cfg(any(linux_android, target_os = "fuchsia"))] - IFF_TAP as libc::c_int; + IFF_TAP as IflagsType; /// IPv4 interface. #[cfg(solarish)] - IFF_IPV4; + IFF_IPV4 as IflagsType; /// IPv6 interface. #[cfg(solarish)] - IFF_IPV6; + IFF_IPV6 as IflagsType; /// in.mpathd test address #[cfg(solarish)] - IFF_NOFAILOVER; + IFF_NOFAILOVER as IflagsType; /// Interface has failed #[cfg(solarish)] - IFF_FAILED; + IFF_FAILED as IflagsType; /// Interface is a hot-spare #[cfg(solarish)] - IFF_STANDBY; + IFF_STANDBY as IflagsType; /// Functioning but not used #[cfg(solarish)] - IFF_INACTIVE; + IFF_INACTIVE as IflagsType; /// Interface is offline #[cfg(solarish)] - IFF_OFFLINE; - #[cfg(target_os = "solaris")] - IFF_COS_ENABLED; - /// Prefer as source addr. - #[cfg(target_os = "solaris")] - IFF_PREFERRED; + IFF_OFFLINE as IflagsType; + /// Has CoS marking supported + #[cfg(solarish)] + IFF_COS_ENABLED as IflagsType; + /// Prefer as source addr + #[cfg(solarish)] + IFF_PREFERRED as IflagsType; /// RFC3041 - #[cfg(target_os = "solaris")] - IFF_TEMPORARY; - /// MTU set with SIOCSLIFMTU - #[cfg(target_os = "solaris")] - IFF_FIXEDMTU; - /// Cannot send / receive packets - #[cfg(target_os = "solaris")] - IFF_VIRTUAL; + #[cfg(solarish)] + IFF_TEMPORARY as IflagsType; + /// MTU set + #[cfg(solarish)] + IFF_FIXEDMTU as IflagsType; + /// Cannot send/receive packets + #[cfg(solarish)] + IFF_VIRTUAL as IflagsType; /// Local address in use - #[cfg(target_os = "solaris")] - IFF_DUPLICATE; + #[cfg(solarish)] + IFF_DUPLICATE as IflagsType; /// IPMP IP interface - #[cfg(target_os = "solaris")] - IFF_IPMP; + #[cfg(solarish)] + IFF_IPMP as IflagsType; } ); @@ -247,7 +256,7 @@ impl fmt::Display for InterfaceFlags { bsd, target_os = "fuchsia", target_os = "linux", - target_os = "illumos", + solarish, ))] mod if_nameindex { use super::*; @@ -374,6 +383,6 @@ mod if_nameindex { bsd, target_os = "fuchsia", target_os = "linux", - target_os = "illumos", + solarish, ))] pub use if_nameindex::*; diff --git a/src/sys/ioctl/bsd.rs b/src/sys/ioctl/bsd.rs index 307994cb96..cedc8e63fe 100644 --- a/src/sys/ioctl/bsd.rs +++ b/src/sys/ioctl/bsd.rs @@ -1,10 +1,10 @@ /// The datatype used for the ioctl number #[doc(hidden)] -#[cfg(not(target_os = "illumos"))] +#[cfg(not(solarish))] pub type ioctl_num_type = ::libc::c_ulong; #[doc(hidden)] -#[cfg(target_os = "illumos")] +#[cfg(solarish)] pub type ioctl_num_type = ::libc::c_int; /// The datatype used for the 3rd argument diff --git a/src/sys/ioctl/mod.rs b/src/sys/ioctl/mod.rs index df222ec86c..e1e808f19e 100644 --- a/src/sys/ioctl/mod.rs +++ b/src/sys/ioctl/mod.rs @@ -234,11 +234,11 @@ mod linux; #[cfg(any(linux_android, target_os = "redox"))] pub use self::linux::*; -#[cfg(any(bsd, target_os = "illumos", target_os = "haiku",))] +#[cfg(any(bsd, solarish, target_os = "haiku",))] #[macro_use] mod bsd; -#[cfg(any(bsd, target_os = "illumos", target_os = "haiku",))] +#[cfg(any(bsd, solarish, target_os = "haiku",))] pub use self::bsd::*; /// Convert raw ioctl return value to a Nix result diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 94302484fb..60700ad8a2 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -31,7 +31,7 @@ feature! { pub mod fanotify; } -#[cfg(any(bsd, linux_android, target_os = "redox", target_os = "illumos"))] +#[cfg(any(bsd, linux_android, target_os = "redox", solarish))] #[cfg(feature = "ioctl")] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] #[macro_use] @@ -88,7 +88,7 @@ feature! { #[cfg(not(any( target_os = "redox", target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "haiku" )))] feature! { @@ -182,7 +182,7 @@ feature! { #[cfg(all( any( target_os = "freebsd", - target_os = "illumos", + solarish, target_os = "linux", target_os = "netbsd" ), diff --git a/src/sys/socket/addr.rs b/src/sys/socket/addr.rs index b8413b6c44..f6800aa5d0 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -1,7 +1,7 @@ #[cfg(any( bsd, linux_android, - target_os = "illumos", + solarish, target_os = "haiku", target_os = "fuchsia", target_os = "aix", @@ -232,7 +232,7 @@ pub enum AddressFamily { #[cfg(bsd)] Hylink = libc::AF_HYLINK, /// Link layer interface - #[cfg(any(bsd, target_os = "illumos"))] + #[cfg(any(bsd, solarish))] Link = libc::AF_LINK, /// connection-oriented IP, aka ST II #[cfg(bsd)] @@ -267,7 +267,7 @@ impl AddressFamily { libc::PF_ROUTE => Some(AddressFamily::Route), #[cfg(linux_android)] libc::AF_PACKET => Some(AddressFamily::Packet), - #[cfg(any(bsd, target_os = "illumos"))] + #[cfg(any(bsd, solarish))] libc::AF_LINK => Some(AddressFamily::Link), #[cfg(any(linux_android, apple_targets))] libc::AF_VSOCK => Some(AddressFamily::Vsock), @@ -508,7 +508,7 @@ impl UnixAddr { cfg_if! { if #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "redox", ))] { @@ -554,7 +554,7 @@ impl SockaddrLike for UnixAddr { cfg_if! { if #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "redox", ))] { let su_len = len.unwrap_or( @@ -584,7 +584,7 @@ impl SockaddrLike for UnixAddr { cfg_if! { if #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "redox", ))] { self.sun_len = new_length as u8; @@ -1126,7 +1126,7 @@ impl SockaddrLike for SockaddrStorage { #[cfg(any( linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, ))] if i32::from(ss.ss_family) == libc::AF_UNIX { // Safe because we UnixAddr is strictly smaller than @@ -1156,7 +1156,7 @@ impl SockaddrLike for SockaddrStorage { libc::AF_INET6 => unsafe { SockaddrIn6::from_raw(addr, l).map(|sin6| Self { sin6 }) }, - #[cfg(any(bsd, target_os = "illumos", target_os = "haiku"))] + #[cfg(any(bsd, solarish, target_os = "haiku"))] #[cfg(feature = "net")] libc::AF_LINK => unsafe { LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) @@ -1183,7 +1183,7 @@ impl SockaddrLike for SockaddrStorage { } } - #[cfg(any(linux_android, target_os = "fuchsia", target_os = "illumos"))] + #[cfg(any(linux_android, target_os = "fuchsia", solarish))] fn len(&self) -> libc::socklen_t { match self.as_unix_addr() { // The UnixAddr type knows its own length @@ -1244,7 +1244,7 @@ impl SockaddrStorage { cfg_if! { if #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, ))] { let p = unsafe{ &self.ss as *const libc::sockaddr_storage }; @@ -1273,7 +1273,7 @@ impl SockaddrStorage { cfg_if! { if #[cfg(any(linux_android, target_os = "fuchsia", - target_os = "illumos", + solarish, ))] { let p = unsafe{ &self.ss as *const libc::sockaddr_storage }; @@ -1307,7 +1307,7 @@ impl SockaddrStorage { as_link_addr, as_link_addr_mut, LinkAddr, AddressFamily::Packet, libc::sockaddr_ll, dl} - #[cfg(any(bsd, target_os = "illumos"))] + #[cfg(any(bsd, solarish))] #[cfg(feature = "net")] accessors! { as_link_addr, as_link_addr_mut, LinkAddr, @@ -1357,7 +1357,7 @@ impl fmt::Display for SockaddrStorage { libc::AF_INET => self.sin.fmt(f), #[cfg(feature = "net")] libc::AF_INET6 => self.sin6.fmt(f), - #[cfg(any(bsd, target_os = "illumos"))] + #[cfg(any(bsd, solarish))] #[cfg(feature = "net")] libc::AF_LINK => self.dl.fmt(f), #[cfg(linux_android)] @@ -1419,7 +1419,7 @@ impl Hash for SockaddrStorage { libc::AF_INET => self.sin.hash(s), #[cfg(feature = "net")] libc::AF_INET6 => self.sin6.hash(s), - #[cfg(any(bsd, target_os = "illumos"))] + #[cfg(any(bsd, solarish))] #[cfg(feature = "net")] libc::AF_LINK => self.dl.hash(s), #[cfg(linux_android)] @@ -1449,7 +1449,7 @@ impl PartialEq for SockaddrStorage { (libc::AF_INET, libc::AF_INET) => self.sin == other.sin, #[cfg(feature = "net")] (libc::AF_INET6, libc::AF_INET6) => self.sin6 == other.sin6, - #[cfg(any(bsd, target_os = "illumos"))] + #[cfg(any(bsd, solarish))] #[cfg(feature = "net")] (libc::AF_LINK, libc::AF_LINK) => self.dl == other.dl, #[cfg(linux_android)] @@ -1879,7 +1879,7 @@ mod datalink { } } -#[cfg(any(bsd, target_os = "illumos", target_os = "haiku", target_os = "aix"))] +#[cfg(any(bsd, solarish, target_os = "haiku", target_os = "aix"))] mod datalink { feature! { #![feature = "net"] @@ -2153,7 +2153,7 @@ mod tests { mod link { #![allow(clippy::cast_ptr_alignment)] - #[cfg(any(apple_targets, target_os = "illumos"))] + #[cfg(any(apple_targets, solarish))] use super::super::super::socklen_t; use super::*; @@ -2240,9 +2240,9 @@ mod tests { } } - #[cfg(target_os = "illumos")] + #[cfg(solarish)] #[test] - fn illumos_tap() { + fn solarish_tap() { let bytes = [25u8, 0, 0, 0, 6, 0, 6, 0, 24, 101, 144, 221, 76, 176]; let ptr = bytes.as_ptr(); let sa = ptr as *const libc::sockaddr; diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 87b56f9169..8556c7d46d 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -256,13 +256,13 @@ libc_bitflags! { #[cfg(any(linux_android, freebsdlike, netbsdlike, - target_os = "illumos"))] + solarish))] SOCK_NONBLOCK; /// Set close-on-exec on the new descriptor #[cfg(any(linux_android, freebsdlike, netbsdlike, - target_os = "illumos"))] + solarish))] SOCK_CLOEXEC; /// Return `EPIPE` instead of raising `SIGPIPE` #[cfg(target_os = "netbsd")] @@ -343,8 +343,7 @@ libc_bitflags! { #[cfg(any(linux_android, netbsdlike, target_os = "fuchsia", - target_os = "freebsd", - target_os = "solaris"))] + target_os = "freebsd"))] MSG_WAITFORONE; } } @@ -2156,7 +2155,7 @@ pub fn accept(sockfd: RawFd) -> Result { netbsdlike, target_os = "emscripten", target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "linux", ))] pub fn accept4(sockfd: RawFd, flags: SockFlag) -> Result { diff --git a/src/sys/time.rs b/src/sys/time.rs index d5e9f3a6b2..ac13de419c 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -18,7 +18,7 @@ const fn zero_init_timespec() -> timespec { all( any( target_os = "freebsd", - target_os = "illumos", + solarish, target_os = "linux", target_os = "netbsd" ), @@ -97,7 +97,7 @@ pub(crate) mod timer { const TFD_TIMER_CANCEL_ON_SET = libc::TFD_TIMER_CANCEL_ON_SET; } } - #[cfg(any(freebsdlike, target_os = "netbsd", target_os = "illumos"))] + #[cfg(any(freebsdlike, target_os = "netbsd", solarish))] bitflags! { /// Flags that are used for arming the timer. #[derive(Copy, Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] diff --git a/src/sys/uio.rs b/src/sys/uio.rs index 29e3647b35..cdf380dd11 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -53,7 +53,7 @@ pub fn readv(fd: Fd, iov: &mut [IoSliceMut<'_>]) -> Result { /// or an error occurs. The file offset is not changed. /// /// See also: [`writev`](fn.writev.html) and [`pwrite`](fn.pwrite.html) -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +#[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "solaris")))] pub fn pwritev( fd: Fd, iov: &[IoSlice<'_>], @@ -82,7 +82,7 @@ pub fn pwritev( /// changed. /// /// See also: [`readv`](fn.readv.html) and [`pread`](fn.pread.html) -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +#[cfg(not(any(target_os = "redox", target_os = "haiku", target_os = "solaris")))] // Clippy doesn't know that we need to pass iov mutably only because the // mutation happens after converting iov to a pointer #[allow(clippy::needless_pass_by_ref_mut)] diff --git a/src/unistd.rs b/src/unistd.rs index 32fa025bbc..466b769a22 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1653,7 +1653,7 @@ pub fn setgroups(groups: &[Gid]) -> Result<()> { /// will only ever return the complete list or else an error. #[cfg(not(any( target_os = "aix", - target_os = "illumos", + solarish, apple_targets, target_os = "redox" )))] @@ -3215,9 +3215,9 @@ impl From for libc::passwd { target_os = "hurd", )))] pw_expire: u.expire, - #[cfg(target_os = "illumos")] + #[cfg(solarish)] pw_age: CString::new("").unwrap().into_raw(), - #[cfg(target_os = "illumos")] + #[cfg(solarish)] pw_comment: CString::new("").unwrap().into_raw(), #[cfg(freebsdlike)] pw_fields: 0, diff --git a/test/sys/test_uio.rs b/test/sys/test_uio.rs index fe0a3bde07..d035a7bb04 100644 --- a/test/sys/test_uio.rs +++ b/test/sys/test_uio.rs @@ -140,7 +140,11 @@ fn test_pread() { } #[test] -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "haiku", + target_os = "solaris" +)))] fn test_pwritev() { use std::io::Read; @@ -175,7 +179,11 @@ fn test_pwritev() { } #[test] -#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +#[cfg(not(any( + target_os = "redox", + target_os = "haiku", + target_os = "solaris" +)))] fn test_preadv() { use std::io::Write; diff --git a/test/test.rs b/test/test.rs index eed532c194..388a0a42e8 100644 --- a/test/test.rs +++ b/test/test.rs @@ -52,7 +52,7 @@ mod test_time; #[cfg(all( any( target_os = "freebsd", - target_os = "illumos", + solarish, target_os = "linux", target_os = "netbsd" ), diff --git a/test/test_dir.rs b/test/test_dir.rs index 2af4aa5c0a..24ecd6963e 100644 --- a/test/test_dir.rs +++ b/test/test_dir.rs @@ -6,10 +6,10 @@ use tempfile::tempdir; #[cfg(test)] fn flags() -> OFlag { - #[cfg(target_os = "illumos")] + #[cfg(solarish)] let f = OFlag::O_RDONLY | OFlag::O_CLOEXEC; - #[cfg(not(target_os = "illumos"))] + #[cfg(not(solarish))] let f = OFlag::O_RDONLY | OFlag::O_CLOEXEC | OFlag::O_DIRECTORY; f diff --git a/test/test_pty.rs b/test/test_pty.rs index ae4127e481..368ec129b0 100644 --- a/test/test_pty.rs +++ b/test/test_pty.rs @@ -96,7 +96,7 @@ fn open_ptty_pair() -> (PtyMaster, File) { open(Path::new(&slave_name), OFlag::O_RDWR, stat::Mode::empty()) .unwrap(); - #[cfg(target_os = "illumos")] + #[cfg(solarish)] // TODO: rewrite using ioctl! #[allow(clippy::comparison_chain)] { diff --git a/test/test_resource.rs b/test/test_resource.rs index 2ab581ba29..beae01c4c8 100644 --- a/test/test_resource.rs +++ b/test/test_resource.rs @@ -1,7 +1,7 @@ #[cfg(not(any( target_os = "redox", target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "haiku" )))] use nix::sys::resource::{getrlimit, setrlimit, Resource}; @@ -18,7 +18,7 @@ use nix::sys::resource::{getrlimit, setrlimit, Resource}; #[cfg(not(any( target_os = "redox", target_os = "fuchsia", - target_os = "illumos", + solarish, target_os = "haiku" )))] pub fn test_resource_limits_nofile() { diff --git a/test/test_stat.rs b/test/test_stat.rs index 6bae35e188..58238249d9 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -383,7 +383,7 @@ fn test_mknod() { #[cfg(not(any( target_os = "dragonfly", target_os = "freebsd", - target_os = "illumos", + solarish, apple_targets, target_os = "haiku", target_os = "redox" diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 1e4b013630..f13bcf7061 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -294,7 +294,7 @@ fn test_setgroups() { target_os = "redox", target_os = "fuchsia", target_os = "haiku", - target_os = "illumos" + solarish )))] fn test_initgroups() { // Skip this test when not run as root as `initgroups()` and `setgroups()` @@ -438,7 +438,7 @@ cfg_if! { // https://github.com/nix-rust/nix/issues/555 execve_test_factory!(test_execve, execve, CString::new("/bin/sh").unwrap().as_c_str()); execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd()); - } else if #[cfg(any(target_os = "illumos", + } else if #[cfg(any(solarish, apple_targets, target_os = "netbsd", target_os = "openbsd", @@ -765,7 +765,7 @@ fn test_pipe() { target_os = "dragonfly", target_os = "emscripten", target_os = "freebsd", - target_os = "illumos", + solarish, target_os = "linux", target_os = "netbsd", target_os = "openbsd", From 6961f0fabddb5d1e882d8127c774262954d3ec08 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 10 Dec 2023 00:15:41 +0800 Subject: [PATCH 091/140] refactor: cfg for test/* (#2230) * refactor: cfg for test/* * one more netbsdlike * more cfg --- test/common/mod.rs | 4 +-- test/sys/mod.rs | 11 ++------ test/sys/test_socket.rs | 59 ++++++++-------------------------------- test/sys/test_sockopt.rs | 17 ++++-------- test/test.rs | 15 ++-------- test/test_fcntl.rs | 12 +++----- test/test_net.rs | 6 +--- test/test_poll.rs | 7 +---- test/test_sendfile.rs | 9 ++---- test/test_stat.rs | 6 ++-- test/test_time.rs | 24 ++-------------- test/test_unistd.rs | 53 ++++++++---------------------------- 12 files changed, 48 insertions(+), 175 deletions(-) diff --git a/test/common/mod.rs b/test/common/mod.rs index 7a9cc23e56..9268a79497 100644 --- a/test/common/mod.rs +++ b/test/common/mod.rs @@ -13,7 +13,7 @@ macro_rules! skip { } cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { #[macro_export] macro_rules! require_capability { ($name:expr, $capname:ident) => { use ::caps::{Capability, CapSet, has_cap}; @@ -87,7 +87,7 @@ macro_rules! skip_if_not_root { } cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { #[macro_export] macro_rules! skip_if_seccomp { ($name:expr) => { if let Ok(s) = std::fs::read_to_string("/proc/self/status") { diff --git a/test/sys/mod.rs b/test/sys/mod.rs index 8812cdd6cd..3a6707ba1d 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -48,15 +48,8 @@ mod test_fanotify; #[cfg(target_os = "linux")] mod test_inotify; mod test_pthread; -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - apple_targets, - target_os = "netbsd", - target_os = "openbsd" -))] + +#[cfg(any(linux_android, freebsdlike, netbsdlike, apple_targets))] mod test_ptrace; #[cfg(linux_android)] mod test_timerfd; diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index ffa54a98c2..736fae1937 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -556,12 +556,7 @@ mod recvfrom { } } - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", - ))] + #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] #[test] pub fn udp_sendmmsg() { use std::io::IoSlice; @@ -623,12 +618,7 @@ mod recvfrom { assert_eq!(AddressFamily::Inet, from.unwrap().family().unwrap()); } - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", - ))] + #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] #[test] pub fn udp_recvmmsg() { use nix::sys::socket::{recvmmsg, MsgFlags}; @@ -704,12 +694,7 @@ mod recvfrom { send_thread.join().unwrap(); } - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "freebsd", - target_os = "netbsd", - ))] + #[cfg(any(linux_android, target_os = "freebsd", target_os = "netbsd"))] #[test] pub fn udp_recvmmsg_dontwait_short_read() { use nix::sys::socket::{recvmmsg, MsgFlags}; @@ -1275,12 +1260,7 @@ pub fn test_sendmsg_ipv6packetinfo() { // // Note that binding to 0.0.0.0 is *required* on FreeBSD; sendmsg // returns EINVAL otherwise. (See FreeBSD's ip(4) man page.) -#[cfg(any( - target_os = "netbsd", - target_os = "freebsd", - target_os = "openbsd", - target_os = "dragonfly", -))] +#[cfg(any(freebsdlike, netbsdlike))] #[test] pub fn test_sendmsg_ipv4sendsrcaddr() { use nix::sys::socket::{ @@ -1429,12 +1409,7 @@ pub fn test_sendmsg_empty_cmsgs() { } } -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "freebsd", - target_os = "dragonfly", -))] +#[cfg(any(linux_android, freebsdlike))] #[test] fn test_scm_credentials() { use nix::sys::socket::{ @@ -1777,12 +1752,7 @@ fn loopback_address( }) } -#[cfg(any( - target_os = "android", - apple_targets, - target_os = "linux", - target_os = "netbsd", -))] +#[cfg(any(linux_android, apple_targets, target_os = "netbsd"))] // qemu doesn't seem to be emulating this correctly in these architectures #[cfg_attr( all( @@ -1987,7 +1957,7 @@ pub fn test_recvif() { } } -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] #[cfg_attr(qemu, ignore)] #[test] pub fn test_recvif_ipv4() { @@ -2073,7 +2043,7 @@ pub fn test_recvif_ipv4() { } } -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] #[cfg_attr(qemu, ignore)] #[test] pub fn test_recvif_ipv6() { @@ -2159,14 +2129,7 @@ pub fn test_recvif_ipv6() { } } -#[cfg(any( - target_os = "android", - target_os = "freebsd", - apple_targets, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", -))] +#[cfg(any(linux_android, target_os = "freebsd", apple_targets, netbsdlike))] // qemu doesn't seem to be emulating this correctly in these architectures #[cfg_attr( all( @@ -2463,7 +2426,7 @@ fn test_recvmmsg_timestampns() { // Disable the test on emulated platforms because it fails in Cirrus-CI. Lack // of QEMU support is suspected. #[cfg_attr(qemu, ignore)] -#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "fuchsia"))] #[test] fn test_recvmsg_rxq_ovfl() { use nix::sys::socket::sockopt::{RcvBuf, RxqOvfl}; @@ -2557,7 +2520,7 @@ fn test_recvmsg_rxq_ovfl() { assert_eq!(drop_counter, 1); } -#[cfg(any(target_os = "linux", target_os = "android",))] +#[cfg(linux_android)] mod linux_errqueue { use super::FromStr; use nix::sys::socket::*; diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index ec25a7e93b..4950213983 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -127,7 +127,7 @@ fn test_so_tcp_maxseg() { // platforms keep it even lower. This might fail if you've tuned your initial MSS to be larger // than 700 cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { let segsize: u32 = 873; assert!(initial < segsize); setsockopt(&rsock, sockopt::TcpMaxSeg, &segsize).unwrap(); @@ -152,7 +152,7 @@ fn test_so_tcp_maxseg() { // Actual max segment size takes header lengths into account, max IPv4 options (60 bytes) + max // TCP options (40 bytes) are subtracted from the requested maximum as a lower boundary. cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { assert!((segsize - 100) <= actual); assert!(actual <= segsize); } else { @@ -177,7 +177,7 @@ fn test_so_type() { /// getsockopt(_, sockopt::SockType) should gracefully handle unknown socket /// types. Regression test for https://github.com/nix-rust/nix/issues/1819 -#[cfg(any(target_os = "android", target_os = "linux",))] +#[cfg(linux_android)] #[test] fn test_so_type_unknown() { use nix::errno::Errno; @@ -254,12 +254,7 @@ fn test_so_tcp_keepalive() { setsockopt(&fd, sockopt::KeepAlive, &true).unwrap(); assert!(getsockopt(&fd, sockopt::KeepAlive).unwrap()); - #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux" - ))] + #[cfg(any(linux_android, freebsdlike))] { let x = getsockopt(&fd, sockopt::TcpKeepIdle).unwrap(); setsockopt(&fd, sockopt::TcpKeepIdle, &(x + 1)).unwrap(); @@ -303,7 +298,7 @@ fn test_get_mtu() { } #[test] -#[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] +#[cfg(any(linux_android, target_os = "freebsd"))] fn test_ttl_opts() { let fd4 = socket( AddressFamily::Inet, @@ -369,7 +364,7 @@ fn test_dontfrag_opts() { } #[test] -#[cfg(any(target_os = "android", apple_targets, target_os = "linux",))] +#[cfg(any(linux_android, apple_targets))] // Disable the test under emulation because it fails in Cirrus-CI. Lack // of QEMU support is suspected. #[cfg_attr(qemu, ignore)] diff --git a/test/test.rs b/test/test.rs index 388a0a42e8..fc6b4b3e32 100644 --- a/test/test.rs +++ b/test/test.rs @@ -11,8 +11,7 @@ mod test_fcntl; #[cfg(linux_android)] mod test_kmod; #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, target_os = "fushsia", target_os = "linux", target_os = "netbsd" @@ -32,20 +31,12 @@ mod test_poll; mod test_pty; mod test_resource; #[cfg(any( - target_os = "android", + linux_android, target_os = "dragonfly", all(target_os = "freebsd", fbsd14), - target_os = "linux" ))] mod test_sched; -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - target_os = "linux", - solarish -))] +#[cfg(any(linux_android, freebsdlike, apple_targets, solarish))] mod test_sendfile; mod test_stat; mod test_time; diff --git a/test/test_fcntl.rs b/test/test_fcntl.rs index df323c4394..6572e8af8d 100644 --- a/test/test_fcntl.rs +++ b/test/test_fcntl.rs @@ -234,10 +234,9 @@ fn test_readlink() { /// The from_offset should be updated by the call to reflect /// the 3 bytes read (6). #[cfg(any( - target_os = "linux", + linux_android, // Not available until FreeBSD 13.0 all(target_os = "freebsd", fbsd14), - target_os = "android" ))] #[test] // QEMU does not support copy_file_range. Skip under qemu @@ -473,8 +472,7 @@ mod linux_android { } #[cfg(any( - target_os = "linux", - target_os = "android", + linux_android, target_os = "emscripten", target_os = "fuchsia", target_os = "wasi", @@ -511,13 +509,11 @@ mod test_posix_fadvise { } #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "dragonfly", + linux_android, + freebsdlike, target_os = "emscripten", target_os = "fuchsia", target_os = "wasi", - target_os = "freebsd" ))] mod test_posix_fallocate { diff --git a/test/test_net.rs b/test/test_net.rs index 00708ace38..faba8503fe 100644 --- a/test/test_net.rs +++ b/test/test_net.rs @@ -3,11 +3,7 @@ use nix::net::if_::*; #[cfg(linux_android)] const LOOPBACK: &[u8] = b"lo"; -#[cfg(not(any( - target_os = "android", - target_os = "linux", - target_os = "haiku" -)))] +#[cfg(not(any(linux_android, target_os = "haiku")))] const LOOPBACK: &[u8] = b"lo0"; #[cfg(target_os = "haiku")] diff --git a/test/test_poll.rs b/test/test_poll.rs index 4227f59994..fcb325494e 100644 --- a/test/test_poll.rs +++ b/test/test_poll.rs @@ -38,12 +38,7 @@ fn test_poll() { // ppoll(2) is the same as poll except for how it handles timeouts and signals. // Repeating the test for poll(2) should be sufficient to check that our // bindings are correct. -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux" -))] +#[cfg(any(linux_android, freebsdlike))] #[test] fn test_ppoll() { use nix::poll::ppoll; diff --git a/test/test_sendfile.rs b/test/test_sendfile.rs index df3445b5c5..6333bf8662 100644 --- a/test/test_sendfile.rs +++ b/test/test_sendfile.rs @@ -5,15 +5,10 @@ use nix::sys::sendfile::*; use tempfile::tempfile; cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { use nix::unistd::{pipe, read}; use std::os::unix::io::AsRawFd; - } else if #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - apple_targets, - solarish - ))] { + } else if #[cfg(any(freebsdlike, apple_targets, solarish))] { use std::net::Shutdown; use std::os::unix::net::UnixStream; } diff --git a/test/test_stat.rs b/test/test_stat.rs index 58238249d9..0dd6fe89c5 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -361,8 +361,7 @@ fn test_mkdirat_fail() { #[test] #[cfg(not(any( - target_os = "dragonfly", - target_os = "freebsd", + freebsdlike, apple_targets, target_os = "haiku", target_os = "redox" @@ -381,9 +380,8 @@ fn test_mknod() { #[test] #[cfg(not(any( - target_os = "dragonfly", - target_os = "freebsd", solarish, + freebsdlike, apple_targets, target_os = "haiku", target_os = "redox" diff --git a/test/test_time.rs b/test/test_time.rs index 5f76e61a2d..6d7dfbedc0 100644 --- a/test/test_time.rs +++ b/test/test_time.rs @@ -1,10 +1,4 @@ -#[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux", - target_os = "android", - target_os = "emscripten", -))] +#[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] use nix::time::clock_getcpuclockid; use nix::time::{clock_gettime, ClockId}; @@ -19,13 +13,7 @@ pub fn test_clock_gettime() { clock_gettime(ClockId::CLOCK_REALTIME).expect("assertion failed"); } -#[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux", - target_os = "android", - target_os = "emscripten", -))] +#[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] #[test] pub fn test_clock_getcpuclockid() { let clock_id = clock_getcpuclockid(nix::unistd::Pid::this()).unwrap(); @@ -43,13 +31,7 @@ pub fn test_clock_id_now() { ClockId::CLOCK_REALTIME.now().unwrap(); } -#[cfg(any( - target_os = "freebsd", - target_os = "dragonfly", - target_os = "linux", - target_os = "android", - target_os = "emscripten", -))] +#[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] #[test] pub fn test_clock_id_pid_cpu_clock_id() { ClockId::pid_cpu_clock_id(nix::unistd::Pid::this()) diff --git a/test/test_unistd.rs b/test/test_unistd.rs index f13bcf7061..354f816362 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -430,19 +430,12 @@ cfg_if! { if #[cfg(target_os = "android")] { execve_test_factory!(test_execve, execve, CString::new("/system/bin/sh").unwrap().as_c_str()); execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd()); - } else if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "hurd", - target_os = "linux"))] { + } else if #[cfg(any(freebsdlike, target_os = "linux", target_os = "hurd"))] { // These tests frequently fail on musl, probably due to // https://github.com/nix-rust/nix/issues/555 execve_test_factory!(test_execve, execve, CString::new("/bin/sh").unwrap().as_c_str()); execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd()); - } else if #[cfg(any(solarish, - apple_targets, - target_os = "netbsd", - target_os = "openbsd", - target_os = "solaris"))] { + } else if #[cfg(any(solarish, apple_targets, netbsdlike))] { execve_test_factory!(test_execve, execve, CString::new("/bin/sh").unwrap().as_c_str()); // No fexecve() on ios, macos, NetBSD, OpenBSD. } @@ -610,7 +603,7 @@ fn test_lseek64() { } cfg_if! { - if #[cfg(any(target_os = "android", target_os = "linux"))] { + if #[cfg(linux_android)] { macro_rules! require_acct{ () => { require_capability!("test_acct", CAP_SYS_PACCT); @@ -712,13 +705,7 @@ fn test_sysconf_unsupported() { assert!(open_max.expect("sysconf failed").is_none()) } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))] #[test] fn test_getresuid() { let resuids = getresuid().unwrap(); @@ -727,13 +714,7 @@ fn test_getresuid() { assert_ne!(resuids.saved.as_raw(), libc::uid_t::MAX); } -#[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "openbsd" -))] +#[cfg(any(linux_android, freebsdlike, target_os = "openbsd"))] #[test] fn test_getresgid() { let resgids = getresgid().unwrap(); @@ -761,16 +742,12 @@ fn test_pipe() { // pipe2(2) is the same as pipe(2), except it allows setting some flags. Check // that we can set a flag. #[cfg(any( - target_os = "android", - target_os = "dragonfly", - target_os = "emscripten", - target_os = "freebsd", + linux_android, + freebsdlike, solarish, - target_os = "linux", - target_os = "netbsd", - target_os = "openbsd", + netbsdlike, + target_os = "emscripten", target_os = "redox", - target_os = "solaris" ))] #[test] fn test_pipe2() { @@ -1367,11 +1344,7 @@ fn test_faccessat_file_exists() { } #[test] -#[cfg(any( - all(target_os = "linux", not(target_env = "uclibc")), - target_os = "freebsd", - target_os = "dragonfly" -))] +#[cfg(any(all(target_os = "linux", not(target_env = "uclibc")), freebsdlike))] fn test_eaccess_not_existing() { let tempdir = tempdir().unwrap(); let dir = tempdir.path().join("does_not_exist.txt"); @@ -1382,11 +1355,7 @@ fn test_eaccess_not_existing() { } #[test] -#[cfg(any( - all(target_os = "linux", not(target_env = "uclibc")), - target_os = "freebsd", - target_os = "dragonfly" -))] +#[cfg(any(all(target_os = "linux", not(target_env = "uclibc")), freebsdlike))] fn test_eaccess_file_exists() { let tempdir = tempdir().unwrap(); let path = tempdir.path().join("does_exist.txt"); From a09971fd10bc952a81f651b1489d669b70df56ce Mon Sep 17 00:00:00 2001 From: sgasse <47532708+sgasse@users.noreply.github.com> Date: Sat, 9 Dec 2023 17:18:22 +0100 Subject: [PATCH 092/140] Fix setting sockopt::IpMulticastTtl (#2072) * Fix the value of optlen as passed to libc::setsockopt Ever since the sockopt macro was written in 979faf097691dc35bb12b91dcde0d804a3d32b79 we've been passing the wrong size for u8 and usize sockopts. * Add tests for sockopt::IpMulticastTtl #2073 On Linux and Android, sockopt::IpMulticastTtl can be set for both IPv4 and IPv6 sockets, but not on FreeBSD. --------- Co-authored-by: Alan Somers Co-authored-by: Simon B. Gasse --- changelog/2072.fixed.md | 1 + src/sys/socket/sockopt.rs | 6 +++--- test/sys/test_sockopt.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) create mode 100644 changelog/2072.fixed.md diff --git a/changelog/2072.fixed.md b/changelog/2072.fixed.md new file mode 100644 index 0000000000..200a8f60b0 --- /dev/null +++ b/changelog/2072.fixed.md @@ -0,0 +1 @@ +Fixed `::sys::socket::sockopt::IpMulticastTtl` by fixing the value of optlen passed to `libc::setsockopt` and added tests. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 63db9b9e21..cbc7beca34 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -1247,7 +1247,7 @@ impl<'a> Set<'a, bool> for SetBool { } fn ffi_len(&self) -> socklen_t { - mem::size_of::() as socklen_t + mem::size_of_val(&self.val) as socklen_t } } @@ -1298,7 +1298,7 @@ impl<'a> Set<'a, u8> for SetU8 { } fn ffi_len(&self) -> socklen_t { - mem::size_of::() as socklen_t + mem::size_of_val(&self.val) as socklen_t } } @@ -1349,7 +1349,7 @@ impl<'a> Set<'a, usize> for SetUsize { } fn ffi_len(&self) -> socklen_t { - mem::size_of::() as socklen_t + mem::size_of_val(&self.val) as socklen_t } } diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 4950213983..d7e00e3b1b 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -320,6 +320,34 @@ fn test_ttl_opts() { .expect("setting ipv6ttl on an inet6 socket should succeed"); } +#[test] +#[cfg(any(linux_android, target_os = "freebsd"))] +fn test_multicast_ttl_opts_ipv4() { + let fd4 = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(&fd4, sockopt::IpMulticastTtl, &2) + .expect("setting ipmulticastttl on an inet socket should succeed"); +} + +#[test] +#[cfg(linux_android)] +fn test_multicast_ttl_opts_ipv6() { + let fd6 = socket( + AddressFamily::Inet6, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + setsockopt(&fd6, sockopt::IpMulticastTtl, &2) + .expect("setting ipmulticastttl on an inet6 socket should succeed"); +} + #[test] fn test_ipv6_multicast_hops() { let fd6 = socket( From d518abd5e8718213538da8a2b99a2ee0c962dd44 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 10 Dec 2023 00:20:11 +0800 Subject: [PATCH 093/140] feat: reboot(2) for OpenBSD/NetBSD (#2251) --- changelog/2251.added.md | 1 + src/sys/mod.rs | 2 +- src/sys/reboot.rs | 175 ++++++++++++++++++++++++++++++---------- 3 files changed, 136 insertions(+), 42 deletions(-) create mode 100644 changelog/2251.added.md diff --git a/changelog/2251.added.md b/changelog/2251.added.md new file mode 100644 index 0000000000..d925affa56 --- /dev/null +++ b/changelog/2251.added.md @@ -0,0 +1 @@ +Add `reboot(2)` for OpenBSD/NetBSD \ No newline at end of file diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 60700ad8a2..1d875ccd51 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -79,7 +79,7 @@ feature! { pub mod quota; } -#[cfg(target_os = "linux")] +#[cfg(any(target_os = "linux", netbsdlike))] feature! { #![feature = "reboot"] pub mod reboot; diff --git a/src/sys/reboot.rs b/src/sys/reboot.rs index 02d98162bd..2e4d888de4 100644 --- a/src/sys/reboot.rs +++ b/src/sys/reboot.rs @@ -1,48 +1,141 @@ -//! Reboot/shutdown or enable/disable Ctrl-Alt-Delete. +//! Reboot/shutdown +//! +//! On Linux, This can also be used to enable/disable Ctrl-Alt-Delete. use crate::errno::Errno; use crate::Result; +use cfg_if::cfg_if; use std::convert::Infallible; -use std::mem::drop; - -libc_enum! { - /// How exactly should the system be rebooted. - /// - /// See [`set_cad_enabled()`](fn.set_cad_enabled.html) for - /// enabling/disabling Ctrl-Alt-Delete. - #[repr(i32)] - #[non_exhaustive] - pub enum RebootMode { - /// Halt the system. - RB_HALT_SYSTEM, - /// Execute a kernel that has been loaded earlier with - /// [`kexec_load(2)`](https://man7.org/linux/man-pages/man2/kexec_load.2.html). - RB_KEXEC, - /// Stop the system and switch off power, if possible. - RB_POWER_OFF, - /// Restart the system. - RB_AUTOBOOT, - // we do not support Restart2. - /// Suspend the system using software suspend. - RB_SW_SUSPEND, - } -} -/// Reboots or shuts down the system. -pub fn reboot(how: RebootMode) -> Result { - unsafe { libc::reboot(how as libc::c_int) }; - Err(Errno::last()) -} +cfg_if! { + if #[cfg(target_os = "linux")] { + use std::mem::drop; + + libc_enum! { + /// How exactly should the system be rebooted. + /// + /// See [`set_cad_enabled()`](fn.set_cad_enabled.html) for + /// enabling/disabling Ctrl-Alt-Delete. + #[repr(i32)] + #[non_exhaustive] + pub enum RebootMode { + /// Halt the system. + RB_HALT_SYSTEM, + /// Execute a kernel that has been loaded earlier with + /// [`kexec_load(2)`](https://man7.org/linux/man-pages/man2/kexec_load.2.html). + RB_KEXEC, + /// Stop the system and switch off power, if possible. + RB_POWER_OFF, + /// Restart the system. + RB_AUTOBOOT, + // we do not support Restart2. + /// Suspend the system using software suspend. + RB_SW_SUSPEND, + } + } + + /// Reboots or shuts down the system. + pub fn reboot(how: RebootMode) -> Result { + unsafe { libc::reboot(how as libc::c_int) }; + Err(Errno::last()) + } -/// Enable or disable the reboot keystroke (Ctrl-Alt-Delete). -/// -/// Corresponds to calling `reboot(RB_ENABLE_CAD)` or `reboot(RB_DISABLE_CAD)` in C. -pub fn set_cad_enabled(enable: bool) -> Result<()> { - let cmd = if enable { - libc::RB_ENABLE_CAD - } else { - libc::RB_DISABLE_CAD - }; - let res = unsafe { libc::reboot(cmd) }; - Errno::result(res).map(drop) + /// Enable or disable the reboot keystroke (Ctrl-Alt-Delete). + /// + /// Corresponds to calling `reboot(RB_ENABLE_CAD)` or `reboot(RB_DISABLE_CAD)` in C. + pub fn set_cad_enabled(enable: bool) -> Result<()> { + let cmd = if enable { + libc::RB_ENABLE_CAD + } else { + libc::RB_DISABLE_CAD + }; + let res = unsafe { libc::reboot(cmd) }; + Errno::result(res).map(drop) + } + } else if #[cfg(netbsdlike)] { + use libc::c_int; + + libc_bitflags! { + /// How exactly should the system be rebooted. + pub struct RebootMode: c_int { + /// The default, causing the system to reboot in its usual fashion. + RB_AUTOBOOT; + /// Interpreted by the bootstrap program itself, causing it to + /// prompt on the console as to what file should be booted. + /// Normally, the system is booted from the file “xx(0,0)bsd”, + /// where xx is the default disk name, without prompting for + /// the file name. + RB_ASKNAME; + /// Dump kernel memory before rebooting; see `savecore(8)` for + /// more information. + RB_DUMP; + /// The processor is simply halted; no reboot takes place. + RB_HALT; + /// Power off the system if the system hardware supports the + /// function, otherwise it has no effect. + /// + /// Should be used in conjunction with `RB_HALT`. + RB_POWERDOWN; + /// By default, the system will halt if `reboot()` is called during + /// startup (before the system has finished autoconfiguration), even + /// if `RB_HALT` is not specified. This is because `panic(9)`s + /// during startup will probably just repeat on the next boot. + /// Use of this option implies that the user has requested the + /// action specified (for example, using the `ddb(4)` boot reboot + /// command), so the system will reboot if a halt is not explicitly + /// requested. + #[cfg(target_os = "openbsd")] + RB_USERREQ; + /// Load the symbol table and enable a built-in debugger in the + /// system. This option will have no useful function if the kernel + /// is not configured for debugging. Several other options have + /// different meaning if combined with this option, although their + /// use may not be possible via the `reboot()` call. See `ddb(4)` for + /// more information. + RB_KDB; + /// Normally, the disks are sync'd (see `sync(8)`) before the + /// processor is halted or rebooted. This option may be useful + /// if file system changes have been made manually or if the + /// processor is on fire. + RB_NOSYNC; + /// Normally, the reboot procedure involves an automatic disk + /// consistency check and then multi-user operations. `RB_SINGLE` + /// prevents this, booting the system with a single-user shell on + /// the console. `RB_SINGLE` is actually interpreted by the `init(8)` + /// program in the newly booted system. + /// + /// When no options are given (i.e., `RB_AUTOBOOT` is used), the + /// system is rebooted from file /bsd in the root file system of + /// unit 0 of a disk chosen in a processor specific way. An automatic + /// consistency check of the disks is normally performed (see `fsck(8)`). + RB_SINGLE; + /// Initially invoke the `userconf(4)` facility when the system + /// starts up again, if it has been compiled into the kernel + /// that is loaded. + #[cfg(target_os = "netbsd")] + RB_USERCONF; + /// Don't update the hardware clock from the system clock, presumably + /// because the system clock is suspect. + #[cfg(target_os = "openbsd")] + RB_TIMEBAD; + } + } + + /// Reboot system or halt processor + /// + /// For more information, see the man pages: + /// + /// * [NetBSD](https://man.netbsd.org/reboot.2) + /// * [OpenBSD](https://man.openbsd.org/reboot.2) + #[cfg(netbsdlike)] + pub fn reboot(how: RebootMode) -> Result { + #[cfg(target_os = "openbsd")] + unsafe { libc::reboot(how.bits()) }; + #[cfg(target_os = "netbsd")] + unsafe { libc::reboot(how.bits(), std::ptr::null_mut()) }; + + Err(Errno::last()) + } + } } + From 1c189d99bceb3662d83ffcb557ab71cd13892284 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 10 Dec 2023 08:27:36 +0800 Subject: [PATCH 094/140] feat: Add associated constants `UTIME_OMIT` `UTIME_NOW` to `TimeSpec` (#1879) * feat: support UTIME_NOW & UTIME_OMIT * fmt * fmt * linux x32 type cast * fmt --- changelog/1879.added.md | 1 + src/sys/stat.rs | 8 ++++- src/sys/time.rs | 11 +++++++ test/test_stat.rs | 72 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 changelog/1879.added.md diff --git a/changelog/1879.added.md b/changelog/1879.added.md new file mode 100644 index 0000000000..6f2b9a04d6 --- /dev/null +++ b/changelog/1879.added.md @@ -0,0 +1 @@ +Add associated constants `UTIME_OMIT` `UTIME_NOW` for `TimeSpec` diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 20b5294b31..369008a800 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -376,6 +376,9 @@ pub fn lutimes( /// Change the access and modification times of the file specified by a file descriptor. /// +/// If you want to set the timestamp to now, use `TimeSpec::UTIME_NOW`. Use +/// `TimeSpec::UTIME_OMIT` if you don't want to change it. +/// /// # References /// /// [futimens(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/futimens.html). @@ -408,6 +411,9 @@ pub enum UtimensatFlags { /// `utimes(path, times)`. The latter is a deprecated API so prefer using the /// former if the platforms you care about support it. /// +/// If you want to set the timestamp to now, use `TimeSpec::UTIME_NOW`. Use +/// `TimeSpec::UTIME_OMIT` if you don't want to change it. +/// /// # References /// /// [utimensat(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/utimens.html). @@ -448,4 +454,4 @@ pub fn mkdirat( })?; Errno::result(res).map(drop) -} +} \ No newline at end of file diff --git a/src/sys/time.rs b/src/sys/time.rs index ac13de419c..a63a03dc88 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -329,6 +329,17 @@ impl TimeValLike for TimeSpec { } impl TimeSpec { + /// Leave the timestamp unchanged. + #[cfg(not(target_os = "redox"))] + // At the time of writing this PR, redox does not support this feature + pub const UTIME_OMIT: TimeSpec = + TimeSpec::new(0, libc::UTIME_OMIT as timespec_tv_nsec_t); + /// Update the timestamp to `Now` + // At the time of writing this PR, redox does not support this feature + #[cfg(not(target_os = "redox"))] + pub const UTIME_NOW: TimeSpec = + TimeSpec::new(0, libc::UTIME_NOW as timespec_tv_nsec_t); + /// Construct a new `TimeSpec` from its components #[cfg_attr(target_env = "musl", allow(deprecated))] // https://github.com/rust-lang/libc/issues/1848 pub const fn new(seconds: time_t, nanoseconds: timespec_tv_nsec_t) -> Self { diff --git a/test/test_stat.rs b/test/test_stat.rs index 0dd6fe89c5..386f1084cc 100644 --- a/test/test_stat.rs +++ b/test/test_stat.rs @@ -413,3 +413,75 @@ fn test_mknodat() { assert_eq!(mode & libc::S_IFREG, libc::S_IFREG); assert_eq!(mode & libc::S_IRWXU, libc::S_IRWXU); } + +#[test] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +fn test_futimens_unchanged() { + let tempdir = tempfile::tempdir().unwrap(); + let fullpath = tempdir.path().join("file"); + drop(File::create(&fullpath).unwrap()); + let fd = fcntl::open(&fullpath, fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); + + let old_atime = fs::metadata(fullpath.as_path()) + .unwrap() + .accessed() + .unwrap(); + let old_mtime = fs::metadata(fullpath.as_path()) + .unwrap() + .modified() + .unwrap(); + + futimens(fd, &TimeSpec::UTIME_OMIT, &TimeSpec::UTIME_OMIT).unwrap(); + + let new_atime = fs::metadata(fullpath.as_path()) + .unwrap() + .accessed() + .unwrap(); + let new_mtime = fs::metadata(fullpath.as_path()) + .unwrap() + .modified() + .unwrap(); + assert_eq!(old_atime, new_atime); + assert_eq!(old_mtime, new_mtime); +} + +#[test] +#[cfg(not(any(target_os = "redox", target_os = "haiku")))] +fn test_utimensat_unchanged() { + let _dr = crate::DirRestore::new(); + let tempdir = tempfile::tempdir().unwrap(); + let filename = "foo.txt"; + let fullpath = tempdir.path().join(filename); + drop(File::create(&fullpath).unwrap()); + let dirfd = + fcntl::open(tempdir.path(), fcntl::OFlag::empty(), stat::Mode::empty()) + .unwrap(); + + let old_atime = fs::metadata(fullpath.as_path()) + .unwrap() + .accessed() + .unwrap(); + let old_mtime = fs::metadata(fullpath.as_path()) + .unwrap() + .modified() + .unwrap(); + utimensat( + Some(dirfd), + filename, + &TimeSpec::UTIME_OMIT, + &TimeSpec::UTIME_OMIT, + UtimensatFlags::NoFollowSymlink, + ) + .unwrap(); + let new_atime = fs::metadata(fullpath.as_path()) + .unwrap() + .accessed() + .unwrap(); + let new_mtime = fs::metadata(fullpath.as_path()) + .unwrap() + .modified() + .unwrap(); + assert_eq!(old_atime, new_atime); + assert_eq!(old_mtime, new_mtime); +} From 9113d606be7104585164718e81d2cc663c26df29 Mon Sep 17 00:00:00 2001 From: Jonathan Woollett-Light Date: Sun, 10 Dec 2023 02:56:43 +0000 Subject: [PATCH 095/140] feat: EventFd type (#1945) --- changelog/1945.added.md | 1 + changelog/1945.changed.md | 1 + src/sys/epoll.rs | 6 ++-- src/sys/eventfd.rs | 71 +++++++++++++++++++++++++++++++++++++-- 4 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 changelog/1945.added.md create mode 100644 changelog/1945.changed.md diff --git a/changelog/1945.added.md b/changelog/1945.added.md new file mode 100644 index 0000000000..19bea06715 --- /dev/null +++ b/changelog/1945.added.md @@ -0,0 +1 @@ +Added `EventFd` type. \ No newline at end of file diff --git a/changelog/1945.changed.md b/changelog/1945.changed.md new file mode 100644 index 0000000000..145d9287b8 --- /dev/null +++ b/changelog/1945.changed.md @@ -0,0 +1 @@ +Deprecated `sys::eventfd::eventfd`. \ No newline at end of file diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index 88314ef926..ec146a8c53 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -72,7 +72,7 @@ impl EpollEvent { /// A safe wrapper around [`epoll`](https://man7.org/linux/man-pages/man7/epoll.7.html). /// ``` -/// # use nix::sys::{epoll::{EpollTimeout, Epoll, EpollEvent, EpollFlags, EpollCreateFlags}, eventfd::{eventfd, EfdFlags}}; +/// # use nix::sys::{epoll::{EpollTimeout, Epoll, EpollEvent, EpollFlags, EpollCreateFlags}, eventfd::{EventFd, EfdFlags}}; /// # use nix::unistd::write; /// # use std::os::unix::io::{OwnedFd, FromRawFd, AsFd}; /// # use std::time::{Instant, Duration}; @@ -84,11 +84,11 @@ impl EpollEvent { /// let epoll = Epoll::new(EpollCreateFlags::empty())?; /// /// // Create eventfd & Add event -/// let eventfd = eventfd(0, EfdFlags::empty())?; +/// let eventfd = EventFd::new()?; /// epoll.add(&eventfd, EpollEvent::new(EpollFlags::EPOLLIN,DATA))?; /// /// // Arm eventfd & Time wait -/// write(&eventfd, &1u64.to_ne_bytes())?; +/// eventfd.arm()?; /// let now = Instant::now(); /// /// // Wait on event diff --git a/src/sys/eventfd.rs b/src/sys/eventfd.rs index f1723519cf..704a3e6873 100644 --- a/src/sys/eventfd.rs +++ b/src/sys/eventfd.rs @@ -1,6 +1,6 @@ use crate::errno::Errno; -use crate::Result; -use std::os::unix::io::{FromRawFd, OwnedFd}; +use crate::{Result,unistd}; +use std::os::unix::io::{FromRawFd, OwnedFd, AsRawFd, AsFd, RawFd, BorrowedFd}; libc_bitflags! { pub struct EfdFlags: libc::c_int { @@ -10,8 +10,75 @@ libc_bitflags! { } } +#[deprecated(since = "0.28.0", note = "Use EventFd::from_value_and_flags() instead")] pub fn eventfd(initval: libc::c_uint, flags: EfdFlags) -> Result { let res = unsafe { libc::eventfd(initval, flags.bits()) }; Errno::result(res).map(|r| unsafe { OwnedFd::from_raw_fd(r) }) } + +#[derive(Debug)] +#[repr(transparent)] +pub struct EventFd(OwnedFd); +impl EventFd { + /// [`EventFd::from_value_and_flags`] with `init_val = 0` and `flags = EfdFlags::empty()`. + pub fn new() -> Result { + Self::from_value_and_flags(0, EfdFlags::empty()) + } + /// Constructs [`EventFd`] with the given `init_val` and `flags`. + /// + /// Wrapper around [`libc::eventfd`]. + pub fn from_value_and_flags(init_val: u32, flags: EfdFlags) -> Result { + let res = unsafe { libc::eventfd(init_val, flags.bits()) }; + Errno::result(res).map(|r| Self(unsafe { OwnedFd::from_raw_fd(r) })) + } + /// [`EventFd::from_value_and_flags`] with `init_val = 0` and given `flags`. + pub fn from_flags(flags: EfdFlags) -> Result { + Self::from_value_and_flags(0, flags) + } + /// [`EventFd::from_value_and_flags`] with given `init_val` and `flags = EfdFlags::empty()`. + pub fn from_value(init_val: u32) -> Result { + Self::from_value_and_flags(init_val, EfdFlags::empty()) + } + /// Arms `self`, a following call to `poll`, `select` or `epoll` will return immediately. + /// + /// [`EventFd::write`] with `1`. + pub fn arm(&self) -> Result { + self.write(1) + } + /// Defuses `self`, a following call to `poll`, `select` or `epoll` will block. + /// + /// [`EventFd::write`] with `0`. + pub fn defuse(&self) -> Result { + self.write(0) + } + /// Enqueues `value` triggers. + /// + /// The next `value` calls to `poll`, `select` or `epoll` will return immediately. + /// + /// [`EventFd::write`] with `value`. + pub fn write(&self, value: u64) -> Result { + unistd::write(&self.0,&value.to_ne_bytes()) + } + // Reads the value from the file descriptor. + pub fn read(&self) -> Result { + let mut arr = [0; std::mem::size_of::()]; + unistd::read(self.0.as_raw_fd(),&mut arr)?; + Ok(u64::from_ne_bytes(arr)) + } +} +impl AsFd for EventFd { + fn as_fd(&self) -> BorrowedFd { + self.0.as_fd() + } +} +impl AsRawFd for EventFd { + fn as_raw_fd(&self) -> RawFd { + self.0.as_raw_fd() + } +} +impl From for OwnedFd { + fn from(x: EventFd) -> OwnedFd { + x.0 + } +} \ No newline at end of file From 43505e0c86dd1740a8e675b137dbe175f8d31602 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Sun, 10 Dec 2023 06:20:12 +0000 Subject: [PATCH 096/140] sys::eventfd enabled for FreeBSD. (#2259) * sys::eventfd enabled for FreeBSD. * CHANGELOG entry --- changelog/2259.added.md | 1 + src/sys/eventfd.rs | 8 ++++---- src/sys/mod.rs | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) create mode 100644 changelog/2259.added.md diff --git a/changelog/2259.added.md b/changelog/2259.added.md new file mode 100644 index 0000000000..244d9adb23 --- /dev/null +++ b/changelog/2259.added.md @@ -0,0 +1 @@ +Added `sys::eventfd` support on FreeBSD diff --git a/src/sys/eventfd.rs b/src/sys/eventfd.rs index 704a3e6873..50a4f091bd 100644 --- a/src/sys/eventfd.rs +++ b/src/sys/eventfd.rs @@ -4,9 +4,9 @@ use std::os::unix::io::{FromRawFd, OwnedFd, AsRawFd, AsFd, RawFd, BorrowedFd}; libc_bitflags! { pub struct EfdFlags: libc::c_int { - EFD_CLOEXEC; // Since Linux 2.6.27 - EFD_NONBLOCK; // Since Linux 2.6.27 - EFD_SEMAPHORE; // Since Linux 2.6.30 + EFD_CLOEXEC; // Since Linux 2.6.27/FreeBSD 13.0 + EFD_NONBLOCK; // Since Linux 2.6.27/FreeBSD 13.0 + EFD_SEMAPHORE; // Since Linux 2.6.30/FreeBSD 13.0 } } @@ -81,4 +81,4 @@ impl From for OwnedFd { fn from(x: EventFd) -> OwnedFd { x.0 } -} \ No newline at end of file +} diff --git a/src/sys/mod.rs b/src/sys/mod.rs index 1d875ccd51..93339d1935 100644 --- a/src/sys/mod.rs +++ b/src/sys/mod.rs @@ -20,7 +20,7 @@ feature! { #[cfg(bsd)] pub mod event; - #[cfg(linux_android)] + #[cfg(any(linux_android, target_os = "freebsd"))] #[allow(missing_docs)] pub mod eventfd; } From 8db07014f499fb81557b1314b10f904b0142a48e Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Mon, 11 Dec 2023 08:29:06 +0000 Subject: [PATCH 097/140] sys::mman adding MMAP_TRYFIXED for netbsdlike platforms. (#2260) --- Cargo.toml | 2 +- changelog/2260.added.md | 1 + src/sys/mman.rs | 4 ++++ 3 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 changelog/2260.added.md diff --git a/Cargo.toml b/Cargo.toml index 06302aac6d..38fc390087 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { git = "https://github.com/rust-lang/libc", rev = "497ac428bc010b5db9682ecf94cd567b31d53e5c", features = ["extra_traits"] } +libc = { git = "https://github.com/rust-lang/libc", rev = "f37806e499409eab8cfa897280a869bc5e2623a9", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } diff --git a/changelog/2260.added.md b/changelog/2260.added.md new file mode 100644 index 0000000000..6ab54f3082 --- /dev/null +++ b/changelog/2260.added.md @@ -0,0 +1 @@ +Added `MmapFlags::MAP_FIXED` constant in `sys::mman` for netbsd and openbsd diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 3518662756..a64f14f588 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -154,6 +154,10 @@ libc_bitflags! { /// Pages will be discarded in the core dumps. #[cfg(target_os = "openbsd")] MAP_CONCEAL; + /// Attempt to place the mapping at exactly the address specified in `addr`. + /// it's a default behavior on OpenBSD. + #[cfg(netbsdlike)] + MAP_TRYFIXED; } } From 26b070a0584645a5ab175e5914d1d60bcc615460 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Tue, 12 Dec 2023 01:45:33 +0800 Subject: [PATCH 098/140] test: enable test_aio_suspend on both Linux and macOS (#2262) --- test/sys/test_aio.rs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/test/sys/test_aio.rs b/test/sys/test_aio.rs index e8eb818024..b3eb258a08 100644 --- a/test/sys/test_aio.rs +++ b/test/sys/test_aio.rs @@ -569,12 +569,6 @@ fn test_aio_cancel_all() { } #[test] -// On Cirrus on Linux, this test fails due to a glibc bug. -// https://github.com/nix-rust/nix/issues/1099 -#[cfg_attr(target_os = "linux", ignore)] -// On Cirrus, aio_suspend is failing with EINVAL -// https://github.com/nix-rust/nix/issues/1361 -#[cfg_attr(apple_targets, ignore)] fn test_aio_suspend() { const INITIAL: &[u8] = b"abcdef123456"; const WBUF: &[u8] = b"CDEFG"; From c0d8ad4df4ab306e3c06c68b92f4a7d340df3ac5 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Tue, 12 Dec 2023 06:29:22 +0800 Subject: [PATCH 099/140] refactor: move tests to the test dir (#2257) * refactor: move tests to the test dir * try fixing it * try fixing it * fix Redox and FreeBSD * document it --- CONVENTIONS.md | 7 + src/sys/aio.rs | 53 ------- src/sys/event.rs | 39 ----- src/sys/resource.rs | 25 --- src/sys/select.rs | 224 -------------------------- src/sys/signal.rs | 268 -------------------------------- src/sys/signalfd.rs | 31 ---- src/sys/socket/mod.rs | 122 --------------- src/sys/socket/sockopt.rs | 69 -------- src/sys/statfs.rs | 104 ------------- src/sys/statvfs.rs | 17 -- src/sys/termios.rs | 15 -- src/sys/time.rs | 98 ------------ src/sys/utsname.rs | 21 --- test/sys/mod.rs | 29 ++++ test/sys/test_aio.rs | 50 ++++++ test/sys/test_event.rs | 41 +++++ test/{ => sys}/test_resource.rs | 33 ++-- test/sys/test_select.rs | 220 +++++++++++++++++++++++++- test/sys/test_signal.rs | 264 ++++++++++++++++++++++++++++++- test/sys/test_signalfd.rs | 34 ++++ test/sys/test_socket.rs | 124 +++++++++++++++ test/sys/test_sockopt.rs | 71 +++++++++ test/sys/test_statfs.rs | 99 ++++++++++++ test/sys/test_statvfs.rs | 13 ++ test/sys/test_termios.rs | 12 +- test/sys/test_time.rs | 91 +++++++++++ test/{ => sys}/test_timer.rs | 0 test/sys/test_utsname.rs | 17 ++ test/test.rs | 12 -- 30 files changed, 1089 insertions(+), 1114 deletions(-) create mode 100644 test/sys/test_event.rs rename test/{ => sys}/test_resource.rs (56%) create mode 100644 test/sys/test_statfs.rs create mode 100644 test/sys/test_statvfs.rs create mode 100644 test/sys/test_time.rs rename test/{ => sys}/test_timer.rs (100%) create mode 100644 test/sys/test_utsname.rs diff --git a/CONVENTIONS.md b/CONVENTIONS.md index 540cdce666..d71a3d17dd 100644 --- a/CONVENTIONS.md +++ b/CONVENTIONS.md @@ -124,3 +124,10 @@ cases, it will be the version of the next release. And a user-friendly note should be added. Normally, there should be a new interface that will replace the old one, so a note should be something like: "`` should be used instead". + +## Where to put a test + +If you want to add a test for a feature that is in `xxx.rs`, then the test should +be put in the corresponding `test_xxx.rs` file unless you cannot do this, e.g., +the test involves private stuff and thus cannot be added outside of Nix, then +it is allowed to leave the test in `xxx.rs`. diff --git a/src/sys/aio.rs b/src/sys/aio.rs index fbf5b27695..e3c44db654 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -1191,56 +1191,3 @@ pub fn lio_listio( }) .map(drop) } - -#[cfg(test)] -mod t { - use super::*; - - /// aio_suspend relies on casting Rust Aio* struct pointers to libc::aiocb - /// pointers. This test ensures that such casts are valid. - #[test] - fn casting() { - let sev = SigevNotify::SigevNone; - let aiof = AioFsync::new(666, AioFsyncMode::O_SYNC, 0, sev); - assert_eq!( - aiof.as_ref() as *const libc::aiocb, - &aiof as *const AioFsync as *const libc::aiocb - ); - - let mut rbuf = []; - let aior = AioRead::new(666, 0, &mut rbuf, 0, sev); - assert_eq!( - aior.as_ref() as *const libc::aiocb, - &aior as *const AioRead as *const libc::aiocb - ); - - let wbuf = []; - let aiow = AioWrite::new(666, 0, &wbuf, 0, sev); - assert_eq!( - aiow.as_ref() as *const libc::aiocb, - &aiow as *const AioWrite as *const libc::aiocb - ); - } - - #[cfg(target_os = "freebsd")] - #[test] - fn casting_vectored() { - let sev = SigevNotify::SigevNone; - - let mut rbuf = []; - let mut rbufs = [IoSliceMut::new(&mut rbuf)]; - let aiorv = AioReadv::new(666, 0, &mut rbufs[..], 0, sev); - assert_eq!( - aiorv.as_ref() as *const libc::aiocb, - &aiorv as *const AioReadv as *const libc::aiocb - ); - - let wbuf = []; - let wbufs = [IoSlice::new(&wbuf)]; - let aiowv = AioWritev::new(666, 0, &wbufs, 0, sev); - assert_eq!( - aiowv.as_ref() as *const libc::aiocb, - &aiowv as *const AioWritev as *const libc::aiocb - ); - } -} diff --git a/src/sys/event.rs b/src/sys/event.rs index d30896aaeb..968c5a4ae2 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -441,42 +441,3 @@ pub fn ev_set( ev.kevent.data = 0; ev.kevent.udata = udata as type_of_udata; } - -#[test] -fn test_struct_kevent() { - use std::mem; - - let udata: intptr_t = 12345; - - let actual = KEvent::new( - 0xdead_beef, - EventFilter::EVFILT_READ, - EventFlag::EV_ONESHOT | EventFlag::EV_ADD, - FilterFlag::NOTE_CHILD | FilterFlag::NOTE_EXIT, - 0x1337, - udata, - ); - assert_eq!(0xdead_beef, actual.ident()); - let filter = actual.kevent.filter; - assert_eq!(libc::EVFILT_READ, filter); - assert_eq!(libc::EV_ONESHOT | libc::EV_ADD, actual.flags().bits()); - assert_eq!(libc::NOTE_CHILD | libc::NOTE_EXIT, actual.fflags().bits()); - assert_eq!(0x1337, actual.data()); - assert_eq!(udata as type_of_udata, actual.udata() as type_of_udata); - assert_eq!(mem::size_of::(), mem::size_of::()); -} - -#[test] -fn test_kevent_filter() { - let udata: intptr_t = 12345; - - let actual = KEvent::new( - 0xdead_beef, - EventFilter::EVFILT_READ, - EventFlag::EV_ONESHOT | EventFlag::EV_ADD, - FilterFlag::NOTE_CHILD | FilterFlag::NOTE_EXIT, - 0x1337, - udata, - ); - assert_eq!(EventFilter::EVFILT_READ, actual.filter().unwrap()); -} diff --git a/src/sys/resource.rs b/src/sys/resource.rs index f57db47944..71315072d4 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -396,28 +396,3 @@ pub fn getrusage(who: UsageWho) -> Result { Errno::result(res).map(|_| Usage(rusage.assume_init())) } } - -#[cfg(test)] -mod test { - use super::{getrusage, UsageWho}; - - #[test] - pub fn test_self_cpu_time() { - // Make sure some CPU time is used. - let mut numbers: Vec = (1..1_000_000).collect(); - numbers.iter_mut().for_each(|item| *item *= 2); - - // FIXME: this is here to help ensure the compiler does not optimize the whole - // thing away. Replace the assert with test::black_box once stabilized. - assert_eq!(numbers[100..200].iter().sum::(), 30_100); - - let usage = getrusage(UsageWho::RUSAGE_SELF) - .expect("Failed to call getrusage for SELF"); - let rusage = usage.as_ref(); - - let user = usage.user_time(); - assert!(user.tv_sec() > 0 || user.tv_usec() > 0); - assert_eq!(user.tv_sec(), rusage.ru_utime.tv_sec); - assert_eq!(user.tv_usec(), rusage.ru_utime.tv_usec); - } -} diff --git a/src/sys/select.rs b/src/sys/select.rs index ea0c41d4be..64a8e258cf 100644 --- a/src/sys/select.rs +++ b/src/sys/select.rs @@ -317,227 +317,3 @@ where Errno::result(res) } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::sys::time::{TimeVal, TimeValLike}; - use crate::unistd::{pipe, write}; - use std::os::unix::io::{AsFd, RawFd}; - - #[test] - fn fdset_insert() { - let mut fd_set = FdSet::new(); - - for i in 0..FD_SETSIZE { - let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(borrowed_i)); - } - - let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; - fd_set.insert(fd_seven); - - assert!(fd_set.contains(fd_seven)); - } - - #[test] - fn fdset_remove() { - let mut fd_set = FdSet::new(); - - for i in 0..FD_SETSIZE { - let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(borrowed_i)); - } - - let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; - fd_set.insert(fd_seven); - fd_set.remove(fd_seven); - - for i in 0..FD_SETSIZE { - let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(borrowed_i)); - } - } - - #[test] - #[allow(non_snake_case)] - fn fdset_clear() { - let mut fd_set = FdSet::new(); - let fd_one = unsafe { BorrowedFd::borrow_raw(1) }; - let fd_FD_SETSIZE_divided_by_two = - unsafe { BorrowedFd::borrow_raw((FD_SETSIZE / 2) as RawFd) }; - let fd_FD_SETSIZE_minus_one = - unsafe { BorrowedFd::borrow_raw((FD_SETSIZE - 1) as RawFd) }; - fd_set.insert(fd_one); - fd_set.insert(fd_FD_SETSIZE_divided_by_two); - fd_set.insert(fd_FD_SETSIZE_minus_one); - - fd_set.clear(); - - for i in 0..FD_SETSIZE { - let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; - assert!(!fd_set.contains(borrowed_i)); - } - } - - #[test] - fn fdset_highest() { - let mut set = FdSet::new(); - assert_eq!( - set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), - None - ); - let fd_zero = unsafe { BorrowedFd::borrow_raw(0) }; - let fd_ninety = unsafe { BorrowedFd::borrow_raw(90) }; - set.insert(fd_zero); - assert_eq!( - set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), - Some(0) - ); - set.insert(fd_ninety); - assert_eq!( - set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), - Some(90) - ); - set.remove(fd_zero); - assert_eq!( - set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), - Some(90) - ); - set.remove(fd_ninety); - assert_eq!( - set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), - None - ); - - let fd_four = unsafe { BorrowedFd::borrow_raw(4) }; - let fd_five = unsafe { BorrowedFd::borrow_raw(5) }; - let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; - set.insert(fd_four); - set.insert(fd_five); - set.insert(fd_seven); - assert_eq!( - set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), - Some(7) - ); - } - - #[test] - fn fdset_fds() { - let mut set = FdSet::new(); - let fd_zero = unsafe { BorrowedFd::borrow_raw(0) }; - let fd_ninety = unsafe { BorrowedFd::borrow_raw(90) }; - assert_eq!( - set.fds(None) - .map(|borrowed_fd| borrowed_fd.as_raw_fd()) - .collect::>(), - vec![] - ); - set.insert(fd_zero); - assert_eq!( - set.fds(None) - .map(|borrowed_fd| borrowed_fd.as_raw_fd()) - .collect::>(), - vec![0] - ); - set.insert(fd_ninety); - assert_eq!( - set.fds(None) - .map(|borrowed_fd| borrowed_fd.as_raw_fd()) - .collect::>(), - vec![0, 90] - ); - - // highest limit - assert_eq!( - set.fds(Some(89)) - .map(|borrowed_fd| borrowed_fd.as_raw_fd()) - .collect::>(), - vec![0] - ); - assert_eq!( - set.fds(Some(90)) - .map(|borrowed_fd| borrowed_fd.as_raw_fd()) - .collect::>(), - vec![0, 90] - ); - } - - #[test] - fn test_select() { - let (r1, w1) = pipe().unwrap(); - let (r2, _w2) = pipe().unwrap(); - - write(&w1, b"hi!").unwrap(); - let mut fd_set = FdSet::new(); - fd_set.insert(r1.as_fd()); - fd_set.insert(r2.as_fd()); - - let mut timeout = TimeVal::seconds(10); - assert_eq!( - 1, - select(None, &mut fd_set, None, None, &mut timeout).unwrap() - ); - assert!(fd_set.contains(r1.as_fd())); - assert!(!fd_set.contains(r2.as_fd())); - } - - #[test] - fn test_select_nfds() { - let (r1, w1) = pipe().unwrap(); - let (r2, _w2) = pipe().unwrap(); - - write(&w1, b"hi!").unwrap(); - let mut fd_set = FdSet::new(); - fd_set.insert(r1.as_fd()); - fd_set.insert(r2.as_fd()); - - let mut timeout = TimeVal::seconds(10); - { - assert_eq!( - 1, - select( - Some( - fd_set - .highest() - .map(|borrowed_fd| borrowed_fd.as_raw_fd()) - .unwrap() - + 1 - ), - &mut fd_set, - None, - None, - &mut timeout - ) - .unwrap() - ); - } - assert!(fd_set.contains(r1.as_fd())); - assert!(!fd_set.contains(r2.as_fd())); - } - - #[test] - fn test_select_nfds2() { - let (r1, w1) = pipe().unwrap(); - write(&w1, b"hi!").unwrap(); - let (r2, _w2) = pipe().unwrap(); - let mut fd_set = FdSet::new(); - fd_set.insert(r1.as_fd()); - fd_set.insert(r2.as_fd()); - - let mut timeout = TimeVal::seconds(10); - assert_eq!( - 1, - select( - std::cmp::max(r1.as_raw_fd(), r2.as_raw_fd()) + 1, - &mut fd_set, - None, - None, - &mut timeout - ) - .unwrap() - ); - assert!(fd_set.contains(r1.as_fd())); - assert!(!fd_set.contains(r2.as_fd())); - } -} diff --git a/src/sys/signal.rs b/src/sys/signal.rs index 10f1de85b0..efa11a134b 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -1379,271 +1379,3 @@ mod sigevent { } } } - -#[cfg(test)] -mod tests { - use super::*; - #[cfg(not(target_os = "redox"))] - use std::thread; - - #[test] - fn test_contains() { - let mut mask = SigSet::empty(); - mask.add(SIGUSR1); - - assert!(mask.contains(SIGUSR1)); - assert!(!mask.contains(SIGUSR2)); - - let all = SigSet::all(); - assert!(all.contains(SIGUSR1)); - assert!(all.contains(SIGUSR2)); - } - - #[test] - fn test_clear() { - let mut set = SigSet::all(); - set.clear(); - for signal in Signal::iterator() { - assert!(!set.contains(signal)); - } - } - - #[test] - fn test_from_str_round_trips() { - for signal in Signal::iterator() { - assert_eq!(signal.as_ref().parse::().unwrap(), signal); - assert_eq!(signal.to_string().parse::().unwrap(), signal); - } - } - - #[test] - fn test_from_str_invalid_value() { - let errval = Err(Errno::EINVAL); - assert_eq!("NOSIGNAL".parse::(), errval); - assert_eq!("kill".parse::(), errval); - assert_eq!("9".parse::(), errval); - } - - #[test] - fn test_extend() { - let mut one_signal = SigSet::empty(); - one_signal.add(SIGUSR1); - - let mut two_signals = SigSet::empty(); - two_signals.add(SIGUSR2); - two_signals.extend(&one_signal); - - assert!(two_signals.contains(SIGUSR1)); - assert!(two_signals.contains(SIGUSR2)); - } - - #[test] - #[cfg(not(target_os = "redox"))] - fn test_thread_signal_set_mask() { - thread::spawn(|| { - let prev_mask = SigSet::thread_get_mask() - .expect("Failed to get existing signal mask!"); - - let mut test_mask = prev_mask; - test_mask.add(SIGUSR1); - - test_mask.thread_set_mask().expect("assertion failed"); - let new_mask = - SigSet::thread_get_mask().expect("Failed to get new mask!"); - - assert!(new_mask.contains(SIGUSR1)); - assert!(!new_mask.contains(SIGUSR2)); - - prev_mask - .thread_set_mask() - .expect("Failed to revert signal mask!"); - }) - .join() - .unwrap(); - } - - #[test] - #[cfg(not(target_os = "redox"))] - fn test_thread_signal_block() { - thread::spawn(|| { - let mut mask = SigSet::empty(); - mask.add(SIGUSR1); - - mask.thread_block().expect("assertion failed"); - - assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); - }) - .join() - .unwrap(); - } - - #[test] - #[cfg(not(target_os = "redox"))] - fn test_thread_signal_unblock() { - thread::spawn(|| { - let mut mask = SigSet::empty(); - mask.add(SIGUSR1); - - mask.thread_unblock().expect("assertion failed"); - - assert!(!SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); - }) - .join() - .unwrap(); - } - - #[test] - #[cfg(not(target_os = "redox"))] - fn test_thread_signal_swap() { - thread::spawn(|| { - let mut mask = SigSet::empty(); - mask.add(SIGUSR1); - mask.thread_block().unwrap(); - - assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); - - let mut mask2 = SigSet::empty(); - mask2.add(SIGUSR2); - - let oldmask = - mask2.thread_swap_mask(SigmaskHow::SIG_SETMASK).unwrap(); - - assert!(oldmask.contains(SIGUSR1)); - assert!(!oldmask.contains(SIGUSR2)); - - assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR2)); - }) - .join() - .unwrap(); - } - - #[test] - fn test_from_and_into_iterator() { - let sigset = SigSet::from_iter(vec![Signal::SIGUSR1, Signal::SIGUSR2]); - let signals = sigset.into_iter().collect::>(); - assert_eq!(signals, [Signal::SIGUSR1, Signal::SIGUSR2]); - } - - #[test] - #[cfg(not(target_os = "redox"))] - fn test_sigaction() { - thread::spawn(|| { - extern "C" fn test_sigaction_handler(_: libc::c_int) {} - extern "C" fn test_sigaction_action( - _: libc::c_int, - _: *mut libc::siginfo_t, - _: *mut libc::c_void, - ) { - } - - let handler_sig = SigHandler::Handler(test_sigaction_handler); - - let flags = - SaFlags::SA_ONSTACK | SaFlags::SA_RESTART | SaFlags::SA_SIGINFO; - - let mut mask = SigSet::empty(); - mask.add(SIGUSR1); - - let action_sig = SigAction::new(handler_sig, flags, mask); - - assert_eq!( - action_sig.flags(), - SaFlags::SA_ONSTACK | SaFlags::SA_RESTART - ); - assert_eq!(action_sig.handler(), handler_sig); - - mask = action_sig.mask(); - assert!(mask.contains(SIGUSR1)); - assert!(!mask.contains(SIGUSR2)); - - let handler_act = SigHandler::SigAction(test_sigaction_action); - let action_act = SigAction::new(handler_act, flags, mask); - assert_eq!(action_act.handler(), handler_act); - - let action_dfl = SigAction::new(SigHandler::SigDfl, flags, mask); - assert_eq!(action_dfl.handler(), SigHandler::SigDfl); - - let action_ign = SigAction::new(SigHandler::SigIgn, flags, mask); - assert_eq!(action_ign.handler(), SigHandler::SigIgn); - }) - .join() - .unwrap(); - } - - #[test] - #[cfg(not(target_os = "redox"))] - fn test_sigwait() { - thread::spawn(|| { - let mut mask = SigSet::empty(); - mask.add(SIGUSR1); - mask.add(SIGUSR2); - mask.thread_block().unwrap(); - - raise(SIGUSR1).unwrap(); - assert_eq!(mask.wait().unwrap(), SIGUSR1); - }) - .join() - .unwrap(); - } - - #[test] - fn test_from_sigset_t_unchecked() { - let src_set = SigSet::empty(); - let set = unsafe { SigSet::from_sigset_t_unchecked(src_set.sigset) }; - - for signal in Signal::iterator() { - assert!(!set.contains(signal)); - } - - let src_set = SigSet::all(); - let set = unsafe { SigSet::from_sigset_t_unchecked(src_set.sigset) }; - - for signal in Signal::iterator() { - assert!(set.contains(signal)); - } - } - - #[test] - fn test_eq_empty() { - let set0 = SigSet::empty(); - let set1 = SigSet::empty(); - assert_eq!(set0, set1); - } - - #[test] - fn test_eq_all() { - let set0 = SigSet::all(); - let set1 = SigSet::all(); - assert_eq!(set0, set1); - } - - #[test] - fn test_hash_empty() { - use std::collections::hash_map::DefaultHasher; - - let set0 = SigSet::empty(); - let mut h0 = DefaultHasher::new(); - set0.hash(&mut h0); - - let set1 = SigSet::empty(); - let mut h1 = DefaultHasher::new(); - set1.hash(&mut h1); - - assert_eq!(h0.finish(), h1.finish()); - } - - #[test] - fn test_hash_all() { - use std::collections::hash_map::DefaultHasher; - - let set0 = SigSet::all(); - let mut h0 = DefaultHasher::new(); - set0.hash(&mut h0); - - let set1 = SigSet::all(); - let mut h1 = DefaultHasher::new(); - set1.hash(&mut h1); - - assert_eq!(h0.finish(), h1.finish()); - } -} diff --git a/src/sys/signalfd.rs b/src/sys/signalfd.rs index aefc89bc73..ccba774d1a 100644 --- a/src/sys/signalfd.rs +++ b/src/sys/signalfd.rs @@ -155,34 +155,3 @@ impl Iterator for SignalFd { } } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn create_signalfd() { - let mask = SigSet::empty(); - SignalFd::new(&mask).unwrap(); - } - - #[test] - fn create_signalfd_with_opts() { - let mask = SigSet::empty(); - SignalFd::with_flags( - &mask, - SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK, - ) - .unwrap(); - } - - #[test] - fn read_empty_signalfd() { - let mask = SigSet::empty(); - let mut fd = - SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap(); - - let res = fd.read_signal(); - assert!(res.unwrap().is_none()); - } -} diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 8556c7d46d..dfc37db745 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1774,108 +1774,6 @@ impl<'a> Iterator for IoSliceIterator<'a> { } } -// test contains both recvmmsg and timestaping which is linux only -// there are existing tests for recvmmsg only in tests/ -#[cfg(target_os = "linux")] -#[cfg(test)] -mod test { - use crate::sys::socket::{AddressFamily, ControlMessageOwned}; - use crate::*; - use std::str::FromStr; - use std::os::unix::io::AsRawFd; - - #[cfg_attr(qemu, ignore)] - #[test] - fn test_recvmm2() -> crate::Result<()> { - use crate::sys::socket::{ - sendmsg, setsockopt, socket, sockopt::Timestamping, MsgFlags, SockFlag, SockType, - SockaddrIn, TimestampingFlag, - }; - use std::io::{IoSlice, IoSliceMut}; - - let sock_addr = SockaddrIn::from_str("127.0.0.1:6790").unwrap(); - - let ssock = socket( - AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None, - )?; - - let rsock = socket( - AddressFamily::Inet, - SockType::Datagram, - SockFlag::SOCK_NONBLOCK, - None, - )?; - - crate::sys::socket::bind(rsock.as_raw_fd(), &sock_addr)?; - - setsockopt(&rsock, Timestamping, &TimestampingFlag::all())?; - - let sbuf = (0..400).map(|i| i as u8).collect::>(); - - let mut recv_buf = vec![0; 1024]; - - let mut recv_iovs = Vec::new(); - let mut pkt_iovs = Vec::new(); - - for (ix, chunk) in recv_buf.chunks_mut(256).enumerate() { - pkt_iovs.push(IoSliceMut::new(chunk)); - if ix % 2 == 1 { - recv_iovs.push(pkt_iovs); - pkt_iovs = Vec::new(); - } - } - drop(pkt_iovs); - - let flags = MsgFlags::empty(); - let iov1 = [IoSlice::new(&sbuf)]; - - let cmsg = cmsg_space!(crate::sys::socket::Timestamps); - sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap(); - - let mut data = super::MultiHeaders::<()>::preallocate(recv_iovs.len(), Some(cmsg)); - - let t = sys::time::TimeSpec::from_duration(std::time::Duration::from_secs(10)); - - let recv = super::recvmmsg(rsock.as_raw_fd(), &mut data, recv_iovs.iter_mut(), flags, Some(t))?; - - for rmsg in recv { - #[cfg(not(any(qemu, target_arch = "aarch64")))] - let mut saw_time = false; - let mut recvd = 0; - for cmsg in rmsg.cmsgs() { - if let ControlMessageOwned::ScmTimestampsns(timestamps) = cmsg { - let ts = timestamps.system; - - let sys_time = - crate::time::clock_gettime(crate::time::ClockId::CLOCK_REALTIME)?; - let diff = if ts > sys_time { - ts - sys_time - } else { - sys_time - ts - }; - assert!(std::time::Duration::from(diff).as_secs() < 60); - #[cfg(not(any(qemu, target_arch = "aarch64")))] - { - saw_time = true; - } - } - } - - #[cfg(not(any(qemu, target_arch = "aarch64")))] - assert!(saw_time); - - for iov in rmsg.iovs() { - recvd += iov.len(); - } - assert_eq!(recvd, 400); - } - - Ok(()) - } -} unsafe fn read_mhdr<'a, 'i, S>( mhdr: msghdr, r: isize, @@ -2364,23 +2262,3 @@ pub fn shutdown(df: RawFd, how: Shutdown) -> Result<()> { } } -#[cfg(test)] -mod tests { - #[cfg(not(target_os = "redox"))] - #[test] - fn can_use_cmsg_space() { - let _ = cmsg_space!(u8); - } - - #[cfg(not(any(linux_android, target_os = "redox", target_os = "haiku")))] - #[test] - fn can_open_routing_socket() { - let _ = super::socket( - super::AddressFamily::Route, - super::SockType::Raw, - super::SockFlag::empty(), - None, - ) - .expect("Failed to open routing socket"); - } -} diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index cbc7beca34..6ce57c6f96 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -1403,72 +1403,3 @@ impl<'a> Set<'a, OsString> for SetOsString<'a> { } } -#[cfg(test)] -mod test { - #[cfg(linux_android)] - #[test] - fn can_get_peercred_on_unix_socket() { - use super::super::*; - - let (a, b) = socketpair( - AddressFamily::Unix, - SockType::Stream, - None, - SockFlag::empty(), - ) - .unwrap(); - let a_cred = getsockopt(&a, super::PeerCredentials).unwrap(); - let b_cred = getsockopt(&b, super::PeerCredentials).unwrap(); - assert_eq!(a_cred, b_cred); - assert_ne!(a_cred.pid(), 0); - } - - #[test] - fn is_socket_type_unix() { - use super::super::*; - - let (a, _b) = socketpair( - AddressFamily::Unix, - SockType::Stream, - None, - SockFlag::empty(), - ) - .unwrap(); - let a_type = getsockopt(&a, super::SockType).unwrap(); - assert_eq!(a_type, SockType::Stream); - } - - #[test] - fn is_socket_type_dgram() { - use super::super::*; - - let s = socket( - AddressFamily::Inet, - SockType::Datagram, - SockFlag::empty(), - None, - ) - .unwrap(); - let s_type = getsockopt(&s, super::SockType).unwrap(); - assert_eq!(s_type, SockType::Datagram); - } - - #[cfg(any(target_os = "freebsd", target_os = "linux"))] - #[test] - fn can_get_listen_on_tcp_socket() { - use super::super::*; - - let s = socket( - AddressFamily::Inet, - SockType::Stream, - SockFlag::empty(), - None, - ) - .unwrap(); - let s_listening = getsockopt(&s, super::AcceptConn).unwrap(); - assert!(!s_listening); - listen(&s, 10).unwrap(); - let s_listening2 = getsockopt(&s, super::AcceptConn).unwrap(); - assert!(s_listening2); - } -} diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index 377e303e99..d4335cf388 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -657,107 +657,3 @@ pub fn fstatfs(fd: Fd) -> Result { .map(|_| Statfs(stat.assume_init())) } } - -#[cfg(test)] -mod test { - use std::fs::File; - - use crate::sys::statfs::*; - use crate::sys::statvfs::*; - use std::path::Path; - - #[test] - fn statfs_call() { - check_statfs("/tmp"); - check_statfs("/dev"); - check_statfs("/run"); - check_statfs("/"); - } - - #[test] - fn fstatfs_call() { - check_fstatfs("/tmp"); - check_fstatfs("/dev"); - check_fstatfs("/run"); - check_fstatfs("/"); - } - - fn check_fstatfs(path: &str) { - if !Path::new(path).exists() { - return; - } - let vfs = statvfs(path.as_bytes()).unwrap(); - let file = File::open(path).unwrap(); - let fs = fstatfs(&file).unwrap(); - assert_fs_equals(fs, vfs); - } - - fn check_statfs(path: &str) { - if !Path::new(path).exists() { - return; - } - let vfs = statvfs(path.as_bytes()).unwrap(); - let fs = statfs(path.as_bytes()).unwrap(); - assert_fs_equals(fs, vfs); - } - - // The cast is not unnecessary on all platforms. - #[allow(clippy::unnecessary_cast)] - fn assert_fs_equals(fs: Statfs, vfs: Statvfs) { - assert_eq!(fs.files() as u64, vfs.files() as u64); - assert_eq!(fs.blocks() as u64, vfs.blocks() as u64); - assert_eq!(fs.block_size() as u64, vfs.fragment_size() as u64); - } - - // This test is ignored because files_free/blocks_free can change after statvfs call and before - // statfs call. - #[test] - #[ignore] - fn statfs_call_strict() { - check_statfs_strict("/tmp"); - check_statfs_strict("/dev"); - check_statfs_strict("/run"); - check_statfs_strict("/"); - } - - // This test is ignored because files_free/blocks_free can change after statvfs call and before - // fstatfs call. - #[test] - #[ignore] - fn fstatfs_call_strict() { - check_fstatfs_strict("/tmp"); - check_fstatfs_strict("/dev"); - check_fstatfs_strict("/run"); - check_fstatfs_strict("/"); - } - - fn check_fstatfs_strict(path: &str) { - if !Path::new(path).exists() { - return; - } - let vfs = statvfs(path.as_bytes()); - let file = File::open(path).unwrap(); - let fs = fstatfs(&file); - assert_fs_equals_strict(fs.unwrap(), vfs.unwrap()) - } - - fn check_statfs_strict(path: &str) { - if !Path::new(path).exists() { - return; - } - let vfs = statvfs(path.as_bytes()); - let fs = statfs(path.as_bytes()); - assert_fs_equals_strict(fs.unwrap(), vfs.unwrap()) - } - - // The cast is not unnecessary on all platforms. - #[allow(clippy::unnecessary_cast)] - fn assert_fs_equals_strict(fs: Statfs, vfs: Statvfs) { - assert_eq!(fs.files_free() as u64, vfs.files_free() as u64); - assert_eq!(fs.blocks_free() as u64, vfs.blocks_free() as u64); - assert_eq!(fs.blocks_available() as u64, vfs.blocks_available() as u64); - assert_eq!(fs.files() as u64, vfs.files() as u64); - assert_eq!(fs.blocks() as u64, vfs.blocks() as u64); - assert_eq!(fs.block_size() as u64, vfs.fragment_size() as u64); - } -} diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 72f38ab7ab..7de326200e 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -148,20 +148,3 @@ pub fn fstatvfs(fd: Fd) -> Result { .map(|_| Statvfs(stat.assume_init())) } } - -#[cfg(test)] -mod test { - use crate::sys::statvfs::*; - use std::fs::File; - - #[test] - fn statvfs_call() { - statvfs(&b"/"[..]).unwrap(); - } - - #[test] - fn fstatvfs_call() { - let root = File::open("/").unwrap(); - fstatvfs(&root).unwrap(); - } -} diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 57b42254ea..e006c2f1b0 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -923,18 +923,3 @@ pub fn tcgetsid(fd: Fd) -> Result { Errno::result(res).map(Pid::from_raw) } } - -#[cfg(test)] -mod test { - use super::*; - use std::convert::TryFrom; - - #[test] - fn try_from() { - assert_eq!(Ok(BaudRate::B0), BaudRate::try_from(libc::B0)); - #[cfg(not(target_os = "haiku"))] - BaudRate::try_from(999999999).expect_err("assertion failed"); - #[cfg(target_os = "haiku")] - BaudRate::try_from(99).expect_err("assertion failed"); - } -} diff --git a/src/sys/time.rs b/src/sys/time.rs index a63a03dc88..b19dee91a0 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -718,101 +718,3 @@ fn mod_floor_64(this: i64, other: i64) -> i64 { fn div_rem_64(this: i64, other: i64) -> (i64, i64) { (this / other, this % other) } - -#[cfg(test)] -mod test { - use super::{TimeSpec, TimeVal, TimeValLike}; - use std::time::Duration; - - #[test] - pub fn test_timespec() { - assert_ne!(TimeSpec::seconds(1), TimeSpec::zero()); - assert_eq!( - TimeSpec::seconds(1) + TimeSpec::seconds(2), - TimeSpec::seconds(3) - ); - assert_eq!( - TimeSpec::minutes(3) + TimeSpec::seconds(2), - TimeSpec::seconds(182) - ); - } - - #[test] - pub fn test_timespec_from() { - let duration = Duration::new(123, 123_456_789); - let timespec = TimeSpec::nanoseconds(123_123_456_789); - - assert_eq!(TimeSpec::from(duration), timespec); - assert_eq!(Duration::from(timespec), duration); - } - - #[test] - pub fn test_timespec_neg() { - let a = TimeSpec::seconds(1) + TimeSpec::nanoseconds(123); - let b = TimeSpec::seconds(-1) + TimeSpec::nanoseconds(-123); - - assert_eq!(a, -b); - } - - #[test] - pub fn test_timespec_ord() { - assert_eq!(TimeSpec::seconds(1), TimeSpec::nanoseconds(1_000_000_000)); - assert!(TimeSpec::seconds(1) < TimeSpec::nanoseconds(1_000_000_001)); - assert!(TimeSpec::seconds(1) > TimeSpec::nanoseconds(999_999_999)); - assert!(TimeSpec::seconds(-1) < TimeSpec::nanoseconds(-999_999_999)); - assert!(TimeSpec::seconds(-1) > TimeSpec::nanoseconds(-1_000_000_001)); - } - - #[test] - pub fn test_timespec_fmt() { - assert_eq!(TimeSpec::zero().to_string(), "0 seconds"); - assert_eq!(TimeSpec::seconds(42).to_string(), "42 seconds"); - assert_eq!(TimeSpec::milliseconds(42).to_string(), "0.042 seconds"); - assert_eq!(TimeSpec::microseconds(42).to_string(), "0.000042 seconds"); - assert_eq!( - TimeSpec::nanoseconds(42).to_string(), - "0.000000042 seconds" - ); - assert_eq!(TimeSpec::seconds(-86401).to_string(), "-86401 seconds"); - } - - #[test] - pub fn test_timeval() { - assert_ne!(TimeVal::seconds(1), TimeVal::zero()); - assert_eq!( - TimeVal::seconds(1) + TimeVal::seconds(2), - TimeVal::seconds(3) - ); - assert_eq!( - TimeVal::minutes(3) + TimeVal::seconds(2), - TimeVal::seconds(182) - ); - } - - #[test] - pub fn test_timeval_ord() { - assert_eq!(TimeVal::seconds(1), TimeVal::microseconds(1_000_000)); - assert!(TimeVal::seconds(1) < TimeVal::microseconds(1_000_001)); - assert!(TimeVal::seconds(1) > TimeVal::microseconds(999_999)); - assert!(TimeVal::seconds(-1) < TimeVal::microseconds(-999_999)); - assert!(TimeVal::seconds(-1) > TimeVal::microseconds(-1_000_001)); - } - - #[test] - pub fn test_timeval_neg() { - let a = TimeVal::seconds(1) + TimeVal::microseconds(123); - let b = TimeVal::seconds(-1) + TimeVal::microseconds(-123); - - assert_eq!(a, -b); - } - - #[test] - pub fn test_timeval_fmt() { - assert_eq!(TimeVal::zero().to_string(), "0 seconds"); - assert_eq!(TimeVal::seconds(42).to_string(), "42 seconds"); - assert_eq!(TimeVal::milliseconds(42).to_string(), "0.042 seconds"); - assert_eq!(TimeVal::microseconds(42).to_string(), "0.000042 seconds"); - assert_eq!(TimeVal::nanoseconds(1402).to_string(), "0.000001 seconds"); - assert_eq!(TimeVal::seconds(-86401).to_string(), "-86401 seconds"); - } -} diff --git a/src/sys/utsname.rs b/src/sys/utsname.rs index f07067b5b1..cf4e6cc738 100644 --- a/src/sys/utsname.rs +++ b/src/sys/utsname.rs @@ -62,24 +62,3 @@ fn cast_and_trim(slice: &[c_char]) -> &OsStr { OsStr::from_bytes(bytes) } - -#[cfg(test)] -mod test { - #[cfg(target_os = "linux")] - #[test] - pub fn test_uname_linux() { - assert_eq!(super::uname().unwrap().sysname(), "Linux"); - } - - #[cfg(apple_targets)] - #[test] - pub fn test_uname_darwin() { - assert_eq!(super::uname().unwrap().sysname(), "Darwin"); - } - - #[cfg(target_os = "freebsd")] - #[test] - pub fn test_uname_freebsd() { - assert_eq!(super::uname().unwrap().sysname(), "FreeBSD"); - } -} diff --git a/test/sys/mod.rs b/test/sys/mod.rs index 3a6707ba1d..fb3f6be0e5 100644 --- a/test/sys/mod.rs +++ b/test/sys/mod.rs @@ -53,3 +53,32 @@ mod test_pthread; mod test_ptrace; #[cfg(linux_android)] mod test_timerfd; + +#[cfg(all( + any( + target_os = "freebsd", + solarish, + target_os = "linux", + target_os = "netbsd" + ), + feature = "time", + feature = "signal" +))] +mod test_timer; + +#[cfg(bsd)] +mod test_event; +mod test_statvfs; +mod test_time; +mod test_utsname; + +#[cfg(any(linux_android, freebsdlike, apple_targets, target_os = "openbsd"))] +mod test_statfs; + +#[cfg(not(any( + target_os = "redox", + target_os = "fuchsia", + solarish, + target_os = "haiku" +)))] +mod test_resource; diff --git a/test/sys/test_aio.rs b/test/sys/test_aio.rs index b3eb258a08..ba5ad02ec3 100644 --- a/test/sys/test_aio.rs +++ b/test/sys/test_aio.rs @@ -618,3 +618,53 @@ fn test_aio_suspend() { assert_eq!(wcb.as_mut().aio_return().unwrap(), WBUF.len()); assert_eq!(rcb.as_mut().aio_return().unwrap(), rlen); } + +/// aio_suspend relies on casting Rust Aio* struct pointers to libc::aiocb +/// pointers. This test ensures that such casts are valid. +#[test] +fn casting() { + let sev = SigevNotify::SigevNone; + let aiof = AioFsync::new(666, AioFsyncMode::O_SYNC, 0, sev); + assert_eq!( + aiof.as_ref() as *const libc::aiocb, + &aiof as *const AioFsync as *const libc::aiocb + ); + + let mut rbuf = []; + let aior = AioRead::new(666, 0, &mut rbuf, 0, sev); + assert_eq!( + aior.as_ref() as *const libc::aiocb, + &aior as *const AioRead as *const libc::aiocb + ); + + let wbuf = []; + let aiow = AioWrite::new(666, 0, &wbuf, 0, sev); + assert_eq!( + aiow.as_ref() as *const libc::aiocb, + &aiow as *const AioWrite as *const libc::aiocb + ); +} + +#[cfg(target_os = "freebsd")] +#[test] +fn casting_vectored() { + use std::io::{IoSlice, IoSliceMut}; + + let sev = SigevNotify::SigevNone; + + let mut rbuf = []; + let mut rbufs = [IoSliceMut::new(&mut rbuf)]; + let aiorv = AioReadv::new(666, 0, &mut rbufs[..], 0, sev); + assert_eq!( + aiorv.as_ref() as *const libc::aiocb, + &aiorv as *const AioReadv as *const libc::aiocb + ); + + let wbuf = []; + let wbufs = [IoSlice::new(&wbuf)]; + let aiowv = AioWritev::new(666, 0, &wbufs, 0, sev); + assert_eq!( + aiowv.as_ref() as *const libc::aiocb, + &aiowv as *const AioWritev as *const libc::aiocb + ); +} diff --git a/test/sys/test_event.rs b/test/sys/test_event.rs new file mode 100644 index 0000000000..a10b1e5d12 --- /dev/null +++ b/test/sys/test_event.rs @@ -0,0 +1,41 @@ +use libc::intptr_t; +use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent}; + +#[test] +fn test_struct_kevent() { + use std::mem; + + let udata: intptr_t = 12345; + let data: intptr_t = 0x1337; + + let actual = KEvent::new( + 0xdead_beef, + EventFilter::EVFILT_READ, + EventFlag::EV_ONESHOT | EventFlag::EV_ADD, + FilterFlag::NOTE_CHILD | FilterFlag::NOTE_EXIT, + data, + udata, + ); + assert_eq!(0xdead_beef, actual.ident()); + assert_eq!(EventFilter::EVFILT_READ, actual.filter().unwrap()); + assert_eq!(libc::EV_ONESHOT | libc::EV_ADD, actual.flags().bits()); + assert_eq!(libc::NOTE_CHILD | libc::NOTE_EXIT, actual.fflags().bits()); + assert_eq!(data, actual.data()); + assert_eq!(udata, actual.udata()); + assert_eq!(mem::size_of::(), mem::size_of::()); +} + +#[test] +fn test_kevent_filter() { + let udata: intptr_t = 12345; + + let actual = KEvent::new( + 0xdead_beef, + EventFilter::EVFILT_READ, + EventFlag::EV_ONESHOT | EventFlag::EV_ADD, + FilterFlag::NOTE_CHILD | FilterFlag::NOTE_EXIT, + 0x1337, + udata, + ); + assert_eq!(EventFilter::EVFILT_READ, actual.filter().unwrap()); +} diff --git a/test/test_resource.rs b/test/sys/test_resource.rs similarity index 56% rename from test/test_resource.rs rename to test/sys/test_resource.rs index beae01c4c8..8b12a9495b 100644 --- a/test/test_resource.rs +++ b/test/sys/test_resource.rs @@ -1,10 +1,5 @@ -#[cfg(not(any( - target_os = "redox", - target_os = "fuchsia", - solarish, - target_os = "haiku" -)))] use nix::sys::resource::{getrlimit, setrlimit, Resource}; +use nix::sys::resource::{getrusage, UsageWho}; /// Tests the RLIMIT_NOFILE functionality of getrlimit(), where the resource RLIMIT_NOFILE refers /// to the maximum file descriptor number that can be opened by the process (aka the maximum number @@ -15,12 +10,6 @@ use nix::sys::resource::{getrlimit, setrlimit, Resource}; /// to put the new soft limit in effect, and then getrlimit() once more to ensure the limits have /// been updated. #[test] -#[cfg(not(any( - target_os = "redox", - target_os = "fuchsia", - solarish, - target_os = "haiku" -)))] pub fn test_resource_limits_nofile() { let (mut soft_limit, hard_limit) = getrlimit(Resource::RLIMIT_NOFILE).unwrap(); @@ -32,3 +21,23 @@ pub fn test_resource_limits_nofile() { let (new_soft_limit, _) = getrlimit(Resource::RLIMIT_NOFILE).unwrap(); assert_eq!(new_soft_limit, soft_limit); } + +#[test] +pub fn test_self_cpu_time() { + // Make sure some CPU time is used. + let mut numbers: Vec = (1..1_000_000).collect(); + numbers.iter_mut().for_each(|item| *item *= 2); + + // FIXME: this is here to help ensure the compiler does not optimize the whole + // thing away. Replace the assert with test::black_box once stabilized. + assert_eq!(numbers[100..200].iter().sum::(), 30_100); + + let usage = getrusage(UsageWho::RUSAGE_SELF) + .expect("Failed to call getrusage for SELF"); + let rusage = usage.as_ref(); + + let user = usage.user_time(); + assert!(user.tv_sec() > 0 || user.tv_usec() > 0); + assert_eq!(user.tv_sec(), rusage.ru_utime.tv_sec); + assert_eq!(user.tv_usec(), rusage.ru_utime.tv_usec); +} diff --git a/test/sys/test_select.rs b/test/sys/test_select.rs index 111e444d49..746c6b6966 100644 --- a/test/sys/test_select.rs +++ b/test/sys/test_select.rs @@ -1,8 +1,8 @@ use nix::sys::select::*; use nix::sys::signal::SigSet; -use nix::sys::time::{TimeSpec, TimeValLike}; +use nix::sys::time::{TimeSpec, TimeVal, TimeValLike}; use nix::unistd::{pipe, write}; -use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd}; +use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, RawFd}; #[test] pub fn test_pselect() { @@ -76,3 +76,219 @@ mod test_fdset_too_large_fd { contains, ); } + +#[test] +fn fdset_insert() { + let mut fd_set = FdSet::new(); + + for i in 0..FD_SETSIZE { + let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; + assert!(!fd_set.contains(borrowed_i)); + } + + let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; + fd_set.insert(fd_seven); + + assert!(fd_set.contains(fd_seven)); +} + +#[test] +fn fdset_remove() { + let mut fd_set = FdSet::new(); + + for i in 0..FD_SETSIZE { + let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; + assert!(!fd_set.contains(borrowed_i)); + } + + let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; + fd_set.insert(fd_seven); + fd_set.remove(fd_seven); + + for i in 0..FD_SETSIZE { + let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; + assert!(!fd_set.contains(borrowed_i)); + } +} + +#[test] +#[allow(non_snake_case)] +fn fdset_clear() { + let mut fd_set = FdSet::new(); + let fd_one = unsafe { BorrowedFd::borrow_raw(1) }; + let fd_FD_SETSIZE_divided_by_two = + unsafe { BorrowedFd::borrow_raw((FD_SETSIZE / 2) as RawFd) }; + let fd_FD_SETSIZE_minus_one = + unsafe { BorrowedFd::borrow_raw((FD_SETSIZE - 1) as RawFd) }; + fd_set.insert(fd_one); + fd_set.insert(fd_FD_SETSIZE_divided_by_two); + fd_set.insert(fd_FD_SETSIZE_minus_one); + + fd_set.clear(); + + for i in 0..FD_SETSIZE { + let borrowed_i = unsafe { BorrowedFd::borrow_raw(i as RawFd) }; + assert!(!fd_set.contains(borrowed_i)); + } +} + +#[test] +fn fdset_highest() { + let mut set = FdSet::new(); + assert_eq!( + set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), + None + ); + let fd_zero = unsafe { BorrowedFd::borrow_raw(0) }; + let fd_ninety = unsafe { BorrowedFd::borrow_raw(90) }; + set.insert(fd_zero); + assert_eq!( + set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), + Some(0) + ); + set.insert(fd_ninety); + assert_eq!( + set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), + Some(90) + ); + set.remove(fd_zero); + assert_eq!( + set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), + Some(90) + ); + set.remove(fd_ninety); + assert_eq!( + set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), + None + ); + + let fd_four = unsafe { BorrowedFd::borrow_raw(4) }; + let fd_five = unsafe { BorrowedFd::borrow_raw(5) }; + let fd_seven = unsafe { BorrowedFd::borrow_raw(7) }; + set.insert(fd_four); + set.insert(fd_five); + set.insert(fd_seven); + assert_eq!( + set.highest().map(|borrowed_fd| borrowed_fd.as_raw_fd()), + Some(7) + ); +} + +#[test] +fn fdset_fds() { + let mut set = FdSet::new(); + let fd_zero = unsafe { BorrowedFd::borrow_raw(0) }; + let fd_ninety = unsafe { BorrowedFd::borrow_raw(90) }; + assert_eq!( + set.fds(None) + .map(|borrowed_fd| borrowed_fd.as_raw_fd()) + .collect::>(), + vec![] + ); + set.insert(fd_zero); + assert_eq!( + set.fds(None) + .map(|borrowed_fd| borrowed_fd.as_raw_fd()) + .collect::>(), + vec![0] + ); + set.insert(fd_ninety); + assert_eq!( + set.fds(None) + .map(|borrowed_fd| borrowed_fd.as_raw_fd()) + .collect::>(), + vec![0, 90] + ); + + // highest limit + assert_eq!( + set.fds(Some(89)) + .map(|borrowed_fd| borrowed_fd.as_raw_fd()) + .collect::>(), + vec![0] + ); + assert_eq!( + set.fds(Some(90)) + .map(|borrowed_fd| borrowed_fd.as_raw_fd()) + .collect::>(), + vec![0, 90] + ); +} + +#[test] +fn test_select() { + let (r1, w1) = pipe().unwrap(); + let (r2, _w2) = pipe().unwrap(); + + write(&w1, b"hi!").unwrap(); + let mut fd_set = FdSet::new(); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); + + let mut timeout = TimeVal::seconds(10); + assert_eq!( + 1, + select(None, &mut fd_set, None, None, &mut timeout).unwrap() + ); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); +} + +#[test] +fn test_select_nfds() { + let (r1, w1) = pipe().unwrap(); + let (r2, _w2) = pipe().unwrap(); + + write(&w1, b"hi!").unwrap(); + let mut fd_set = FdSet::new(); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); + + let mut timeout = TimeVal::seconds(10); + { + assert_eq!( + 1, + select( + Some( + fd_set + .highest() + .map(|borrowed_fd| borrowed_fd.as_raw_fd()) + .unwrap() + + 1 + ), + &mut fd_set, + None, + None, + &mut timeout + ) + .unwrap() + ); + } + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); +} + +#[test] +fn test_select_nfds2() { + let (r1, w1) = pipe().unwrap(); + write(&w1, b"hi!").unwrap(); + let (r2, _w2) = pipe().unwrap(); + let mut fd_set = FdSet::new(); + fd_set.insert(r1.as_fd()); + fd_set.insert(r2.as_fd()); + + let mut timeout = TimeVal::seconds(10); + assert_eq!( + 1, + select( + std::cmp::max(r1.as_raw_fd(), r2.as_raw_fd()) + 1, + &mut fd_set, + None, + None, + &mut timeout + ) + .unwrap() + ); + assert!(fd_set.contains(r1.as_fd())); + assert!(!fd_set.contains(r2.as_fd())); +} diff --git a/test/sys/test_signal.rs b/test/sys/test_signal.rs index bf201ab800..eb6347d5b0 100644 --- a/test/sys/test_signal.rs +++ b/test/sys/test_signal.rs @@ -1,9 +1,11 @@ -#[cfg(not(target_os = "redox"))] use nix::errno::Errno; use nix::sys::signal::*; use nix::unistd::*; use std::convert::TryFrom; +use std::hash::{Hash, Hasher}; use std::sync::atomic::{AtomicBool, Ordering}; +#[cfg(not(target_os = "redox"))] +use std::thread; #[test] fn test_kill_none() { @@ -141,3 +143,263 @@ fn test_signal() { // Restore default signal handler unsafe { signal(Signal::SIGINT, SigHandler::SigDfl) }.unwrap(); } + +#[test] +fn test_contains() { + let mut mask = SigSet::empty(); + mask.add(SIGUSR1); + + assert!(mask.contains(SIGUSR1)); + assert!(!mask.contains(SIGUSR2)); + + let all = SigSet::all(); + assert!(all.contains(SIGUSR1)); + assert!(all.contains(SIGUSR2)); +} + +#[test] +fn test_clear() { + let mut set = SigSet::all(); + set.clear(); + for signal in Signal::iterator() { + assert!(!set.contains(signal)); + } +} + +#[test] +fn test_from_str_round_trips() { + for signal in Signal::iterator() { + assert_eq!(signal.as_ref().parse::().unwrap(), signal); + assert_eq!(signal.to_string().parse::().unwrap(), signal); + } +} + +#[test] +fn test_from_str_invalid_value() { + let errval = Err(Errno::EINVAL); + assert_eq!("NOSIGNAL".parse::(), errval); + assert_eq!("kill".parse::(), errval); + assert_eq!("9".parse::(), errval); +} + +#[test] +fn test_extend() { + let mut one_signal = SigSet::empty(); + one_signal.add(SIGUSR1); + + let mut two_signals = SigSet::empty(); + two_signals.add(SIGUSR2); + two_signals.extend(&one_signal); + + assert!(two_signals.contains(SIGUSR1)); + assert!(two_signals.contains(SIGUSR2)); +} + +#[test] +#[cfg(not(target_os = "redox"))] +fn test_thread_signal_set_mask() { + thread::spawn(|| { + let prev_mask = SigSet::thread_get_mask() + .expect("Failed to get existing signal mask!"); + + let mut test_mask = prev_mask; + test_mask.add(SIGUSR1); + + test_mask.thread_set_mask().expect("assertion failed"); + let new_mask = + SigSet::thread_get_mask().expect("Failed to get new mask!"); + + assert!(new_mask.contains(SIGUSR1)); + assert!(!new_mask.contains(SIGUSR2)); + + prev_mask + .thread_set_mask() + .expect("Failed to revert signal mask!"); + }) + .join() + .unwrap(); +} + +#[test] +#[cfg(not(target_os = "redox"))] +fn test_thread_signal_block() { + thread::spawn(|| { + let mut mask = SigSet::empty(); + mask.add(SIGUSR1); + + mask.thread_block().expect("assertion failed"); + + assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); + }) + .join() + .unwrap(); +} + +#[test] +#[cfg(not(target_os = "redox"))] +fn test_thread_signal_unblock() { + thread::spawn(|| { + let mut mask = SigSet::empty(); + mask.add(SIGUSR1); + + mask.thread_unblock().expect("assertion failed"); + + assert!(!SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); + }) + .join() + .unwrap(); +} + +#[test] +#[cfg(not(target_os = "redox"))] +fn test_thread_signal_swap() { + thread::spawn(|| { + let mut mask = SigSet::empty(); + mask.add(SIGUSR1); + mask.thread_block().unwrap(); + + assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR1)); + + let mut mask2 = SigSet::empty(); + mask2.add(SIGUSR2); + + let oldmask = mask2.thread_swap_mask(SigmaskHow::SIG_SETMASK).unwrap(); + + assert!(oldmask.contains(SIGUSR1)); + assert!(!oldmask.contains(SIGUSR2)); + + assert!(SigSet::thread_get_mask().unwrap().contains(SIGUSR2)); + }) + .join() + .unwrap(); +} + +#[test] +fn test_from_and_into_iterator() { + let sigset = SigSet::from_iter(vec![Signal::SIGUSR1, Signal::SIGUSR2]); + let signals = sigset.into_iter().collect::>(); + assert_eq!(signals, [Signal::SIGUSR1, Signal::SIGUSR2]); +} + +#[test] +#[cfg(not(target_os = "redox"))] +fn test_sigaction() { + thread::spawn(|| { + extern "C" fn test_sigaction_handler(_: libc::c_int) {} + extern "C" fn test_sigaction_action( + _: libc::c_int, + _: *mut libc::siginfo_t, + _: *mut libc::c_void, + ) { + } + + let handler_sig = SigHandler::Handler(test_sigaction_handler); + + let flags = + SaFlags::SA_ONSTACK | SaFlags::SA_RESTART | SaFlags::SA_SIGINFO; + + let mut mask = SigSet::empty(); + mask.add(SIGUSR1); + + let action_sig = SigAction::new(handler_sig, flags, mask); + + assert_eq!( + action_sig.flags(), + SaFlags::SA_ONSTACK | SaFlags::SA_RESTART + ); + assert_eq!(action_sig.handler(), handler_sig); + + mask = action_sig.mask(); + assert!(mask.contains(SIGUSR1)); + assert!(!mask.contains(SIGUSR2)); + + let handler_act = SigHandler::SigAction(test_sigaction_action); + let action_act = SigAction::new(handler_act, flags, mask); + assert_eq!(action_act.handler(), handler_act); + + let action_dfl = SigAction::new(SigHandler::SigDfl, flags, mask); + assert_eq!(action_dfl.handler(), SigHandler::SigDfl); + + let action_ign = SigAction::new(SigHandler::SigIgn, flags, mask); + assert_eq!(action_ign.handler(), SigHandler::SigIgn); + }) + .join() + .unwrap(); +} + +#[test] +#[cfg(not(target_os = "redox"))] +fn test_sigwait() { + thread::spawn(|| { + let mut mask = SigSet::empty(); + mask.add(SIGUSR1); + mask.add(SIGUSR2); + mask.thread_block().unwrap(); + + raise(SIGUSR1).unwrap(); + assert_eq!(mask.wait().unwrap(), SIGUSR1); + }) + .join() + .unwrap(); +} + +#[test] +fn test_from_sigset_t_unchecked() { + let src_set = SigSet::empty(); + let set = unsafe { SigSet::from_sigset_t_unchecked(*src_set.as_ref()) }; + + for signal in Signal::iterator() { + assert!(!set.contains(signal)); + } + + let src_set = SigSet::all(); + let set = unsafe { SigSet::from_sigset_t_unchecked(*src_set.as_ref()) }; + + for signal in Signal::iterator() { + assert!(set.contains(signal)); + } +} + +#[test] +fn test_eq_empty() { + let set0 = SigSet::empty(); + let set1 = SigSet::empty(); + assert_eq!(set0, set1); +} + +#[test] +fn test_eq_all() { + let set0 = SigSet::all(); + let set1 = SigSet::all(); + assert_eq!(set0, set1); +} + +#[test] +fn test_hash_empty() { + use std::collections::hash_map::DefaultHasher; + + let set0 = SigSet::empty(); + let mut h0 = DefaultHasher::new(); + set0.hash(&mut h0); + + let set1 = SigSet::empty(); + let mut h1 = DefaultHasher::new(); + set1.hash(&mut h1); + + assert_eq!(h0.finish(), h1.finish()); +} + +#[test] +fn test_hash_all() { + use std::collections::hash_map::DefaultHasher; + + let set0 = SigSet::all(); + let mut h0 = DefaultHasher::new(); + set0.hash(&mut h0); + + let set1 = SigSet::all(); + let mut h1 = DefaultHasher::new(); + set1.hash(&mut h1); + + assert_eq!(h0.finish(), h1.finish()); +} diff --git a/test/sys/test_signalfd.rs b/test/sys/test_signalfd.rs index 6a279d1832..4e0971aba7 100644 --- a/test/sys/test_signalfd.rs +++ b/test/sys/test_signalfd.rs @@ -1,5 +1,39 @@ use std::convert::TryFrom; +#[test] +fn create_signalfd() { + use nix::sys::{signal::SigSet, signalfd::SignalFd}; + + let mask = SigSet::empty(); + SignalFd::new(&mask).unwrap(); +} + +#[test] +fn create_signalfd_with_opts() { + use nix::sys::{ + signal::SigSet, + signalfd::{SfdFlags, SignalFd}, + }; + + let mask = SigSet::empty(); + SignalFd::with_flags(&mask, SfdFlags::SFD_CLOEXEC | SfdFlags::SFD_NONBLOCK) + .unwrap(); +} + +#[test] +fn read_empty_signalfd() { + use nix::sys::{ + signal::SigSet, + signalfd::{SfdFlags, SignalFd}, + }; + + let mask = SigSet::empty(); + let mut fd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap(); + + let res = fd.read_signal(); + assert!(res.unwrap().is_none()); +} + #[test] fn test_signalfd() { use nix::sys::signal::{self, raise, SigSet, Signal}; diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 736fae1937..504ad44fde 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -2791,3 +2791,127 @@ fn test_icmp_protocol() { sendto(owned_fd.as_raw_fd(), &packet, &dest_addr, MsgFlags::empty()) .unwrap(); } + +// test contains both recvmmsg and timestaping which is linux only +// there are existing tests for recvmmsg only in tests/ +#[cfg_attr(qemu, ignore)] +#[cfg(target_os = "linux")] +#[test] +fn test_recvmm2() -> nix::Result<()> { + use nix::sys::{ + socket::{ + bind, recvmmsg, sendmsg, setsockopt, socket, sockopt::Timestamping, + AddressFamily, ControlMessageOwned, MsgFlags, MultiHeaders, + SockFlag, SockType, SockaddrIn, TimestampingFlag, Timestamps, + }, + time::TimeSpec, + }; + use std::io::{IoSlice, IoSliceMut}; + use std::os::unix::io::AsRawFd; + use std::str::FromStr; + + let sock_addr = SockaddrIn::from_str("127.0.0.1:6790").unwrap(); + + let ssock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + )?; + + let rsock = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::SOCK_NONBLOCK, + None, + )?; + + bind(rsock.as_raw_fd(), &sock_addr)?; + + setsockopt(&rsock, Timestamping, &TimestampingFlag::all())?; + + let sbuf = (0..400).map(|i| i as u8).collect::>(); + + let mut recv_buf = vec![0; 1024]; + + let mut recv_iovs = Vec::new(); + let mut pkt_iovs = Vec::new(); + + for (ix, chunk) in recv_buf.chunks_mut(256).enumerate() { + pkt_iovs.push(IoSliceMut::new(chunk)); + if ix % 2 == 1 { + recv_iovs.push(pkt_iovs); + pkt_iovs = Vec::new(); + } + } + drop(pkt_iovs); + + let flags = MsgFlags::empty(); + let iov1 = [IoSlice::new(&sbuf)]; + + let cmsg = cmsg_space!(Timestamps); + sendmsg(ssock.as_raw_fd(), &iov1, &[], flags, Some(&sock_addr)).unwrap(); + + let mut data = MultiHeaders::<()>::preallocate(recv_iovs.len(), Some(cmsg)); + + let t = TimeSpec::from_duration(std::time::Duration::from_secs(10)); + + let recv = recvmmsg( + rsock.as_raw_fd(), + &mut data, + recv_iovs.iter_mut(), + flags, + Some(t), + )?; + + for rmsg in recv { + #[cfg(not(any(qemu, target_arch = "aarch64")))] + let mut saw_time = false; + let mut recvd = 0; + for cmsg in rmsg.cmsgs() { + if let ControlMessageOwned::ScmTimestampsns(timestamps) = cmsg { + let ts = timestamps.system; + + let sys_time = nix::time::clock_gettime( + nix::time::ClockId::CLOCK_REALTIME, + )?; + let diff = if ts > sys_time { + ts - sys_time + } else { + sys_time - ts + }; + assert!(std::time::Duration::from(diff).as_secs() < 60); + #[cfg(not(any(qemu, target_arch = "aarch64")))] + { + saw_time = true; + } + } + } + + #[cfg(not(any(qemu, target_arch = "aarch64")))] + assert!(saw_time); + + for iov in rmsg.iovs() { + recvd += iov.len(); + } + assert_eq!(recvd, 400); + } + + Ok(()) +} + +#[cfg(not(target_os = "redox"))] +#[test] +fn can_use_cmsg_space() { + let _ = cmsg_space!(u8); +} + +#[cfg(not(any(linux_android, target_os = "redox", target_os = "haiku")))] +#[test] +fn can_open_routing_socket() { + use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType}; + + let _ = + socket(AddressFamily::Route, SockType::Raw, SockFlag::empty(), None) + .expect("Failed to open routing socket"); +} diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index d7e00e3b1b..876df7a56d 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -636,3 +636,74 @@ fn test_tcp_fast_open_connect() { "getting TCP_FASTOPEN_CONNECT on an inet stream socket should succeed", )); } + +#[cfg(linux_android)] +#[test] +fn can_get_peercred_on_unix_socket() { + use nix::sys::socket::{socketpair, sockopt, SockFlag, SockType}; + + let (a, b) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); + let a_cred = getsockopt(&a, sockopt::PeerCredentials).unwrap(); + let b_cred = getsockopt(&b, sockopt::PeerCredentials).unwrap(); + assert_eq!(a_cred, b_cred); + assert_ne!(a_cred.pid(), 0); +} + +#[test] +fn is_socket_type_unix() { + use nix::sys::socket::{socketpair, sockopt, SockFlag, SockType}; + + let (a, _b) = socketpair( + AddressFamily::Unix, + SockType::Stream, + None, + SockFlag::empty(), + ) + .unwrap(); + let a_type = getsockopt(&a, sockopt::SockType).unwrap(); + assert_eq!(a_type, SockType::Stream); +} + +#[test] +fn is_socket_type_dgram() { + use nix::sys::socket::{ + getsockopt, sockopt, AddressFamily, SockFlag, SockType, + }; + + let s = socket( + AddressFamily::Inet, + SockType::Datagram, + SockFlag::empty(), + None, + ) + .unwrap(); + let s_type = getsockopt(&s, sockopt::SockType).unwrap(); + assert_eq!(s_type, SockType::Datagram); +} + +#[cfg(any(target_os = "freebsd", target_os = "linux"))] +#[test] +fn can_get_listen_on_tcp_socket() { + use nix::sys::socket::{ + getsockopt, listen, socket, sockopt, AddressFamily, SockFlag, SockType, + }; + + let s = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + None, + ) + .unwrap(); + let s_listening = getsockopt(&s, sockopt::AcceptConn).unwrap(); + assert!(!s_listening); + listen(&s, 10).unwrap(); + let s_listening2 = getsockopt(&s, sockopt::AcceptConn).unwrap(); + assert!(s_listening2); +} diff --git a/test/sys/test_statfs.rs b/test/sys/test_statfs.rs new file mode 100644 index 0000000000..66b3f2ce96 --- /dev/null +++ b/test/sys/test_statfs.rs @@ -0,0 +1,99 @@ +use nix::sys::statfs::*; +use nix::sys::statvfs::*; +use std::fs::File; +use std::path::Path; + +fn check_fstatfs(path: &str) { + if !Path::new(path).exists() { + return; + } + let vfs = statvfs(path.as_bytes()).unwrap(); + let file = File::open(path).unwrap(); + let fs = fstatfs(&file).unwrap(); + assert_fs_equals(fs, vfs); +} + +fn check_statfs(path: &str) { + if !Path::new(path).exists() { + return; + } + let vfs = statvfs(path.as_bytes()).unwrap(); + let fs = statfs(path.as_bytes()).unwrap(); + assert_fs_equals(fs, vfs); +} + +fn check_fstatfs_strict(path: &str) { + if !Path::new(path).exists() { + return; + } + let vfs = statvfs(path.as_bytes()); + let file = File::open(path).unwrap(); + let fs = fstatfs(&file); + assert_fs_equals_strict(fs.unwrap(), vfs.unwrap()) +} + +fn check_statfs_strict(path: &str) { + if !Path::new(path).exists() { + return; + } + let vfs = statvfs(path.as_bytes()); + let fs = statfs(path.as_bytes()); + assert_fs_equals_strict(fs.unwrap(), vfs.unwrap()) +} + +// The cast is not unnecessary on all platforms. +#[allow(clippy::unnecessary_cast)] +fn assert_fs_equals(fs: Statfs, vfs: Statvfs) { + assert_eq!(fs.files() as u64, vfs.files() as u64); + assert_eq!(fs.blocks() as u64, vfs.blocks() as u64); + assert_eq!(fs.block_size() as u64, vfs.fragment_size() as u64); +} + +#[test] +fn statfs_call() { + check_statfs("/tmp"); + check_statfs("/dev"); + check_statfs("/run"); + check_statfs("/"); +} + +#[test] +fn fstatfs_call() { + check_fstatfs("/tmp"); + check_fstatfs("/dev"); + check_fstatfs("/run"); + check_fstatfs("/"); +} + +// This test is ignored because files_free/blocks_free can change after statvfs call and before +// statfs call. +#[test] +#[ignore] +fn statfs_call_strict() { + check_statfs_strict("/tmp"); + check_statfs_strict("/dev"); + check_statfs_strict("/run"); + check_statfs_strict("/"); +} + +// This test is ignored because files_free/blocks_free can change after statvfs call and before +// fstatfs call. +#[test] +#[ignore] +fn fstatfs_call_strict() { + check_fstatfs_strict("/tmp"); + check_fstatfs_strict("/dev"); + check_fstatfs_strict("/run"); + check_fstatfs_strict("/"); +} + +// The cast is not unnecessary on all platforms. +#[allow(clippy::unnecessary_cast)] +fn assert_fs_equals_strict(fs: Statfs, vfs: Statvfs) { + assert_eq!(fs.files_free() as u64, vfs.files_free() as u64); + assert_eq!(fs.blocks_free() as u64, vfs.blocks_free() as u64); + assert_eq!(fs.blocks_available() as u64, vfs.blocks_available() as u64); + assert_eq!(fs.files() as u64, vfs.files() as u64); + assert_eq!(fs.blocks() as u64, vfs.blocks() as u64); + assert_eq!(fs.block_size() as u64, vfs.fragment_size() as u64); +} diff --git a/test/sys/test_statvfs.rs b/test/sys/test_statvfs.rs new file mode 100644 index 0000000000..5c80965253 --- /dev/null +++ b/test/sys/test_statvfs.rs @@ -0,0 +1,13 @@ +use nix::sys::statvfs::*; +use std::fs::File; + +#[test] +fn statvfs_call() { + statvfs(&b"/"[..]).unwrap(); +} + +#[test] +fn fstatvfs_call() { + let root = File::open("/").unwrap(); + fstatvfs(&root).unwrap(); +} diff --git a/test/sys/test_termios.rs b/test/sys/test_termios.rs index 21bb8c61ef..72399cf6a5 100644 --- a/test/sys/test_termios.rs +++ b/test/sys/test_termios.rs @@ -1,10 +1,11 @@ +use std::convert::TryFrom; use std::os::unix::io::{AsFd, AsRawFd}; use tempfile::tempfile; use nix::errno::Errno; use nix::fcntl; use nix::pty::openpty; -use nix::sys::termios::{self, tcgetattr, LocalFlags, OutputFlags}; +use nix::sys::termios::{self, tcgetattr, BaudRate, LocalFlags, OutputFlags}; use nix::unistd::{read, write}; /// Helper function analogous to `std::io::Write::write_all`, but for `Fd`s @@ -15,6 +16,15 @@ fn write_all(f: Fd, buf: &[u8]) { } } +#[test] +fn test_baudrate_try_from() { + assert_eq!(Ok(BaudRate::B0), BaudRate::try_from(libc::B0)); + #[cfg(not(target_os = "haiku"))] + BaudRate::try_from(999999999).expect_err("assertion failed"); + #[cfg(target_os = "haiku")] + BaudRate::try_from(99).expect_err("assertion failed"); +} + // Test tcgetattr on a terminal #[test] fn test_tcgetattr_pty() { diff --git a/test/sys/test_time.rs b/test/sys/test_time.rs new file mode 100644 index 0000000000..0510225a92 --- /dev/null +++ b/test/sys/test_time.rs @@ -0,0 +1,91 @@ +use nix::sys::time::{TimeSpec, TimeVal, TimeValLike}; +use std::time::Duration; + +#[test] +pub fn test_timespec() { + assert_ne!(TimeSpec::seconds(1), TimeSpec::zero()); + assert_eq!( + TimeSpec::seconds(1) + TimeSpec::seconds(2), + TimeSpec::seconds(3) + ); + assert_eq!( + TimeSpec::minutes(3) + TimeSpec::seconds(2), + TimeSpec::seconds(182) + ); +} + +#[test] +pub fn test_timespec_from() { + let duration = Duration::new(123, 123_456_789); + let timespec = TimeSpec::nanoseconds(123_123_456_789); + + assert_eq!(TimeSpec::from(duration), timespec); + assert_eq!(Duration::from(timespec), duration); +} + +#[test] +pub fn test_timespec_neg() { + let a = TimeSpec::seconds(1) + TimeSpec::nanoseconds(123); + let b = TimeSpec::seconds(-1) + TimeSpec::nanoseconds(-123); + + assert_eq!(a, -b); +} + +#[test] +pub fn test_timespec_ord() { + assert_eq!(TimeSpec::seconds(1), TimeSpec::nanoseconds(1_000_000_000)); + assert!(TimeSpec::seconds(1) < TimeSpec::nanoseconds(1_000_000_001)); + assert!(TimeSpec::seconds(1) > TimeSpec::nanoseconds(999_999_999)); + assert!(TimeSpec::seconds(-1) < TimeSpec::nanoseconds(-999_999_999)); + assert!(TimeSpec::seconds(-1) > TimeSpec::nanoseconds(-1_000_000_001)); +} + +#[test] +pub fn test_timespec_fmt() { + assert_eq!(TimeSpec::zero().to_string(), "0 seconds"); + assert_eq!(TimeSpec::seconds(42).to_string(), "42 seconds"); + assert_eq!(TimeSpec::milliseconds(42).to_string(), "0.042 seconds"); + assert_eq!(TimeSpec::microseconds(42).to_string(), "0.000042 seconds"); + assert_eq!(TimeSpec::nanoseconds(42).to_string(), "0.000000042 seconds"); + assert_eq!(TimeSpec::seconds(-86401).to_string(), "-86401 seconds"); +} + +#[test] +pub fn test_timeval() { + assert_ne!(TimeVal::seconds(1), TimeVal::zero()); + assert_eq!( + TimeVal::seconds(1) + TimeVal::seconds(2), + TimeVal::seconds(3) + ); + assert_eq!( + TimeVal::minutes(3) + TimeVal::seconds(2), + TimeVal::seconds(182) + ); +} + +#[test] +pub fn test_timeval_ord() { + assert_eq!(TimeVal::seconds(1), TimeVal::microseconds(1_000_000)); + assert!(TimeVal::seconds(1) < TimeVal::microseconds(1_000_001)); + assert!(TimeVal::seconds(1) > TimeVal::microseconds(999_999)); + assert!(TimeVal::seconds(-1) < TimeVal::microseconds(-999_999)); + assert!(TimeVal::seconds(-1) > TimeVal::microseconds(-1_000_001)); +} + +#[test] +pub fn test_timeval_neg() { + let a = TimeVal::seconds(1) + TimeVal::microseconds(123); + let b = TimeVal::seconds(-1) + TimeVal::microseconds(-123); + + assert_eq!(a, -b); +} + +#[test] +pub fn test_timeval_fmt() { + assert_eq!(TimeVal::zero().to_string(), "0 seconds"); + assert_eq!(TimeVal::seconds(42).to_string(), "42 seconds"); + assert_eq!(TimeVal::milliseconds(42).to_string(), "0.042 seconds"); + assert_eq!(TimeVal::microseconds(42).to_string(), "0.000042 seconds"); + assert_eq!(TimeVal::nanoseconds(1402).to_string(), "0.000001 seconds"); + assert_eq!(TimeVal::seconds(-86401).to_string(), "-86401 seconds"); +} diff --git a/test/test_timer.rs b/test/sys/test_timer.rs similarity index 100% rename from test/test_timer.rs rename to test/sys/test_timer.rs diff --git a/test/sys/test_utsname.rs b/test/sys/test_utsname.rs new file mode 100644 index 0000000000..8f84ac074f --- /dev/null +++ b/test/sys/test_utsname.rs @@ -0,0 +1,17 @@ +#[cfg(target_os = "linux")] +#[test] +pub fn test_uname_linux() { + assert_eq!(nix::sys::utsname::uname().unwrap().sysname(), "Linux"); +} + +#[cfg(apple_targets)] +#[test] +pub fn test_uname_darwin() { + assert_eq!(nix::sys::utsname::uname().unwrap().sysname(), "Darwin"); +} + +#[cfg(target_os = "freebsd")] +#[test] +pub fn test_uname_freebsd() { + assert_eq!(nix::sys::utsname::uname().unwrap().sysname(), "FreeBSD"); +} diff --git a/test/test.rs b/test/test.rs index fc6b4b3e32..205ae3329c 100644 --- a/test/test.rs +++ b/test/test.rs @@ -29,7 +29,6 @@ mod test_poll; target_os = "haiku" )))] mod test_pty; -mod test_resource; #[cfg(any( linux_android, target_os = "dragonfly", @@ -40,17 +39,6 @@ mod test_sched; mod test_sendfile; mod test_stat; mod test_time; -#[cfg(all( - any( - target_os = "freebsd", - solarish, - target_os = "linux", - target_os = "netbsd" - ), - feature = "time", - feature = "signal" -))] -mod test_timer; mod test_unistd; use nix::unistd::{chdir, getcwd, read}; From 88c73492f616f15fd4135849f0a692f6a9651071 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Tue, 12 Dec 2023 06:29:46 +0800 Subject: [PATCH 100/140] docs: add hurd to tier 3 in README (#2256) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 157b8da120..fb9f84ca44 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,7 @@ The following targets are supported by `nix`:
  • x86_64-unknown-linux-gnux32
  • x86_64-unknown-openbsd
  • x86_64-unknown-redox
  • +
  • i686-unknown-hurd-gnu
  • From 7c3d84beb73bc77421415de7ac091f1a2a08adce Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Thu, 14 Dec 2023 17:33:57 -0700 Subject: [PATCH 101/140] Use the latest libc release (#2265) It looks like the libc team cut a release just after @devnexen's last PR. Switch to it. That makes it easier for downstream crates to use a git dependency on Nix. --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 38fc390087..bde93fcdde 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { git = "https://github.com/rust-lang/libc", rev = "f37806e499409eab8cfa897280a869bc5e2623a9", features = ["extra_traits"] } +libc = { version = "0.2.151", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } From 510237616459d390ec4f20a2ba00a1adefa8f986 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Fri, 15 Dec 2023 20:59:07 -0700 Subject: [PATCH 102/140] Add the ListenQLimit sockopt (SO_LISTENQLIMIT) (#2263) --- changelog/2263.added.md | 1 + src/sys/socket/sockopt.rs | 11 +++++++++++ test/sys/test_sockopt.rs | 25 +++++++++++++++++++++++++ 3 files changed, 37 insertions(+) create mode 100644 changelog/2263.added.md diff --git a/changelog/2263.added.md b/changelog/2263.added.md new file mode 100644 index 0000000000..9c343b6ab1 --- /dev/null +++ b/changelog/2263.added.md @@ -0,0 +1 @@ +Added the `SO_LISTENQLIMIT` sockopt. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 6ce57c6f96..01a0c2c625 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -522,6 +522,17 @@ sockopt_impl!( libc::SO_PEERCRED, super::UnixCredentials ); +#[cfg(target_os = "freebsd")] +#[cfg(feature = "net")] +sockopt_impl!( + #[cfg_attr(docsrs, doc(cfg(feature = "net")))] + /// Get backlog limit of the socket + ListenQLimit, + GetOnly, + libc::SOL_SOCKET, + libc::SO_LISTENQLIMIT, + u32 +); #[cfg(apple_targets)] #[cfg(feature = "net")] sockopt_impl!( diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 876df7a56d..5c58c2c828 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -103,6 +103,31 @@ fn test_so_buf() { assert!(actual >= bufsize); } +#[cfg(target_os = "freebsd")] +#[test] +fn test_so_listen_q_limit() { + use nix::sys::socket::{bind, listen, SockaddrIn}; + use std::net::SocketAddrV4; + use std::str::FromStr; + + let std_sa = SocketAddrV4::from_str("127.0.0.1:4004").unwrap(); + let sock_addr = SockaddrIn::from(std_sa); + + let rsock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); + let pre_limit = getsockopt(&rsock, sockopt::ListenQLimit).unwrap(); + assert_eq!(pre_limit, 0); + listen(&rsock, 42).unwrap(); + let post_limit = getsockopt(&rsock, sockopt::ListenQLimit).unwrap(); + assert_eq!(post_limit, 42); +} + #[test] fn test_so_tcp_maxseg() { use nix::sys::socket::{accept, bind, connect, listen, SockaddrIn}; From b9b40776fec109037733231ad62844016ed83b1e Mon Sep 17 00:00:00 2001 From: "lauren n. liberda" Date: Sat, 16 Dec 2023 07:16:56 +0100 Subject: [PATCH 103/140] statfs: fixes for s390x+musl (#1835) --- src/sys/statfs.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index d4335cf388..c3f7388a4d 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -51,7 +51,7 @@ pub struct Statfs(type_of_statfs); type fs_type_t = u32; #[cfg(target_os = "android")] type fs_type_t = libc::c_ulong; -#[cfg(all(target_os = "linux", target_arch = "s390x"))] +#[cfg(all(target_os = "linux", target_arch = "s390x", not(target_env = "musl")))] type fs_type_t = libc::c_uint; #[cfg(all(target_os = "linux", target_env = "musl"))] type fs_type_t = libc::c_ulong; @@ -314,7 +314,7 @@ impl Statfs { } /// Optimal transfer block size - #[cfg(all(target_os = "linux", target_arch = "s390x"))] + #[cfg(all(target_os = "linux", target_arch = "s390x", not(target_env = "musl")))] pub fn optimal_transfer_size(&self) -> u32 { self.0.f_bsize } @@ -367,7 +367,7 @@ impl Statfs { /// Size of a block // f_bsize on linux: https://github.com/torvalds/linux/blob/master/fs/nfs/super.c#L471 - #[cfg(all(target_os = "linux", target_arch = "s390x"))] + #[cfg(all(target_os = "linux", target_arch = "s390x", not(target_env = "musl")))] pub fn block_size(&self) -> u32 { self.0.f_bsize } @@ -440,7 +440,7 @@ impl Statfs { } /// Maximum length of filenames - #[cfg(all(target_os = "linux", target_arch = "s390x"))] + #[cfg(all(target_os = "linux", target_arch = "s390x", not(target_env = "musl")))] pub fn maximum_name_length(&self) -> u32 { self.0.f_namelen } From 172ca24d1956400d23e4cfe472045c872ea472c7 Mon Sep 17 00:00:00 2001 From: Louis Date: Mon, 18 Dec 2023 09:31:01 +0200 Subject: [PATCH 104/140] Add mkdtemp (#1297) --- changelog/1297.added.md | 1 + src/unistd.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 changelog/1297.added.md diff --git a/changelog/1297.added.md b/changelog/1297.added.md new file mode 100644 index 0000000000..5e4820101a --- /dev/null +++ b/changelog/1297.added.md @@ -0,0 +1 @@ +Added `mkdtemp` wrapper diff --git a/src/unistd.rs b/src/unistd.rs index 466b769a22..93187a67c5 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1938,6 +1938,38 @@ pub fn mkstemp(template: &P) -> Result<(RawFd, PathBuf)> { feature! { #![all(feature = "fs", feature = "feature")] +/// Creates a directory which persists even after process termination +/// +/// * `template`: a path whose rightmost characters contain some number of X, e.g. `/tmp/tmpdir_XXXXXX` +/// * returns: filename +/// +/// Err is returned either if no temporary filename could be created or the template had insufficient X +/// +/// See also [mkstemp(2)](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mkdtemp.html) +/// +/// ``` +/// use nix::unistd; +/// +/// match unistd::mkdtemp("/tmp/tempdir_XXXXXX") { +/// Ok(_path) => { +/// // do something with directory +/// } +/// Err(e) => panic!("mkdtemp failed: {}", e) +/// }; +/// ``` +pub fn mkdtemp(template: &P) -> Result { + let mut path = template.with_nix_path(|path| {path.to_bytes_with_nul().to_owned()})?; + let p = path.as_mut_ptr() as *mut _; + let p = unsafe { libc::mkdtemp(p) }; + if p.is_null() { + return Err(Errno::last()); + } + let last = path.pop(); // drop the trailing nul + debug_assert!(last == Some(b'\0')); + let pathname = OsString::from_vec(path); + Ok(PathBuf::from(pathname)) +} + /// Variable names for `pathconf` /// /// Nix uses the same naming convention for these variables as the From cc42c028a24223af88dd12e826ebbccfd846c4fe Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Wed, 20 Dec 2023 05:39:53 +0800 Subject: [PATCH 105/140] feat: AT_EMPTY_PATH for FreeBSD/Hurd (#2270) --- changelog/2270.added.md | 1 + src/fcntl.rs | 8 +++++--- 2 files changed, 6 insertions(+), 3 deletions(-) create mode 100644 changelog/2270.added.md diff --git a/changelog/2270.added.md b/changelog/2270.added.md new file mode 100644 index 0000000000..37160bad61 --- /dev/null +++ b/changelog/2270.added.md @@ -0,0 +1 @@ +Add `AtFlags::AT_EMPTY_FLAG` for FreeBSD and Hurd diff --git a/src/fcntl.rs b/src/fcntl.rs index c89b304554..be399db6d2 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -52,7 +52,7 @@ libc_bitflags! { AT_SYMLINK_NOFOLLOW; #[cfg(linux_android)] AT_NO_AUTOMOUNT; - #[cfg(linux_android)] + #[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))] AT_EMPTY_PATH; #[cfg(not(target_os = "android"))] AT_EACCESS; @@ -328,7 +328,7 @@ fn inner_readlink( let reported_size = match dirfd { #[cfg(target_os = "redox")] Some(_) => unreachable!(), - #[cfg(linux_android)] + #[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))] Some(dirfd) => { let flags = if path.is_empty() { AtFlags::AT_EMPTY_PATH @@ -343,7 +343,9 @@ fn inner_readlink( } #[cfg(not(any( linux_android, - target_os = "redox" + target_os = "redox", + target_os = "freebsd", + target_os = "hurd" )))] Some(dirfd) => super::sys::stat::fstatat( Some(dirfd), From 2c6bbc44a531861003b7c97c6e0deb1339e015aa Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 22 Dec 2023 09:22:31 +0800 Subject: [PATCH 106/140] chore: fix wrong changelog of 2270[skip ci] (#2272) --- changelog/2270.added.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog/2270.added.md b/changelog/2270.added.md index 37160bad61..ff0841ef31 100644 --- a/changelog/2270.added.md +++ b/changelog/2270.added.md @@ -1 +1 @@ -Add `AtFlags::AT_EMPTY_FLAG` for FreeBSD and Hurd +Add `AtFlags::AT_EMPTY_PATH` for FreeBSD and Hurd From e73182c441266d13d616a44dc31aa2bff58c44f0 Mon Sep 17 00:00:00 2001 From: Yiming Date: Fri, 22 Dec 2023 22:16:47 -0500 Subject: [PATCH 107/140] fix: typo "fr" (#2274) --- src/sys/stat.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 369008a800..c5854eec01 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -39,7 +39,7 @@ libc_bitflags! { S_IXUSR; /// Read write and execute for group. S_IRWXG; - /// Read fr group. + /// Read for group. S_IRGRP; /// Write for group. S_IWGRP; @@ -454,4 +454,4 @@ pub fn mkdirat( })?; Errno::result(res).map(drop) -} \ No newline at end of file +} From 4e2d917a2a3a97a1b3a70d83563e998dafca4a66 Mon Sep 17 00:00:00 2001 From: Travis Paul Date: Tue, 26 Dec 2023 20:22:02 -0600 Subject: [PATCH 108/140] Enable OFlag::O_DIRECTORY for Solarish (#2275) * No longer omit O_DIRECTORY for Solarish * Add changelog * Change changelog type and message --- changelog/2275.added.md | 1 + src/fcntl.rs | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 changelog/2275.added.md diff --git a/changelog/2275.added.md b/changelog/2275.added.md new file mode 100644 index 0000000000..05a8e46817 --- /dev/null +++ b/changelog/2275.added.md @@ -0,0 +1 @@ +Enable `OFlag::O_DIRECTORY for Solarish diff --git a/src/fcntl.rs b/src/fcntl.rs index be399db6d2..338944fd04 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -96,7 +96,6 @@ libc_bitflags!( ))] O_DIRECT; /// If the specified path isn't a directory, fail. - #[cfg(not(solarish))] O_DIRECTORY; /// Implicitly follow each `write()` with an `fdatasync()`. #[cfg(any(linux_android, apple_targets, netbsdlike))] From d2445bfdc9534967caf374515168679bde9dfa51 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Sat, 30 Dec 2023 09:49:05 +0000 Subject: [PATCH 109/140] sys::socket listen's Backlog wrapper type addition. (#2276) changing the sys::socket::listen backlog type from `usize` to a `i32` wrapper, offering known sane values, from -1/0, to SOMAXCONN. close gh-2264 --- Cargo.toml | 2 +- changelog/2276.added.md | 1 + src/sys/socket/mod.rs | 40 ++++++++++++++++++++++++++++++++++++++-- test/sys/test_socket.rs | 14 ++++++++++++-- test/sys/test_sockopt.rs | 15 +++++++++------ 5 files changed, 61 insertions(+), 11 deletions(-) create mode 100644 changelog/2276.added.md diff --git a/Cargo.toml b/Cargo.toml index bde93fcdde..f428548584 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { version = "0.2.151", features = ["extra_traits"] } +libc = { git = "https://github.com/rust-lang/libc", rev = "6a203e955b60cca48562f020f0e4e003079f3199", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } diff --git a/changelog/2276.added.md b/changelog/2276.added.md new file mode 100644 index 0000000000..9a05cc5ca8 --- /dev/null +++ b/changelog/2276.added.md @@ -0,0 +1 @@ +Added the `Backlog` wrapper type for the `listen` call. diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index dfc37db745..2f7f9815cb 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -2009,12 +2009,48 @@ pub fn socketpair>>( unsafe { Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1]))) } } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Backlog(i32); + +impl Backlog { + /// Sets the listen queue size to system `SOMAXCONN` value + pub const MAXCONN: Self = Self(libc::SOMAXCONN); + /// Sets the listen queue size to -1 for system supporting it + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + pub const MAXALLOWABLE: Self = Self(-1); + + /// Create a `Backlog`, an `EINVAL` will be returned if `val` is invalid. + pub fn new>(val: I) -> Result { + cfg_if! { + if #[cfg(any(target_os = "linux", target_os = "freebsd"))] { + const MIN: i32 = -1; + } else { + const MIN: i32 = 0; + } + } + + let val = val.into(); + + if !(MIN..Self::MAXCONN.0).contains(&val) { + return Err(Errno::EINVAL); + } + + Ok(Self(val)) + } +} + +impl From for i32 { + fn from(backlog: Backlog) -> Self { + backlog.0 + } +} + /// Listen for connections on a socket /// /// [Further reading](https://pubs.opengroup.org/onlinepubs/9699919799/functions/listen.html) -pub fn listen(sock: &F, backlog: usize) -> Result<()> { +pub fn listen(sock: &F, backlog: Backlog) -> Result<()> { let fd = sock.as_fd().as_raw_fd(); - let res = unsafe { libc::listen(fd, backlog as c_int) }; + let res = unsafe { libc::listen(fd, backlog.into()) }; Errno::result(res).map(drop) } diff --git a/test/sys/test_socket.rs b/test/sys/test_socket.rs index 504ad44fde..90b8a6f528 100644 --- a/test/sys/test_socket.rs +++ b/test/sys/test_socket.rs @@ -1611,7 +1611,9 @@ fn test_impl_scm_credentials_and_rights(mut space: Vec) { // Test creating and using named unix domain sockets #[test] pub fn test_named_unixdomain() { - use nix::sys::socket::{accept, bind, connect, listen, socket, UnixAddr}; + use nix::sys::socket::{ + accept, bind, connect, listen, socket, Backlog, UnixAddr, + }; use nix::sys::socket::{SockFlag, SockType}; use nix::unistd::{read, write}; use std::thread; @@ -1627,7 +1629,7 @@ pub fn test_named_unixdomain() { .expect("socket failed"); let sockaddr = UnixAddr::new(&sockname).unwrap(); bind(s1.as_raw_fd(), &sockaddr).expect("bind failed"); - listen(&s1, 10).expect("listen failed"); + listen(&s1, Backlog::new(10).unwrap()).expect("listen failed"); let thr = thread::spawn(move || { let s2 = socket( @@ -1650,6 +1652,14 @@ pub fn test_named_unixdomain() { assert_eq!(&buf[..], b"hello"); } +#[test] +pub fn test_listen_wrongbacklog() { + use nix::sys::socket::Backlog; + + assert!(Backlog::new(libc::SOMAXCONN + 1).is_err()); + assert!(Backlog::new(-2).is_err()); +} + // Test using unnamed unix domain addresses #[cfg(linux_android)] #[test] diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 5c58c2c828..5f7b5e8bf3 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -106,7 +106,7 @@ fn test_so_buf() { #[cfg(target_os = "freebsd")] #[test] fn test_so_listen_q_limit() { - use nix::sys::socket::{bind, listen, SockaddrIn}; + use nix::sys::socket::{bind, listen, Backlog, SockaddrIn}; use std::net::SocketAddrV4; use std::str::FromStr; @@ -123,14 +123,16 @@ fn test_so_listen_q_limit() { bind(rsock.as_raw_fd(), &sock_addr).unwrap(); let pre_limit = getsockopt(&rsock, sockopt::ListenQLimit).unwrap(); assert_eq!(pre_limit, 0); - listen(&rsock, 42).unwrap(); + listen(&rsock, Backlog::new(42).unwrap()).unwrap(); let post_limit = getsockopt(&rsock, sockopt::ListenQLimit).unwrap(); assert_eq!(post_limit, 42); } #[test] fn test_so_tcp_maxseg() { - use nix::sys::socket::{accept, bind, connect, listen, SockaddrIn}; + use nix::sys::socket::{ + accept, bind, connect, listen, Backlog, SockaddrIn, + }; use nix::unistd::write; use std::net::SocketAddrV4; use std::str::FromStr; @@ -146,7 +148,7 @@ fn test_so_tcp_maxseg() { ) .unwrap(); bind(rsock.as_raw_fd(), &sock_addr).unwrap(); - listen(&rsock, 10).unwrap(); + listen(&rsock, Backlog::new(10).unwrap()).unwrap(); let initial = getsockopt(&rsock, sockopt::TcpMaxSeg).unwrap(); // Initial MSS is expected to be 536 (https://tools.ietf.org/html/rfc879#section-1) but some // platforms keep it even lower. This might fail if you've tuned your initial MSS to be larger @@ -716,7 +718,8 @@ fn is_socket_type_dgram() { #[test] fn can_get_listen_on_tcp_socket() { use nix::sys::socket::{ - getsockopt, listen, socket, sockopt, AddressFamily, SockFlag, SockType, + getsockopt, listen, socket, sockopt, AddressFamily, Backlog, SockFlag, + SockType, }; let s = socket( @@ -728,7 +731,7 @@ fn can_get_listen_on_tcp_socket() { .unwrap(); let s_listening = getsockopt(&s, sockopt::AcceptConn).unwrap(); assert!(!s_listening); - listen(&s, 10).unwrap(); + listen(&s, Backlog::new(10).unwrap()).unwrap(); let s_listening2 = getsockopt(&s, sockopt::AcceptConn).unwrap(); assert!(s_listening2); } From a1aa3433ca90c5c75b4a8fedbab23013889d34b1 Mon Sep 17 00:00:00 2001 From: David CARLIER Date: Tue, 2 Jan 2024 03:38:01 +0000 Subject: [PATCH 110/140] fcntl::OFlags enabling O_DIRECT flag for solarish (#2278) --- Cargo.toml | 2 +- changelog/2278.added.md | 1 + src/fcntl.rs | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 changelog/2278.added.md diff --git a/Cargo.toml b/Cargo.toml index f428548584..f064e20f1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { git = "https://github.com/rust-lang/libc", rev = "6a203e955b60cca48562f020f0e4e003079f3199", features = ["extra_traits"] } +libc = { git = "https://github.com/rust-lang/libc", rev = "cb18b837963c37a8d21732f3ca2c2096f04e6830", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } diff --git a/changelog/2278.added.md b/changelog/2278.added.md new file mode 100644 index 0000000000..88a07c79a8 --- /dev/null +++ b/changelog/2278.added.md @@ -0,0 +1 @@ +Enabled `O_DIRECT` in `fcntl::OFlags` for solarish diff --git a/src/fcntl.rs b/src/fcntl.rs index 338944fd04..8ede0777b3 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -92,6 +92,7 @@ libc_bitflags!( #[cfg(any( freebsdlike, linux_android, + solarish, target_os = "netbsd" ))] O_DIRECT; From 57c611cb13b20dafac78d57e8bfb98250adc96e9 Mon Sep 17 00:00:00 2001 From: Arnav Singh Date: Tue, 2 Jan 2024 17:07:57 -0800 Subject: [PATCH 111/140] Add `SetSockOpt` definitions related to Linux Kernel TLS. (#2175) 1. kTLS is implemented as a TCP ULP, so add a `SetSockOpt` impl for it. 2. kTLS parameters are pushed to the kernel using `setsockopt(SOL_TLS)`, so add `SetSockOpt` impls for them. Other test fixes: 1. Change `setsockopt` tests to bind to port 0 so that they bind to an unbound port and don't affect each other. 2. Fix `skip!` macro used to skip tests to generate its own block so that it can be used as an expr. --- changelog/2175.added.md | 1 + src/sys/socket/sockopt.rs | 156 +++++++++++++++++++++++++++++++++++++- test/common/mod.rs | 4 +- test/sys/test_sockopt.rs | 103 +++++++++++++++++++++++-- 4 files changed, 256 insertions(+), 8 deletions(-) create mode 100644 changelog/2175.added.md diff --git a/changelog/2175.added.md b/changelog/2175.added.md new file mode 100644 index 0000000000..9da4ef470f --- /dev/null +++ b/changelog/2175.added.md @@ -0,0 +1 @@ +Added `SetSockOpt` impls to enable Linux Kernel TLS on a TCP socket and to import TLS parameters. diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 01a0c2c625..4357695f56 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -127,7 +127,7 @@ macro_rules! getsockopt_impl { /// both of them. /// * `$name:ident`: name of type `GetSockOpt`/`SetSockOpt` will be implemented for. /// * `$level:expr` : socket layer, or a `protocol level`: could be *raw sockets* -/// (`lic::SOL_SOCKET`), *ip protocol* (libc::IPPROTO_IP), *tcp protocol* (`libc::IPPROTO_TCP`), +/// (`libc::SOL_SOCKET`), *ip protocol* (libc::IPPROTO_IP), *tcp protocol* (`libc::IPPROTO_TCP`), /// and more. Please refer to your system manual for more options. Will be passed as the second /// argument (`level`) to the `getsockopt`/`setsockopt` call. /// * `$flag:path`: a flag name to set. Some examples: `libc::SO_REUSEADDR`, `libc::TCP_NODELAY`, @@ -1126,6 +1126,160 @@ where } } +/// Set the Upper Layer Protocol (ULP) on the TCP socket. +/// +/// For example, to enable the TLS ULP on a socket, the C function call would be: +/// +/// ```c +/// setsockopt(sock, SOL_TCP, TCP_ULP, "tls", sizeof("tls")); +/// ``` +/// +/// ... and the `nix` equivalent is: +/// +/// ```ignore,rust +/// setsockopt(sock, TcpUlp::default(), b"tls"); +/// ``` +/// +/// Note that the ULP name does not need a trailing NUL terminator (`\0`). +#[cfg(linux_android)] +#[derive(Clone, Debug)] +pub struct TcpUlp(::std::marker::PhantomData); + +#[cfg(linux_android)] +impl Default for TcpUlp { + fn default() -> Self { + TcpUlp(Default::default()) + } +} + +#[cfg(linux_android)] +impl SetSockOpt for TcpUlp +where + T: AsRef<[u8]> + Clone, +{ + type Val = T; + + fn set(&self, fd: &F, val: &Self::Val) -> Result<()> { + unsafe { + let res = libc::setsockopt( + fd.as_fd().as_raw_fd(), + libc::SOL_TCP, + libc::TCP_ULP, + val.as_ref().as_ptr().cast(), + val.as_ref().len() as libc::socklen_t, + ); + Errno::result(res).map(drop) + } + } +} + +/// Value used with the [`TcpTlsTx`] and [`TcpTlsRx`] socket options. +#[cfg(target_os = "linux")] +#[derive(Copy, Clone, Debug)] +pub enum TlsCryptoInfo { + /// AES-128-GCM + Aes128Gcm(libc::tls12_crypto_info_aes_gcm_128), + + /// AES-256-GCM + Aes256Gcm(libc::tls12_crypto_info_aes_gcm_256), + + /// CHACHA20-POLY1305 + Chacha20Poly1305(libc::tls12_crypto_info_chacha20_poly1305), +} + +/// Set the Kernel TLS write parameters on the TCP socket. +/// +/// For example, the C function call would be: +/// +/// ```c +/// setsockopt(sock, SOL_TLS, TLS_TX, &crypto_info, sizeof(crypto_info)); +/// ``` +/// +/// ... and the `nix` equivalent is: +/// +/// ```ignore,rust +/// setsockopt(sock, TcpTlsTx, &crypto_info); +/// ``` +#[cfg(target_os = "linux")] +#[derive(Copy, Clone, Debug)] +pub struct TcpTlsTx; + +#[cfg(target_os = "linux")] +impl SetSockOpt for TcpTlsTx { + type Val = TlsCryptoInfo; + + fn set(&self, fd: &F, val: &Self::Val) -> Result<()> { + let (ffi_ptr, ffi_len) = match val { + TlsCryptoInfo::Aes128Gcm(crypto_info) => { + (<*const _>::cast(crypto_info), mem::size_of_val(crypto_info)) + } + TlsCryptoInfo::Aes256Gcm(crypto_info) => { + (<*const _>::cast(crypto_info), mem::size_of_val(crypto_info)) + } + TlsCryptoInfo::Chacha20Poly1305(crypto_info) => { + (<*const _>::cast(crypto_info), mem::size_of_val(crypto_info)) + } + }; + unsafe { + let res = libc::setsockopt( + fd.as_fd().as_raw_fd(), + libc::SOL_TLS, + libc::TLS_TX, + ffi_ptr, + ffi_len as libc::socklen_t, + ); + Errno::result(res).map(drop) + } + } +} + +/// Set the Kernel TLS read parameters on the TCP socket. +/// +/// For example, the C function call would be: +/// +/// ```c +/// setsockopt(sock, SOL_TLS, TLS_RX, &crypto_info, sizeof(crypto_info)); +/// ``` +/// +/// ... and the `nix` equivalent is: +/// +/// ```ignore,rust +/// setsockopt(sock, TcpTlsRx, &crypto_info); +/// ``` +#[cfg(target_os = "linux")] +#[derive(Copy, Clone, Debug)] +pub struct TcpTlsRx; + +#[cfg(target_os = "linux")] +impl SetSockOpt for TcpTlsRx { + type Val = TlsCryptoInfo; + + fn set(&self, fd: &F, val: &Self::Val) -> Result<()> { + let (ffi_ptr, ffi_len) = match val { + TlsCryptoInfo::Aes128Gcm(crypto_info) => { + (<*const _>::cast(crypto_info), mem::size_of_val(crypto_info)) + } + TlsCryptoInfo::Aes256Gcm(crypto_info) => { + (<*const _>::cast(crypto_info), mem::size_of_val(crypto_info)) + } + TlsCryptoInfo::Chacha20Poly1305(crypto_info) => { + (<*const _>::cast(crypto_info), mem::size_of_val(crypto_info)) + } + }; + unsafe { + let res = libc::setsockopt( + fd.as_fd().as_raw_fd(), + libc::SOL_TLS, + libc::TLS_RX, + ffi_ptr, + ffi_len as libc::socklen_t, + ); + Errno::result(res).map(drop) + } + } +} + + /* * * ===== Accessor helpers ===== diff --git a/test/common/mod.rs b/test/common/mod.rs index 9268a79497..db4aed2598 100644 --- a/test/common/mod.rs +++ b/test/common/mod.rs @@ -2,14 +2,14 @@ use cfg_if::cfg_if; #[macro_export] macro_rules! skip { - ($($reason: expr),+) => { + ($($reason: expr),+) => {{ use ::std::io::{self, Write}; let stderr = io::stderr(); let mut handle = stderr.lock(); writeln!(handle, $($reason),+).unwrap(); return; - } + }} } cfg_if! { diff --git a/test/sys/test_sockopt.rs b/test/sys/test_sockopt.rs index 5f7b5e8bf3..a99d4e39ed 100644 --- a/test/sys/test_sockopt.rs +++ b/test/sys/test_sockopt.rs @@ -131,14 +131,14 @@ fn test_so_listen_q_limit() { #[test] fn test_so_tcp_maxseg() { use nix::sys::socket::{ - accept, bind, connect, listen, Backlog, SockaddrIn, + accept, bind, connect, getsockname, listen, Backlog, SockaddrIn, }; use nix::unistd::write; use std::net::SocketAddrV4; use std::str::FromStr; - let std_sa = SocketAddrV4::from_str("127.0.0.1:4003").unwrap(); - let sock_addr = SockaddrIn::from(std_sa); + let std_sa = SocketAddrV4::from_str("127.0.0.1:0").unwrap(); + let mut sock_addr = SockaddrIn::from(std_sa); let rsock = socket( AddressFamily::Inet, @@ -148,6 +148,7 @@ fn test_so_tcp_maxseg() { ) .unwrap(); bind(rsock.as_raw_fd(), &sock_addr).unwrap(); + sock_addr = getsockname(rsock.as_raw_fd()).unwrap(); listen(&rsock, Backlog::new(10).unwrap()).unwrap(); let initial = getsockopt(&rsock, sockopt::TcpMaxSeg).unwrap(); // Initial MSS is expected to be 536 (https://tools.ietf.org/html/rfc879#section-1) but some @@ -305,7 +306,7 @@ fn test_get_mtu() { use std::net::SocketAddrV4; use std::str::FromStr; - let std_sa = SocketAddrV4::from_str("127.0.0.1:4001").unwrap(); + let std_sa = SocketAddrV4::from_str("127.0.0.1:0").unwrap(); let std_sb = SocketAddrV4::from_str("127.0.0.1:4002").unwrap(); let usock = socket( @@ -615,7 +616,7 @@ fn test_ts_clock_monotonic() { #[test] #[cfg(linux_android)] -// Disable the test under emulation because it failsi with ENOPROTOOPT in CI +// Disable the test under emulation because it fails with ENOPROTOOPT in CI // on cross target. Lack of QEMU support is suspected. #[cfg_attr(qemu, ignore)] fn test_ip_bind_address_no_port() { @@ -735,3 +736,95 @@ fn can_get_listen_on_tcp_socket() { let s_listening2 = getsockopt(&s, sockopt::AcceptConn).unwrap(); assert!(s_listening2); } + +#[cfg(target_os = "linux")] +// Some architectures running under cross don't support `setsockopt(SOL_TCP, TCP_ULP)` +// because the cross image is based on Ubuntu 16.04 which predates TCP ULP support +// (it was added in kernel v4.13 released in 2017). For these architectures, +// the `setsockopt(SOL_TCP, TCP_ULP, "tls", sizeof("tls"))` call succeeds +// but the subsequent `setsockopt(SOL_TLS, TLS_TX, ...)` call fails with `ENOPROTOOPT`. +// It's as if the first `setsockopt` call enabled some other option, not `TCP_ULP`. +// For example, `strace` says: +// +// [pid 813] setsockopt(4, SOL_TCP, 0x1f /* TCP_??? */, [7564404], 4) = 0 +// +// It's not clear why `setsockopt(SOL_TCP, TCP_ULP)` succeeds if the container image libc doesn't support it, +// but in any case we can't run the test on such an architecture, so skip it. +#[cfg_attr(qemu, ignore)] +#[test] +fn test_ktls() { + use nix::sys::socket::{ + accept, bind, connect, getsockname, listen, Backlog, SockaddrIn, + }; + use std::net::SocketAddrV4; + use std::str::FromStr; + + let std_sa = SocketAddrV4::from_str("127.0.0.1:0").unwrap(); + let mut sock_addr = SockaddrIn::from(std_sa); + + let rsock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + bind(rsock.as_raw_fd(), &sock_addr).unwrap(); + sock_addr = getsockname(rsock.as_raw_fd()).unwrap(); + listen(&rsock, Backlog::new(10).unwrap()).unwrap(); + + let ssock = socket( + AddressFamily::Inet, + SockType::Stream, + SockFlag::empty(), + SockProtocol::Tcp, + ) + .unwrap(); + connect(ssock.as_raw_fd(), &sock_addr).unwrap(); + + let _rsess = accept(rsock.as_raw_fd()).unwrap(); + + match setsockopt(&ssock, sockopt::TcpUlp::default(), b"tls") { + Ok(()) => (), + + // TLS ULP is not enabled, so we can't test kTLS. + Err(nix::Error::ENOENT) => skip!("TLS ULP is not enabled"), + + Err(err) => panic!("{err:?}"), + } + + // In real life we would do a TLS handshake and extract the protocol version and secrets. + // For this test we just make some up. + + let tx = sockopt::TlsCryptoInfo::Aes128Gcm(libc::tls12_crypto_info_aes_gcm_128 { + info: libc::tls_crypto_info { + version: libc::TLS_1_2_VERSION, + cipher_type: libc::TLS_CIPHER_AES_GCM_128, + }, + iv: *b"\x04\x05\x06\x07\x08\x09\x0a\x0b", + key: *b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", + salt: *b"\x00\x01\x02\x03", + rec_seq: *b"\x00\x00\x00\x00\x00\x00\x00\x00", + }); + setsockopt(&ssock, sockopt::TcpTlsTx, &tx) + .expect("setting TLS_TX after enabling TLS ULP should succeed"); + + let rx = sockopt::TlsCryptoInfo::Aes128Gcm(libc::tls12_crypto_info_aes_gcm_128 { + info: libc::tls_crypto_info { + version: libc::TLS_1_2_VERSION, + cipher_type: libc::TLS_CIPHER_AES_GCM_128, + }, + iv: *b"\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb", + key: *b"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef", + salt: *b"\xf0\xf1\xf2\xf3", + rec_seq: *b"\x00\x00\x00\x00\x00\x00\x00\x00", + }); + match setsockopt(&ssock, sockopt::TcpTlsRx, &rx) { + Ok(()) => (), + Err(nix::Error::ENOPROTOOPT) => { + // TLS_TX was added in v4.13 and TLS_RX in v4.17, so we appear to be between that range. + // It's good enough that TLS_TX worked, so let the test succeed. + } + Err(err) => panic!("{err:?}"), + } +} From 3195d9e94430a0e0eb0afa8cb368a3b821095f00 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 7 Jan 2024 06:16:44 +0800 Subject: [PATCH 112/140] fix unused_tuple_struct_fields on FreeBSD, DragonFlyBSD, and Apple (#2281) --- src/sys/sendfile.rs | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 579013b4b8..d7452edd7c 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -81,11 +81,11 @@ cfg_if! { use std::io::IoSlice; #[derive(Clone, Debug)] - struct SendfileHeaderTrailer<'a>( - libc::sf_hdtr, - Option>>, - Option>>, - ); + struct SendfileHeaderTrailer<'a> { + raw: libc::sf_hdtr, + _headers: Option>>, + _trailers: Option>>, + } impl<'a> SendfileHeaderTrailer<'a> { fn new( @@ -96,8 +96,9 @@ cfg_if! { headers.map(|s| s.iter().map(|b| IoSlice::new(b)).collect()); let mut trailer_iovecs: Option>> = trailers.map(|s| s.iter().map(|b| IoSlice::new(b)).collect()); - SendfileHeaderTrailer( - libc::sf_hdtr { + + SendfileHeaderTrailer { + raw: libc::sf_hdtr { headers: { header_iovecs .as_mut() @@ -113,9 +114,9 @@ cfg_if! { }, trl_cnt: trailer_iovecs.as_ref().map(|v| v.len()).unwrap_or(0) as i32 }, - header_iovecs, - trailer_iovecs, - ) + _headers: header_iovecs, + _trailers: trailer_iovecs, + } } } } else if #[cfg(solarish)] { @@ -221,7 +222,7 @@ cfg_if! { let flags: u32 = (ra32 << 16) | (flags.bits() as u32); let mut bytes_sent: off_t = 0; let hdtr = headers.or(trailers).map(|_| SendfileHeaderTrailer::new(headers, trailers)); - let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.0 as *const libc::sf_hdtr); + let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.raw as *const libc::sf_hdtr); let return_code = unsafe { libc::sendfile(in_fd.as_fd().as_raw_fd(), out_sock.as_fd().as_raw_fd(), @@ -264,7 +265,7 @@ cfg_if! { ) -> (Result<()>, off_t) { let mut bytes_sent: off_t = 0; let hdtr = headers.or(trailers).map(|_| SendfileHeaderTrailer::new(headers, trailers)); - let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.0 as *const libc::sf_hdtr); + let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.raw as *const libc::sf_hdtr); let return_code = unsafe { libc::sendfile(in_fd.as_fd().as_raw_fd(), out_sock.as_fd().as_raw_fd(), @@ -310,7 +311,7 @@ cfg_if! { ) -> (Result<()>, off_t) { let mut len = count.unwrap_or(0); let hdtr = headers.or(trailers).map(|_| SendfileHeaderTrailer::new(headers, trailers)); - let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.0 as *const libc::sf_hdtr); + let hdtr_ptr = hdtr.as_ref().map_or(ptr::null(), |s| &s.raw as *const libc::sf_hdtr); let return_code = unsafe { libc::sendfile(in_fd.as_fd().as_raw_fd(), out_sock.as_fd().as_raw_fd(), From aeea7cf1836fa5a2515984691ef1adf20cabe340 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 7 Jan 2024 06:17:31 +0800 Subject: [PATCH 113/140] refactor: make dup3 wrapper call the real dup3 (#2268) * refactor: make dup3 wrapper call the real dup3 * fix imports * respond to review --- changelog/2268.fixed.md | 1 + changelog/2268.removed.md | 1 + src/unistd.rs | 42 ++++++++++++++++++++------------------- 3 files changed, 24 insertions(+), 20 deletions(-) create mode 100644 changelog/2268.fixed.md create mode 100644 changelog/2268.removed.md diff --git a/changelog/2268.fixed.md b/changelog/2268.fixed.md new file mode 100644 index 0000000000..108553d984 --- /dev/null +++ b/changelog/2268.fixed.md @@ -0,0 +1 @@ +Changed the `dup3` wrapper to perform a real call to `dup3` instead of emulating it via `dup2` and `fcntl` to get rid of race condition diff --git a/changelog/2268.removed.md b/changelog/2268.removed.md new file mode 100644 index 0000000000..a69aba3a45 --- /dev/null +++ b/changelog/2268.removed.md @@ -0,0 +1 @@ +Removed the `dup3` wrapper on macOS, which was emulated via `dup2` and `fcntl` and could cause a race condition. The `dup3` system call is not supported on macOS. diff --git a/src/unistd.rs b/src/unistd.rs index 93187a67c5..92840f7e8b 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -12,7 +12,17 @@ use crate::fcntl::at_rawfd; use crate::fcntl::AtFlags; #[cfg(feature = "fs")] -use crate::fcntl::{fcntl, FcntlArg::F_SETFD, FdFlag, OFlag}; +#[cfg(any( + linux_android, + freebsdlike, + solarish, + netbsdlike, + target_os = "emscripten", + target_os = "fuchsia", + target_os = "hurd", + target_os = "redox", +))] +use crate::fcntl::OFlag; #[cfg(all(feature = "fs", bsd))] use crate::sys::stat::FileFlag; #[cfg(feature = "fs")] @@ -426,30 +436,22 @@ pub fn dup2(oldfd: RawFd, newfd: RawFd) -> Result { } /// Create a new copy of the specified file descriptor using the specified fd -/// and flags (see [dup(2)](https://man7.org/linux/man-pages/man2/dup.2.html)). +/// and flags (see [`dup(2)`](https://man7.org/linux/man-pages/man2/dup.2.html)). /// /// This function behaves similar to `dup2()` but allows for flags to be /// specified. +#[cfg(any( + netbsdlike, + solarish, + target_os = "freebsd", + target_os = "fuchsia", + target_os = "hurd", + target_os = "linux" +))] pub fn dup3(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result { - dup3_polyfill(oldfd, newfd, flags) -} + let res = unsafe { libc::dup3(oldfd, newfd, flags.bits()) }; -#[inline] -fn dup3_polyfill(oldfd: RawFd, newfd: RawFd, flags: OFlag) -> Result { - if oldfd == newfd { - return Err(Errno::EINVAL); - } - - let fd = dup2(oldfd, newfd)?; - - if flags.contains(OFlag::O_CLOEXEC) { - if let Err(e) = fcntl(fd, F_SETFD(FdFlag::FD_CLOEXEC)) { - let _ = close(fd); - return Err(e); - } - } - - Ok(fd) + Errno::result(res) } /// Change the current working directory of the calling process (see From 20db3f39826ae6b11fa6757a70e56a6f06675239 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sat, 6 Jan 2024 18:51:49 -0700 Subject: [PATCH 114/140] Correct a comment (#2282) And while here, make cmsg_space a const fn, though I doubt it will make a difference since it's already inline. The original comment was _almost_ correct. Changing the cmsg_space macro to return an array works in most locations. However, it fails in the test_recverr_impl function in the tests due to a E0401 Error "Inner items do not inherit the generic parameters from the items they are embedded in." That error is very difficult to fix in our test, and it might occur in user code, too. The root of the problem is that each length of array is its own distinct type, and in a generic function cmsg_space returns an array type that may depend on the generic parameters. Alternatively we could provide a second macro that always heap allocates. But that may be too complicated just to save a single allocation. --- src/sys/socket/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 2f7f9815cb..d7f94d80d1 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -567,8 +567,6 @@ feature! { /// let _ = cmsg_space!(RawFd, TimeVal); /// # } /// ``` -// Unfortunately, CMSG_SPACE isn't a const_fn, or else we could return a -// stack-allocated array. #[macro_export] macro_rules! cmsg_space { ( $( $x:ty ),* ) => { @@ -581,7 +579,7 @@ macro_rules! cmsg_space { #[inline] #[doc(hidden)] -pub fn cmsg_space() -> usize { +pub const fn cmsg_space() -> usize { // SAFETY: CMSG_SPACE is always safe unsafe { libc::CMSG_SPACE(mem::size_of::() as libc::c_uint) as usize } } From 0e8efe94f7be45b19b5808cd4eeeb42a31d921a5 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 7 Jan 2024 10:12:06 +0800 Subject: [PATCH 115/140] feat: clock_nanosleep() (#2277) --- changelog/2277.added.md | 1 + src/time.rs | 52 +++++++++++++++++++++++++++++++++++++++++ test/test_time.rs | 25 ++++++++++++++++++++ 3 files changed, 78 insertions(+) create mode 100644 changelog/2277.added.md diff --git a/changelog/2277.added.md b/changelog/2277.added.md new file mode 100644 index 0000000000..0b6e8611c4 --- /dev/null +++ b/changelog/2277.added.md @@ -0,0 +1 @@ +Add `clock_nanosleep()` diff --git a/src/time.rs b/src/time.rs index 96e84900dd..72915c25df 100644 --- a/src/time.rs +++ b/src/time.rs @@ -199,3 +199,55 @@ pub fn clock_getcpuclockid(pid: Pid) -> Result { Err(Errno::from_i32(ret)) } } + +#[cfg(any( + linux_android, + solarish, + freebsdlike, + target_os = "netbsd", + target_os = "hurd", + target_os = "aix" +))] +libc_bitflags! { + /// Flags that are used for arming the timer. + pub struct ClockNanosleepFlags: libc::c_int { + TIMER_ABSTIME; + } +} + +/// Suspend execution of this thread for the amount of time specified by `request` +/// and measured against the clock speficied by `clock_id`. If `flags` is +/// `TIMER_ABSTIME`, this function will suspend execution until the time value of +/// clock_id reaches the absolute time specified by `request`. If a signal is caught +/// by a signal-catching function, or a signal causes the process to terminate, +/// this sleep is interrrupted. +/// +/// see also [man 3 clock_nanosleep](https://pubs.opengroup.org/onlinepubs/009695399/functions/clock_nanosleep.html) +#[cfg(any( + linux_android, + solarish, + freebsdlike, + target_os = "netbsd", + target_os = "hurd", + target_os = "aix" +))] +pub fn clock_nanosleep( + clock_id: ClockId, + flags: ClockNanosleepFlags, + request: &TimeSpec, +) -> Result { + let mut remain = TimeSpec::new(0, 0); + let ret = unsafe { + libc::clock_nanosleep( + clock_id.as_raw(), + flags.bits(), + request.as_ref() as *const _, + remain.as_mut() as *mut _, + ) + }; + if ret == 0 { + Ok(remain) + } else { + Err(Errno::from_i32(ret)) + } +} diff --git a/test/test_time.rs b/test/test_time.rs index 6d7dfbedc0..64c8161dbf 100644 --- a/test/test_time.rs +++ b/test/test_time.rs @@ -39,3 +39,28 @@ pub fn test_clock_id_pid_cpu_clock_id() { .unwrap() .unwrap(); } + +#[cfg(any( + linux_android, + solarish, + freebsdlike, + target_os = "netbsd", + target_os = "hurd", + target_os = "aix" +))] +#[test] +pub fn test_clock_nanosleep() { + use nix::{ + sys::time::{TimeSpec, TimeValLike}, + time::{clock_nanosleep, ClockNanosleepFlags}, + }; + + let sleep_time = TimeSpec::microseconds(1); + let res = clock_nanosleep( + ClockId::CLOCK_MONOTONIC, + ClockNanosleepFlags::empty(), + &sleep_time, + ); + let expected = TimeSpec::microseconds(0); + assert_eq!(res, Ok(expected)); +} From 833828e725f75481ec4b59f6c6dee5ae48c42d27 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 7 Jan 2024 11:35:03 +0800 Subject: [PATCH 116/140] feat: AT_EMPTY_PATH for fchownat on Linux/Android/FreeBSD/Hurd (#2267) --- changelog/2267.added.md | 1 + changelog/2267.removed.md | 1 + src/fcntl.rs | 2 +- src/unistd.rs | 28 +++++++++++++++------------- test/test_unistd.rs | 9 +++++---- 5 files changed, 23 insertions(+), 18 deletions(-) create mode 100644 changelog/2267.added.md create mode 100644 changelog/2267.removed.md diff --git a/changelog/2267.added.md b/changelog/2267.added.md new file mode 100644 index 0000000000..0a09558511 --- /dev/null +++ b/changelog/2267.added.md @@ -0,0 +1 @@ +Enable the `AT_EMPTY_PATH` flag for the `fchownat()` function diff --git a/changelog/2267.removed.md b/changelog/2267.removed.md new file mode 100644 index 0000000000..bedb77fd20 --- /dev/null +++ b/changelog/2267.removed.md @@ -0,0 +1 @@ +The `FchownatFlags` type has been deprecated, please use `AtFlags` instead. diff --git a/src/fcntl.rs b/src/fcntl.rs index 8ede0777b3..638d6f6ea6 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -43,7 +43,7 @@ use crate::{sys::stat::Mode, NixPath, Result}; pub use self::posix_fadvise::{posix_fadvise, PosixFadviseAdvice}; #[cfg(not(target_os = "redox"))] -#[cfg(any(feature = "fs", feature = "process"))] +#[cfg(any(feature = "fs", feature = "process", feature = "user"))] libc_bitflags! { #[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "process"))))] pub struct AtFlags: c_int { diff --git a/src/unistd.rs b/src/unistd.rs index 92840f7e8b..a7f784eae4 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -737,11 +737,17 @@ pub fn fchown(fd: RawFd, owner: Option, group: Option) -> Result<()> { Errno::result(res).map(drop) } -/// Flags for `fchownat` function. -#[derive(Clone, Copy, Debug)] -pub enum FchownatFlags { - FollowSymlink, - NoFollowSymlink, +// Just a wrapper around `AtFlags` so that we can help our users migrate. +#[cfg(not(target_os = "redox"))] +pub type FchownatFlags = AtFlags; +#[cfg(not(target_os = "redox"))] +impl FchownatFlags { + #[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")] + #[allow(non_upper_case_globals)] + pub const FollowSymlink: FchownatFlags = FchownatFlags::empty(); + #[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")] + #[allow(non_upper_case_globals)] + pub const NoFollowSymlink: FchownatFlags = FchownatFlags::AT_SYMLINK_NOFOLLOW; } /// Change the ownership of the file at `path` to be owned by the specified @@ -755,10 +761,10 @@ pub enum FchownatFlags { /// with the file descriptor `dirfd` or the current working directory /// if `dirfd` is `None`. /// -/// If `flag` is `FchownatFlags::NoFollowSymlink` and `path` names a symbolic link, +/// If `flag` is `AtFlags::AT_SYMLINK_NOFOLLOW` and `path` names a symbolic link, /// then the mode of the symbolic link is changed. /// -/// `fchownat(None, path, owner, group, FchownatFlags::NoFollowSymlink)` is identical to +/// `fchownat(None, path, owner, group, AtFlags::AT_SYMLINK_NOFOLLOW)` is identical to /// a call `libc::lchown(path, owner, group)`. That's why `lchown` is unimplemented in /// the `nix` crate. /// @@ -771,12 +777,8 @@ pub fn fchownat( path: &P, owner: Option, group: Option, - flag: FchownatFlags, + flag: AtFlags, ) -> Result<()> { - let atflag = match flag { - FchownatFlags::FollowSymlink => AtFlags::empty(), - FchownatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, - }; let res = path.with_nix_path(|cstr| unsafe { let (uid, gid) = chown_raw_ids(owner, group); libc::fchownat( @@ -784,7 +786,7 @@ pub fn fchownat( cstr.as_ptr(), uid, gid, - atflag.bits() as libc::c_int, + flag.bits() ) })?; diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 354f816362..b156951e93 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -551,6 +551,8 @@ fn test_fchown() { #[test] #[cfg(not(target_os = "redox"))] fn test_fchownat() { + use nix::fcntl::AtFlags; + let _dr = crate::DirRestore::new(); // Testing for anything other than our own UID/GID is hard. let uid = Some(getuid()); @@ -564,14 +566,13 @@ fn test_fchownat() { let dirfd = open(tempdir.path(), OFlag::empty(), Mode::empty()).unwrap(); - fchownat(Some(dirfd), "file", uid, gid, FchownatFlags::FollowSymlink) - .unwrap(); + fchownat(Some(dirfd), "file", uid, gid, AtFlags::empty()).unwrap(); chdir(tempdir.path()).unwrap(); - fchownat(None, "file", uid, gid, FchownatFlags::FollowSymlink).unwrap(); + fchownat(None, "file", uid, gid, AtFlags::empty()).unwrap(); fs::remove_file(&path).unwrap(); - fchownat(None, "file", uid, gid, FchownatFlags::FollowSymlink).unwrap_err(); + fchownat(None, "file", uid, gid, AtFlags::empty()).unwrap_err(); } #[test] From 4bc85e466e4602427537deddbd5ef5fb77175e14 Mon Sep 17 00:00:00 2001 From: Toru3 Date: Sun, 7 Jan 2024 13:10:36 +0900 Subject: [PATCH 117/140] Add sigsuspend (#2279) * add sigsuspend * add cfg for sigsuspend * add fuchsia to target_os * Ok is unreachable > Since sigsuspend() suspends thread execution indefinitely, there is no > successful completion return value. If a return occurs, -1 shall be > returned and errno set to indicate the error. https://pubs.opengroup.org/onlinepubs/9699919799/functions/sigsuspend.html * add test_sigsuspend * clippy * fix bug of test * add changelog * update doc * remove unnnessesary sleep * Revert "remove unnnessesary sleep" This reverts commit c174bd2fe076429226048608f80e9cdf55634a98. * move to SigSet::suspend * reorder doc * update test * update test * change memory order * Revert "change memory order" This reverts commit f63e65643d4627492bfa5cb83ba4d3ed3698f31c. * rename added.md * add unreachable reason * use alias * remove nto * Update libc I updated libc to use below commit which add sigsuspend to more targets. https://github.com/rust-lang/libc/commit/11f7c7b89d9bfe8c53dcca7571c4965fa3375aab * Add target bsd, solarish and haiku to sigsuspend --- 2279.added.md | 1 + Cargo.toml | 2 +- src/sys/signal.rs | 29 +++++++++++++++++++++++ test/sys/test_signal.rs | 51 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 2279.added.md diff --git a/2279.added.md b/2279.added.md new file mode 100644 index 0000000000..5bbbbb40f7 --- /dev/null +++ b/2279.added.md @@ -0,0 +1 @@ +Added a new API sigsuspend. diff --git a/Cargo.toml b/Cargo.toml index f064e20f1c..202c57b52a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { git = "https://github.com/rust-lang/libc", rev = "cb18b837963c37a8d21732f3ca2c2096f04e6830", features = ["extra_traits"] } +libc = { git = "https://github.com/rust-lang/libc", rev = "2f93bfb7678e18a9fc5373dec49384bd23f601c3", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } diff --git a/src/sys/signal.rs b/src/sys/signal.rs index efa11a134b..c9b593d0db 100644 --- a/src/sys/signal.rs +++ b/src/sys/signal.rs @@ -582,6 +582,35 @@ impl SigSet { }) } + /// Wait for a signal + /// + /// # Return value + /// If `sigsuspend(2)` is interrupted (EINTR), this function returns `Ok`. + /// If `sigsuspend(2)` set other error, this function returns `Err`. + /// + /// For more information see the + /// [`sigsuspend(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sigsuspend.html). + #[cfg(any( + bsd, + linux_android, + solarish, + target_os = "haiku", + target_os = "hurd", + target_os = "aix", + target_os = "fushsia" + ))] + #[doc(alias("sigsuspend"))] + pub fn suspend(&self) -> Result<()> { + let res = unsafe { + libc::sigsuspend(&self.sigset as *const libc::sigset_t) + }; + match Errno::result(res).map(drop) { + Err(Errno::EINTR) => Ok(()), + Err(e) => Err(e), + Ok(_) => unreachable!("because this syscall always returns -1 if returns"), + } + } + /// Converts a `libc::sigset_t` object to a [`SigSet`] without checking whether the /// `libc::sigset_t` is already initialized. /// diff --git a/test/sys/test_signal.rs b/test/sys/test_signal.rs index eb6347d5b0..12872f1228 100644 --- a/test/sys/test_signal.rs +++ b/test/sys/test_signal.rs @@ -343,6 +343,57 @@ fn test_sigwait() { .unwrap(); } +#[cfg(any( + bsd, + linux_android, + solarish, + target_os = "haiku", + target_os = "hurd", + target_os = "aix", + target_os = "fushsia" +))] +#[test] +fn test_sigsuspend() { + // This test change signal handler + let _m = crate::SIGNAL_MTX.lock(); + static SIGNAL_RECIEVED: AtomicBool = AtomicBool::new(false); + extern "C" fn test_sigsuspend_handler(_: libc::c_int) { + assert!(!SIGNAL_RECIEVED.swap(true, Ordering::SeqCst)); + } + thread::spawn(|| { + const SIGNAL: Signal = Signal::SIGUSR1; + + // Add signal mask to this thread + let mut signal_set = SigSet::empty(); + signal_set.add(SIGNAL); + signal_set.thread_block().unwrap(); + + // Set signal handler and save old one. + let act = SigAction::new( + SigHandler::Handler(test_sigsuspend_handler), + SaFlags::empty(), + SigSet::empty(), + ); + let old_act = unsafe { sigaction(SIGNAL, &act) } + .expect("expect to be able to set new action and get old action"); + + raise(SIGNAL).expect("expect be able to send signal"); + // Now `SIGNAL` was sended but it is blocked. + let mut not_wait_set = SigSet::all(); + not_wait_set.remove(SIGNAL); + // signal handler must run in SigSet::suspend() + assert!(!SIGNAL_RECIEVED.load(Ordering::SeqCst)); + not_wait_set.suspend().unwrap(); + assert!(SIGNAL_RECIEVED.load(Ordering::SeqCst)); + + // Restore the signal handler. + unsafe { sigaction(SIGNAL, &old_act) } + .expect("expect to be able to restore old action "); + }) + .join() + .unwrap(); +} + #[test] fn test_from_sigset_t_unchecked() { let src_set = SigSet::empty(); From 24b70dc1d4a60532896449928e22e59ccb51c2b3 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sun, 7 Jan 2024 14:51:51 +0800 Subject: [PATCH 118/140] chore: move the changelog of #2279 to right place (#2285) --- 2279.added.md => changelog/2279.added.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 2279.added.md => changelog/2279.added.md (100%) diff --git a/2279.added.md b/changelog/2279.added.md similarity index 100% rename from 2279.added.md rename to changelog/2279.added.md From c505277f4000da38f37c5ccd9368041d287ab44c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bart=C5=82omiej=20Mary=C5=84czak?= Date: Mon, 8 Jan 2024 02:02:11 +0100 Subject: [PATCH 119/140] Introduce set_errno (#2283) * Introduce set_errno * set_errno test * Add a changelog * Add some docs to errno module * Errno API Cleanup * Stop using deprecated function of errno * Update docs to not use deprecated functions * Add since to deprecated attributes * Update changelog * Fix after rebase * Use Errno::set_raw in Errno::clear implementation * Use self in Errno::set * Use errno.set() syntax in docs * errno_set_and_clear test * Remove Errno::clear from errno_set_and_read --- changelog/2283.added.md | 4 ++ changelog/2283.changed.md | 3 + src/errno.rs | 132 ++++++++++++++++++++++++++++++++------ src/fcntl.rs | 4 +- src/sys/aio.rs | 2 +- src/time.rs | 4 +- src/unistd.rs | 10 +-- test/test.rs | 1 + test/test_errno.rs | 16 +++++ test/test_mount.rs | 2 +- 10 files changed, 149 insertions(+), 29 deletions(-) create mode 100644 changelog/2283.added.md create mode 100644 changelog/2283.changed.md create mode 100644 test/test_errno.rs diff --git a/changelog/2283.added.md b/changelog/2283.added.md new file mode 100644 index 0000000000..fbf357d0f3 --- /dev/null +++ b/changelog/2283.added.md @@ -0,0 +1,4 @@ +- Added `errno::Errno::set` function +- Added `errno::Errno::set_raw` function +- Added `errno::Errno::last_raw` function +- Added `errno::Errno::from_raw` function diff --git a/changelog/2283.changed.md b/changelog/2283.changed.md new file mode 100644 index 0000000000..44bb1d5405 --- /dev/null +++ b/changelog/2283.changed.md @@ -0,0 +1,3 @@ +- Deprecated `errno::errno()` function (use `Errno::last_raw()`) +- Deprecated `errno::from_i32()` function (use `Errno::from_raw()`) +- Deprecated `errno::Errno::from_i32()` function (use `Errno::from_raw()`) diff --git a/src/errno.rs b/src/errno.rs index cde462d958..114a4a1eab 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -1,3 +1,16 @@ +//! Safe wrappers around errno functions +//! +//! # Example +//! ``` +//! use nix::errno::Errno; +//! +//! Errno::EIO.set(); +//! assert_eq!(Errno::last(), Errno::EIO); +//! +//! Errno::clear(); +//! assert_eq!(Errno::last(), Errno::from_raw(0)); +//! ``` + use crate::Result; use cfg_if::cfg_if; use libc::{c_int, c_void}; @@ -39,34 +52,77 @@ cfg_if! { } } -/// Sets the platform-specific errno to no-error -fn clear() { - // Safe because errno is a thread-local variable - unsafe { - *errno_location() = 0; - } -} - /// Returns the platform-specific value of errno +#[deprecated(since = "0.28.0", note = "please use `Errno::last_raw()` instead")] pub fn errno() -> i32 { - unsafe { *errno_location() } + Errno::last_raw() } impl Errno { + /// Returns the current value of errno pub fn last() -> Self { - last() + Self::from_raw(Self::last_raw()) } - pub fn desc(self) -> &'static str { - desc(self) + /// Returns the current raw i32 value of errno + pub fn last_raw() -> i32 { + unsafe { *errno_location() } + } + + /// Sets the value of errno. + /// + /// # Example + /// ``` + /// use nix::errno::Errno; + /// + /// Errno::EIO.set(); + /// + /// assert_eq!(Errno::last(), Errno::EIO); + /// ``` + pub fn set(self) { + Self::set_raw(self as i32) } + /// Sets the raw i32 value of errno. + pub fn set_raw(errno: i32) { + // Safe because errno is a thread-local variable + unsafe { + *errno_location() = errno; + } + } + + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(err: i32) -> Errno { + Self::from_raw(err) + } + + pub const fn from_raw(err: i32) -> Errno { + #[allow(deprecated)] from_i32(err) } + pub fn desc(self) -> &'static str { + desc(self) + } + + /// Sets the platform-specific errno to no-error + /// + /// ``` + /// use nix::errno::Errno; + /// + /// Errno::EIO.set(); + /// + /// Errno::clear(); + /// + /// let err = Errno::last(); + /// assert_ne!(err, Errno::EIO); + /// assert_eq!(err, Errno::from_raw(0)); + /// ``` pub fn clear() { - clear() + Self::set_raw(0) } /// Returns `Ok(value)` if it does not contain the sentinel value. This @@ -135,14 +191,10 @@ impl TryFrom for Errno { type Error = io::Error; fn try_from(ioerror: io::Error) -> std::result::Result { - ioerror.raw_os_error().map(Errno::from_i32).ok_or(ioerror) + ioerror.raw_os_error().map(Errno::from_raw).ok_or(ioerror) } } -fn last() -> Errno { - Errno::from_i32(errno()) -} - fn desc(errno: Errno) -> &'static str { use self::Errno::*; match errno { @@ -929,6 +981,10 @@ mod consts { pub const ENOTSUP: Errno = Errno::EOPNOTSUPP; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -1192,6 +1248,10 @@ mod consts { pub const EDEADLOCK: Errno = Errno::EDEADLK; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -1419,6 +1479,10 @@ mod consts { pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -1636,6 +1700,10 @@ mod consts { pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -1848,6 +1916,10 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -2062,6 +2134,10 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -2265,6 +2341,10 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -2494,6 +2574,10 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -2714,6 +2798,10 @@ mod consts { pub const EOPNOTSUPP: Errno = Errno::ENOTSUP; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -2905,6 +2993,10 @@ mod consts { EOPNOTSUPP = libc::EOPNOTSUPP, } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; @@ -3128,6 +3220,10 @@ mod consts { pub const EWOULDBLOCK: Errno = Errno::EAGAIN; } + #[deprecated( + since = "0.28.0", + note = "please use `Errno::from_raw()` instead" + )] pub const fn from_i32(e: i32) -> Errno { use self::Errno::*; diff --git a/src/fcntl.rs b/src/fcntl.rs index 638d6f6ea6..e4a2d73c41 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -1109,7 +1109,7 @@ mod posix_fadvise { if res == 0 { Ok(()) } else { - Err(Errno::from_i32(res)) + Err(Errno::from_raw(res)) } } } @@ -1131,7 +1131,7 @@ pub fn posix_fallocate( match Errno::result(res) { Err(err) => Err(err), Ok(0) => Ok(()), - Ok(errno) => Err(Errno::from_i32(errno)), + Ok(errno) => Err(Errno::from_raw(errno)), } } } diff --git a/src/sys/aio.rs b/src/sys/aio.rs index e3c44db654..e9213c6434 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -158,7 +158,7 @@ impl AioCb { let r = unsafe { libc::aio_error(&self.aiocb().0) }; match r { 0 => Ok(()), - num if num > 0 => Err(Errno::from_i32(num)), + num if num > 0 => Err(Errno::from_raw(num)), -1 => Err(Errno::last()), num => panic!("unknown aio_error return value {num:?}"), } diff --git a/src/time.rs b/src/time.rs index 72915c25df..d50324ddd3 100644 --- a/src/time.rs +++ b/src/time.rs @@ -196,7 +196,7 @@ pub fn clock_getcpuclockid(pid: Pid) -> Result { let res = unsafe { clk_id.assume_init() }; Ok(ClockId::from(res)) } else { - Err(Errno::from_i32(ret)) + Err(Errno::from_raw(ret)) } } @@ -248,6 +248,6 @@ pub fn clock_nanosleep( if ret == 0 { Ok(remain) } else { - Err(Errno::from_i32(ret)) + Err(Errno::from_raw(ret)) } } diff --git a/src/unistd.rs b/src/unistd.rs index a7f784eae4..564dafbb3e 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1,6 +1,6 @@ //! Safe wrappers around functions found in libc "unistd.h" header -use crate::errno::{self, Errno}; +use crate::errno::Errno; #[cfg(any( all(feature = "fs", not(target_os = "redox")), @@ -2148,7 +2148,7 @@ pub fn fpathconf(fd: F, var: PathconfVar) -> Result> { libc::fpathconf(fd.as_fd().as_raw_fd(), var as c_int) }; if raw == -1 { - if errno::errno() == 0 { + if Errno::last_raw() == 0 { Ok(None) } else { Err(Errno::last()) @@ -2188,7 +2188,7 @@ pub fn pathconf( libc::pathconf(cstr.as_ptr(), var as c_int) })?; if raw == -1 { - if errno::errno() == 0 { + if Errno::last_raw() == 0 { Ok(None) } else { Err(Errno::last()) @@ -2787,7 +2787,7 @@ pub fn sysconf(var: SysconfVar) -> Result> { libc::sysconf(var as c_int) }; if raw == -1 { - if errno::errno() == 0 { + if Errno::last_raw() == 0 { Ok(None) } else { Err(Errno::last()) @@ -3543,7 +3543,7 @@ pub fn ttyname(fd: F) -> Result { let ret = unsafe { libc::ttyname_r(fd.as_fd().as_raw_fd(), c_buf, buf.len()) }; if ret != 0 { - return Err(Errno::from_i32(ret)); + return Err(Errno::from_raw(ret)); } CStr::from_bytes_until_nul(&buf[..]) diff --git a/test/test.rs b/test/test.rs index 205ae3329c..00f0e74efb 100644 --- a/test/test.rs +++ b/test/test.rs @@ -7,6 +7,7 @@ mod common; mod sys; #[cfg(not(target_os = "redox"))] mod test_dir; +mod test_errno; mod test_fcntl; #[cfg(linux_android)] mod test_kmod; diff --git a/test/test_errno.rs b/test/test_errno.rs new file mode 100644 index 0000000000..750fc924ff --- /dev/null +++ b/test/test_errno.rs @@ -0,0 +1,16 @@ +use nix::errno::Errno; + +#[test] +fn errno_set_and_read() { + Errno::ENFILE.set(); + assert_eq!(Errno::last(), Errno::ENFILE); +} + +#[test] +fn errno_set_and_clear() { + Errno::ENFILE.set(); + assert_eq!(Errno::last(), Errno::ENFILE); + + Errno::clear(); + assert_eq!(Errno::last(), Errno::from_raw(0)); +} diff --git a/test/test_mount.rs b/test/test_mount.rs index 5cf00408e8..09d80bcc6a 100644 --- a/test/test_mount.rs +++ b/test/test_mount.rs @@ -49,7 +49,7 @@ exit 23"; .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) .open(&test_path) .or_else(|e| { - if Errno::from_i32(e.raw_os_error().unwrap()) + if Errno::from_raw(e.raw_os_error().unwrap()) == Errno::EOVERFLOW { // Skip tests on certain Linux kernels which have a bug From f55dee95ceff8a167dde52a79f07d48c0405d7f8 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 8 Jan 2024 09:02:52 +0800 Subject: [PATCH 120/140] feat: expose the inner fd of Kqueue (#2258) * feat: expose the inner fd of Kqueue * changelog --- changelog/2258.added.md | 4 ++++ src/sys/event.rs | 13 +++++++++++++ 2 files changed, 17 insertions(+) create mode 100644 changelog/2258.added.md diff --git a/changelog/2258.added.md b/changelog/2258.added.md new file mode 100644 index 0000000000..7aa74fdaa4 --- /dev/null +++ b/changelog/2258.added.md @@ -0,0 +1,4 @@ +Expose the inner fd of `Kqueue` through: + +* impl AsFd for Kqueue +* impl From\ for OwnedFd diff --git a/src/sys/event.rs b/src/sys/event.rs index 968c5a4ae2..b294d27c70 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -10,6 +10,7 @@ use libc::{c_int, c_long, intptr_t, time_t, timespec, uintptr_t}; use libc::{c_long, intptr_t, size_t, time_t, timespec, uintptr_t}; use std::convert::TryInto; use std::mem; +use std::os::fd::{AsFd, BorrowedFd}; use std::os::unix::io::{AsRawFd, FromRawFd, OwnedFd}; use std::ptr; @@ -29,6 +30,18 @@ pub struct KEvent { #[derive(Debug)] pub struct Kqueue(OwnedFd); +impl AsFd for Kqueue { + fn as_fd(&self) -> BorrowedFd<'_> { + self.0.as_fd() + } +} + +impl From for OwnedFd { + fn from(value: Kqueue) -> Self { + value.0 + } +} + impl Kqueue { /// Create a new kernel event queue. pub fn new() -> Result { From 3554102175524bd4ed3203692a4cb28e492598ef Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Mon, 8 Jan 2024 09:22:12 +0800 Subject: [PATCH 121/140] feat: AT_EMPTY_PATH for linkat() (#2284) * feat: AT_EMPTY_PATH for linkat() * try fixing import * fix changelog name --- changelog/2284.added.md | 1 + changelog/2284.removed.md | 1 + src/unistd.rs | 26 +++++++++++++------------- test/test_unistd.rs | 20 +++++++++++++++----- 4 files changed, 30 insertions(+), 18 deletions(-) create mode 100644 changelog/2284.added.md create mode 100644 changelog/2284.removed.md diff --git a/changelog/2284.added.md b/changelog/2284.added.md new file mode 100644 index 0000000000..522a9341ce --- /dev/null +++ b/changelog/2284.added.md @@ -0,0 +1 @@ +Enable the `AT_EMPTY_PATH` flag for the `linkat()` function diff --git a/changelog/2284.removed.md b/changelog/2284.removed.md new file mode 100644 index 0000000000..8dde5ffdfe --- /dev/null +++ b/changelog/2284.removed.md @@ -0,0 +1 @@ +The `LinkatFlags` type has been deprecated, please use `AtFlags` instead. diff --git a/src/unistd.rs b/src/unistd.rs index 564dafbb3e..5b8a6dfcff 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1253,11 +1253,16 @@ pub fn isatty(fd: RawFd) -> Result { } } -/// Flags for `linkat` function. -#[derive(Clone, Copy, Debug)] -pub enum LinkatFlags { - SymlinkFollow, - NoSymlinkFollow, +#[cfg(not(target_os = "redox"))] +pub type LinkatFlags = AtFlags; +#[cfg(not(target_os = "redox"))] +impl LinkatFlags { + #[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")] + #[allow(non_upper_case_globals)] + pub const SymlinkFollow: LinkatFlags = LinkatFlags::AT_SYMLINK_FOLLOW; + #[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")] + #[allow(non_upper_case_globals)] + pub const NoSymlinkFollow: LinkatFlags = LinkatFlags::empty(); } /// Link one file to another file @@ -1265,7 +1270,7 @@ pub enum LinkatFlags { /// Creates a new link (directory entry) at `newpath` for the existing file at `oldpath`. In the /// case of a relative `oldpath`, the path is interpreted relative to the directory associated /// with file descriptor `olddirfd` instead of the current working directory and similiarly for -/// `newpath` and file descriptor `newdirfd`. In case `flag` is LinkatFlags::SymlinkFollow and +/// `newpath` and file descriptor `newdirfd`. In case `flag` is `AtFlags::AT_SYMLINK_FOLLOW` and /// `oldpath` names a symoblic link, a new link for the target of the symbolic link is created. /// If either `olddirfd` or `newdirfd` is `None`, `AT_FDCWD` is used respectively where `oldpath` /// and/or `newpath` is then interpreted relative to the current working directory of the calling @@ -1279,13 +1284,8 @@ pub fn linkat( oldpath: &P, newdirfd: Option, newpath: &P, - flag: LinkatFlags, + flag: AtFlags, ) -> Result<()> { - let atflag = match flag { - LinkatFlags::SymlinkFollow => AtFlags::AT_SYMLINK_FOLLOW, - LinkatFlags::NoSymlinkFollow => AtFlags::empty(), - }; - let res = oldpath.with_nix_path(|oldcstr| { newpath.with_nix_path(|newcstr| unsafe { libc::linkat( @@ -1293,7 +1293,7 @@ pub fn linkat( oldcstr.as_ptr(), at_rawfd(newdirfd), newcstr.as_ptr(), - atflag.bits() as libc::c_int, + flag.bits(), ) }) })??; diff --git a/test/test_unistd.rs b/test/test_unistd.rs index b156951e93..ddabbd4fd4 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -897,6 +897,8 @@ fn test_symlinkat() { #[test] #[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_file() { + use nix::fcntl::AtFlags; + let tempdir = tempdir().unwrap(); let oldfilename = "foo.txt"; let oldfilepath = tempdir.path().join(oldfilename); @@ -918,7 +920,7 @@ fn test_linkat_file() { oldfilename, Some(dirfd), newfilename, - LinkatFlags::SymlinkFollow, + AtFlags::AT_SYMLINK_FOLLOW, ) .unwrap(); assert!(newfilepath.exists()); @@ -927,6 +929,8 @@ fn test_linkat_file() { #[test] #[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_olddirfd_none() { + use nix::fcntl::AtFlags; + let _dr = crate::DirRestore::new(); let tempdir_oldfile = tempdir().unwrap(); @@ -955,7 +959,7 @@ fn test_linkat_olddirfd_none() { oldfilename, Some(dirfd), newfilename, - LinkatFlags::SymlinkFollow, + AtFlags::AT_SYMLINK_FOLLOW, ) .unwrap(); assert!(newfilepath.exists()); @@ -964,6 +968,8 @@ fn test_linkat_olddirfd_none() { #[test] #[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_newdirfd_none() { + use nix::fcntl::AtFlags; + let _dr = crate::DirRestore::new(); let tempdir_oldfile = tempdir().unwrap(); @@ -992,7 +998,7 @@ fn test_linkat_newdirfd_none() { oldfilename, None, newfilename, - LinkatFlags::SymlinkFollow, + AtFlags::AT_SYMLINK_FOLLOW, ) .unwrap(); assert!(newfilepath.exists()); @@ -1001,6 +1007,8 @@ fn test_linkat_newdirfd_none() { #[test] #[cfg(not(any(apple_targets, target_os = "redox", target_os = "haiku")))] fn test_linkat_no_follow_symlink() { + use nix::fcntl::AtFlags; + let _m = crate::CWD_LOCK.read(); let tempdir = tempdir().unwrap(); @@ -1030,7 +1038,7 @@ fn test_linkat_no_follow_symlink() { symoldfilename, Some(dirfd), newfilename, - LinkatFlags::NoSymlinkFollow, + AtFlags::empty(), ) .unwrap(); @@ -1044,6 +1052,8 @@ fn test_linkat_no_follow_symlink() { #[test] #[cfg(not(any(target_os = "redox", target_os = "haiku")))] fn test_linkat_follow_symlink() { + use nix::fcntl::AtFlags; + let _m = crate::CWD_LOCK.read(); let tempdir = tempdir().unwrap(); @@ -1073,7 +1083,7 @@ fn test_linkat_follow_symlink() { symoldfilename, Some(dirfd), newfilename, - LinkatFlags::SymlinkFollow, + AtFlags::AT_SYMLINK_FOLLOW, ) .unwrap(); From 1acc5e86138ee796f4c6b4a407cdcfc9b70edac0 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Wed, 10 Jan 2024 18:49:05 +0800 Subject: [PATCH 122/140] docs: fix 2 invalid links[skip ci] (#2286) --- src/sys/socket/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index d7f94d80d1..65a579cd03 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -639,7 +639,7 @@ impl<'a> Iterator for CmsgIterator<'a> { } /// A type-safe wrapper around a single control message, as used with -/// [`recvmsg`](#fn.recvmsg). +/// [`recvmsg`]. /// /// [Further reading](https://man7.org/linux/man-pages/man3/cmsg.3.html) // Nix version 0.13.0 and earlier used ControlMessage for both recvmsg and @@ -1009,9 +1009,9 @@ impl ControlMessageOwned { } } -/// A type-safe zero-copy wrapper around a single control message, as used wih -/// [`sendmsg`](#fn.sendmsg). More types may be added to this enum; do not -/// exhaustively pattern-match it. +/// A type-safe zero-copy wrapper around a single control message, as used with +/// [`sendmsg`]. More types may be added to this enum; do not exhaustively +/// pattern-match it. /// /// [Further reading](https://man7.org/linux/man-pages/man3/cmsg.3.html) #[derive(Clone, Copy, Debug, Eq, PartialEq)] From bfcb2269d1f5e97723a1639cf6a33a85814afdf3 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 14 Jan 2024 17:49:17 -0700 Subject: [PATCH 123/140] deny missing docs in the kmod module (#2292) --- src/kmod.rs | 4 ++++ src/lib.rs | 1 - 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/kmod.rs b/src/kmod.rs index d3725c3f8a..5cf2ed2c39 100644 --- a/src/kmod.rs +++ b/src/kmod.rs @@ -102,7 +102,11 @@ libc_bitflags!( /// See [`man delete_module(2)`](https://man7.org/linux/man-pages/man2/delete_module.2.html) /// for a detailed description how these flags work. pub struct DeleteModuleFlags: libc::c_int { + /// `delete_module` will return immediately, with an error, if the module has a nonzero + /// reference count. O_NONBLOCK; + /// `delete_module` will unload the module immediately, regardless of whether it has a + /// nonzero reference count. O_TRUNC; } ); diff --git a/src/lib.rs b/src/lib.rs index aaf1c2d4c8..87027dd9a7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -135,7 +135,6 @@ feature! { #[cfg(linux_android)] feature! { #![feature = "kmod"] - #[allow(missing_docs)] pub mod kmod; } feature! { From 338d2b36a46dfbf1106597caf3aeac17329507a2 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 14 Jan 2024 18:33:09 -0700 Subject: [PATCH 124/140] Add missing docs for the unistd module (#2290) * Add missing docs for the unistd module * Capitalization Co-authored-by: SteveLauC --------- Co-authored-by: SteveLauC --- src/lib.rs | 1 - src/unistd.rs | 62 +++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 87027dd9a7..728250e57a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -182,7 +182,6 @@ feature! { #[allow(missing_docs)] pub mod ucontext; } -#[allow(missing_docs)] pub mod unistd; #[cfg(any(feature = "poll", feature = "event"))] diff --git a/src/unistd.rs b/src/unistd.rs index 5b8a6dfcff..5860f0dacf 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -217,7 +217,12 @@ impl fmt::Display for Pid { /// you are now executing in the parent process or in the child. #[derive(Clone, Copy, Debug)] pub enum ForkResult { - Parent { child: Pid }, + /// This is the parent process of the fork. + Parent { + /// The PID of the fork's child process + child: Pid + }, + /// This is the child process of the fork. Child, } @@ -324,6 +329,9 @@ pub fn setpgid(pid: Pid, pgid: Pid) -> Result<()> { let res = unsafe { libc::setpgid(pid.into(), pgid.into()) }; Errno::result(res).map(drop) } +/// Get process group +/// +/// See Also [`getpgid`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/getpgid.html) #[inline] pub fn getpgid(pid: Option) -> Result { let res = unsafe { libc::getpgid(pid.unwrap_or(Pid(0)).into()) }; @@ -738,8 +746,10 @@ pub fn fchown(fd: RawFd, owner: Option, group: Option) -> Result<()> { } // Just a wrapper around `AtFlags` so that we can help our users migrate. +#[allow(missing_docs)] #[cfg(not(target_os = "redox"))] pub type FchownatFlags = AtFlags; +#[allow(missing_docs)] #[cfg(not(target_os = "redox"))] impl FchownatFlags { #[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")] @@ -1152,6 +1162,10 @@ pub fn lseek(fd: RawFd, offset: off_t, whence: Whence) -> Result { Errno::result(res).map(|r| r as off_t) } +/// Move the read/write file offset. +/// +/// Unlike [`lseek`], it takes a 64-bit argument even on platforms where [`libc::off_t`] is +/// 32 bits. #[cfg(linux_android)] pub fn lseek64( fd: RawFd, @@ -1238,6 +1252,7 @@ pub fn ftruncate(fd: Fd, len: off_t) -> Result<()> { Errno::result(unsafe { libc::ftruncate(fd.as_fd().as_raw_fd(), len) }).map(drop) } +/// Determines if the file descriptor refers to a valid terminal type device. pub fn isatty(fd: RawFd) -> Result { unsafe { // ENOTTY means `fd` is a valid file descriptor, but not a TTY, so @@ -1253,8 +1268,10 @@ pub fn isatty(fd: RawFd) -> Result { } } +#[allow(missing_docs)] #[cfg(not(target_os = "redox"))] pub type LinkatFlags = AtFlags; +#[allow(missing_docs)] #[cfg(not(target_os = "redox"))] impl LinkatFlags { #[deprecated(since = "0.28.0", note = "The variant is deprecated, please use `AtFlags` instead")] @@ -1312,7 +1329,9 @@ pub fn unlink(path: &P) -> Result<()> { /// Flags for `unlinkat` function. #[derive(Clone, Copy, Debug)] pub enum UnlinkatFlags { + /// Remove the directory entry as a directory, not a normal file RemoveDir, + /// Remove the directory entry as a normal file, not a directory NoRemoveDir, } @@ -1346,6 +1365,7 @@ pub fn unlinkat( Errno::result(res).map(drop) } +/// Change a process's root directory #[inline] #[cfg(not(target_os = "fuchsia"))] pub fn chroot(path: &P) -> Result<()> { @@ -1874,6 +1894,7 @@ pub fn sleep(seconds: c_uint) -> c_uint { feature! { #![feature = "acct"] +/// Process accounting #[cfg(not(any(target_os = "redox", target_os = "haiku")))] pub mod acct { use crate::errno::Errno; @@ -2258,7 +2279,7 @@ pub enum SysconfVar { BC_STRING_MAX = libc::_SC_BC_STRING_MAX, /// Maximum number of simultaneous processes per real user ID. CHILD_MAX = libc::_SC_CHILD_MAX, - // The number of clock ticks per second. + /// The frequency of the statistics clock in ticks per second. CLK_TCK = libc::_SC_CLK_TCK, /// Maximum number of weights that can be assigned to an entry of the /// LC_COLLATE order keyword in the locale definition file @@ -2427,6 +2448,8 @@ pub enum SysconfVar { ))] /// The implementation supports the Process Sporadic Server option. _POSIX_SPORADIC_SERVER = libc::_SC_SPORADIC_SERVER, + /// The number of replenishment operations that can be simultaneously pending for a particular + /// sporadic server scheduler. #[cfg(any( apple_targets, target_os = "linux", @@ -2518,6 +2541,7 @@ pub enum SysconfVar { ))] /// The implementation supports the Trace Event Filter option. _POSIX_TRACE_EVENT_FILTER = libc::_SC_TRACE_EVENT_FILTER, + /// Maximum size of a trace event name in characters. #[cfg(any( apple_targets, target_os = "linux", @@ -2540,18 +2564,22 @@ pub enum SysconfVar { ))] /// The implementation supports the Trace Log option. _POSIX_TRACE_LOG = libc::_SC_TRACE_LOG, + /// The length in bytes of a trace generation version string or a trace stream name. #[cfg(any( apple_targets, target_os = "linux", target_os = "openbsd" ))] _POSIX_TRACE_NAME_MAX = libc::_SC_TRACE_NAME_MAX, + /// Maximum number of times `posix_trace_create` may be called from the same or different + /// processes. #[cfg(any( apple_targets, target_os = "linux", target_os = "openbsd" ))] _POSIX_TRACE_SYS_MAX = libc::_SC_TRACE_SYS_MAX, + /// Maximum number of user trace event type identifiers for a single process. #[cfg(any( apple_targets, target_os = "linux", @@ -2641,16 +2669,24 @@ pub enum SysconfVar { /// POSIX also defines an alias named `PAGESIZE`, but Rust does not allow two /// enum constants to have the same value, so nix omits `PAGESIZE`. PAGE_SIZE = libc::_SC_PAGE_SIZE, + /// Maximum number of attempts made to destroy a thread's thread-specific data values on thread + /// exit. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] PTHREAD_DESTRUCTOR_ITERATIONS = libc::_SC_THREAD_DESTRUCTOR_ITERATIONS, + /// Maximum number of data keys that can be created by a process. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] PTHREAD_KEYS_MAX = libc::_SC_THREAD_KEYS_MAX, + /// Minimum size in bytes of thread stack storage. #[cfg(not(target_os = "redox"))] PTHREAD_STACK_MIN = libc::_SC_THREAD_STACK_MIN, + /// Maximum number of threads that can be created per process. #[cfg(not(any(target_os = "redox", target_os = "haiku")))] PTHREAD_THREADS_MAX = libc::_SC_THREAD_THREADS_MAX, + /// The maximum number of repeated occurrences of a regular expression permitted when using + /// interval notation. #[cfg(not(target_os = "haiku"))] RE_DUP_MAX = libc::_SC_RE_DUP_MAX, + /// Maximum number of realtime signals reserved for application use. #[cfg(any( linux_android, freebsdlike, @@ -2658,8 +2694,10 @@ pub enum SysconfVar { target_os = "openbsd" ))] RTSIG_MAX = libc::_SC_RTSIG_MAX, + /// Maximum number of semaphores that a process may have. #[cfg(not(target_os = "redox"))] SEM_NSEMS_MAX = libc::_SC_SEM_NSEMS_MAX, + /// The maximum value a semaphore may have. #[cfg(any( linux_android, freebsdlike, @@ -2667,6 +2705,8 @@ pub enum SysconfVar { target_os = "openbsd" ))] SEM_VALUE_MAX = libc::_SC_SEM_VALUE_MAX, + /// Maximum number of queued signals that a process may send and have pending at the + /// receiver(s) at any time. #[cfg(any( linux_android, freebsdlike, @@ -2674,12 +2714,18 @@ pub enum SysconfVar { target_os = "openbsd" ))] SIGQUEUE_MAX = libc::_SC_SIGQUEUE_MAX, + /// The minimum maximum number of streams that a process may have open at any one time. STREAM_MAX = libc::_SC_STREAM_MAX, + /// Maximum number of symbolic links that can be reliably traversed in the resolution of a + /// pathname in the absence of a loop. #[cfg(any(bsd, target_os = "linux"))] SYMLOOP_MAX = libc::_SC_SYMLOOP_MAX, + /// Maximum number of timers per process supported. #[cfg(not(target_os = "redox"))] TIMER_MAX = libc::_SC_TIMER_MAX, + /// Maximum length of terminal device name. TTY_NAME_MAX = libc::_SC_TTY_NAME_MAX, + /// The minimum maximum number of types supported for the name of a timezone. TZNAME_MAX = libc::_SC_TZNAME_MAX, #[cfg(any( linux_android, @@ -2704,6 +2750,9 @@ pub enum SysconfVar { apple_targets, target_os = "openbsd" ))] + /// The implementation supports the XOpen Legacy Option group. + /// + /// See Also _XOPEN_LEGACY = libc::_SC_XOPEN_LEGACY, #[cfg(any( linux_android, @@ -2804,6 +2853,9 @@ mod pivot_root { use crate::errno::Errno; use crate::{NixPath, Result}; + /// Change the root file system. + /// + /// See Also [`pivot_root`](https://man7.org/linux/man-pages/man2/pivot_root.2.html) pub fn pivot_root( new_root: &P1, put_old: &P2, @@ -2879,16 +2931,22 @@ mod getres { /// Real, effective and saved user IDs. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct ResUid { + /// Real UID pub real: Uid, + /// Effective UID pub effective: Uid, + /// Saved UID pub saved: Uid, } /// Real, effective and saved group IDs. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub struct ResGid { + /// Real GID pub real: Gid, + /// Effective GID pub effective: Gid, + /// Saved GID pub saved: Gid, } From df7e56afb0e1e3a047ced471d8ad6af7a578374e Mon Sep 17 00:00:00 2001 From: Terts Diepraam Date: Wed, 17 Jan 2024 13:49:38 +0100 Subject: [PATCH 125/140] enable unistd::{sync, syncfs} on Android (#2296) --- changelog/2296.added.md | 1 + src/unistd.rs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 changelog/2296.added.md diff --git a/changelog/2296.added.md b/changelog/2296.added.md new file mode 100644 index 0000000000..4ec5fe0a29 --- /dev/null +++ b/changelog/2296.added.md @@ -0,0 +1 @@ +Enable unistd::{sync, syncfs} for Android \ No newline at end of file diff --git a/src/unistd.rs b/src/unistd.rs index 5860f0dacf..6d8e66f424 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -1378,7 +1378,7 @@ pub fn chroot(path: &P) -> Result<()> { /// Commit filesystem caches to disk /// /// See also [sync(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/sync.html) -#[cfg(any(freebsdlike, target_os = "linux", netbsdlike))] +#[cfg(any(freebsdlike, linux_android, netbsdlike))] pub fn sync() { unsafe { libc::sync() }; } @@ -1387,7 +1387,7 @@ pub fn sync() { /// descriptor `fd` to disk /// /// See also [syncfs(2)](https://man7.org/linux/man-pages/man2/sync.2.html) -#[cfg(target_os = "linux")] +#[cfg(linux_android)] pub fn syncfs(fd: RawFd) -> Result<()> { let res = unsafe { libc::syncfs(fd) }; From dcd30a55f453b7fa5c38a21efc1fdb5c8b599159 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Thu, 18 Jan 2024 10:57:22 +0800 Subject: [PATCH 126/140] ci: run Linux aarch64 && FreeBSD checks in parallel (#2297) --- .cirrus.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.cirrus.yml b/.cirrus.yml index d2df3ba4f5..1daf2c8ad1 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -72,8 +72,6 @@ task: arm_container: image: rust:1.69.0 cpu: 1 - depends_on: - - FreeBSD 14 amd64 & i686 env: TARGET: aarch64-unknown-linux-gnu setup_script: From 254ded9f0a80d0a8ee6db1f10575df428c1a5cfa Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 21 Jan 2024 18:09:38 -0700 Subject: [PATCH 127/140] Add a Safety section to rfork's docs. (#2299) --- src/unistd.rs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/unistd.rs b/src/unistd.rs index 6d8e66f424..3d98a0efe8 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -3032,9 +3032,17 @@ libc_bitflags! { feature! { #![feature = "process"] #[cfg(target_os = "freebsd")] -/// rfork can be used to have a tigher control about which resources child -/// and parent process will be sharing, file descriptors, address spaces -/// and child exit's behavior. +/// Like [`fork`], `rfork` can be used to have a tigher control about which +/// resources child and parent process will be sharing, file descriptors, +/// address spaces and child exit's behavior. +/// +/// # Safety +/// +/// The same restrictions apply as for [`fork`]. +/// +/// # See Also +/// +/// * [rfork(2)](https://man.freebsd.org/cgi/man.cgi?query=rfork) pub unsafe fn rfork(flags: RforkFlags) -> Result { use ForkResult::*; let res = unsafe { libc::rfork(flags.bits()) }; From d9e1146898522cde59878ad1c0aececdc2ed76ef Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Sun, 21 Jan 2024 20:00:42 -0700 Subject: [PATCH 128/140] Add docs to the time and fcntl modules (#2289) * Add docs to the time and fcntl modules Also, deprecate FlockArg::UnlockNonblock. That combination of flags doesn't make sense. And indeed, reviewing the kernel source code shows that the kernel will ignore LOCK_NB when LOCK_UN is set. * Respond to @SteveLauC's review feedback. --- src/fcntl.rs | 143 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 2 - src/time.rs | 44 +++++++++++++--- 3 files changed, 181 insertions(+), 8 deletions(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index e4a2d73c41..c1c8a4f196 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -1,3 +1,4 @@ +//! file control options use crate::errno::Errno; #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] use core::slice; @@ -45,15 +46,29 @@ pub use self::posix_fadvise::{posix_fadvise, PosixFadviseAdvice}; #[cfg(not(target_os = "redox"))] #[cfg(any(feature = "fs", feature = "process", feature = "user"))] libc_bitflags! { + /// Flags that control how the various *at syscalls behave. #[cfg_attr(docsrs, doc(cfg(any(feature = "fs", feature = "process"))))] pub struct AtFlags: c_int { + #[allow(missing_docs)] + #[doc(hidden)] + // Should not be used by the public API, but only internally. AT_REMOVEDIR; + /// Used with [`linkat`](crate::unistd::linkat`) to create a link to a symbolic link's + /// target, instead of to the symbolic link itself. AT_SYMLINK_FOLLOW; + /// Used with functions like [`fstatat`](crate::sys::stat::fstatat`) to operate on a link + /// itself, instead of the symbolic link's target. AT_SYMLINK_NOFOLLOW; + /// Don't automount the terminal ("basename") component of pathname if it is a directory + /// that is an automount point. #[cfg(linux_android)] AT_NO_AUTOMOUNT; + /// If the provided path is an empty string, operate on the provided directory file + /// descriptor instead. #[cfg(any(linux_android, target_os = "freebsd", target_os = "hurd"))] AT_EMPTY_PATH; + /// Used with [`faccessat`](crate::unistd::faccessat), the checks for accessibility are + /// performed using the effective user and group IDs instead of the real user and group ID #[cfg(not(target_os = "android"))] AT_EACCESS; } @@ -186,6 +201,10 @@ pub(crate) fn at_rawfd(fd: Option) -> raw::c_int { feature! { #![feature = "fs"] +/// open or create a file for reading, writing or executing +/// +/// # See Also +/// [`open`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html) // The conversion is not identical on all operating systems. #[allow(clippy::useless_conversion)] pub fn open( @@ -200,6 +219,14 @@ pub fn open( Errno::result(fd) } +/// open or create a file for reading, writing or executing +/// +/// The `openat` function is equivalent to the [`open`] function except in the case where the path +/// specifies a relative path. In that case, the file to be opened is determined relative to the +/// directory associated with the file descriptor `fd`. +/// +/// # See Also +/// [`openat`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/openat.html) // The conversion is not identical on all operating systems. #[allow(clippy::useless_conversion)] #[cfg(not(target_os = "redox"))] @@ -215,6 +242,14 @@ pub fn openat( Errno::result(fd) } +/// Change the name of a file. +/// +/// The `renameat` function is equivalent to `rename` except in the case where either `old_path` +/// or `new_path` specifies a relative path. In such cases, the file to be renamed (or the its new +/// name, respectively) is located relative to `old_dirfd` or `new_dirfd`, respectively +/// +/// # See Also +/// [`renameat`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html) #[cfg(not(target_os = "redox"))] pub fn renameat( old_dirfd: Option, @@ -239,16 +274,30 @@ pub fn renameat( #[cfg(all(target_os = "linux", target_env = "gnu"))] #[cfg(feature = "fs")] libc_bitflags! { + /// Flags for use with [`renameat2`]. #[cfg_attr(docsrs, doc(cfg(feature = "fs")))] pub struct RenameFlags: u32 { + /// Atomically exchange `old_path` and `new_path`. RENAME_EXCHANGE; + /// Don't overwrite `new_path` of the rename. Return an error if `new_path` already + /// exists. RENAME_NOREPLACE; + /// creates a "whiteout" object at the source of the rename at the same time as performing + /// the rename. + /// + /// This operation makes sense only for overlay/union filesystem implementations. RENAME_WHITEOUT; } } feature! { #![feature = "fs"] +/// Like [`renameat`], but with an additional `flags` argument. +/// +/// A `renameat2` call with an empty flags argument is equivalent to `renameat`. +/// +/// # See Also +/// * [`rename`](https://man7.org/linux/man-pages/man2/rename.2.html) #[cfg(all(target_os = "linux", target_env = "gnu"))] pub fn renameat2( old_dirfd: Option, @@ -389,10 +438,21 @@ fn inner_readlink( } } +/// Read value of a symbolic link +/// +/// # See Also +/// * [`readlink`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html) pub fn readlink(path: &P) -> Result { inner_readlink(None, path) } +/// Read value of a symbolic link. +/// +/// Equivalent to [`readlink` ] except where `path` specifies a relative path. In that case, +/// interpret `path` relative to open file specified by `dirfd`. +/// +/// # See Also +/// * [`readlink`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readlink.html) #[cfg(not(target_os = "redox"))] pub fn readlinkat( dirfd: Option, @@ -437,69 +497,105 @@ libc_bitflags!( feature! { #![feature = "fs"] +/// Commands for use with [`fcntl`]. #[cfg(not(target_os = "redox"))] #[derive(Debug, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum FcntlArg<'a> { + /// Duplicate the provided file descriptor F_DUPFD(RawFd), + /// Duplicate the provided file descriptor and set the `FD_CLOEXEC` flag on it. F_DUPFD_CLOEXEC(RawFd), + /// Get the close-on-exec flag associated with the file descriptor F_GETFD, + /// Set the close-on-exec flag associated with the file descriptor F_SETFD(FdFlag), // FD_FLAGS + /// Get descriptor status flags F_GETFL, + /// Set descriptor status flags F_SETFL(OFlag), // O_NONBLOCK + /// Set or clear a file segment lock F_SETLK(&'a libc::flock), + /// Like [`F_SETLK`](FcntlArg::F_SETLK) except that if a shared or exclusive lock is blocked by + /// other locks, the process waits until the request can be satisfied. F_SETLKW(&'a libc::flock), + /// Get the first lock that blocks the lock description F_GETLK(&'a mut libc::flock), + /// Acquire or release an open file description lock #[cfg(linux_android)] F_OFD_SETLK(&'a libc::flock), + /// Like [`F_OFD_SETLK`](FcntlArg::F_OFD_SETLK) except that if a conflicting lock is held on + /// the file, then wait for that lock to be released. #[cfg(linux_android)] F_OFD_SETLKW(&'a libc::flock), + /// Determine whether it would be possible to create the given lock. If not, return details + /// about one existing lock that would prevent it. #[cfg(linux_android)] F_OFD_GETLK(&'a mut libc::flock), + /// Add seals to the file #[cfg(any( linux_android, target_os = "freebsd" ))] F_ADD_SEALS(SealFlag), + /// Get seals associated with the file #[cfg(any( linux_android, target_os = "freebsd" ))] F_GET_SEALS, + /// Asks the drive to flush all buffered data to permanent storage. #[cfg(apple_targets)] F_FULLFSYNC, + /// fsync + issue barrier to drive #[cfg(apple_targets)] F_BARRIERFSYNC, + /// Return the capacity of a pipe #[cfg(linux_android)] F_GETPIPE_SZ, + /// Change the capacity of a pipe #[cfg(linux_android)] F_SETPIPE_SZ(c_int), + /// Look up the path of an open file descriptor, if possible. #[cfg(any( target_os = "netbsd", target_os = "dragonfly", apple_targets, ))] F_GETPATH(&'a mut PathBuf), + /// Look up the path of an open file descriptor, if possible. #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] F_KINFO(&'a mut PathBuf), + /// Return the full path without firmlinks of the fd. #[cfg(apple_targets)] F_GETPATH_NOFIRMLINK(&'a mut PathBuf), // TODO: Rest of flags } +/// Commands for use with [`fcntl`]. #[cfg(target_os = "redox")] #[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum FcntlArg { + /// Duplicate the provided file descriptor F_DUPFD(RawFd), + /// Duplicate the provided file descriptor and set the `FD_CLOEXEC` flag on it. F_DUPFD_CLOEXEC(RawFd), + /// Get the close-on-exec flag associated with the file descriptor F_GETFD, + /// Set the close-on-exec flag associated with the file descriptor F_SETFD(FdFlag), // FD_FLAGS + /// Get descriptor status flags F_GETFL, + /// Set descriptor status flags F_SETFL(OFlag), // O_NONBLOCK } pub use self::FcntlArg::*; +/// Perform various operations on open file descriptors. +/// +/// # See Also +/// * [`fcntl`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/fcntl.html) // TODO: Figure out how to handle value fcntl returns pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { let res = unsafe { @@ -584,17 +680,27 @@ pub fn fcntl(fd: RawFd, arg: FcntlArg) -> Result { Errno::result(res) } +/// Operations for use with [`Flock::lock`]. +#[cfg(not(any(target_os = "redox", target_os = "solaris")))] #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] #[non_exhaustive] pub enum FlockArg { + /// shared file lock LockShared, + /// exclusive file lock LockExclusive, + /// Unlock file Unlock, + /// Shared lock. Do not block when locking. LockSharedNonblock, + /// Exclusive lock. Do not block when locking. LockExclusiveNonblock, + #[allow(missing_docs)] + #[deprecated(since = "0.28.0", note = "Use FlockArg::Unlock instead")] UnlockNonblock, } +#[allow(missing_docs)] #[cfg(not(any(target_os = "redox", target_os = "solaris")))] #[deprecated(since = "0.28.0", note = "`fcntl::Flock` should be used instead.")] pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> { @@ -611,6 +717,7 @@ pub fn flock(fd: RawFd, arg: FlockArg) -> Result<()> { LockExclusiveNonblock => { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) } + #[allow(deprecated)] UnlockNonblock => libc::flock(fd, libc::LOCK_UN | libc::LOCK_NB), } }; @@ -683,6 +790,7 @@ impl Flock { FlockArg::LockExclusive => libc::LOCK_EX, FlockArg::LockSharedNonblock => libc::LOCK_SH | libc::LOCK_NB, FlockArg::LockExclusiveNonblock => libc::LOCK_EX | libc::LOCK_NB, + #[allow(deprecated)] FlockArg::Unlock | FlockArg::UnlockNonblock => return Err((t, Errno::EINVAL)), }; match Errno::result(unsafe { libc::flock(t.as_raw_fd(), flags) }) { @@ -827,6 +935,10 @@ pub fn copy_file_range( Errno::result(ret).map(|r| r as usize) } +/// Splice data to/from a pipe +/// +/// # See Also +/// *[`splice`](https://man7.org/linux/man-pages/man2/splice.2.html) #[cfg(linux_android)] pub fn splice( fd_in: RawFd, @@ -849,6 +961,10 @@ pub fn splice( Errno::result(ret).map(|r| r as usize) } +/// Duplicate pipe content +/// +/// # See Also +/// *[`tee`](https://man7.org/linux/man-pages/man2/tee.2.html) #[cfg(linux_android)] pub fn tee( fd_in: RawFd, @@ -860,6 +976,10 @@ pub fn tee( Errno::result(ret).map(|r| r as usize) } +/// Splice user pages to/from a pipe +/// +/// # See Also +/// *[`vmsplice`](https://man7.org/linux/man-pages/man2/vmsplice.2.html) #[cfg(linux_android)] pub fn vmsplice( fd: RawFd, @@ -938,16 +1058,22 @@ pub struct SpacectlRange(pub libc::off_t, pub libc::off_t); #[cfg(any(target_os = "freebsd"))] impl SpacectlRange { + /// Is the range empty? + /// + /// After a successful call to [`fspacectl`], A value of `true` for `SpacectlRange::is_empty` + /// indicates that the operation is complete. #[inline] pub fn is_empty(&self) -> bool { self.1 == 0 } + /// Remaining length of the range #[inline] pub fn len(&self) -> libc::off_t { self.1 } + /// Next file offset to operate on #[inline] pub fn offset(&self) -> libc::off_t { self.0 @@ -1083,21 +1209,34 @@ mod posix_fadvise { #[cfg(feature = "fs")] libc_enum! { + /// The specific advice provided to [`posix_fadvise`]. #[repr(i32)] #[non_exhaustive] #[cfg_attr(docsrs, doc(cfg(feature = "fs")))] pub enum PosixFadviseAdvice { + /// Revert to the default data access behavior. POSIX_FADV_NORMAL, + /// The file data will be accessed sequentially. POSIX_FADV_SEQUENTIAL, + /// A hint that file data will be accessed randomly, and prefetching is likely not + /// advantageous. POSIX_FADV_RANDOM, + /// The specified data will only be accessed once and then not reused. POSIX_FADV_NOREUSE, + /// The specified data will be accessed in the near future. POSIX_FADV_WILLNEED, + /// The specified data will not be accessed in the near future. POSIX_FADV_DONTNEED, } } feature! { #![feature = "fs"] + /// Allows a process to describe to the system its data access behavior for an open file + /// descriptor. + /// + /// # See Also + /// * [`posix_fadvise`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_fadvise.html) pub fn posix_fadvise( fd: RawFd, offset: libc::off_t, @@ -1115,6 +1254,10 @@ mod posix_fadvise { } } +/// Pre-allocate storage for a range in a file +/// +/// # See Also +/// * [`posix_fallocate`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/posix_fallocate.html) #[cfg(any( linux_android, freebsdlike, diff --git a/src/lib.rs b/src/lib.rs index 728250e57a..dffac29b54 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -118,7 +118,6 @@ feature! { #[deny(missing_docs)] pub mod features; } -#[allow(missing_docs)] pub mod fcntl; feature! { #![feature = "net"] @@ -163,7 +162,6 @@ feature! { pub mod sys; feature! { #![feature = "time"] - #[allow(missing_docs)] pub mod time; } // This can be implemented for other platforms as soon as libc diff --git a/src/time.rs b/src/time.rs index d50324ddd3..195df71211 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,3 +1,4 @@ +//! Sleep, query system clocks, and set system clock use crate::sys::time::TimeSpec; #[cfg(any(freebsdlike, linux_android, target_os = "emscripten"))] #[cfg(feature = "process")] @@ -8,8 +9,7 @@ use std::mem::MaybeUninit; /// Clock identifier /// -/// Newtype pattern around `clockid_t` (which is just alias). It prevents bugs caused by -/// accidentally passing wrong value. +/// Newtype pattern around [`libc::clockid_t`]. #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct ClockId(clockid_t); @@ -57,20 +57,30 @@ impl ClockId { } #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] + /// Starts at zero when the kernel boots and increments monotonically in SI seconds while the + /// machine is running. pub const CLOCK_BOOTTIME: ClockId = ClockId(libc::CLOCK_BOOTTIME); + /// Like [`CLOCK_BOOTTIME`](ClockId::CLOCK_BOOTTIME), but will wake the system if it is + /// suspended.. #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_BOOTTIME_ALARM: ClockId = ClockId(libc::CLOCK_BOOTTIME_ALARM); + /// Increments in SI seconds. pub const CLOCK_MONOTONIC: ClockId = ClockId(libc::CLOCK_MONOTONIC); + /// Like [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but optimized for execution time at the expense of accuracy. #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_MONOTONIC_COARSE: ClockId = ClockId(libc::CLOCK_MONOTONIC_COARSE); #[cfg(freebsdlike)] + /// Like [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but optimized for execution time at the expense of accuracy. pub const CLOCK_MONOTONIC_FAST: ClockId = ClockId(libc::CLOCK_MONOTONIC_FAST); #[cfg(freebsdlike)] + /// Like [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but optimized for accuracy at the expense of execution time. pub const CLOCK_MONOTONIC_PRECISE: ClockId = ClockId(libc::CLOCK_MONOTONIC_PRECISE); + /// Similar to [`CLOCK_MONOTONIC`](ClockId::CLOCK_MONOTONIC), but provides access to a raw + /// hardware-based time that is not subject to NTP adjustments. #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_MONOTONIC_RAW: ClockId = ClockId(libc::CLOCK_MONOTONIC_RAW); #[cfg(any( @@ -81,30 +91,43 @@ impl ClockId { target_os = "fuchsia", target_os = "redox", ))] + /// Returns the execution time of the calling process. pub const CLOCK_PROCESS_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_PROCESS_CPUTIME_ID); #[cfg(freebsdlike)] + /// Increments when the CPU is running in user or kernel mode pub const CLOCK_PROF: ClockId = ClockId(libc::CLOCK_PROF); + /// Increments as a wall clock should. pub const CLOCK_REALTIME: ClockId = ClockId(libc::CLOCK_REALTIME); + /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but not settable. #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_REALTIME_ALARM: ClockId = ClockId(libc::CLOCK_REALTIME_ALARM); + /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but optimized for execution time at the expense of accuracy. #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_REALTIME_COARSE: ClockId = ClockId(libc::CLOCK_REALTIME_COARSE); #[cfg(freebsdlike)] + /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but optimized for execution time at the expense of accuracy. pub const CLOCK_REALTIME_FAST: ClockId = ClockId(libc::CLOCK_REALTIME_FAST); #[cfg(freebsdlike)] + /// Like [`CLOCK_REALTIME`](ClockId::CLOCK_REALTIME), but optimized for accuracy at the expense of execution time. pub const CLOCK_REALTIME_PRECISE: ClockId = ClockId(libc::CLOCK_REALTIME_PRECISE); #[cfg(freebsdlike)] + /// Returns the current second without performing a full time counter query, using an in-kernel + /// cached value of the current second. pub const CLOCK_SECOND: ClockId = ClockId(libc::CLOCK_SECOND); + #[allow(missing_docs)] // Undocumented on Linux! #[cfg(any( target_os = "emscripten", target_os = "fuchsia", all(target_os = "linux", target_env = "musl") ))] pub const CLOCK_SGI_CYCLE: ClockId = ClockId(libc::CLOCK_SGI_CYCLE); + /// International Atomic Time. + /// + /// A nonsettable system-wide clock derived from wall-clock time but ignoring leap seconds. #[cfg(any(linux_android, target_os = "emscripten", target_os = "fuchsia"))] pub const CLOCK_TAI: ClockId = ClockId(libc::CLOCK_TAI); #[cfg(any( @@ -114,16 +137,22 @@ impl ClockId { target_os = "emscripten", target_os = "fuchsia", ))] + /// Returns the execution time of the calling thread. pub const CLOCK_THREAD_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_THREAD_CPUTIME_ID); #[cfg(freebsdlike)] + /// Starts at zero when the kernel boots and increments monotonically in SI seconds while the + /// machine is running. pub const CLOCK_UPTIME: ClockId = ClockId(libc::CLOCK_UPTIME); #[cfg(freebsdlike)] + /// Like [`CLOCK_UPTIME`](ClockId::CLOCK_UPTIME), but optimized for execution time at the expense of accuracy. pub const CLOCK_UPTIME_FAST: ClockId = ClockId(libc::CLOCK_UPTIME_FAST); #[cfg(freebsdlike)] + /// Like [`CLOCK_UPTIME`](ClockId::CLOCK_UPTIME), but optimized for accuracy at the expense of execution time. pub const CLOCK_UPTIME_PRECISE: ClockId = ClockId(libc::CLOCK_UPTIME_PRECISE); #[cfg(freebsdlike)] + /// Increments only when the CPU is running in user mode on behalf of the calling process. pub const CLOCK_VIRTUAL: ClockId = ClockId(libc::CLOCK_VIRTUAL); } @@ -211,15 +240,18 @@ pub fn clock_getcpuclockid(pid: Pid) -> Result { libc_bitflags! { /// Flags that are used for arming the timer. pub struct ClockNanosleepFlags: libc::c_int { + /// Indicates that a requested time value should be treated as absolute instead of + /// relative. TIMER_ABSTIME; } } /// Suspend execution of this thread for the amount of time specified by `request` -/// and measured against the clock speficied by `clock_id`. If `flags` is -/// `TIMER_ABSTIME`, this function will suspend execution until the time value of -/// clock_id reaches the absolute time specified by `request`. If a signal is caught -/// by a signal-catching function, or a signal causes the process to terminate, +/// and measured against the clock speficied by `clock_id`. +/// +/// If `flags` is [`TIMER_ABSTIME`](ClockNanosleepFlags::TIMER_ABSTIME), this function will suspend +/// execution until the time value of clock_id reaches the absolute time specified by `request`. If +/// a signal is caught by a signal-catching function, or a signal causes the process to terminate, /// this sleep is interrrupted. /// /// see also [man 3 clock_nanosleep](https://pubs.opengroup.org/onlinepubs/009695399/functions/clock_nanosleep.html) From 6d308834fd1bc949dedc2c25923e6283ebe59859 Mon Sep 17 00:00:00 2001 From: Keeyou Date: Tue, 30 Jan 2024 10:14:05 +0800 Subject: [PATCH 129/140] Fix compilation error with target_env=ohos (#2301) OpenHarmony(alias ohos) is tie 3 supported target for rust. see https://github.com/rust-lang/compiler-team/issues/568. In implementation it sits close to musl instead of bionic and napi instead jni when comparing with android. Tested with: - cargo build --target x86_64-unknown-linux-ohos --features acct,dir,env,fs - cargo build --target aarch64-unknown-linux-ohos --features acct,dir,env,fs --- src/fcntl.rs | 2 +- src/sys/statfs.rs | 19 +++++++++++++++++-- src/sys/statvfs.rs | 2 +- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/fcntl.rs b/src/fcntl.rs index c1c8a4f196..ed197ecf26 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -126,7 +126,7 @@ libc_bitflags!( O_EXLOCK; /// Same as `O_SYNC`. #[cfg(any(bsd, - all(target_os = "linux", not(target_env = "musl")), + all(target_os = "linux", not(target_env = "musl"), not(target_env = "ohos")), target_os = "redox"))] O_FSYNC; /// Allow files whose sizes can't be represented in an `off_t` to be opened. diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index c3f7388a4d..b2315f4ceb 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -55,6 +55,8 @@ type fs_type_t = libc::c_ulong; type fs_type_t = libc::c_uint; #[cfg(all(target_os = "linux", target_env = "musl"))] type fs_type_t = libc::c_ulong; +#[cfg(all(target_os = "linux", target_env = "ohos"))] +type fs_type_t = libc::c_ulong; #[cfg(all(target_os = "linux", target_env = "uclibc"))] type fs_type_t = libc::c_int; #[cfg(all( @@ -62,6 +64,7 @@ type fs_type_t = libc::c_int; not(any( target_arch = "s390x", target_env = "musl", + target_env = "ohos", target_env = "uclibc" )) ))] @@ -73,6 +76,7 @@ type fs_type_t = libc::__fsword_t; target_os = "android", all(target_os = "linux", target_arch = "s390x"), all(target_os = "linux", target_env = "musl"), + all(target_os = "linux", target_env = "ohos"), all( target_os = "linux", not(any(target_arch = "s390x", target_env = "musl")) @@ -279,7 +283,7 @@ pub const XENFS_SUPER_MAGIC: FsType = #[cfg(linux_android)] #[allow(missing_docs)] pub const NSFS_MAGIC: FsType = FsType(libc::NSFS_MAGIC as fs_type_t); -#[cfg(all(linux_android, not(target_env = "musl")))] +#[cfg(all(linux_android, not(target_env = "musl"), not(target_env = "ohos")))] #[allow(missing_docs)] pub const XFS_SUPER_MAGIC: FsType = FsType(libc::XFS_SUPER_MAGIC as fs_type_t); @@ -322,7 +326,8 @@ impl Statfs { /// Optimal transfer block size #[cfg(any( target_os = "android", - all(target_os = "linux", target_env = "musl") + all(target_os = "linux", target_env = "musl"), + all(target_os = "linux", target_env = "ohos") ))] pub fn optimal_transfer_size(&self) -> libc::c_ulong { self.0.f_bsize @@ -334,6 +339,7 @@ impl Statfs { not(any( target_arch = "s390x", target_env = "musl", + target_env = "ohos", target_env = "uclibc" )) ))] @@ -379,6 +385,13 @@ impl Statfs { self.0.f_bsize } + /// Size of a block + // f_bsize on linux: https://github.com/torvalds/linux/blob/master/fs/nfs/super.c#L471 + #[cfg(all(target_os = "linux", target_env = "ohos"))] + pub fn block_size(&self) -> libc::c_ulong { + self.0.f_bsize + } + /// Size of a block // f_bsize on linux: https://github.com/torvalds/linux/blob/master/fs/nfs/super.c#L471 #[cfg(all(target_os = "linux", target_env = "uclibc"))] @@ -393,6 +406,7 @@ impl Statfs { not(any( target_arch = "s390x", target_env = "musl", + target_env = "ohos", target_env = "uclibc" )) ))] @@ -463,6 +477,7 @@ impl Statfs { not(any( target_arch = "s390x", target_env = "musl", + target_env = "ohos", target_env = "uclibc" )) ))] diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 7de326200e..db1abdd4fe 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -48,7 +48,7 @@ libc_bitflags!( #[cfg(linux_android)] ST_NODIRATIME; /// Update access time relative to modify/change time - #[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"))))] + #[cfg(any(target_os = "android", all(target_os = "linux", not(target_env = "musl"), not(target_env = "ohos"))))] ST_RELATIME; } ); From 64e2de072a4e27c5946237873482223d449a4414 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Wed, 31 Jan 2024 09:58:00 +0800 Subject: [PATCH 130/140] chore(deps): try libc 0.2.152 (#2302) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 202c57b52a..448eb8083b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { git = "https://github.com/rust-lang/libc", rev = "2f93bfb7678e18a9fc5373dec49384bd23f601c3", features = ["extra_traits"] } +libc = { version = "0.2.152", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } From 0fb346031f6ddc87a57377101a6063133a25e443 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Tue, 6 Feb 2024 00:19:43 -0700 Subject: [PATCH 131/140] Temporarily disable CI on GNU hurd (#2307) https://github.com/nix-rust/nix/issues/2306 --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b84767897..257b262f61 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -271,7 +271,9 @@ jobs: # https://github.com/nix-rust/nix/issues/2200 #- target: armv7-unknown-linux-uclibceabihf - target: x86_64-unknown-haiku - - target: i686-unknown-hurd-gnu + # Disable hurd due to + # https://github.com/nix-rust/nix/issues/2306 + # - target: i686-unknown-hurd-gnu steps: - name: checkout uses: actions/checkout@v4 From 0dfcf3228489a5060a53e69783a1eea6f43b11a9 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Tue, 6 Feb 2024 15:29:49 +0800 Subject: [PATCH 132/140] test: tweak test_fanotify to monitor ONLY 1 file (#2294) --- test/sys/test_fanotify.rs | 89 ++++++++++++++++++--------------------- 1 file changed, 42 insertions(+), 47 deletions(-) diff --git a/test/sys/test_fanotify.rs b/test/sys/test_fanotify.rs index 9fd23395ae..20226c272a 100644 --- a/test/sys/test_fanotify.rs +++ b/test/sys/test_fanotify.rs @@ -23,43 +23,31 @@ fn test_fanotify_notifications() { Fanotify::init(InitFlags::FAN_CLASS_NOTIF, EventFFlags::O_RDONLY) .unwrap(); let tempdir = tempfile::tempdir().unwrap(); + let tempfile = tempdir.path().join("test"); + OpenOptions::new() + .write(true) + .create_new(true) + .open(&tempfile) + .unwrap(); group .mark( - MarkFlags::FAN_MARK_ADD | MarkFlags::FAN_MARK_MOUNT, + MarkFlags::FAN_MARK_ADD, MaskFlags::FAN_OPEN | MaskFlags::FAN_MODIFY | MaskFlags::FAN_CLOSE, None, - Some(tempdir.path()), + Some(&tempfile), ) .unwrap(); - let tempfile = tempdir.path().join("test"); - - // create test file - File::create(&tempfile).unwrap(); - - let [event] = &group.read_events().unwrap()[..] else { - panic!("should have read exactly one event"); - }; - assert!(event.check_version()); - assert_eq!( - event.mask(), - MaskFlags::FAN_OPEN | MaskFlags::FAN_CLOSE_WRITE - ); - let fd_opt = event.fd(); - let fd = fd_opt.as_ref().unwrap(); - let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); - assert_eq!(path, tempfile); - // modify test file { let mut f = OpenOptions::new().write(true).open(&tempfile).unwrap(); f.write_all(b"hello").unwrap(); } - let [event] = &group.read_events().unwrap()[..] else { - panic!("should have read exactly one event"); - }; + let mut events = group.read_events().unwrap(); + assert_eq!(events.len(), 1, "should have read exactly one event"); + let event = events.pop().unwrap(); assert!(event.check_version()); assert_eq!( event.mask(), @@ -79,9 +67,9 @@ fn test_fanotify_notifications() { f.read_to_string(&mut s).unwrap(); } - let [event] = &group.read_events().unwrap()[..] else { - panic!("should have read exactly one event"); - }; + let mut events = group.read_events().unwrap(); + assert_eq!(events.len(), 1, "should have read exactly one event"); + let event = events.pop().unwrap(); assert!(event.check_version()); assert_eq!( event.mask(), @@ -98,54 +86,61 @@ fn test_fanotify_responses() { Fanotify::init(InitFlags::FAN_CLASS_CONTENT, EventFFlags::O_RDONLY) .unwrap(); let tempdir = tempfile::tempdir().unwrap(); + let tempfile = tempdir.path().join("test"); + OpenOptions::new() + .write(true) + .create_new(true) + .open(&tempfile) + .unwrap(); group .mark( - MarkFlags::FAN_MARK_ADD | MarkFlags::FAN_MARK_MOUNT, + MarkFlags::FAN_MARK_ADD, MaskFlags::FAN_OPEN_PERM, None, - Some(tempdir.path()), + Some(&tempfile), ) .unwrap(); - let tempfile = tempdir.path().join("test"); - let tempfname = tempfile.clone(); + let file_thread = thread::spawn({ + let tempfile = tempfile.clone(); - let file_thread = thread::spawn(move || { - // first try, should fail - let Err(err) = File::create(&tempfile) else { - panic!("first open is denied, should return error"); - }; - assert_eq!(err.kind(), ErrorKind::PermissionDenied); + move || { + // first open, should fail + let Err(e) = File::open(&tempfile) else { + panic!("The first open should fail"); + }; + assert_eq!(e.kind(), ErrorKind::PermissionDenied); - // second try, should succeed - File::create(&tempfile).unwrap(); + // second open, should succeed + File::open(&tempfile).unwrap(); + } }); // Deny the first open try - let [event] = &group.read_events().unwrap()[..] else { - panic!("should have read exactly one event"); - }; + let mut events = group.read_events().unwrap(); + assert_eq!(events.len(), 1, "should have read exactly one event"); + let event = events.pop().unwrap(); assert!(event.check_version()); assert_eq!(event.mask(), MaskFlags::FAN_OPEN_PERM); let fd_opt = event.fd(); let fd = fd_opt.as_ref().unwrap(); let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); - assert_eq!(path, tempfname); + assert_eq!(path, tempfile); group .write_response(FanotifyResponse::new(*fd, Response::FAN_DENY)) .unwrap(); - //// Allow the second open try - let [event] = &group.read_events().unwrap()[..] else { - panic!("should have read exactly one event"); - }; + // Allow the second open try + let mut events = group.read_events().unwrap(); + assert_eq!(events.len(), 1, "should have read exactly one event"); + let event = events.pop().unwrap(); assert!(event.check_version()); assert_eq!(event.mask(), MaskFlags::FAN_OPEN_PERM); let fd_opt = event.fd(); let fd = fd_opt.as_ref().unwrap(); let path = read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(); - assert_eq!(path, tempfname); + assert_eq!(path, tempfile); group .write_response(FanotifyResponse::new(*fd, Response::FAN_ALLOW)) .unwrap(); From ca173ff30cc42e0fc7a7ba2cf7c1fcbe61dccfa5 Mon Sep 17 00:00:00 2001 From: Alan Somers Date: Thu, 8 Feb 2024 18:11:50 -0700 Subject: [PATCH 133/140] Fix the mount tests (#2269) * Fix the mount tests As originally written by @kamalmarhubi in #231, these tests made clever use of Linux namespaces in order to run as unprivileged users. However, a subsequent kernel bug broke this functionality, and it hasn't been fixed even 6 years later. The tests have been skipped ever since. Get the tests to run again by removing the namespace stuff and requiring privileges instead. Also, remove the custom test harness. Now Nix will be compatible with tools like cargo-nextest. https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1659087 * Move the mount tests into the "test" program Now that we aren't using namespaces, they don't need their own program. * Use "sudo" to run tests on github workflows. Because several of the tests require root privileges. But don't use sudo with cross. It fails due to a known issue upstream: https://github.com/cross-rs/cross/issues/526 --- .github/actions/test/action.yml | 7 +- .github/workflows/ci.yml | 1 + Cargo.toml | 5 - test/test.rs | 2 + test/test_mount.rs | 390 +++++++++++++------------------- 5 files changed, 162 insertions(+), 243 deletions(-) diff --git a/.github/actions/test/action.yml b/.github/actions/test/action.yml index ce011a2da2..e4b7ea455f 100644 --- a/.github/actions/test/action.yml +++ b/.github/actions/test/action.yml @@ -5,6 +5,11 @@ inputs: TARGET: required: true + SUDO: + description: 'Set it to an empty string to run the tests as the current user, leave it with the default value to test with "sudo"' + required: false + default: sudo --preserve-env=HOME + TOOL: description: 'Tool used to involve the test command, can be cargo or cross' required: false @@ -24,4 +29,4 @@ runs: - name: test shell: bash - run: ${{ inputs.TOOL }} test --target ${{ inputs.TARGET }} --all-features + run: ${{ inputs.SUDO }} $(which ${{ inputs.TOOL }}) test --target ${{ inputs.TARGET }} --all-features diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 257b262f61..5fe8ae8e8d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -92,6 +92,7 @@ jobs: uses: ./.github/actions/test with: TARGET: '${{ matrix.target }}' + SUDO: "" TOOL: cross RUSTFLAGS: --cfg qemu -D warnings diff --git a/Cargo.toml b/Cargo.toml index 448eb8083b..47d0a77661 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -99,11 +99,6 @@ path = "test/sys/test_aio_drop.rs" name = "test-clearenv" path = "test/test_clearenv.rs" -[[test]] -name = "test-mount" -path = "test/test_mount.rs" -harness = false - [[test]] name = "test-prctl" path = "test/sys/test_prctl.rs" diff --git a/test/test.rs b/test/test.rs index 00f0e74efb..c7231426c2 100644 --- a/test/test.rs +++ b/test/test.rs @@ -11,6 +11,8 @@ mod test_errno; mod test_fcntl; #[cfg(linux_android)] mod test_kmod; +#[cfg(target_os = "linux")] +mod test_mount; #[cfg(any( freebsdlike, target_os = "fushsia", diff --git a/test/test_mount.rs b/test/test_mount.rs index 09d80bcc6a..a4f0903dba 100644 --- a/test/test_mount.rs +++ b/test/test_mount.rs @@ -1,267 +1,183 @@ -mod common; - -// Implementation note: to allow unprivileged users to run it, this test makes -// use of user and mount namespaces. On systems that allow unprivileged user -// namespaces (Linux >= 3.8 compiled with CONFIG_USER_NS), the test should run -// without root. - -#[cfg(target_os = "linux")] -mod test_mount { - use std::fs::{self, File}; - use std::io::{self, Read, Write}; - use std::os::unix::fs::OpenOptionsExt; - use std::os::unix::fs::PermissionsExt; - use std::process::{self, Command}; - - use libc::{EACCES, EROFS}; - - use nix::errno::Errno; - use nix::mount::{mount, umount, MsFlags}; - use nix::sched::{unshare, CloneFlags}; - use nix::sys::stat::{self, Mode}; - use nix::unistd::getuid; - - static SCRIPT_CONTENTS: &[u8] = b"#!/bin/sh +use std::fs::{self, File}; +use std::io::{Read, Write}; +use std::os::unix::fs::OpenOptionsExt; +use std::os::unix::fs::PermissionsExt; +use std::process::Command; + +use libc::{EACCES, EROFS}; + +use nix::mount::{mount, umount, MsFlags}; +use nix::sys::stat::{self, Mode}; + +use crate::*; + +static SCRIPT_CONTENTS: &[u8] = b"#!/bin/sh exit 23"; - const EXPECTED_STATUS: i32 = 23; +const EXPECTED_STATUS: i32 = 23; - const NONE: Option<&'static [u8]> = None; - #[allow(clippy::bind_instead_of_map)] // False positive - pub fn test_mount_tmpfs_without_flags_allows_rwx() { - let tempdir = tempfile::tempdir().unwrap(); +const NONE: Option<&'static [u8]> = None; - mount( - NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::empty(), - NONE, - ) - .unwrap_or_else(|e| panic!("mount failed: {e}")); +#[test] +fn test_mount_tmpfs_without_flags_allows_rwx() { + require_capability!( + "test_mount_tmpfs_without_flags_allows_rwx", + CAP_SYS_ADMIN + ); + let tempdir = tempfile::tempdir().unwrap(); + + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::empty(), + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {e}")); + + let test_path = tempdir.path().join("test"); + + // Verify write. + fs::OpenOptions::new() + .create(true) + .write(true) + .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) + .open(&test_path) + .and_then(|mut f| f.write(SCRIPT_CONTENTS)) + .unwrap_or_else(|e| panic!("write failed: {e}")); + + // Verify read. + let mut buf = Vec::new(); + File::open(&test_path) + .and_then(|mut f| f.read_to_end(&mut buf)) + .unwrap_or_else(|e| panic!("read failed: {e}")); + assert_eq!(buf, SCRIPT_CONTENTS); + + // Verify execute. + assert_eq!( + EXPECTED_STATUS, + Command::new(&test_path) + .status() + .unwrap_or_else(|e| panic!("exec failed: {e}")) + .code() + .unwrap_or_else(|| panic!("child killed by signal")) + ); - let test_path = tempdir.path().join("test"); + umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {e}")); +} - // Verify write. - fs::OpenOptions::new() - .create(true) - .write(true) - .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) - .open(&test_path) - .or_else(|e| { - if Errno::from_raw(e.raw_os_error().unwrap()) - == Errno::EOVERFLOW - { - // Skip tests on certain Linux kernels which have a bug - // regarding tmpfs in namespaces. - // Ubuntu 14.04 and 16.04 are known to be affected; 16.10 is - // not. There is no legitimate reason for open(2) to return - // EOVERFLOW here. - // https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1659087 - let stderr = io::stderr(); - let mut handle = stderr.lock(); - writeln!( - handle, - "Buggy Linux kernel detected. Skipping test." - ) - .unwrap(); - process::exit(0); - } else { - panic!("open failed: {e}"); - } - }) - .and_then(|mut f| f.write(SCRIPT_CONTENTS)) - .unwrap_or_else(|e| panic!("write failed: {e}")); +#[test] +fn test_mount_rdonly_disallows_write() { + require_capability!("test_mount_rdonly_disallows_write", CAP_SYS_ADMIN); + let tempdir = tempfile::tempdir().unwrap(); + + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_RDONLY, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {e}")); + + // EROFS: Read-only file system + assert_eq!( + EROFS, + File::create(tempdir.path().join("test")) + .unwrap_err() + .raw_os_error() + .unwrap() + ); - // Verify read. - let mut buf = Vec::new(); - File::open(&test_path) - .and_then(|mut f| f.read_to_end(&mut buf)) - .unwrap_or_else(|e| panic!("read failed: {e}")); - assert_eq!(buf, SCRIPT_CONTENTS); - - // Verify execute. - assert_eq!( - EXPECTED_STATUS, - Command::new(&test_path) - .status() - .unwrap_or_else(|e| panic!("exec failed: {e}")) - .code() - .unwrap_or_else(|| panic!("child killed by signal")) - ); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {e}")); - } + umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {e}")); +} - pub fn test_mount_rdonly_disallows_write() { - let tempdir = tempfile::tempdir().unwrap(); +#[test] +fn test_mount_noexec_disallows_exec() { + require_capability!("test_mount_noexec_disallows_exec", CAP_SYS_ADMIN); + let tempdir = tempfile::tempdir().unwrap(); + + mount( + NONE, + tempdir.path(), + Some(b"tmpfs".as_ref()), + MsFlags::MS_NOEXEC, + NONE, + ) + .unwrap_or_else(|e| panic!("mount failed: {e}")); + + let test_path = tempdir.path().join("test"); + + fs::OpenOptions::new() + .create(true) + .write(true) + .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) + .open(&test_path) + .and_then(|mut f| f.write(SCRIPT_CONTENTS)) + .unwrap_or_else(|e| panic!("write failed: {e}")); + + // Verify that we cannot execute despite a+x permissions being set. + let mode = stat::Mode::from_bits_truncate( + fs::metadata(&test_path) + .map(|md| md.permissions().mode()) + .unwrap_or_else(|e| panic!("metadata failed: {e}")), + ); - mount( - NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_RDONLY, - NONE, - ) - .unwrap_or_else(|e| panic!("mount failed: {e}")); + assert!( + mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), + "{:?} did not have execute permissions", + &test_path + ); + + // EACCES: Permission denied + assert_eq!( + EACCES, + Command::new(&test_path) + .status() + .unwrap_err() + .raw_os_error() + .unwrap() + ); - // EROFS: Read-only file system - assert_eq!( - EROFS, - File::create(tempdir.path().join("test")) - .unwrap_err() - .raw_os_error() - .unwrap() - ); + umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {e}")); +} - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {e}")); - } +#[test] +fn test_mount_bind() { + require_capability!("test_mount_bind", CAP_SYS_ADMIN); + let tempdir = tempfile::tempdir().unwrap(); + let file_name = "test"; - pub fn test_mount_noexec_disallows_exec() { - let tempdir = tempfile::tempdir().unwrap(); + { + let mount_point = tempfile::tempdir().unwrap(); mount( + Some(tempdir.path()), + mount_point.path(), NONE, - tempdir.path(), - Some(b"tmpfs".as_ref()), - MsFlags::MS_NOEXEC, + MsFlags::MS_BIND, NONE, ) .unwrap_or_else(|e| panic!("mount failed: {e}")); - let test_path = tempdir.path().join("test"); - fs::OpenOptions::new() .create(true) .write(true) .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) - .open(&test_path) + .open(mount_point.path().join(file_name)) .and_then(|mut f| f.write(SCRIPT_CONTENTS)) .unwrap_or_else(|e| panic!("write failed: {e}")); - // Verify that we cannot execute despite a+x permissions being set. - let mode = stat::Mode::from_bits_truncate( - fs::metadata(&test_path) - .map(|md| md.permissions().mode()) - .unwrap_or_else(|e| panic!("metadata failed: {e}")), - ); - - assert!( - mode.contains(Mode::S_IXUSR | Mode::S_IXGRP | Mode::S_IXOTH), - "{:?} did not have execute permissions", - &test_path - ); - - // EACCES: Permission denied - assert_eq!( - EACCES, - Command::new(&test_path) - .status() - .unwrap_err() - .raw_os_error() - .unwrap() - ); - - umount(tempdir.path()).unwrap_or_else(|e| panic!("umount failed: {e}")); + umount(mount_point.path()) + .unwrap_or_else(|e| panic!("umount failed: {e}")); } - pub fn test_mount_bind() { - let tempdir = tempfile::tempdir().unwrap(); - let file_name = "test"; - - { - let mount_point = tempfile::tempdir().unwrap(); - - mount( - Some(tempdir.path()), - mount_point.path(), - NONE, - MsFlags::MS_BIND, - NONE, - ) - .unwrap_or_else(|e| panic!("mount failed: {e}")); - - fs::OpenOptions::new() - .create(true) - .write(true) - .mode((Mode::S_IRWXU | Mode::S_IRWXG | Mode::S_IRWXO).bits()) - .open(mount_point.path().join(file_name)) - .and_then(|mut f| f.write(SCRIPT_CONTENTS)) - .unwrap_or_else(|e| panic!("write failed: {e}")); - - umount(mount_point.path()) - .unwrap_or_else(|e| panic!("umount failed: {e}")); - } - - // Verify the file written in the mount shows up in source directory, even - // after unmounting. - - let mut buf = Vec::new(); - File::open(tempdir.path().join(file_name)) - .and_then(|mut f| f.read_to_end(&mut buf)) - .unwrap_or_else(|e| panic!("read failed: {e}")); - assert_eq!(buf, SCRIPT_CONTENTS); - } + // Verify the file written in the mount shows up in source directory, even + // after unmounting. - pub fn setup_namespaces() { - // Hold on to the uid in the parent namespace. - let uid = getuid(); - - unshare(CloneFlags::CLONE_NEWNS | CloneFlags::CLONE_NEWUSER).unwrap_or_else(|e| { - let stderr = io::stderr(); - let mut handle = stderr.lock(); - writeln!(handle, - "unshare failed: {e}. Are unprivileged user namespaces available?").unwrap(); - writeln!(handle, "mount is not being tested").unwrap(); - // Exit with success because not all systems support unprivileged user namespaces, and - // that's not what we're testing for. - process::exit(0); - }); - - // Map user as uid 1000. - fs::OpenOptions::new() - .write(true) - .open("/proc/self/uid_map") - .and_then(|mut f| f.write(format!("1000 {uid} 1\n").as_bytes())) - .unwrap_or_else(|e| panic!("could not write uid map: {e}")); - } + let mut buf = Vec::new(); + File::open(tempdir.path().join(file_name)) + .and_then(|mut f| f.read_to_end(&mut buf)) + .unwrap_or_else(|e| panic!("read failed: {e}")); + assert_eq!(buf, SCRIPT_CONTENTS); } - -// Test runner - -/// Mimic normal test output (hackishly). -#[cfg(target_os = "linux")] -macro_rules! run_tests { - ( $($test_fn:ident),* ) => {{ - println!(); - - $( - print!("test test_mount::{} ... ", stringify!($test_fn)); - $test_fn(); - println!("ok"); - )* - - println!(); - }} -} - -#[cfg(target_os = "linux")] -fn main() { - use test_mount::{ - setup_namespaces, test_mount_bind, test_mount_noexec_disallows_exec, - test_mount_rdonly_disallows_write, - test_mount_tmpfs_without_flags_allows_rwx, - }; - skip_if_cirrus!("Fails for an unknown reason Cirrus CI. Bug #1351"); - setup_namespaces(); - - run_tests!( - test_mount_tmpfs_without_flags_allows_rwx, - test_mount_rdonly_disallows_write, - test_mount_noexec_disallows_exec, - test_mount_bind - ); -} - -#[cfg(not(target_os = "linux"))] -fn main() {} From 062f6c0f0306743a401138fc2612d59e818d5768 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 9 Feb 2024 09:12:14 +0800 Subject: [PATCH 134/140] test: clean clippy needless_borrow false positive issue (#2310) --- test/test_unistd.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/test/test_unistd.rs b/test/test_unistd.rs index ddabbd4fd4..56dc59e720 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -1180,8 +1180,6 @@ fn test_access_file_exists() { .expect("assertion failed"); } -//Clippy false positive https://github.com/rust-lang/rust-clippy/issues/9111 -#[allow(clippy::needless_borrow)] #[cfg(not(target_os = "redox"))] #[test] fn test_user_into_passwd() { From f34d00d353a8ebcb16eb8810b00d613e4a294925 Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Fri, 9 Feb 2024 09:12:26 +0800 Subject: [PATCH 135/140] chore(deps): try libc 0.2.153 (#2309) --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 47d0a77661..5abd1344da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,7 @@ targets = [ ] [dependencies] -libc = { version = "0.2.152", features = ["extra_traits"] } +libc = { version = "0.2.153", features = ["extra_traits"] } bitflags = "2.3.1" cfg-if = "1.0" pin-utils = { version = "0.1.0", optional = true } From 197f55b3ccbce3273bf6ce119d1a8541b5df5d66 Mon Sep 17 00:00:00 2001 From: tt rt <6380129+anonkey@users.noreply.github.com> Date: Sat, 17 Feb 2024 03:55:39 +0100 Subject: [PATCH 136/140] refactor: update nix (#2311) --- .github/workflows/ci.yml | 26 ++++++++++++++++++++++++++ changelog/2311.fixed.md | 1 + src/unistd.rs | 7 +++---- test/test_unistd.rs | 11 +++++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) create mode 100644 changelog/2311.fixed.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5fe8ae8e8d..5a3a02c707 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,6 +44,32 @@ jobs: - name: before_cache_script run: rm -rf $CARGO_HOME/registry/index + macos-aarch64: + runs-on: macos-14 + env: + TARGET: aarch64-apple-darwin + steps: + - name: checkout + uses: actions/checkout@v4 + + - name: setup Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: '${{ env.MSRV }}' + components: clippy + + - name: build + uses: ./.github/actions/build + with: + TARGET: "${{ env.TARGET }}" + + - name: test + uses: ./.github/actions/test + with: + TARGET: "${{ env.TARGET }}" + + - name: before_cache_script + run: rm -rf $CARGO_HOME/registry/index # Use cross for QEMU-based testing # cross needs to execute Docker, GitHub Action already has it installed diff --git a/changelog/2311.fixed.md b/changelog/2311.fixed.md new file mode 100644 index 0000000000..c1b4013f05 --- /dev/null +++ b/changelog/2311.fixed.md @@ -0,0 +1 @@ +Fixed `::unistd::Group::members` using read_unaligned to avoid crash on misaligned pointers diff --git a/src/unistd.rs b/src/unistd.rs index 3d98a0efe8..ce2d42455a 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -3476,18 +3476,17 @@ impl Group { let mut ret = Vec::new(); for i in 0.. { - let u = unsafe { mem.offset(i) }; - if unsafe { (*u).is_null() } { + let u = unsafe { mem.offset(i).read_unaligned() }; + if u.is_null() { break; } else { - let s = unsafe {CStr::from_ptr(*u).to_string_lossy().into_owned()}; + let s = unsafe {CStr::from_ptr(u).to_string_lossy().into_owned()}; ret.push(s); } } ret } - /// # Safety /// /// If `f` writes to its `*mut *mut libc::group` parameter, then it must diff --git a/test/test_unistd.rs b/test/test_unistd.rs index 56dc59e720..aa2e5e56d7 100644 --- a/test/test_unistd.rs +++ b/test/test_unistd.rs @@ -1372,3 +1372,14 @@ fn test_eaccess_file_exists() { eaccess(&path, AccessFlags::R_OK | AccessFlags::W_OK) .expect("assertion failed"); } + +#[test] +#[cfg(bsd)] +fn test_group_from() { + let group = Group::from_name("wheel").unwrap().unwrap(); + assert!(group.name == "wheel"); + let group_id = group.gid; + let group = Group::from_gid(group_id).unwrap().unwrap(); + assert_eq!(group.gid, group_id); + assert_eq!(group.name, "wheel"); +} From 08e05a5f66d14d4f06288c9a725e87f473eba41a Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sat, 24 Feb 2024 10:59:35 +0800 Subject: [PATCH 137/140] refactor: remove redundant imports to fix CI (#2320) * refactor: remove redundant imports to fix CI * refactor: remove redundant imports to fix CI --- src/errno.rs | 1 - src/fcntl.rs | 2 +- src/sys/time.rs | 1 - src/unistd.rs | 3 +-- test/sys/test_select.rs | 1 - test/sys/test_signal.rs | 1 - test/sys/test_termios.rs | 1 - 7 files changed, 2 insertions(+), 8 deletions(-) diff --git a/src/errno.rs b/src/errno.rs index 114a4a1eab..2e74a84454 100644 --- a/src/errno.rs +++ b/src/errno.rs @@ -14,7 +14,6 @@ use crate::Result; use cfg_if::cfg_if; use libc::{c_int, c_void}; -use std::convert::TryFrom; use std::{error, fmt, io}; pub use self::consts::*; diff --git a/src/fcntl.rs b/src/fcntl.rs index ed197ecf26..ccefe955de 100644 --- a/src/fcntl.rs +++ b/src/fcntl.rs @@ -2,7 +2,7 @@ use crate::errno::Errno; #[cfg(all(target_os = "freebsd", target_arch = "x86_64"))] use core::slice; -use libc::{self, c_int, c_uint, size_t, ssize_t}; +use libc::{c_int, c_uint, size_t, ssize_t}; #[cfg(any( target_os = "netbsd", apple_targets, diff --git a/src/sys/time.rs b/src/sys/time.rs index b19dee91a0..af436cabd5 100644 --- a/src/sys/time.rs +++ b/src/sys/time.rs @@ -2,7 +2,6 @@ // https://github.com/rust-lang/libc/issues/1848 pub use libc::{suseconds_t, time_t}; use libc::{timespec, timeval}; -use std::convert::From; use std::time::Duration; use std::{cmp, fmt, ops}; diff --git a/src/unistd.rs b/src/unistd.rs index ce2d42455a..4502766c5d 100644 --- a/src/unistd.rs +++ b/src/unistd.rs @@ -31,8 +31,7 @@ use crate::{Error, NixPath, Result}; #[cfg(not(target_os = "redox"))] use cfg_if::cfg_if; use libc::{ - self, c_char, c_int, c_long, c_uint, gid_t, mode_t, off_t, pid_t, size_t, - uid_t, + c_char, c_int, c_long, c_uint, gid_t, mode_t, off_t, pid_t, size_t, uid_t, }; use std::convert::Infallible; #[cfg(not(target_os = "redox"))] diff --git a/test/sys/test_select.rs b/test/sys/test_select.rs index 746c6b6966..e39a31923a 100644 --- a/test/sys/test_select.rs +++ b/test/sys/test_select.rs @@ -68,7 +68,6 @@ macro_rules! generate_fdset_bad_fd_tests { mod test_fdset_too_large_fd { use super::*; - use std::convert::TryInto; generate_fdset_bad_fd_tests!( FD_SETSIZE.try_into().unwrap(), insert, diff --git a/test/sys/test_signal.rs b/test/sys/test_signal.rs index 12872f1228..bf607497be 100644 --- a/test/sys/test_signal.rs +++ b/test/sys/test_signal.rs @@ -1,7 +1,6 @@ use nix::errno::Errno; use nix::sys::signal::*; use nix::unistd::*; -use std::convert::TryFrom; use std::hash::{Hash, Hasher}; use std::sync::atomic::{AtomicBool, Ordering}; #[cfg(not(target_os = "redox"))] diff --git a/test/sys/test_termios.rs b/test/sys/test_termios.rs index 72399cf6a5..35cc7ab739 100644 --- a/test/sys/test_termios.rs +++ b/test/sys/test_termios.rs @@ -1,4 +1,3 @@ -use std::convert::TryFrom; use std::os::unix::io::{AsFd, AsRawFd}; use tempfile::tempfile; From 79b86a7dff071a2a59858d1c98e202fdf38ebd06 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20Ad=C3=A4?= Date: Sat, 24 Feb 2024 05:09:59 +0100 Subject: [PATCH 138/140] mmsg revert signature simplification (#2227) --- changelog/2119.changed.md | 1 - src/sys/socket/mod.rs | 14 +++++++------- 2 files changed, 7 insertions(+), 8 deletions(-) delete mode 100644 changelog/2119.changed.md diff --git a/changelog/2119.changed.md b/changelog/2119.changed.md deleted file mode 100644 index 88b88fa595..0000000000 --- a/changelog/2119.changed.md +++ /dev/null @@ -1 +0,0 @@ -Simplified the function signatures of `recvmmsg` and `sendmmsg` diff --git a/src/sys/socket/mod.rs b/src/sys/socket/mod.rs index 65a579cd03..3d1651bd3f 100644 --- a/src/sys/socket/mod.rs +++ b/src/sys/socket/mod.rs @@ -1499,11 +1499,11 @@ pub fn sendmmsg<'a, XS, AS, C, I, S>( flags: MsgFlags ) -> crate::Result> where - XS: IntoIterator, + XS: IntoIterator, AS: AsRef<[Option]>, - I: AsRef<[IoSlice<'a>]>, - C: AsRef<[ControlMessage<'a>]>, - S: SockaddrLike, + I: AsRef<[IoSlice<'a>]> + 'a, + C: AsRef<[ControlMessage<'a>]> + 'a, + S: SockaddrLike + 'a, { let mut count = 0; @@ -1650,11 +1650,11 @@ pub fn recvmmsg<'a, XS, S, I>( mut timeout: Option, ) -> crate::Result> where - XS: IntoIterator, - I: AsMut<[IoSliceMut<'a>]>, + XS: IntoIterator, + I: AsMut<[IoSliceMut<'a>]> + 'a, { let mut count = 0; - for (i, (mut slice, mmsghdr)) in slices.into_iter().zip(data.items.iter_mut()).enumerate() { + for (i, (slice, mmsghdr)) in slices.into_iter().zip(data.items.iter_mut()).enumerate() { let p = &mut mmsghdr.msg_hdr; p.msg_iov = slice.as_mut().as_mut_ptr().cast(); p.msg_iovlen = slice.as_mut().len() as _; From 595c6eb2515723eae1f1db1b9103c95f339380ec Mon Sep 17 00:00:00 2001 From: SteveLauC Date: Sat, 24 Feb 2024 12:20:16 +0800 Subject: [PATCH 139/140] chore: changelog for 0.28.0 (#2303) --- CHANGELOG.md | 197 ++++++++++++++++++++++++++++++++++++++ changelog/1297.added.md | 1 - changelog/1876.changed.md | 1 - changelog/1879.added.md | 1 - changelog/1945.added.md | 1 - changelog/1945.changed.md | 1 - changelog/1946.fixed.md | 1 - changelog/1959.added.md | 4 - changelog/2000.changed.md | 1 - changelog/2065.added.md | 1 - changelog/2072.fixed.md | 1 - changelog/2074.added.md | 2 - changelog/2103.added.md | 1 - changelog/2119.fixed.md | 1 - changelog/2121.added.md | 1 - changelog/2125.added.md | 1 - changelog/2127.added.md | 1 - changelog/2127.changed.md | 1 - changelog/2134.changed.md | 2 - changelog/2136.changed.md | 2 - changelog/2137.changed.md | 8 -- changelog/2138.added.md | 1 - changelog/2139.changed.md | 1 - changelog/2141.fixed.md | 1 - changelog/2142.added.md | 1 - changelog/2144.changed.md | 1 - changelog/2151.changed.md | 2 - changelog/2152.added.md | 1 - changelog/2155.added.md | 2 - changelog/2157.changed.md | 7 -- changelog/2170.added.md | 2 - changelog/2175.added.md | 1 - changelog/2187.added.md | 2 - changelog/2194.added.md | 1 - changelog/2195.added.md | 1 - changelog/2198.added.md | 1 - changelog/2202.changed.md | 1 - changelog/2206.added.md | 1 - changelog/2207.added.md | 1 - changelog/2213.added.md | 1 - changelog/2234.added.md | 1 - changelog/2240.added.md | 1 - changelog/2241.added.md | 1 - changelog/2242.fixed.md | 2 - changelog/2244.added.md | 1 - changelog/2245.added.md | 1 - changelog/2247.added.md | 1 - changelog/2248.fixed.md | 1 - changelog/2251.added.md | 1 - changelog/2252.added.md | 1 - changelog/2258.added.md | 4 - changelog/2259.added.md | 1 - changelog/2260.added.md | 1 - changelog/2263.added.md | 1 - changelog/2267.added.md | 1 - changelog/2267.removed.md | 1 - changelog/2268.fixed.md | 1 - changelog/2268.removed.md | 1 - changelog/2270.added.md | 1 - changelog/2275.added.md | 1 - changelog/2276.added.md | 1 - changelog/2277.added.md | 1 - changelog/2278.added.md | 1 - changelog/2279.added.md | 1 - changelog/2283.added.md | 4 - changelog/2283.changed.md | 3 - changelog/2284.added.md | 1 - changelog/2284.removed.md | 1 - changelog/2296.added.md | 1 - changelog/2311.fixed.md | 1 - 70 files changed, 197 insertions(+), 101 deletions(-) delete mode 100644 changelog/1297.added.md delete mode 100644 changelog/1876.changed.md delete mode 100644 changelog/1879.added.md delete mode 100644 changelog/1945.added.md delete mode 100644 changelog/1945.changed.md delete mode 100644 changelog/1946.fixed.md delete mode 100644 changelog/1959.added.md delete mode 100644 changelog/2000.changed.md delete mode 100644 changelog/2065.added.md delete mode 100644 changelog/2072.fixed.md delete mode 100644 changelog/2074.added.md delete mode 100644 changelog/2103.added.md delete mode 100644 changelog/2119.fixed.md delete mode 100644 changelog/2121.added.md delete mode 100644 changelog/2125.added.md delete mode 100644 changelog/2127.added.md delete mode 100644 changelog/2127.changed.md delete mode 100644 changelog/2134.changed.md delete mode 100644 changelog/2136.changed.md delete mode 100644 changelog/2137.changed.md delete mode 100644 changelog/2138.added.md delete mode 100644 changelog/2139.changed.md delete mode 100644 changelog/2141.fixed.md delete mode 100644 changelog/2142.added.md delete mode 100644 changelog/2144.changed.md delete mode 100644 changelog/2151.changed.md delete mode 100644 changelog/2152.added.md delete mode 100644 changelog/2155.added.md delete mode 100644 changelog/2157.changed.md delete mode 100644 changelog/2170.added.md delete mode 100644 changelog/2175.added.md delete mode 100644 changelog/2187.added.md delete mode 100644 changelog/2194.added.md delete mode 100644 changelog/2195.added.md delete mode 100644 changelog/2198.added.md delete mode 100644 changelog/2202.changed.md delete mode 100644 changelog/2206.added.md delete mode 100644 changelog/2207.added.md delete mode 100644 changelog/2213.added.md delete mode 100644 changelog/2234.added.md delete mode 100644 changelog/2240.added.md delete mode 100644 changelog/2241.added.md delete mode 100644 changelog/2242.fixed.md delete mode 100644 changelog/2244.added.md delete mode 100644 changelog/2245.added.md delete mode 100644 changelog/2247.added.md delete mode 100644 changelog/2248.fixed.md delete mode 100644 changelog/2251.added.md delete mode 100644 changelog/2252.added.md delete mode 100644 changelog/2258.added.md delete mode 100644 changelog/2259.added.md delete mode 100644 changelog/2260.added.md delete mode 100644 changelog/2263.added.md delete mode 100644 changelog/2267.added.md delete mode 100644 changelog/2267.removed.md delete mode 100644 changelog/2268.fixed.md delete mode 100644 changelog/2268.removed.md delete mode 100644 changelog/2270.added.md delete mode 100644 changelog/2275.added.md delete mode 100644 changelog/2276.added.md delete mode 100644 changelog/2277.added.md delete mode 100644 changelog/2278.added.md delete mode 100644 changelog/2279.added.md delete mode 100644 changelog/2283.added.md delete mode 100644 changelog/2283.changed.md delete mode 100644 changelog/2284.added.md delete mode 100644 changelog/2284.removed.md delete mode 100644 changelog/2296.added.md delete mode 100644 changelog/2311.fixed.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 934d611e84..37e4ab2d4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,203 @@ This project adheres to [Semantic Versioning](https://semver.org/). # Change Log +## [0.28.0] - 2024-02-24 + + +### Added + +- Added `mkdtemp` wrapper ([#1297](https://github.com/nix-rust/nix/pull/1297)) +- Add associated constants `UTIME_OMIT` `UTIME_NOW` for `TimeSpec` + ([#1879](https://github.com/nix-rust/nix/pull/1879)) +- Added `EventFd` type. ([#1945](https://github.com/nix-rust/nix/pull/1945)) +- - Added `impl From for SigSet`. + - Added `impl std::ops::BitOr for SigSet`. + - Added `impl std::ops::BitOr for Signal`. + - Added `impl std::ops::BitOr for SigSet` + + ([#1959](https://github.com/nix-rust/nix/pull/1959)) +- Added `TlsGetRecordType` control message type and corresponding enum for + linux ([#2065](https://github.com/nix-rust/nix/pull/2065)) +- Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, + MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. + ([#2074](https://github.com/nix-rust/nix/pull/2074)) +- Added `Icmp` and `IcmpV6` to `SockProtocol` + ([#2103](https://github.com/nix-rust/nix/pull/2103)) +- Added rfork support for FreeBSD in `unistd` + ([#2121](https://github.com/nix-rust/nix/pull/2121)) +- Added `MapFlags::map_hugetlb_with_size_log2` method for Linux targets + ([#2125](https://github.com/nix-rust/nix/pull/2125)) +- Added `mmap_anonymous` function + ([#2127](https://github.com/nix-rust/nix/pull/2127)) +- Added `mips32r6` and `mips64r6` support for signal, ioctl and ptrace + ([#2138](https://github.com/nix-rust/nix/pull/2138)) +- Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for + `::nix::fcntl`. ([#2142](https://github.com/nix-rust/nix/pull/2142)) +- Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. + ([#2152](https://github.com/nix-rust/nix/pull/2152)) +- Added `F_GETPATH_NOFIRMLINK` and `F_BARRIERFSYNC` FcntlFlags entry + on Apple for `::nix::fcntl`. + ([#2155](https://github.com/nix-rust/nix/pull/2155)) +- Added newtype `Flock` to automatically unlock a held flock upon drop. + Added `Flockable` trait to represent valid types for `Flock`. + ([#2170](https://github.com/nix-rust/nix/pull/2170)) +- Added `SetSockOpt` impls to enable Linux Kernel TLS on a TCP socket and to + import TLS parameters. ([#2175](https://github.com/nix-rust/nix/pull/2175)) +- - Added the `::nix::sys::socket::SocketTimestamp` enum for configuring the + `TsClock` (a.k.a `SO_TS_CLOCK`) sockopt + - Added FreeBSD's `ScmRealtime` and `ScmMonotonic` as new options in + `::nix::sys::socket::ControlMessageOwned` + + ([#2187](https://github.com/nix-rust/nix/pull/2187)) +- Added new fanotify API: wrappers for `fanotify_init` and `fanotify_mark` + ([#2194](https://github.com/nix-rust/nix/pull/2194)) +- Added `SpecialCharacterindices` support for haiku. + ([#2195](https://github.com/nix-rust/nix/pull/2195)) +- Added `sys::sendfile` support for solaris/illumos. + ([#2198](https://github.com/nix-rust/nix/pull/2198)) +- impl Display for InterfaceFlags + ([#2206](https://github.com/nix-rust/nix/pull/2206)) +- Added `sendfilev` in sys::sendfile for solarish + ([#2207](https://github.com/nix-rust/nix/pull/2207)) +- Added `fctrl::SealFlag::F_SEAL_FUTURE_WRITE` + ([#2213](https://github.com/nix-rust/nix/pull/2213)) +- Added `Ipv6MulticastHops` as socket option to set and read. + ([#2234](https://github.com/nix-rust/nix/pull/2234)) +- Enable `ControlMessageOwned::Ipv4RecvIf` and + `ControlMessageOwned::Ipv4RecvDstAddr` for DragonFlyBSD + ([#2240](https://github.com/nix-rust/nix/pull/2240)) +- `ClockId::set_time()` and `time::clock_settime()` are now enabled on macOS + ([#2241](https://github.com/nix-rust/nix/pull/2241)) +- Added `IpBindAddressNoPort` sockopt to support `IP_BIND_ADDRESS_NO_PORT` + available on linux. ([#2244](https://github.com/nix-rust/nix/pull/2244)) +- Enable `MapFlags::map_hugetlb_with_size_log2` method for Android/Fuchsia + ([#2245](https://github.com/nix-rust/nix/pull/2245)) +- Added `TcpFastOpenConnect` sockopt to support `TCP_FASTOPEN_CONNECT` + available on linux. ([#2247](https://github.com/nix-rust/nix/pull/2247)) +- Add `reboot(2)` for OpenBSD/NetBSD + ([#2251](https://github.com/nix-rust/nix/pull/2251)) +- Added new `MemFdCreateFlag` constants to `sys::memfd` on Linux and Android + related to hugetlbfs support. + ([#2252](https://github.com/nix-rust/nix/pull/2252)) +- Expose the inner fd of `Kqueue` through: + + * impl AsFd for Kqueue + * impl From\ for OwnedFd + + ([#2258](https://github.com/nix-rust/nix/pull/2258)) +- Added `sys::eventfd` support on FreeBSD + ([#2259](https://github.com/nix-rust/nix/pull/2259)) +- Added `MmapFlags::MAP_FIXED` constant in `sys::mman` for netbsd and openbsd + ([#2260](https://github.com/nix-rust/nix/pull/2260)) +- Added the `SO_LISTENQLIMIT` sockopt. + ([#2263](https://github.com/nix-rust/nix/pull/2263)) +- Enable the `AT_EMPTY_PATH` flag for the `fchownat()` function + ([#2267](https://github.com/nix-rust/nix/pull/2267)) +- Add `AtFlags::AT_EMPTY_PATH` for FreeBSD and Hurd + ([#2270](https://github.com/nix-rust/nix/pull/2270)) +- Enable `OFlag::O_DIRECTORY for Solarish + ([#2275](https://github.com/nix-rust/nix/pull/2275)) +- Added the `Backlog` wrapper type for the `listen` call. + ([#2276](https://github.com/nix-rust/nix/pull/2276)) +- Add `clock_nanosleep()` ([#2277](https://github.com/nix-rust/nix/pull/2277)) +- Enabled `O_DIRECT` in `fcntl::OFlags` for solarish + ([#2278](https://github.com/nix-rust/nix/pull/2278)) +- Added a new API sigsuspend. + ([#2279](https://github.com/nix-rust/nix/pull/2279)) +- - Added `errno::Errno::set` function + - Added `errno::Errno::set_raw` function + - Added `errno::Errno::last_raw` function + - Added `errno::Errno::from_raw` function + + ([#2283](https://github.com/nix-rust/nix/pull/2283)) +- Enable the `AT_EMPTY_PATH` flag for the `linkat()` function + ([#2284](https://github.com/nix-rust/nix/pull/2284)) +- Enable unistd::{sync, syncfs} for Android + ([#2296](https://github.com/nix-rust/nix/pull/2296)) + +### Changed + +- `poll` now takes `PollTimeout` replacing `libc::c_int`. + ([#1876](https://github.com/nix-rust/nix/pull/1876)) +- Deprecated `sys::eventfd::eventfd`. + ([#1945](https://github.com/nix-rust/nix/pull/1945)) +- `mmap`, `mmap_anonymous`, `munmap`, `mremap`, `madvise`, `msync`, `mprotect`, + `munlock` and `mlock` updated to use `NonNull`. + ([#2000](https://github.com/nix-rust/nix/pull/2000)) +- `mmap` function now accepts `F` instead of `Option` + ([#2127](https://github.com/nix-rust/nix/pull/2127)) +- `PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime + requirements relative to the previous version. + ([#2134](https://github.com/nix-rust/nix/pull/2134)) +- `FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have + relaxed lifetime requirements relative to 0.27.1. + ([#2136](https://github.com/nix-rust/nix/pull/2136)) +- The following APIs now take an implementation of `AsFd` rather than a + `RawFd`: + + - `unistd::tcgetpgrp` + - `unistd::tcsetpgrp` + - `unistd::fpathconf` + - `unistd::ttyname` + - `unistd::getpeereid` ([#2137](https://github.com/nix-rust/nix/pull/2137)) +- Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s + ([#2139](https://github.com/nix-rust/nix/pull/2139)) +- The MSRV is now 1.69 ([#2144](https://github.com/nix-rust/nix/pull/2144)) +- Changed function `SockaddrIn::ip()` to return `net::Ipv4Addr` and refactored + `SocketAddrV6::ip()` to be `const` + ([#2151](https://github.com/nix-rust/nix/pull/2151)) +- The following APIs now take optional `dirfd`s: + + - `readlinkat()` + - `fstatat()` + - `mknodat()` + - `mkdirat()` + - `execveat()` + + ([#2157](https://github.com/nix-rust/nix/pull/2157)) +- `Epoll::wait` now takes `EpollTimeout` replacing `isize`. + ([#2202](https://github.com/nix-rust/nix/pull/2202)) +- - Deprecated `errno::errno()` function (use `Errno::last_raw()`) + - Deprecated `errno::from_i32()` function (use `Errno::from_raw()`) + - Deprecated `errno::Errno::from_i32()` function (use `Errno::from_raw()`) + + ([#2283](https://github.com/nix-rust/nix/pull/2283)) + +### Fixed + +- Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` + ([#1946](https://github.com/nix-rust/nix/pull/1946)) +- Fixed `::sys::socket::sockopt::IpMulticastTtl` by fixing the value of optlen + passed to `libc::setsockopt` and added tests. + ([#2072](https://github.com/nix-rust/nix/pull/2072)) +- Fixed the function signature of `recvmmsg`, potentially causing UB + ([#2119](https://github.com/nix-rust/nix/pull/2119)) +- Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file + descriptor. ([#2141](https://github.com/nix-rust/nix/pull/2141)) +- Fixed UnixAddr::new for haiku, it did not record the `sun_len` value as + needed. + Fixed `sys::socket::addr::from_raw_parts` and + `sys::socket::Sockaddrlike::len` build for solaris. + ([#2242](https://github.com/nix-rust/nix/pull/2242)) +- Fixed solaris build globally. + ([#2248](https://github.com/nix-rust/nix/pull/2248)) +- Changed the `dup3` wrapper to perform a real call to `dup3` instead of + emulating it via `dup2` and `fcntl` to get rid of race condition + ([#2268](https://github.com/nix-rust/nix/pull/2268)) +- Fixed `::unistd::Group::members` using read_unaligned to avoid crash on + misaligned pointers ([#2311](https://github.com/nix-rust/nix/pull/2311)) + +### Removed + +- The `FchownatFlags` type has been deprecated, please use `AtFlags` instead. + ([#2267](https://github.com/nix-rust/nix/pull/2267)) +- Removed the `dup3` wrapper on macOS, which was emulated via `dup2` and + `fcntl` and could cause a race condition. The `dup3` system call is not + supported on macOS. ([#2268](https://github.com/nix-rust/nix/pull/2268)) +- The `LinkatFlags` type has been deprecated, please use `AtFlags` instead. + ([#2284](https://github.com/nix-rust/nix/pull/2284)) + + ## [0.27.1] - 2023-08-28 ### Fixed diff --git a/changelog/1297.added.md b/changelog/1297.added.md deleted file mode 100644 index 5e4820101a..0000000000 --- a/changelog/1297.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `mkdtemp` wrapper diff --git a/changelog/1876.changed.md b/changelog/1876.changed.md deleted file mode 100644 index 858f228396..0000000000 --- a/changelog/1876.changed.md +++ /dev/null @@ -1 +0,0 @@ -`poll` now takes `PollTimeout` replacing `libc::c_int`. \ No newline at end of file diff --git a/changelog/1879.added.md b/changelog/1879.added.md deleted file mode 100644 index 6f2b9a04d6..0000000000 --- a/changelog/1879.added.md +++ /dev/null @@ -1 +0,0 @@ -Add associated constants `UTIME_OMIT` `UTIME_NOW` for `TimeSpec` diff --git a/changelog/1945.added.md b/changelog/1945.added.md deleted file mode 100644 index 19bea06715..0000000000 --- a/changelog/1945.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `EventFd` type. \ No newline at end of file diff --git a/changelog/1945.changed.md b/changelog/1945.changed.md deleted file mode 100644 index 145d9287b8..0000000000 --- a/changelog/1945.changed.md +++ /dev/null @@ -1 +0,0 @@ -Deprecated `sys::eventfd::eventfd`. \ No newline at end of file diff --git a/changelog/1946.fixed.md b/changelog/1946.fixed.md deleted file mode 100644 index 7c96cde003..0000000000 --- a/changelog/1946.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fix `SigSet` incorrect implementation of `Eq`, `PartialEq` and `Hash` diff --git a/changelog/1959.added.md b/changelog/1959.added.md deleted file mode 100644 index c7dfb49465..0000000000 --- a/changelog/1959.added.md +++ /dev/null @@ -1,4 +0,0 @@ -- Added `impl From for SigSet`. -- Added `impl std::ops::BitOr for SigSet`. -- Added `impl std::ops::BitOr for Signal`. -- Added `impl std::ops::BitOr for SigSet` \ No newline at end of file diff --git a/changelog/2000.changed.md b/changelog/2000.changed.md deleted file mode 100644 index 613e9dfef7..0000000000 --- a/changelog/2000.changed.md +++ /dev/null @@ -1 +0,0 @@ -`mmap`, `mmap_anonymous`, `munmap`, `mremap`, `madvise`, `msync`, `mprotect`, `munlock` and `mlock` updated to use `NonNull`. \ No newline at end of file diff --git a/changelog/2065.added.md b/changelog/2065.added.md deleted file mode 100644 index a3dcd5a833..0000000000 --- a/changelog/2065.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `TlsGetRecordType` control message type and corresponding enum for linux \ No newline at end of file diff --git a/changelog/2072.fixed.md b/changelog/2072.fixed.md deleted file mode 100644 index 200a8f60b0..0000000000 --- a/changelog/2072.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed `::sys::socket::sockopt::IpMulticastTtl` by fixing the value of optlen passed to `libc::setsockopt` and added tests. diff --git a/changelog/2074.added.md b/changelog/2074.added.md deleted file mode 100644 index e11a09c47e..0000000000 --- a/changelog/2074.added.md +++ /dev/null @@ -1,2 +0,0 @@ -Added `Ipv6HopLimit` to `::nix::sys::socket::ControlMessage` for Linux, -MacOS, FreeBSD, DragonflyBSD, Android, iOS and Haiku. diff --git a/changelog/2103.added.md b/changelog/2103.added.md deleted file mode 100644 index dc39d75258..0000000000 --- a/changelog/2103.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `Icmp` and `IcmpV6` to `SockProtocol` diff --git a/changelog/2119.fixed.md b/changelog/2119.fixed.md deleted file mode 100644 index d0d665fc5c..0000000000 --- a/changelog/2119.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed the function signature of `recvmmsg`, potentially causing UB diff --git a/changelog/2121.added.md b/changelog/2121.added.md deleted file mode 100644 index 687c373947..0000000000 --- a/changelog/2121.added.md +++ /dev/null @@ -1 +0,0 @@ -Added rfork support for FreeBSD in `unistd` diff --git a/changelog/2125.added.md b/changelog/2125.added.md deleted file mode 100644 index 1a7600be9f..0000000000 --- a/changelog/2125.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `MapFlags::map_hugetlb_with_size_log2` method for Linux targets \ No newline at end of file diff --git a/changelog/2127.added.md b/changelog/2127.added.md deleted file mode 100644 index c3302bb592..0000000000 --- a/changelog/2127.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `mmap_anonymous` function \ No newline at end of file diff --git a/changelog/2127.changed.md b/changelog/2127.changed.md deleted file mode 100644 index 10cfdea7ad..0000000000 --- a/changelog/2127.changed.md +++ /dev/null @@ -1 +0,0 @@ -`mmap` function now accepts `F` instead of `Option` \ No newline at end of file diff --git a/changelog/2134.changed.md b/changelog/2134.changed.md deleted file mode 100644 index d884c596c6..0000000000 --- a/changelog/2134.changed.md +++ /dev/null @@ -1,2 +0,0 @@ -`PollFd::new` now takes a `BorrowedFd` argument, with relaxed lifetime - requirements relative to the previous version. diff --git a/changelog/2136.changed.md b/changelog/2136.changed.md deleted file mode 100644 index 991a6c5d03..0000000000 --- a/changelog/2136.changed.md +++ /dev/null @@ -1,2 +0,0 @@ -`FdSet::{insert, remove, contains}` now take `BorrowedFd` arguments, and have -relaxed lifetime requirements relative to 0.27.1. diff --git a/changelog/2137.changed.md b/changelog/2137.changed.md deleted file mode 100644 index d5df4836c9..0000000000 --- a/changelog/2137.changed.md +++ /dev/null @@ -1,8 +0,0 @@ -The following APIs now take an implementation of `AsFd` rather than a - `RawFd`: - - - `unistd::tcgetpgrp` - - `unistd::tcsetpgrp` - - `unistd::fpathconf` - - `unistd::ttyname` - - `unistd::getpeereid` diff --git a/changelog/2138.added.md b/changelog/2138.added.md deleted file mode 100644 index 888e364984..0000000000 --- a/changelog/2138.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `mips32r6` and `mips64r6` support for signal, ioctl and ptrace diff --git a/changelog/2139.changed.md b/changelog/2139.changed.md deleted file mode 100644 index e6df6a0000..0000000000 --- a/changelog/2139.changed.md +++ /dev/null @@ -1 +0,0 @@ -Changed `openat()` and `Dir::openat()`, now take optional `dirfd`s diff --git a/changelog/2141.fixed.md b/changelog/2141.fixed.md deleted file mode 100644 index d14401b93c..0000000000 --- a/changelog/2141.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fix `SignalFd::set_mask`. In 0.27.0 it would actually close the file descriptor. diff --git a/changelog/2142.added.md b/changelog/2142.added.md deleted file mode 100644 index 077a800927..0000000000 --- a/changelog/2142.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `F_GETPATH` FcntlFlags entry on Apple/NetBSD/DragonflyBSD for `::nix::fcntl`. diff --git a/changelog/2144.changed.md b/changelog/2144.changed.md deleted file mode 100644 index 250c9fde9d..0000000000 --- a/changelog/2144.changed.md +++ /dev/null @@ -1 +0,0 @@ -The MSRV is now 1.69 diff --git a/changelog/2151.changed.md b/changelog/2151.changed.md deleted file mode 100644 index 922acc820b..0000000000 --- a/changelog/2151.changed.md +++ /dev/null @@ -1,2 +0,0 @@ -Changed function `SockaddrIn::ip()` to return `net::Ipv4Addr` and refactored -`SocketAddrV6::ip()` to be `const` diff --git a/changelog/2152.added.md b/changelog/2152.added.md deleted file mode 100644 index 3b39063a2b..0000000000 --- a/changelog/2152.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `F_KINFO` FcntlFlags entry on FreeBSD for `::nix::fcntl`. diff --git a/changelog/2155.added.md b/changelog/2155.added.md deleted file mode 100644 index 5a550c925c..0000000000 --- a/changelog/2155.added.md +++ /dev/null @@ -1,2 +0,0 @@ -Added `F_GETPATH_NOFIRMLINK` and `F_BARRIERFSYNC` FcntlFlags entry -on Apple for `::nix::fcntl`. diff --git a/changelog/2157.changed.md b/changelog/2157.changed.md deleted file mode 100644 index 6af97f8942..0000000000 --- a/changelog/2157.changed.md +++ /dev/null @@ -1,7 +0,0 @@ -The following APIs now take optional `dirfd`s: - -- `readlinkat()` -- `fstatat()` -- `mknodat()` -- `mkdirat()` -- `execveat()` diff --git a/changelog/2170.added.md b/changelog/2170.added.md deleted file mode 100644 index 6d089a120a..0000000000 --- a/changelog/2170.added.md +++ /dev/null @@ -1,2 +0,0 @@ -Added newtype `Flock` to automatically unlock a held flock upon drop. -Added `Flockable` trait to represent valid types for `Flock`. diff --git a/changelog/2175.added.md b/changelog/2175.added.md deleted file mode 100644 index 9da4ef470f..0000000000 --- a/changelog/2175.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `SetSockOpt` impls to enable Linux Kernel TLS on a TCP socket and to import TLS parameters. diff --git a/changelog/2187.added.md b/changelog/2187.added.md deleted file mode 100644 index a13ef70990..0000000000 --- a/changelog/2187.added.md +++ /dev/null @@ -1,2 +0,0 @@ -- Added the `::nix::sys::socket::SocketTimestamp` enum for configuring the `TsClock` (a.k.a `SO_TS_CLOCK`) sockopt -- Added FreeBSD's `ScmRealtime` and `ScmMonotonic` as new options in `::nix::sys::socket::ControlMessageOwned` \ No newline at end of file diff --git a/changelog/2194.added.md b/changelog/2194.added.md deleted file mode 100644 index 18e39b1ccd..0000000000 --- a/changelog/2194.added.md +++ /dev/null @@ -1 +0,0 @@ -Added new fanotify API: wrappers for `fanotify_init` and `fanotify_mark` diff --git a/changelog/2195.added.md b/changelog/2195.added.md deleted file mode 100644 index c523f22fd1..0000000000 --- a/changelog/2195.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `SpecialCharacterindices` support for haiku. diff --git a/changelog/2198.added.md b/changelog/2198.added.md deleted file mode 100644 index 93d3c50c52..0000000000 --- a/changelog/2198.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `sys::sendfile` support for solaris/illumos. diff --git a/changelog/2202.changed.md b/changelog/2202.changed.md deleted file mode 100644 index c1306d7f7e..0000000000 --- a/changelog/2202.changed.md +++ /dev/null @@ -1 +0,0 @@ -`Epoll::wait` now takes `EpollTimeout` replacing `isize`. \ No newline at end of file diff --git a/changelog/2206.added.md b/changelog/2206.added.md deleted file mode 100644 index 68f16b6cad..0000000000 --- a/changelog/2206.added.md +++ /dev/null @@ -1 +0,0 @@ -impl Display for InterfaceFlags diff --git a/changelog/2207.added.md b/changelog/2207.added.md deleted file mode 100644 index ddaa904221..0000000000 --- a/changelog/2207.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `sendfilev` in sys::sendfile for solarish diff --git a/changelog/2213.added.md b/changelog/2213.added.md deleted file mode 100644 index 7635067eaa..0000000000 --- a/changelog/2213.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `fctrl::SealFlag::F_SEAL_FUTURE_WRITE` diff --git a/changelog/2234.added.md b/changelog/2234.added.md deleted file mode 100644 index 138ac3ed3a..0000000000 --- a/changelog/2234.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `Ipv6MulticastHops` as socket option to set and read. diff --git a/changelog/2240.added.md b/changelog/2240.added.md deleted file mode 100644 index 315c67554c..0000000000 --- a/changelog/2240.added.md +++ /dev/null @@ -1 +0,0 @@ -Enable `ControlMessageOwned::Ipv4RecvIf` and `ControlMessageOwned::Ipv4RecvDstAddr` for DragonFlyBSD diff --git a/changelog/2241.added.md b/changelog/2241.added.md deleted file mode 100644 index 2323b9153f..0000000000 --- a/changelog/2241.added.md +++ /dev/null @@ -1 +0,0 @@ -`ClockId::set_time()` and `time::clock_settime()` are now enabled on macOS diff --git a/changelog/2242.fixed.md b/changelog/2242.fixed.md deleted file mode 100644 index c5194db5fa..0000000000 --- a/changelog/2242.fixed.md +++ /dev/null @@ -1,2 +0,0 @@ -Fixed UnixAddr::new for haiku, it did not record the `sun_len` value as needed. -Fixed `sys::socket::addr::from_raw_parts` and `sys::socket::Sockaddrlike::len` build for solaris. diff --git a/changelog/2244.added.md b/changelog/2244.added.md deleted file mode 100644 index c5d9465c76..0000000000 --- a/changelog/2244.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `IpBindAddressNoPort` sockopt to support `IP_BIND_ADDRESS_NO_PORT` available on linux. diff --git a/changelog/2245.added.md b/changelog/2245.added.md deleted file mode 100644 index 6ea7e0dec7..0000000000 --- a/changelog/2245.added.md +++ /dev/null @@ -1 +0,0 @@ -Enable `MapFlags::map_hugetlb_with_size_log2` method for Android/Fuchsia diff --git a/changelog/2247.added.md b/changelog/2247.added.md deleted file mode 100644 index f79f35495f..0000000000 --- a/changelog/2247.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `TcpFastOpenConnect` sockopt to support `TCP_FASTOPEN_CONNECT` available on linux. diff --git a/changelog/2248.fixed.md b/changelog/2248.fixed.md deleted file mode 100644 index 3115e7ef90..0000000000 --- a/changelog/2248.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed solaris build globally. diff --git a/changelog/2251.added.md b/changelog/2251.added.md deleted file mode 100644 index d925affa56..0000000000 --- a/changelog/2251.added.md +++ /dev/null @@ -1 +0,0 @@ -Add `reboot(2)` for OpenBSD/NetBSD \ No newline at end of file diff --git a/changelog/2252.added.md b/changelog/2252.added.md deleted file mode 100644 index 8737adde79..0000000000 --- a/changelog/2252.added.md +++ /dev/null @@ -1 +0,0 @@ -Added new `MemFdCreateFlag` constants to `sys::memfd` on Linux and Android related to hugetlbfs support. diff --git a/changelog/2258.added.md b/changelog/2258.added.md deleted file mode 100644 index 7aa74fdaa4..0000000000 --- a/changelog/2258.added.md +++ /dev/null @@ -1,4 +0,0 @@ -Expose the inner fd of `Kqueue` through: - -* impl AsFd for Kqueue -* impl From\ for OwnedFd diff --git a/changelog/2259.added.md b/changelog/2259.added.md deleted file mode 100644 index 244d9adb23..0000000000 --- a/changelog/2259.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `sys::eventfd` support on FreeBSD diff --git a/changelog/2260.added.md b/changelog/2260.added.md deleted file mode 100644 index 6ab54f3082..0000000000 --- a/changelog/2260.added.md +++ /dev/null @@ -1 +0,0 @@ -Added `MmapFlags::MAP_FIXED` constant in `sys::mman` for netbsd and openbsd diff --git a/changelog/2263.added.md b/changelog/2263.added.md deleted file mode 100644 index 9c343b6ab1..0000000000 --- a/changelog/2263.added.md +++ /dev/null @@ -1 +0,0 @@ -Added the `SO_LISTENQLIMIT` sockopt. diff --git a/changelog/2267.added.md b/changelog/2267.added.md deleted file mode 100644 index 0a09558511..0000000000 --- a/changelog/2267.added.md +++ /dev/null @@ -1 +0,0 @@ -Enable the `AT_EMPTY_PATH` flag for the `fchownat()` function diff --git a/changelog/2267.removed.md b/changelog/2267.removed.md deleted file mode 100644 index bedb77fd20..0000000000 --- a/changelog/2267.removed.md +++ /dev/null @@ -1 +0,0 @@ -The `FchownatFlags` type has been deprecated, please use `AtFlags` instead. diff --git a/changelog/2268.fixed.md b/changelog/2268.fixed.md deleted file mode 100644 index 108553d984..0000000000 --- a/changelog/2268.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Changed the `dup3` wrapper to perform a real call to `dup3` instead of emulating it via `dup2` and `fcntl` to get rid of race condition diff --git a/changelog/2268.removed.md b/changelog/2268.removed.md deleted file mode 100644 index a69aba3a45..0000000000 --- a/changelog/2268.removed.md +++ /dev/null @@ -1 +0,0 @@ -Removed the `dup3` wrapper on macOS, which was emulated via `dup2` and `fcntl` and could cause a race condition. The `dup3` system call is not supported on macOS. diff --git a/changelog/2270.added.md b/changelog/2270.added.md deleted file mode 100644 index ff0841ef31..0000000000 --- a/changelog/2270.added.md +++ /dev/null @@ -1 +0,0 @@ -Add `AtFlags::AT_EMPTY_PATH` for FreeBSD and Hurd diff --git a/changelog/2275.added.md b/changelog/2275.added.md deleted file mode 100644 index 05a8e46817..0000000000 --- a/changelog/2275.added.md +++ /dev/null @@ -1 +0,0 @@ -Enable `OFlag::O_DIRECTORY for Solarish diff --git a/changelog/2276.added.md b/changelog/2276.added.md deleted file mode 100644 index 9a05cc5ca8..0000000000 --- a/changelog/2276.added.md +++ /dev/null @@ -1 +0,0 @@ -Added the `Backlog` wrapper type for the `listen` call. diff --git a/changelog/2277.added.md b/changelog/2277.added.md deleted file mode 100644 index 0b6e8611c4..0000000000 --- a/changelog/2277.added.md +++ /dev/null @@ -1 +0,0 @@ -Add `clock_nanosleep()` diff --git a/changelog/2278.added.md b/changelog/2278.added.md deleted file mode 100644 index 88a07c79a8..0000000000 --- a/changelog/2278.added.md +++ /dev/null @@ -1 +0,0 @@ -Enabled `O_DIRECT` in `fcntl::OFlags` for solarish diff --git a/changelog/2279.added.md b/changelog/2279.added.md deleted file mode 100644 index 5bbbbb40f7..0000000000 --- a/changelog/2279.added.md +++ /dev/null @@ -1 +0,0 @@ -Added a new API sigsuspend. diff --git a/changelog/2283.added.md b/changelog/2283.added.md deleted file mode 100644 index fbf357d0f3..0000000000 --- a/changelog/2283.added.md +++ /dev/null @@ -1,4 +0,0 @@ -- Added `errno::Errno::set` function -- Added `errno::Errno::set_raw` function -- Added `errno::Errno::last_raw` function -- Added `errno::Errno::from_raw` function diff --git a/changelog/2283.changed.md b/changelog/2283.changed.md deleted file mode 100644 index 44bb1d5405..0000000000 --- a/changelog/2283.changed.md +++ /dev/null @@ -1,3 +0,0 @@ -- Deprecated `errno::errno()` function (use `Errno::last_raw()`) -- Deprecated `errno::from_i32()` function (use `Errno::from_raw()`) -- Deprecated `errno::Errno::from_i32()` function (use `Errno::from_raw()`) diff --git a/changelog/2284.added.md b/changelog/2284.added.md deleted file mode 100644 index 522a9341ce..0000000000 --- a/changelog/2284.added.md +++ /dev/null @@ -1 +0,0 @@ -Enable the `AT_EMPTY_PATH` flag for the `linkat()` function diff --git a/changelog/2284.removed.md b/changelog/2284.removed.md deleted file mode 100644 index 8dde5ffdfe..0000000000 --- a/changelog/2284.removed.md +++ /dev/null @@ -1 +0,0 @@ -The `LinkatFlags` type has been deprecated, please use `AtFlags` instead. diff --git a/changelog/2296.added.md b/changelog/2296.added.md deleted file mode 100644 index 4ec5fe0a29..0000000000 --- a/changelog/2296.added.md +++ /dev/null @@ -1 +0,0 @@ -Enable unistd::{sync, syncfs} for Android \ No newline at end of file diff --git a/changelog/2311.fixed.md b/changelog/2311.fixed.md deleted file mode 100644 index c1b4013f05..0000000000 --- a/changelog/2311.fixed.md +++ /dev/null @@ -1 +0,0 @@ -Fixed `::unistd::Group::members` using read_unaligned to avoid crash on misaligned pointers From 21ab06ef23de214174ddb039be5b5f08750d19e6 Mon Sep 17 00:00:00 2001 From: Steve Lau Date: Sat, 24 Feb 2024 12:24:20 +0800 Subject: [PATCH 140/140] chore: release 0.8.0 --- Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 5abd1344da..d8176a7500 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "nix" description = "Rust friendly bindings to *nix APIs" edition = "2021" -version = "0.27.1" +version = "0.28.0" rust-version = "1.69" authors = ["The nix-rust Project Developers"] repository = "https://github.com/nix-rust/nix"