diff options
author | Alex Saveau <saveau.alexandre@gmail.com> | 2022-11-06 11:27:08 -0800 |
---|---|---|
committer | Alex Saveau <saveau.alexandre@gmail.com> | 2022-11-06 11:39:09 -0800 |
commit | 17833268cb3269d83766bcdb4d9cbe0e25ebd38e (patch) | |
tree | b86885991e1d8b6f9c610747c2e8c3a3370960cd | |
parent | 20df092bd067908fba23e49120eed7ad62f29108 (diff) | |
download | nix-17833268cb3269d83766bcdb4d9cbe0e25ebd38e.zip |
Reformat everything
Signed-off-by: Alex Saveau <saveau.alexandre@gmail.com>
43 files changed, 2530 insertions, 1417 deletions
diff --git a/.cirrus.yml b/.cirrus.yml index 30f1b122..ab1178dd 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -315,4 +315,4 @@ task: container: image: rust:latest setup_script: rustup +$TOOLCHAIN component add rustfmt - test_script: $TOOL +$TOOLCHAIN fmt --all -- --check + test_script: $TOOL +$TOOLCHAIN fmt --all -- --check **/*.rs @@ -1,13 +1,13 @@ //! List directory contents -use crate::{Error, NixPath, Result}; use crate::errno::Errno; use crate::fcntl::{self, OFlag}; -use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; -use std::ptr; -use std::ffi; use crate::sys; +use crate::{Error, NixPath, Result}; use cfg_if::cfg_if; +use std::ffi; +use std::os::unix::io::{AsRawFd, IntoRawFd, RawFd}; +use std::ptr; #[cfg(target_os = "linux")] use libc::{dirent64 as dirent, readdir64_r as readdir_r}; @@ -29,21 +29,26 @@ use libc::{dirent, readdir_r}; /// * returns entries' names as a `CStr` (no allocation or conversion beyond whatever libc /// does). #[derive(Debug, Eq, Hash, PartialEq)] -pub struct Dir( - ptr::NonNull<libc::DIR> -); +pub struct Dir(ptr::NonNull<libc::DIR>); impl Dir { /// Opens the given path as with `fcntl::open`. - pub fn open<P: ?Sized + NixPath>(path: &P, oflag: OFlag, - mode: sys::stat::Mode) -> Result<Self> { + pub fn open<P: ?Sized + NixPath>( + path: &P, + oflag: OFlag, + mode: sys::stat::Mode, + ) -> Result<Self> { let fd = fcntl::open(path, oflag, mode)?; Dir::from_fd(fd) } /// Opens the given path as with `fcntl::openat`. - pub fn openat<P: ?Sized + NixPath>(dirfd: RawFd, path: &P, oflag: OFlag, - mode: sys::stat::Mode) -> Result<Self> { + pub fn openat<P: ?Sized + NixPath>( + dirfd: RawFd, + path: &P, + oflag: OFlag, + mode: sys::stat::Mode, + ) -> Result<Self> { let fd = fcntl::openat(dirfd, path, oflag, mode)?; Dir::from_fd(fd) } @@ -57,11 +62,13 @@ impl Dir { /// Converts from a file descriptor, closing it on success or failure. #[doc(alias("fdopendir"))] pub fn from_fd(fd: RawFd) -> Result<Self> { - let d = ptr::NonNull::new(unsafe { libc::fdopendir(fd) }).ok_or_else(|| { - let e = Error::last(); - unsafe { libc::close(fd) }; - e - })?; + let d = ptr::NonNull::new(unsafe { libc::fdopendir(fd) }).ok_or_else( + || { + let e = Error::last(); + unsafe { libc::close(fd) }; + e + }, + )?; Ok(Dir(d)) } @@ -103,9 +110,11 @@ fn next(dir: &mut Dir) -> Option<Result<Entry>> { // Probably fine here too then. let mut ent = std::mem::MaybeUninit::<dirent>::uninit(); let mut result = ptr::null_mut(); - if let Err(e) = Errno::result( - readdir_r(dir.0.as_ptr(), ent.as_mut_ptr(), &mut result)) - { + if let Err(e) = Errno::result(readdir_r( + dir.0.as_ptr(), + ent.as_mut_ptr(), + &mut result, + )) { return Some(Err(e)); } if result.is_null() { @@ -207,7 +216,7 @@ pub enum Type { impl Entry { /// Returns the inode number (`d_ino`) of the underlying `dirent`. - #[allow(clippy::useless_conversion)] // Not useless on all OSes + #[allow(clippy::useless_conversion)] // Not useless on all OSes // The cast is not unnecessary on all platforms. #[allow(clippy::unnecessary_cast)] pub fn ino(&self) -> u64 { @@ -240,7 +249,11 @@ 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<Type> { - #[cfg(not(any(target_os = "illumos", target_os = "solaris", target_os = "haiku")))] + #[cfg(not(any( + target_os = "illumos", + target_os = "solaris", + target_os = "haiku" + )))] match self.0.d_type { libc::DT_FIFO => Some(Type::Fifo), libc::DT_CHR => Some(Type::CharacterDevice), @@ -253,7 +266,11 @@ impl Entry { } // illumos, Solaris, and Haiku systems do not have the d_type member at all: - #[cfg(any(target_os = "illumos", target_os = "solaris", target_os = "haiku"))] + #[cfg(any( + target_os = "illumos", + target_os = "solaris", + target_os = "haiku" + ))] None } } diff --git a/src/features.rs b/src/features.rs index d2adc169..39d17604 100644 --- a/src/features.rs +++ b/src/features.rs @@ -3,9 +3,9 @@ pub use self::os::*; #[cfg(any(target_os = "linux", target_os = "android"))] mod os { - use std::os::unix::ffi::OsStrExt; use crate::sys::utsname::uname; use crate::Result; + use std::os::unix::ffi::OsStrExt; // Features: // * atomic cloexec on socket: 2.6.27 @@ -13,10 +13,10 @@ mod os { // * accept4: 2.6.28 static VERS_UNKNOWN: usize = 1; - static VERS_2_6_18: usize = 2; - static VERS_2_6_27: usize = 3; - static VERS_2_6_28: usize = 4; - static VERS_3: usize = 5; + static VERS_2_6_18: usize = 2; + static VERS_2_6_27: usize = 3; + static VERS_2_6_28: usize = 4; + static VERS_3: usize = 5; #[inline] fn digit(dst: &mut usize, b: u8) { @@ -27,7 +27,7 @@ mod os { fn parse_kernel_version() -> Result<usize> { let u = uname()?; - let mut curr: usize = 0; + let mut curr: usize = 0; let mut major: usize = 0; let mut minor: usize = 0; let mut patch: usize = 0; @@ -41,13 +41,11 @@ mod os { b'.' | b'-' => { curr += 1; } - b'0'..=b'9' => { - match curr { - 0 => digit(&mut major, b), - 1 => digit(&mut minor, b), - _ => digit(&mut patch, b), - } - } + b'0'..=b'9' => match curr { + 0 => digit(&mut major, b), + 1 => digit(&mut minor, b), + _ => digit(&mut patch, b), + }, _ => break, } } @@ -87,7 +85,9 @@ mod os { /// Check if the OS supports atomic close-on-exec for sockets pub fn socket_atomic_cloexec() -> bool { - kernel_version().map(|version| version >= VERS_2_6_27).unwrap_or(false) + kernel_version() + .map(|version| version >= VERS_2_6_27) + .unwrap_or(false) } #[test] @@ -111,11 +111,13 @@ mod os { } } -#[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "fuchsia", - target_os = "haiku", - target_os = "solaris"))] +#[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "fuchsia", + target_os = "haiku", + target_os = "solaris" +))] mod os { /// Check if the OS supports atomic close-on-exec for sockets pub const fn socket_atomic_cloexec() -> bool { diff --git a/src/ifaddrs.rs b/src/ifaddrs.rs index f834d307..210d4d77 100644 --- a/src/ifaddrs.rs +++ b/src/ifaddrs.rs @@ -9,9 +9,9 @@ use std::iter::Iterator; use std::mem; use std::option::Option; -use crate::{Result, Errno}; -use crate::sys::socket::{SockaddrLike, SockaddrStorage}; use crate::net::if_::*; +use crate::sys::socket::{SockaddrLike, SockaddrStorage}; +use crate::{Errno, Result}; /// Describes a single address for an interface as returned by `getifaddrs`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] @@ -47,7 +47,8 @@ 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) }; - let netmask = unsafe { SockaddrStorage::from_raw(info.ifa_netmask, None) }; + let netmask = + 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), diff --git a/src/kmod.rs b/src/kmod.rs index c42068c7..1fa6c170 100644 --- a/src/kmod.rs +++ b/src/kmod.rs @@ -79,7 +79,11 @@ libc_bitflags!( /// ``` /// /// See [`man init_module(2)`](https://man7.org/linux/man-pages/man2/init_module.2.html) for more information. -pub fn finit_module<T: AsRawFd>(fd: &T, param_values: &CStr, flags: ModuleInitFlags) -> Result<()> { +pub fn finit_module<T: AsRawFd>( + fd: &T, + param_values: &CStr, + flags: ModuleInitFlags, +) -> Result<()> { let res = unsafe { libc::syscall( libc::SYS_finit_module, @@ -116,7 +120,9 @@ libc_bitflags!( /// /// See [`man delete_module(2)`](https://man7.org/linux/man-pages/man2/delete_module.2.html) for more information. pub fn delete_module(name: &CStr, flags: DeleteModuleFlags) -> Result<()> { - let res = unsafe { libc::syscall(libc::SYS_delete_module, name.as_ptr(), flags.bits()) }; + let res = unsafe { + libc::syscall(libc::SYS_delete_module, name.as_ptr(), flags.bits()) + }; Errno::result(res).map(drop) } diff --git a/src/mount/bsd.rs b/src/mount/bsd.rs index 1ba8b809..d124f1f9 100644 --- a/src/mount/bsd.rs +++ b/src/mount/bsd.rs @@ -1,25 +1,17 @@ #[cfg(target_os = "freebsd")] -use crate::{ - Error, -}; -use crate::{ - Errno, - NixPath, - Result, -}; +use crate::Error; +use crate::{Errno, NixPath, Result}; +use libc::c_int; #[cfg(target_os = "freebsd")] use libc::{c_char, c_uint, c_void}; -use libc::c_int; #[cfg(target_os = "freebsd")] use std::{ borrow::Cow, - ffi::{CString, CStr}, + ffi::{CStr, CString}, + fmt, io, marker::PhantomData, - fmt, - io, }; - libc_bitflags!( /// Used with [`Nmount::nmount`]. pub struct MntFlags: c_int { @@ -111,7 +103,6 @@ libc_bitflags!( } ); - /// The Error type of [`Nmount::nmount`]. /// /// It wraps an [`Errno`], but also may contain an additional message returned @@ -120,7 +111,7 @@ libc_bitflags!( #[derive(Debug)] pub struct NmountError { errno: Error, - errmsg: Option<String> + errmsg: Option<String>, } #[cfg(target_os = "freebsd")] @@ -138,7 +129,7 @@ impl NmountError { fn new(error: Error, errmsg: Option<&CStr>) -> Self { Self { errno: error, - errmsg: errmsg.map(CStr::to_string_lossy).map(Cow::into_owned) + errmsg: errmsg.map(CStr::to_string_lossy).map(Cow::into_owned), } } } @@ -199,7 +190,7 @@ pub type NmountResult = std::result::Result<(), NmountError>; /// .str_opt_owned("fspath", mountpoint.path().to_str().unwrap()) /// .str_opt_owned("target", target.path().to_str().unwrap()) /// .nmount(MntFlags::empty()).unwrap(); -/// +/// /// unmount(mountpoint.path(), MntFlags::empty()).unwrap(); /// ``` /// @@ -209,7 +200,7 @@ pub type NmountResult = std::result::Result<(), NmountError>; #[cfg(target_os = "freebsd")] #[cfg_attr(docsrs, doc(cfg(all())))] #[derive(Debug, Default)] -pub struct Nmount<'a>{ +pub struct Nmount<'a> { // n.b. notgull: In reality, this is a list that contains // both mutable and immutable pointers. // Be careful using this. @@ -231,7 +222,12 @@ impl<'a> Nmount<'a> { } /// Helper function to push a pointer and its length onto the `iov` array. - fn push_pointer_and_length(&mut self, val: *const u8, len: usize, is_owned: bool) { + fn push_pointer_and_length( + &mut self, + val: *const u8, + len: usize, + is_owned: bool, + ) { self.iov.push(libc::iovec { iov_base: val as *mut _, iov_len: len, @@ -246,7 +242,8 @@ impl<'a> Nmount<'a> { let ptr = s.to_owned().into_raw() as *const u8; self.push_pointer_and_length(ptr, len, true); - }).unwrap(); + }) + .unwrap(); } /// Add an opaque mount option. @@ -280,9 +277,8 @@ impl<'a> Nmount<'a> { &mut self, name: &'a CStr, val: *mut c_void, - len: usize - ) -> &mut Self - { + len: usize, + ) -> &mut Self { self.push_slice(name.to_bytes_with_nul(), false); self.push_pointer_and_length(val.cast(), len, false); self @@ -321,8 +317,10 @@ impl<'a> Nmount<'a> { /// let mut nmount: Nmount<'static> = Nmount::new(); /// nmount.null_opt_owned(read_only); /// ``` - pub fn null_opt_owned<P: ?Sized + NixPath>(&mut self, name: &P) -> &mut Self - { + pub fn null_opt_owned<P: ?Sized + NixPath>( + &mut self, + name: &P, + ) -> &mut Self { self.push_nix_path(name); self.push_slice(&[], false); self @@ -340,12 +338,7 @@ impl<'a> Nmount<'a> { /// Nmount::new() /// .str_opt(&fstype, &nullfs); /// ``` - pub fn str_opt( - &mut self, - name: &'a CStr, - val: &'a CStr - ) -> &mut Self - { + pub fn str_opt(&mut self, name: &'a CStr, val: &'a CStr) -> &mut Self { self.push_slice(name.to_bytes_with_nul(), false); self.push_slice(val.to_bytes_with_nul(), false); self @@ -367,8 +360,9 @@ impl<'a> Nmount<'a> { /// .str_opt_owned("fspath", mountpoint.to_str().unwrap()); /// ``` pub fn str_opt_owned<P1, P2>(&mut self, name: &P1, val: &P2) -> &mut Self - where P1: ?Sized + NixPath, - P2: ?Sized + NixPath + where + P1: ?Sized + NixPath, + P2: ?Sized + NixPath, { self.push_nix_path(name); self.push_nix_path(val); @@ -398,9 +392,7 @@ impl<'a> Nmount<'a> { let niov = self.iov.len() as c_uint; let iovp = self.iov.as_mut_ptr() as *mut libc::iovec; - let res = unsafe { - libc::nmount(iovp, niov, flags.bits) - }; + let res = unsafe { libc::nmount(iovp, niov, flags.bits) }; match Errno::result(res) { Ok(_) => Ok(()), Err(error) => { @@ -437,7 +429,9 @@ impl<'a> Drop for Nmount<'a> { /// /// Useful flags include /// * `MNT_FORCE` - Unmount even if still in use. -#[cfg_attr(target_os = "freebsd", doc = " +#[cfg_attr( + target_os = "freebsd", + doc = " * `MNT_BYFSID` - `mountpoint` is not a path, but a file system ID encoded as `FSID:val0:val1`, where `val0` and `val1` are the contents of the `fsid_t val[]` array in decimal. @@ -445,12 +439,14 @@ impl<'a> Drop for Nmount<'a> { will be unmounted. See [`statfs`](crate::sys::statfs::statfs) to determine the `fsid`. -")] +" +)] pub fn unmount<P>(mountpoint: &P, flags: MntFlags) -> Result<()> - where P: ?Sized + NixPath +where + P: ?Sized + NixPath, { - let res = mountpoint.with_nix_path(|cstr| { - unsafe { libc::unmount(cstr.as_ptr(), flags.bits) } + let res = mountpoint.with_nix_path(|cstr| unsafe { + libc::unmount(cstr.as_ptr(), flags.bits) })?; Errno::result(res).map(drop) diff --git a/src/mount/linux.rs b/src/mount/linux.rs index 4c976dcb..cf6a60b0 100644 --- a/src/mount/linux.rs +++ b/src/mount/linux.rs @@ -1,7 +1,7 @@ #![allow(missing_docs)] -use libc::{self, c_ulong, c_int}; -use crate::{Result, NixPath}; use crate::errno::Errno; +use crate::{NixPath, Result}; +use libc::{self, c_int, c_ulong}; libc_bitflags!( pub struct MsFlags: c_ulong { @@ -57,36 +57,40 @@ libc_bitflags!( } ); -pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P4: ?Sized + NixPath>( - source: Option<&P1>, - target: &P2, - fstype: Option<&P3>, - flags: MsFlags, - data: Option<&P4>) -> Result<()> { - +pub fn mount< + P1: ?Sized + NixPath, + P2: ?Sized + NixPath, + P3: ?Sized + NixPath, + P4: ?Sized + NixPath, +>( + source: Option<&P1>, + target: &P2, + fstype: Option<&P3>, + flags: MsFlags, + data: Option<&P4>, +) -> Result<()> { fn with_opt_nix_path<P, T, F>(p: Option<&P>, f: F) -> Result<T> - where P: ?Sized + NixPath, - F: FnOnce(*const libc::c_char) -> T + 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())) + None => Ok(f(std::ptr::null())), } } let res = with_opt_nix_path(source, |s| { target.with_nix_path(|t| { with_opt_nix_path(fstype, |ty| { - with_opt_nix_path(data, |d| { - unsafe { - libc::mount( - s, - t.as_ptr(), - ty, - flags.bits, - d as *const libc::c_void - ) - } + with_opt_nix_path(data, |d| unsafe { + libc::mount( + s, + t.as_ptr(), + ty, + flags.bits, + d as *const libc::c_void, + ) }) }) }) @@ -96,16 +100,15 @@ pub fn mount<P1: ?Sized + NixPath, P2: ?Sized + NixPath, P3: ?Sized + NixPath, P } pub fn umount<P: ?Sized + NixPath>(target: &P) -> Result<()> { - let res = target.with_nix_path(|cstr| { - unsafe { libc::umount(cstr.as_ptr()) } - })?; + let res = + target.with_nix_path(|cstr| unsafe { libc::umount(cstr.as_ptr()) })?; Errno::result(res).map(drop) } pub fn umount2<P: ?Sized + NixPath>(target: &P, flags: MntFlags) -> Result<()> { - let res = target.with_nix_path(|cstr| { - unsafe { libc::umount2(cstr.as_ptr(), flags.bits) } + let res = target.with_nix_path(|cstr| unsafe { + libc::umount2(cstr.as_ptr(), flags.bits) })?; Errno::result(res).map(drop) diff --git a/src/mount/mod.rs b/src/mount/mod.rs index e89c1a07..e98b49c3 100644 --- a/src/mount/mod.rs +++ b/src/mount/mod.rs @@ -6,18 +6,21 @@ mod linux; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::linux::*; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] #[cfg_attr(docsrs, doc(cfg(all())))] mod bsd; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" - ))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] pub use self::bsd::*; diff --git a/src/mqueue.rs b/src/mqueue.rs index e3c0c43e..33599bf9 100644 --- a/src/mqueue.rs +++ b/src/mqueue.rs @@ -30,15 +30,15 @@ //! ``` //! [Further reading and details on the C API](https://man7.org/linux/man-pages/man7/mq_overview.7.html) -use crate::Result; use crate::errno::Errno; +use crate::Result; +use crate::sys::stat::Mode; use libc::{self, c_char, mqd_t, size_t}; use std::ffi::CStr; -use crate::sys::stat::Mode; use std::mem; -libc_bitflags!{ +libc_bitflags! { /// Used with [`mq_open`]. pub struct MQ_OFlag: libc::c_int { /// Open the message queue for receiving messages. @@ -96,12 +96,12 @@ impl MqAttr { /// - `mq_maxmsg`: Maximum number of messages on the queue. /// - `mq_msgsize`: Maximum message size in bytes. /// - `mq_curmsgs`: Number of messages currently in the queue. - pub fn new(mq_flags: mq_attr_member_t, - mq_maxmsg: mq_attr_member_t, - mq_msgsize: mq_attr_member_t, - mq_curmsgs: mq_attr_member_t) - -> MqAttr - { + pub fn new( + mq_flags: mq_attr_member_t, + mq_maxmsg: mq_attr_member_t, + mq_msgsize: mq_attr_member_t, + mq_curmsgs: mq_attr_member_t, + ) -> MqAttr { let mut attr = mem::MaybeUninit::<libc::mq_attr>::uninit(); unsafe { let p = attr.as_mut_ptr(); @@ -109,7 +109,9 @@ impl MqAttr { (*p).mq_maxmsg = mq_maxmsg; (*p).mq_msgsize = mq_msgsize; (*p).mq_curmsgs = mq_curmsgs; - MqAttr { mq_attr: attr.assume_init() } + MqAttr { + mq_attr: attr.assume_init(), + } } } @@ -134,23 +136,25 @@ impl MqAttr { } } - /// Open a message queue /// /// See also [`mq_open(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_open.html) // The mode.bits cast is only lossless on some OSes #[allow(clippy::cast_lossless)] -pub fn mq_open(name: &CStr, - oflag: MQ_OFlag, - mode: Mode, - attr: Option<&MqAttr>) - -> Result<MqdT> { +pub fn mq_open( + name: &CStr, + oflag: MQ_OFlag, + mode: Mode, + attr: Option<&MqAttr>, +) -> Result<MqdT> { let res = match attr { Some(mq_attr) => unsafe { - libc::mq_open(name.as_ptr(), - oflag.bits(), - mode.bits() as libc::c_int, - &mq_attr.mq_attr as *const libc::mq_attr) + libc::mq_open( + name.as_ptr(), + oflag.bits(), + mode.bits() as libc::c_int, + &mq_attr.mq_attr as *const libc::mq_attr, + ) }, None => unsafe { libc::mq_open(name.as_ptr(), oflag.bits()) }, }; @@ -176,13 +180,19 @@ pub fn mq_close(mqdes: MqdT) -> Result<()> { /// Receive a message from a message queue /// /// See also [`mq_receive(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/mq_receive.html) -pub fn mq_receive(mqdes: &MqdT, message: &mut [u8], msg_prio: &mut u32) -> Result<usize> { +pub fn mq_receive( + mqdes: &MqdT, + message: &mut [u8], + msg_prio: &mut u32, +) -> Result<usize> { let len = message.len() as size_t; let res = unsafe { - libc::mq_receive(mqdes.0, - message.as_mut_ptr() as *mut c_char, - len, - msg_prio as *mut u32) + libc::mq_receive( + mqdes.0, + message.as_mut_ptr() as *mut c_char, + len, + msg_prio as *mut u32, + ) }; Errno::result(res).map(|r| r as usize) } @@ -192,10 +202,12 @@ pub fn mq_receive(mqdes: &MqdT, message: &mut [u8], msg_prio: &mut u32) -> Resul /// 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() as *const c_char, + message.len(), + msq_prio, + ) }; Errno::result(res).map(drop) } @@ -206,7 +218,11 @@ pub fn mq_send(mqdes: &MqdT, message: &[u8], msq_prio: u32) -> Result<()> { pub fn mq_getattr(mqd: &MqdT) -> Result<MqAttr> { let mut attr = mem::MaybeUninit::<libc::mq_attr>::uninit(); let res = unsafe { libc::mq_getattr(mqd.0, attr.as_mut_ptr()) }; - Errno::result(res).map(|_| unsafe{MqAttr { mq_attr: attr.assume_init() }}) + Errno::result(res).map(|_| unsafe { + MqAttr { + mq_attr: attr.assume_init(), + } + }) } /// Set the attributes of the message queue. Only `O_NONBLOCK` can be set, everything else will be ignored @@ -217,21 +233,31 @@ pub fn mq_getattr(mqd: &MqdT) -> Result<MqAttr> { pub fn mq_setattr(mqd: &MqdT, newattr: &MqAttr) -> Result<MqAttr> { let mut attr = mem::MaybeUninit::<libc::mq_attr>::uninit(); let res = unsafe { - libc::mq_setattr(mqd.0, &newattr.mq_attr as *const libc::mq_attr, attr.as_mut_ptr()) + libc::mq_setattr( + mqd.0, + &newattr.mq_attr as *const libc::mq_attr, + attr.as_mut_ptr(), + ) }; - Errno::result(res).map(|_| unsafe{ MqAttr { mq_attr: attr.assume_init() }}) + Errno::result(res).map(|_| unsafe { + MqAttr { + mq_attr: attr.assume_init(), + } + }) } /// Convenience function. /// Sets the `O_NONBLOCK` attribute for a given message queue descriptor /// Returns the old attributes -#[allow(clippy::useless_conversion)] // Not useless on all OSes +#[allow(clippy::useless_conversion)] // Not useless on all OSes pub fn mq_set_nonblock(mqd: &MqdT) -> Result<MqAttr> { let oldattr = mq_getattr(mqd)?; - let newattr = MqAttr::new(mq_attr_member_t::from(MQ_OFlag::O_NONBLOCK.bits()), - oldattr.mq_attr.mq_maxmsg, - oldattr.mq_attr.mq_msgsize, - oldattr.mq_attr.mq_curmsgs); + let newattr = MqAttr::new( + mq_attr_member_t::from(MQ_OFlag::O_NONBLOCK.bits()), + oldattr.mq_attr.mq_maxmsg, + oldattr.mq_attr.mq_msgsize, + oldattr.mq_attr.mq_curmsgs, + ); mq_setattr(mqd, &newattr) } @@ -240,9 +266,11 @@ pub fn mq_set_nonblock(mqd: &MqdT) -> Result<MqAttr> { /// Returns the old attributes pub fn mq_remove_nonblock(mqd: &MqdT) -> Result<MqAttr> { let oldattr = mq_getattr(mqd)?; - let newattr = MqAttr::new(0, - oldattr.mq_attr.mq_maxmsg, - oldattr.mq_attr.mq_msgsize, - oldattr.mq_attr.mq_curmsgs); + let newattr = MqAttr::new( + 0, + oldattr.mq_attr.mq_maxmsg, + oldattr.mq_attr.mq_msgsize, + oldattr.mq_attr.mq_curmsgs, + ); mq_setattr(mqd, &newattr) } diff --git a/src/net/if_.rs b/src/net/if_.rs index 045efad9..b2423bc6 100644 --- a/src/net/if_.rs +++ b/src/net/if_.rs @@ -8,7 +8,8 @@ use libc::c_uint; /// Resolve an interface into a interface number. pub fn if_nametoindex<P: ?Sized + NixPath>(name: &P) -> Result<c_uint> { - let if_index = name.with_nix_path(|name| unsafe { libc::if_nametoindex(name.as_ptr()) })?; + let if_index = name + .with_nix_path(|name| unsafe { libc::if_nametoindex(name.as_ptr()) })?; if if_index == 0 { Err(Error::last()) diff --git a/src/poll.rs b/src/poll.rs index 3004d24c..e1baa814 100644 --- a/src/poll.rs +++ b/src/poll.rs @@ -1,8 +1,8 @@ //! Wait for events to trigger on specific file descriptors use std::os::unix::io::{AsRawFd, RawFd}; -use crate::Result; use crate::errno::Errno; +use crate::Result; /// This is a wrapper around `libc::pollfd`. /// @@ -134,9 +134,11 @@ libc_bitflags! { /// ready. pub fn poll(fds: &mut [PollFd], timeout: libc::c_int) -> Result<libc::c_int> { 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() as *mut libc::pollfd, + fds.len() as libc::nfds_t, + timeout, + ) }; Errno::result(res) @@ -8,11 +8,11 @@ use std::io; use std::mem; use std::os::unix::prelude::*; +use crate::errno::Errno; use crate::sys::termios::Termios; #[cfg(feature = "process")] use crate::unistd::{ForkResult, Pid}; -use crate::{Result, fcntl, unistd}; -use crate::errno::Errno; +use crate::{fcntl, unistd, Result}; /// Representation of a master/slave pty pair /// @@ -41,7 +41,6 @@ pub struct ForkptyResult { } } - /// Representation of the Master device in a master/slave pty pair /// /// While this datatype is a thin wrapper around `RawFd`, it enforces that the available PTY @@ -159,9 +158,7 @@ pub fn grantpt(fd: &PtyMaster) -> Result<()> { /// ``` #[inline] pub fn posix_openpt(flags: fcntl::OFlag) -> Result<PtyMaster> { - let fd = unsafe { - libc::posix_openpt(flags.bits()) - }; + let fd = unsafe { libc::posix_openpt(flags.bits()) }; if fd < 0 { return Err(Errno::last()); @@ -239,7 +236,6 @@ pub fn unlockpt(fd: &PtyMaster) -> Result<()> { Ok(()) } - /// Create a new pseudoterminal, returning the slave and master file descriptors /// in `OpenptyResult` /// (see [`openpty`](https://man7.org/linux/man-pages/man3/openpty.3.html)). @@ -248,7 +244,15 @@ pub fn unlockpt(fd: &PtyMaster) -> Result<()> { /// the values in `winsize`. If `termios` is not `None`, the pseudoterminal's /// terminal settings of the slave will be set to the values in `termios`. #[inline] -pub fn openpty<'a, 'b, T: Into<Option<&'a Winsize>>, U: Into<Option<&'b Termios>>>(winsize: T, termios: U) -> Result<OpenptyResult> { +pub fn openpty< + 'a, + 'b, + T: Into<Option<&'a Winsize>>, + U: Into<Option<&'b Termios>>, +>( + winsize: T, + termios: U, +) -> Result<OpenptyResult> { use std::ptr; let mut slave = mem::MaybeUninit::<libc::c_int>::uninit(); @@ -267,17 +271,15 @@ pub fn openpty<'a, 'b, T: Into<Option<&'a Winsize>>, U: Into<Option<&'b Termios> ) } } - (None, Some(winsize)) => { - unsafe { - libc::openpty( - master.as_mut_ptr(), - slave.as_mut_ptr(), - ptr::null_mut(), - ptr::null_mut(), - winsize as *const Winsize as *mut _, - ) - } - } + (None, Some(winsize)) => unsafe { + libc::openpty( + master.as_mut_ptr(), + slave.as_mut_ptr(), + ptr::null_mut(), + ptr::null_mut(), + winsize as *const Winsize as *mut _, + ) + }, (Some(termios), None) => { let inner_termios = termios.get_libc_termios(); unsafe { @@ -290,17 +292,15 @@ pub fn openpty<'a, 'b, T: Into<Option<&'a Winsize>>, U: Into<Option<&'b Termios> ) } } - (None, None) => { - unsafe { - libc::openpty( - master.as_mut_ptr(), - slave.as_mut_ptr(), - ptr::null_mut(), - ptr::null_mut(), - ptr::null_mut(), - ) - } - } + (None, None) => unsafe { + libc::openpty( + master.as_mut_ptr(), + slave.as_mut_ptr(), + ptr::null_mut(), + ptr::null_mut(), + ptr::null_mut(), + ) + }, } }; diff --git a/src/sched.rs b/src/sched.rs index aa2b90b4..d5b1233c 100644 --- a/src/sched.rs +++ b/src/sched.rs @@ -11,12 +11,12 @@ pub use self::sched_linux_like::*; #[cfg_attr(docsrs, doc(cfg(all())))] mod sched_linux_like { use crate::errno::Errno; + use crate::unistd::Pid; + use crate::Result; use libc::{self, c_int, c_void}; use std::mem; use std::option::Option; use std::os::unix::io::RawFd; - use crate::unistd::Pid; - use crate::Result; // For some functions taking with a parameter of type CloneFlags, // only a subset of these flags have an effect. @@ -112,7 +112,8 @@ mod sched_linux_like { let ptr_aligned = ptr.sub(ptr as usize % 16); libc::clone( mem::transmute( - callback as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, + callback + as extern "C" fn(*mut Box<dyn FnMut() -> isize>) -> i32, ), ptr_aligned as *mut c_void, combined, @@ -142,15 +143,25 @@ mod sched_linux_like { } } -#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux" +))] pub use self::sched_affinity::*; -#[cfg(any(target_os = "android", target_os = "dragonfly", target_os = "freebsd", target_os = "linux"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux" +))] mod sched_affinity { use crate::errno::Errno; - use std::mem; use crate::unistd::Pid; use crate::Result; + use std::mem; /// CpuSet represent a bit-mask of CPUs. /// CpuSets are used by sched_setaffinity and @@ -190,7 +201,9 @@ mod sched_affinity { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { - unsafe { libc::CPU_SET(field, &mut self.cpu_set); } + unsafe { + libc::CPU_SET(field, &mut self.cpu_set); + } Ok(()) } } @@ -201,7 +214,9 @@ mod sched_affinity { if field >= CpuSet::count() { Err(Errno::EINVAL) } else { - unsafe { libc::CPU_CLR(field, &mut self.cpu_set);} + unsafe { + libc::CPU_CLR(field, &mut self.cpu_set); + } Ok(()) } } diff --git a/src/sys/aio.rs b/src/sys/aio.rs index 6ff88469..e2ce19b7 100644 --- a/src/sys/aio.rs +++ b/src/sys/aio.rs @@ -32,8 +32,7 @@ use std::{ mem, os::unix::io::RawFd, pin::Pin, - ptr, - thread, + ptr, thread, }; use libc::{c_void, off_t}; @@ -107,7 +106,7 @@ unsafe impl Sync for LibcAiocb {} // polymorphism is at the level of `Futures`. #[repr(C)] struct AioCb { - aiocb: LibcAiocb, + aiocb: LibcAiocb, /// Could this `AioCb` potentially have any in-kernel state? // It would be really nice to perform the in-progress check entirely at // compile time. But I can't figure out how, because: @@ -153,7 +152,7 @@ impl AioCb { a.aio_reqprio = prio; a.aio_sigevent = SigEvent::new(sigev_notify).sigevent(); AioCb { - aiocb: LibcAiocb(a), + aiocb: LibcAiocb(a), in_progress: false, } } @@ -432,7 +431,7 @@ macro_rules! aio_methods { #[repr(transparent)] pub struct AioFsync { aiocb: AioCb, - _pin: PhantomPinned, + _pin: PhantomPinned, } impl AioFsync { @@ -546,7 +545,7 @@ impl AsRef<libc::aiocb> for AioFsync { pub struct AioRead<'a> { aiocb: AioCb, _data: PhantomData<&'a [u8]>, - _pin: PhantomPinned, + _pin: PhantomPinned, } impl<'a> AioRead<'a> { @@ -667,7 +666,7 @@ impl<'a> AsRef<libc::aiocb> for AioRead<'a> { pub struct AioReadv<'a> { aiocb: AioCb, _data: PhantomData<&'a [&'a [u8]]>, - _pin: PhantomPinned, + _pin: PhantomPinned, } #[cfg(target_os = "freebsd")] @@ -778,7 +777,7 @@ impl<'a> AsRef<libc::aiocb> for AioReadv<'a> { pub struct AioWrite<'a> { aiocb: AioCb, _data: PhantomData<&'a [u8]>, - _pin: PhantomPinned, + _pin: PhantomPinned, } impl<'a> AioWrite<'a> { @@ -896,7 +895,7 @@ impl<'a> AsRef<libc::aiocb> for AioWrite<'a> { pub struct AioWritev<'a> { aiocb: AioCb, _data: PhantomData<&'a [&'a [u8]]>, - _pin: PhantomPinned, + _pin: PhantomPinned, } #[cfg(target_os = "freebsd")] @@ -1053,8 +1052,7 @@ pub fn aio_suspend( timeout: Option<TimeSpec>, ) -> Result<()> { let p = list as *const [&dyn AsRef<libc::aiocb>] - as *const [*const libc::aiocb] - as *const *const libc::aiocb; + as *const [*const libc::aiocb] as *const *const libc::aiocb; let timep = match timeout { None => ptr::null::<libc::timespec>(), Some(x) => x.as_ref() as *const libc::timespec, @@ -1180,8 +1178,7 @@ pub fn lio_listio( sigev_notify: SigevNotify, ) -> Result<()> { let p = list as *mut [Pin<&mut dyn AsMut<libc::aiocb>>] - as *mut [*mut libc::aiocb] - as *mut *mut libc::aiocb; + as *mut [*mut libc::aiocb] as *mut *mut libc::aiocb; let sigev = SigEvent::new(sigev_notify); let sigevp = &mut sigev.sigevent() as *mut libc::sigevent; Errno::result(unsafe { diff --git a/src/sys/epoll.rs b/src/sys/epoll.rs index 8141ff5c..58def2e7 100644 --- a/src/sys/epoll.rs +++ b/src/sys/epoll.rs @@ -1,9 +1,9 @@ -use crate::Result; use crate::errno::Errno; +use crate::Result; use libc::{self, c_int}; +use std::mem; use std::os::unix::io::RawFd; use std::ptr; -use std::mem; libc_bitflags!( pub struct EpollFlags: c_int { @@ -35,7 +35,7 @@ pub enum EpollOp { EpollCtlMod = libc::EPOLL_CTL_MOD, } -libc_bitflags!{ +libc_bitflags! { pub struct EpollCreateFlags: c_int { EPOLL_CLOEXEC; } @@ -49,7 +49,12 @@ pub struct EpollEvent { impl EpollEvent { pub fn new(events: EpollFlags, data: u64) -> Self { - EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } } + EpollEvent { + event: libc::epoll_event { + events: events.bits() as u32, + u64: data, + }, + } } pub fn empty() -> Self { @@ -80,8 +85,14 @@ pub fn epoll_create1(flags: EpollCreateFlags) -> Result<RawFd> { } #[inline] -pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result<()> - where T: Into<Option<&'a mut EpollEvent>> +pub fn epoll_ctl<'a, T>( + epfd: RawFd, + op: EpollOp, + fd: RawFd, + event: T, +) -> Result<()> +where + T: Into<Option<&'a mut EpollEvent>>, { let mut event: Option<&mut EpollEvent> = event.into(); if event.is_none() && op != EpollOp::EpollCtlDel { @@ -99,9 +110,18 @@ pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result } #[inline] -pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> { +pub fn epoll_wait( + epfd: RawFd, + events: &mut [EpollEvent], + timeout_ms: isize, +) -> Result<usize> { let res = unsafe { - libc::epoll_wait(epfd, events.as_mut_ptr() as *mut libc::epoll_event, events.len() as c_int, timeout_ms as c_int) + libc::epoll_wait( + epfd, + events.as_mut_ptr() as *mut libc::epoll_event, + events.len() as c_int, + timeout_ms as c_int, + ) }; Errno::result(res).map(|r| r as usize) diff --git a/src/sys/event.rs b/src/sys/event.rs index 0d0d23a4..d8ad628e 100644 --- a/src/sys/event.rs +++ b/src/sys/event.rs @@ -3,9 +3,9 @@ use crate::{Errno, Result}; #[cfg(not(target_os = "netbsd"))] -use libc::{timespec, time_t, c_int, c_long, intptr_t, uintptr_t}; +use libc::{c_int, c_long, intptr_t, time_t, timespec, uintptr_t}; #[cfg(target_os = "netbsd")] -use libc::{timespec, time_t, c_long, intptr_t, uintptr_t, size_t}; +use libc::{c_long, intptr_t, size_t, time_t, timespec, uintptr_t}; use std::convert::TryInto; use std::mem; use std::os::unix::io::RawFd; @@ -18,9 +18,13 @@ pub struct KEvent { kevent: libc::kevent, } -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd" +))] type type_of_udata = *mut libc::c_void; #[cfg(any(target_os = "netbsd"))] type type_of_udata = intptr_t; @@ -75,13 +79,17 @@ libc_enum! { impl TryFrom<type_of_event_filter> } -#[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "ios", target_os = "macos", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "openbsd" +))] pub type type_of_event_flag = u16; #[cfg(any(target_os = "netbsd"))] pub type type_of_event_flag = u32; -libc_bitflags!{ +libc_bitflags! { pub struct EventFlag: type_of_event_flag { EV_ADD; EV_CLEAR; @@ -205,27 +213,33 @@ pub fn kqueue() -> Result<RawFd> { Errno::result(res) } - // KEvent can't derive Send because on some operating systems, udata is defined // as a void*. However, KEvent's public API always treats udata as an intptr_t, // which is safe to Send. -unsafe impl Send for KEvent { -} +unsafe impl Send for KEvent {} impl KEvent { - #[allow(clippy::needless_update)] // Not needless on all platforms. - pub fn new(ident: uintptr_t, filter: EventFilter, flags: EventFlag, - fflags:FilterFlag, data: intptr_t, udata: intptr_t) -> KEvent { - KEvent { kevent: libc::kevent { - ident, - filter: filter as type_of_event_filter, - flags: flags.bits(), - fflags: fflags.bits(), - // data can be either i64 or intptr_t, depending on platform - data: data as _, - udata: udata as type_of_udata, - .. unsafe { mem::zeroed() } - } } + #[allow(clippy::needless_update)] // Not needless on all platforms. + pub fn new( + ident: uintptr_t, + filter: EventFilter, + flags: EventFlag, + fflags: FilterFlag, + data: intptr_t, + udata: intptr_t, + ) -> KEvent { + KEvent { + kevent: libc::kevent { + ident, + filter: filter as type_of_event_filter, + flags: flags.bits(), + fflags: fflags.bits(), + // data can be either i64 or intptr_t, depending on platform + data: data as _, + udata: udata as type_of_udata, + ..unsafe { mem::zeroed() } + }, + } } pub fn ident(&self) -> uintptr_t { @@ -253,34 +267,38 @@ impl KEvent { } } -pub fn kevent(kq: RawFd, - changelist: &[KEvent], - eventlist: &mut [KEvent], - timeout_ms: usize) -> Result<usize> { - +pub fn kevent( + kq: RawFd, + changelist: &[KEvent], + eventlist: &mut [KEvent], + timeout_ms: usize, +) -> Result<usize> { // Convert ms to timespec let timeout = timespec { tv_sec: (timeout_ms / 1000) as time_t, - tv_nsec: ((timeout_ms % 1000) * 1_000_000) as c_long + tv_nsec: ((timeout_ms % 1000) * 1_000_000) as c_long, }; kevent_ts(kq, changelist, eventlist, Some(timeout)) } -#[cfg(any(target_os = "macos", - target_os = "ios", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "openbsd"))] +#[cfg(any( + target_os = "macos", + target_os = "ios", + target_os = "freebsd", + target_os = "dragonfly", + target_os = "openbsd" +))] type type_of_nchanges = c_int; #[cfg(target_os = "netbsd")] type type_of_nchanges = size_t; -pub fn kevent_ts(kq: RawFd, - changelist: &[KEvent], - eventlist: &mut [KEvent], - timeout_opt: Option<timespec>) -> Result<usize> { - +pub fn kevent_ts( + kq: RawFd, + changelist: &[KEvent], + eventlist: &mut [KEvent], + timeout_opt: Option<timespec>, +) -> Result<usize> { let res = unsafe { libc::kevent( kq, @@ -288,40 +306,48 @@ pub fn kevent_ts(kq: RawFd, changelist.len() as type_of_nchanges, eventlist.as_mut_ptr() as *mut libc::kevent, eventlist.len() as type_of_nchanges, - if let Some(ref timeout) = timeout_opt {timeout as *const timespec} else {ptr::null()}) + if let Some(ref timeout) = timeout_opt { + timeout as *const timespec + } else { + ptr::null() + }, + ) }; Errno::result(res).map(|r| r as usize) } #[inline] -pub fn ev_set(ev: &mut KEvent, - ident: usize, - filter: EventFilter, - flags: EventFlag, - fflags: FilterFlag, - udata: intptr_t) { - - ev.kevent.ident = ident as uintptr_t; +pub fn ev_set( + ev: &mut KEvent, + ident: usize, + filter: EventFilter, + flags: EventFlag, + fflags: FilterFlag, + udata: intptr_t, +) { + ev.kevent.ident = ident as uintptr_t; ev.kevent.filter = filter as type_of_event_filter; - ev.kevent.flags = flags.bits(); + ev.kevent.flags = flags.bits(); ev.kevent.fflags = fflags.bits(); - ev.kevent.data = 0; - ev.kevent.udata = udata as type_of_udata; + 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 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); + 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); @@ -334,13 +360,15 @@ fn test_struct_kevent() { #[test] fn test_kevent_filter() { - let udata : intptr_t = 12345; + 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); + 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/eventfd.rs b/src/sys/eventfd.rs index c54f952f..cd906720 100644 --- a/src/sys/eventfd.rs +++ b/src/sys/eventfd.rs @@ -1,6 +1,6 @@ -use std::os::unix::io::RawFd; -use crate::Result; use crate::errno::Errno; +use crate::Result; +use std::os::unix::io::RawFd; libc_bitflags! { pub struct EfdFlags: libc::c_int { diff --git a/src/sys/inotify.rs b/src/sys/inotify.rs index b19dbe12..84356ec7 100644 --- a/src/sys/inotify.rs +++ b/src/sys/inotify.rs @@ -23,20 +23,17 @@ //! } //! ``` -use libc::{ - c_char, - c_int, -}; -use std::ffi::{OsString,OsStr,CStr}; -use std::os::unix::ffi::OsStrExt; -use std::mem::{MaybeUninit, size_of}; -use std::os::unix::io::{RawFd,AsRawFd,FromRawFd}; -use std::ptr; +use crate::errno::Errno; use crate::unistd::read; -use crate::Result; use crate::NixPath; -use crate::errno::Errno; +use crate::Result; use cfg_if::cfg_if; +use libc::{c_char, c_int}; +use std::ffi::{CStr, OsStr, OsString}; +use std::mem::{size_of, MaybeUninit}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::ptr; libc_bitflags! { /// Configuration options for [`inotify_add_watch`](fn.inotify_add_watch.html). @@ -106,7 +103,7 @@ libc_bitflags! { /// other interfaces consuming file descriptors, epoll for example. #[derive(Debug, Clone, Copy)] pub struct Inotify { - fd: RawFd + fd: RawFd, } /// This object is returned when you create a new watch on an inotify instance. @@ -114,7 +111,7 @@ pub struct Inotify { /// know which watch triggered which event. #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct WatchDescriptor { - wd: i32 + wd: i32, } /// A single inotify event. @@ -134,7 +131,7 @@ pub struct InotifyEvent { pub cookie: u32, /// Filename. This field exists only if the event was triggered for a file /// inside the watched directory. - pub name: Option<OsString> + pub name: Option<OsString>, } impl Inotify { @@ -144,9 +141,7 @@ impl Inotify { /// /// For more information see, [inotify_init(2)](https://man7.org/linux/man-pages/man2/inotify_init.2.html). pub fn init(flags: InitFlags) -> Result<Inotify> { - let res = Errno::result(unsafe { - libc::inotify_init1(flags.bits()) - }); + let res = Errno::result(unsafe { libc::inotify_init1(flags.bits()) }); res.map(|fd| Inotify { fd }) } @@ -156,15 +151,13 @@ impl Inotify { /// Returns a watch descriptor. This is not a File Descriptor! /// /// For more information see, [inotify_add_watch(2)](https://man7.org/linux/man-pages/man2/inotify_add_watch.2.html). - pub fn add_watch<P: ?Sized + NixPath>(self, - path: &P, - mask: AddWatchFlags) - -> Result<WatchDescriptor> - { - let res = path.with_nix_path(|cstr| { - unsafe { - libc::inotify_add_watch(self.fd, cstr.as_ptr(), mask.bits()) - } + pub fn add_watch<P: ?Sized + NixPath>( + self, + path: &P, + mask: AddWatchFlags, + ) -> Result<WatchDescriptor> { + let res = path.with_nix_path(|cstr| unsafe { + libc::inotify_add_watch(self.fd, cstr.as_ptr(), mask.bits()) })?; Errno::result(res).map(|wd| WatchDescriptor { wd }) @@ -210,7 +203,7 @@ impl Inotify { ptr::copy_nonoverlapping( buffer.as_ptr().add(offset), event.as_mut_ptr() as *mut u8, - (BUFSIZ - offset).min(header_size) + (BUFSIZ - offset).min(header_size), ); event.assume_init() }; @@ -219,9 +212,7 @@ impl Inotify { 0 => None, _ => { let ptr = unsafe { - buffer - .as_ptr() - .add(offset + header_size) + buffer.as_ptr().add(offset + header_size) as *const c_char }; let cstr = unsafe { CStr::from_ptr(ptr) }; @@ -234,7 +225,7 @@ impl Inotify { wd: WatchDescriptor { wd: event.wd }, mask: AddWatchFlags::from_bits_truncate(event.mask), cookie: event.cookie, - name + name, }); offset += header_size + event.len as usize; diff --git a/src/sys/memfd.rs b/src/sys/memfd.rs index 9f08dbb2..ad9345e8 100644 --- a/src/sys/memfd.rs +++ b/src/sys/memfd.rs @@ -1,10 +1,10 @@ //! Interfaces for managing memory-backed files. -use std::os::unix::io::RawFd; use cfg_if::cfg_if; +use std::os::unix::io::RawFd; -use crate::Result; use crate::errno::Errno; +use crate::Result; use std::ffi::CStr; libc_bitflags!( diff --git a/src/sys/mman.rs b/src/sys/mman.rs index 700e231c..869f44c4 100644 --- a/src/sys/mman.rs +++ b/src/sys/mman.rs @@ -1,16 +1,16 @@ //! Memory management declarations. -use crate::Result; +use crate::errno::Errno; #[cfg(not(target_os = "android"))] use crate::NixPath; -use crate::errno::Errno; +use crate::Result; #[cfg(not(target_os = "android"))] #[cfg(feature = "fs")] use crate::{fcntl::OFlag, sys::stat::Mode}; -use libc::{self, c_int, c_void, size_t, off_t}; +use libc::{self, c_int, c_void, off_t, size_t}; use std::os::unix::io::RawFd; -libc_bitflags!{ +libc_bitflags! { /// Desired memory protection of a memory mapping. pub struct ProtFlags: c_int { /// Pages cannot be accessed. @@ -32,7 +32,7 @@ libc_bitflags!{ } } -libc_bitflags!{ +libc_bitflags! { /// Additional parameters for [`mmap`]. pub struct MapFlags: c_int { /// Compatibility flag. Ignored. @@ -188,7 +188,7 @@ libc_bitflags!{ } #[cfg(any(target_os = "linux", target_os = "netbsd"))] -libc_bitflags!{ +libc_bitflags! { /// Options for [`mremap`]. pub struct MRemapFlags: c_int { /// Permit the kernel to relocate the mapping to a new virtual address, if necessary. @@ -210,7 +210,7 @@ libc_bitflags!{ } } -libc_enum!{ +libc_enum! { /// Usage information for a range of memory to allow for performance optimizations by the kernel. /// /// Used by [`madvise`]. @@ -331,7 +331,7 @@ libc_enum!{ } } -libc_bitflags!{ +libc_bitflags! { /// Configuration flags for [`msync`]. pub struct MsFlags: c_int { /// Schedule an update but return immediately. @@ -352,7 +352,7 @@ libc_bitflags!{ } #[cfg(not(target_os = "haiku"))] -libc_bitflags!{ +libc_bitflags! { /// Flags for [`mlockall`]. pub struct MlockAllFlags: c_int { /// Lock pages that are currently mapped into the address space of the process. @@ -416,7 +416,14 @@ pub fn munlockall() -> Result<()> { /// 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(addr: *mut c_void, length: size_t, prot: ProtFlags, flags: MapFlags, fd: RawFd, offset: off_t) -> Result<*mut c_void> { +pub unsafe fn mmap( + addr: *mut c_void, + length: size_t, + prot: ProtFlags, + flags: MapFlags, + fd: RawFd, + offset: off_t, +) -> Result<*mut c_void> { let ret = libc::mmap(addr, length, prot.bits(), flags.bits(), fd, offset); if ret == libc::MAP_FAILED { @@ -439,10 +446,16 @@ pub unsafe fn mremap( old_size: size_t, new_size: size_t, flags: MRemapFlags, - new_address: Option<* mut c_void>, + new_address: Option<*mut c_void>, ) -> Result<*mut c_void> { #[cfg(target_os = "linux")] - let ret = libc::mremap(addr, old_size, new_size, flags.bits(), new_address.unwrap_or(std::ptr::null_mut())); + let ret = libc::mremap( + addr, + old_size, + new_size, + flags.bits(), + new_address.unwrap_or(std::ptr::null_mut()), + ); #[cfg(target_os = "netbsd")] let ret = libc::mremap( addr, @@ -450,7 +463,7 @@ pub unsafe fn mremap( new_address.unwrap_or(std::ptr::null_mut()), new_size, flags.bits(), - ); + ); if ret == libc::MAP_FAILED { Err(Errno::last()) @@ -479,7 +492,11 @@ pub unsafe fn munmap(addr: *mut c_void, len: size_t) -> Result<()> { /// [`MmapAdvise::MADV_FREE`]. /// /// [`madvise(2)`]: https://man7.org/linux/man-pages/man2/madvise.2.html -pub unsafe fn madvise(addr: *mut c_void, length: size_t, advise: MmapAdvise) -> Result<()> { +pub unsafe fn madvise( + addr: *mut c_void, + length: size_t, + advise: MmapAdvise, +) -> Result<()> { Errno::result(libc::madvise(addr, length, advise as i32)).map(drop) } @@ -508,7 +525,11 @@ pub unsafe fn madvise(addr: *mut c_void, length: size_t, advise: MmapAdvise) -> /// slice[0] = 0xFF; /// assert_eq!(slice[0], 0xFF); /// ``` -pub unsafe fn mprotect(addr: *mut c_void, length: size_t, prot: ProtFlags) -> Result<()> { +pub unsafe fn mprotect( + addr: *mut c_void, + length: size_t, + prot: ProtFlags, +) -> Result<()> { Errno::result(libc::mprotect(addr, length, prot.bits())).map(drop) } @@ -520,7 +541,11 @@ pub unsafe fn mprotect(addr: *mut c_void, length: size_t, prot: ProtFlags) -> Re /// page. /// /// [`msync(2)`]: https://man7.org/linux/man-pages/man2/msync.2.html -pub unsafe fn msync(addr: *mut c_void, length: size_t, flags: MsFlags) -> Result<()> { +pub unsafe fn msync( + addr: *mut c_void, + length: size_t, + flags: MsFlags, +) -> Result<()> { Errno::result(libc::msync(addr, length, flags.bits())).map(drop) } @@ -561,9 +586,8 @@ pub fn shm_open<P>( /// [`shm_unlink(3)`]: https://man7.org/linux/man-pages/man3/shm_unlink.3.html #[cfg(not(target_os = "android"))] pub fn shm_unlink<P: ?Sized + NixPath>(name: &P) -> Result<()> { - let ret = name.with_nix_path(|cstr| { - unsafe { libc::shm_unlink(cstr.as_ptr()) } - })?; + let ret = + name.with_nix_path(|cstr| unsafe { libc::shm_unlink(cstr.as_ptr()) })?; Errno::result(ret).map(drop) } diff --git a/src/sys/personality.rs b/src/sys/personality.rs index 9e285ae6..f295a05f 100644 --- a/src/sys/personality.rs +++ b/src/sys/personality.rs @@ -1,6 +1,6 @@ //! Process execution domains -use crate::Result; use crate::errno::Errno; +use crate::Result; use libc::{self, c_int, c_ulong}; @@ -62,9 +62,7 @@ libc_bitflags! { /// assert!(!pers.contains(Persona::WHOLE_SECONDS)); /// ``` pub fn get() -> Result<Persona> { - let res = unsafe { - libc::personality(0xFFFFFFFF) - }; + let res = unsafe { libc::personality(0xFFFFFFFF) }; Errno::result(res).map(Persona::from_bits_truncate) } @@ -89,9 +87,7 @@ pub fn get() -> Result<Persona> { /// personality::set(pers | Persona::ADDR_NO_RANDOMIZE).unwrap(); /// ``` pub fn set(persona: Persona) -> Result<Persona> { - let res = unsafe { - libc::personality(persona.bits() as c_ulong) - }; + let res = unsafe { libc::personality(persona.bits() as c_ulong) }; Errno::result(res).map(Persona::from_bits_truncate) } diff --git a/src/sys/ptrace/bsd.rs b/src/sys/ptrace/bsd.rs index c4cc7403..ba267c65 100644 --- a/src/sys/ptrace/bsd.rs +++ b/src/sys/ptrace/bsd.rs @@ -1,16 +1,16 @@ -use cfg_if::cfg_if; use crate::errno::Errno; -use libc::{self, c_int}; -use std::ptr; use crate::sys::signal::Signal; use crate::unistd::Pid; use crate::Result; +use cfg_if::cfg_if; +use libc::{self, c_int}; +use std::ptr; pub type RequestType = c_int; cfg_if! { - if #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", + if #[cfg(any(target_os = "dragonfly", + target_os = "freebsd", target_os = "macos", target_os = "openbsd"))] { #[doc(hidden)] @@ -71,7 +71,8 @@ unsafe fn ptrace_other( libc::pid_t::from(pid), addr, data, - )).map(|_| 0) + )) + .map(|_| 0) } /// Sets the process as traceable, as with `ptrace(PT_TRACEME, ...)` @@ -79,14 +80,19 @@ unsafe fn ptrace_other( /// Indicates that this process is to be traced by its parent. /// This is the only ptrace request to be issued by the tracee. pub fn traceme() -> Result<()> { - unsafe { ptrace_other(Request::PT_TRACE_ME, Pid::from_raw(0), ptr::null_mut(), 0).map(drop) } + unsafe { + ptrace_other(Request::PT_TRACE_ME, Pid::from_raw(0), ptr::null_mut(), 0) + .map(drop) + } } /// Attach to a running process, as with `ptrace(PT_ATTACH, ...)` /// /// Attaches to the process specified by `pid`, making it a tracee of the calling process. pub fn attach(pid: Pid) -> Result<()> { - unsafe { ptrace_other(Request::PT_ATTACH, pid, ptr::null_mut(), 0).map(drop) } + unsafe { + ptrace_other(Request::PT_ATTACH, pid, ptr::null_mut(), 0).map(drop) + } } /// Detaches the current running process, as with `ptrace(PT_DETACH, ...)` @@ -114,13 +120,14 @@ pub fn cont<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { }; unsafe { // Ignore the useless return value - ptrace_other(Request::PT_CONTINUE, pid, 1 as AddressType, data).map(drop) + ptrace_other(Request::PT_CONTINUE, pid, 1 as AddressType, data) + .map(drop) } } /// Issues a kill request as with `ptrace(PT_KILL, ...)` /// -/// This request is equivalent to `ptrace(PT_CONTINUE, ..., SIGKILL);` +/// This request is equivalent to `ptrace(PT_CONTINUE, ..., SIGKILL);` pub fn kill(pid: Pid) -> Result<()> { unsafe { ptrace_other(Request::PT_KILL, pid, 0 as AddressType, 0).map(drop) @@ -149,21 +156,22 @@ pub fn kill(pid: Pid) -> Result<()> { /// _ => {}, /// } /// ``` -#[cfg( - any( - any(target_os = "dragonfly", target_os = "freebsd", target_os = "macos"), - all(target_os = "openbsd", target_arch = "x86_64"), - all(target_os = "netbsd", - any(target_arch = "x86_64", target_arch = "powerpc") - ) +#[cfg(any( + any(target_os = "dragonfly", target_os = "freebsd", target_os = "macos"), + all(target_os = "openbsd", target_arch = "x86_64"), + all( + target_os = "netbsd", + any(target_arch = "x86_64", target_arch = "powerpc") ) -)] +))] pub fn step<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { let data = match sig.into() { Some(s) => s as c_int, None => 0, }; - unsafe { ptrace_other(Request::PT_STEP, pid, ptr::null_mut(), data).map(drop) } + unsafe { + ptrace_other(Request::PT_STEP, pid, ptr::null_mut(), data).map(drop) + } } /// Reads a word from a processes memory at the given address diff --git a/src/sys/ptrace/linux.rs b/src/sys/ptrace/linux.rs index 1d9b241c..9687e05d 100644 --- a/src/sys/ptrace/linux.rs +++ b/src/sys/ptrace/linux.rs @@ -1,20 +1,24 @@ //! For detailed description of the ptrace requests, consult `man ptrace`. -use cfg_if::cfg_if; -use std::{mem, ptr}; -use crate::Result; use crate::errno::Errno; -use libc::{self, c_void, c_long, siginfo_t}; -use crate::unistd::Pid; use crate::sys::signal::Signal; +use crate::unistd::Pid; +use crate::Result; +use cfg_if::cfg_if; +use libc::{self, c_long, c_void, siginfo_t}; +use std::{mem, ptr}; pub type AddressType = *mut ::libc::c_void; #[cfg(all( target_os = "linux", - any(all(target_arch = "x86_64", - any(target_env = "gnu", target_env = "musl")), - all(target_arch = "x86", target_env = "gnu")) + any( + all( + target_arch = "x86_64", + any(target_env = "gnu", target_env = "musl") + ), + all(target_arch = "x86", target_env = "gnu") + ) ))] use libc::user_regs_struct; @@ -30,7 +34,7 @@ cfg_if! { } } -libc_enum!{ +libc_enum! { #[cfg_attr(not(any(target_env = "musl", target_env = "uclibc", target_os = "android")), repr(u32))] #[cfg_attr(any(target_env = "musl", target_env = "uclibc", target_os = "android"), repr(i32))] /// Ptrace Request enum defining the action to be taken. @@ -120,7 +124,7 @@ libc_enum!{ } } -libc_enum!{ +libc_enum! { #[repr(i32)] /// Using the ptrace options the tracer can configure the tracee to stop /// at certain events. This enum is used to define those events as defined @@ -178,7 +182,12 @@ libc_bitflags! { } } -fn ptrace_peek(request: Request, pid: Pid, addr: AddressType, data: *mut c_void) -> Result<c_long> { +fn ptrace_peek( + request: Request, + pid: Pid, + addr: AddressType, + data: *mut c_void, +) -> Result<c_long> { let ret = unsafe { Errno::clear(); libc::ptrace(request as RequestType, libc::pid_t::from(pid), addr, data) @@ -192,9 +201,13 @@ fn ptrace_peek(request: Request, pid: Pid, addr: AddressType, data: *mut c_void) /// Get user registers, as with `ptrace(PTRACE_GETREGS, ...)` #[cfg(all( target_os = "linux", - any(all(target_arch = "x86_64", - any(target_env = "gnu", target_env = "musl")), - all(target_arch = "x86", target_env = "gnu")) + any( + all( + target_arch = "x86_64", + any(target_env = "gnu", target_env = "musl") + ), + all(target_arch = "x86", target_env = "gnu") + ) ))] pub fn getregs(pid: Pid) -> Result<user_regs_struct> { ptrace_get_data::<user_regs_struct>(Request::PTRACE_GETREGS, pid) @@ -203,16 +216,22 @@ pub fn getregs(pid: Pid) -> Result<user_regs_struct> { /// Set user registers, as with `ptrace(PTRACE_SETREGS, ...)` #[cfg(all( target_os = "linux", - any(all(target_arch = "x86_64", - any(target_env = "gnu", target_env = "musl")), - all(target_arch = "x86", target_env = "gnu")) + any( + all( + target_arch = "x86_64", + any(target_env = "gnu", target_env = "musl") + ), + all(target_arch = "x86", target_env = "gnu") + ) ))] pub fn setregs(pid: Pid, regs: user_regs_struct) -> Result<()> { let res = unsafe { - libc::ptrace(Request::PTRACE_SETREGS as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::<c_void>(), - ®s as *const _ as *const c_void) + libc::ptrace( + Request::PTRACE_SETREGS as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::<c_void>(), + ®s as *const _ as *const c_void, + ) }; Errno::result(res).map(drop) } @@ -224,26 +243,41 @@ pub fn setregs(pid: Pid, regs: user_regs_struct) -> Result<()> { fn ptrace_get_data<T>(request: Request, pid: Pid) -> Result<T> { let mut data = mem::MaybeUninit::uninit(); let res = unsafe { - libc::ptrace(request as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::<T>(), - data.as_mut_ptr() as *const _ as *const c_void) + libc::ptrace( + request as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::<T>(), + data.as_mut_ptr() as *const _ as *const c_void, + ) }; Errno::result(res)?; - Ok(unsafe{ data.assume_init() }) + Ok(unsafe { data.assume_init() }) } -unsafe fn ptrace_other(request: Request, pid: Pid, addr: AddressType, data: *mut c_void) -> Result<c_long> { - Errno::result(libc::ptrace(request as RequestType, libc::pid_t::from(pid), addr, data)).map(|_| 0) +unsafe fn ptrace_other( + request: Request, + pid: Pid, + addr: AddressType, + data: *mut c_void, +) -> Result<c_long> { + Errno::result(libc::ptrace( + request as RequestType, + libc::pid_t::from(pid), + addr, + data, + )) + .map(|_| 0) } /// Set options, as with `ptrace(PTRACE_SETOPTIONS,...)`. pub fn setoptions(pid: Pid, options: Options) -> Result<()> { let res = unsafe { - libc::ptrace(Request::PTRACE_SETOPTIONS as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::<c_void>(), - options.bits() as *mut c_void) + libc::ptrace( + Request::PTRACE_SETOPTIONS as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::<c_void>(), + options.bits() as *mut c_void, + ) }; Errno::result(res).map(drop) } @@ -260,12 +294,14 @@ pub fn getsiginfo(pid: Pid) -> Result<siginfo_t> { /// Set siginfo as with `ptrace(PTRACE_SETSIGINFO,...)` pub fn setsiginfo(pid: Pid, sig: &siginfo_t) -> Result<()> { - let ret = unsafe{ + let ret = unsafe { Errno::clear(); - libc::ptrace(Request::PTRACE_SETSIGINFO as RequestType, - libc::pid_t::from(pid), - ptr::null_mut::<c_void>(), - sig as *const _ as *const c_void) + libc::ptrace( + Request::PTRACE_SETSIGINFO as RequestType, + libc::pid_t::from(pid), + ptr::null_mut::<c_void>(), + sig as *const _ as *const c_void, + ) }; match Errno::result(ret) { Ok(_) => Ok(()), @@ -284,7 +320,8 @@ pub fn traceme() -> Result<()> { Pid::from_raw(0), ptr::null_mut(), ptr::null_mut(), - ).map(drop) // ignore the useless return value + ) + .map(drop) // ignore the useless return value } } @@ -298,12 +335,8 @@ pub fn syscall<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { None => ptr::null_mut(), }; unsafe { - ptrace_other( - Request::PTRACE_SYSCALL, - pid, - ptr::null_mut(), - data, - ).map(drop) // ignore the useless return value + ptrace_other(Request::PTRACE_SYSCALL, pid, ptr::null_mut(), data) + .map(drop) // ignore the useless return value } } @@ -312,14 +345,19 @@ pub fn syscall<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { /// In contrast to the `syscall` function, the syscall stopped at will not be executed. /// Thus the the tracee will only be stopped once per syscall, /// optionally delivering a signal specified by `sig`. -#[cfg(all(target_os = "linux", target_env = "gnu", any(target_arch = "x86", target_arch = "x86_64")))] +#[cfg(all( + target_os = "linux", + target_env = "gnu", + any(target_arch = "x86", target_arch = "x86_64") +))] pub fn sysemu<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { let data = match sig.into() { Some(s) => s as i32 as *mut c_void, None => ptr::null_mut(), }; unsafe { - ptrace_other(Request::PTRACE_SYSEMU, pid, ptr::null_mut(), data).map(drop) + ptrace_other(Request::PTRACE_SYSEMU, pid, ptr::null_mut(), data) + .map(drop) // ignore the useless return value } } @@ -334,7 +372,8 @@ pub fn attach(pid: Pid) -> Result<()> { pid, ptr::null_mut(), ptr::null_mut(), - ).map(drop) // ignore the useless return value + ) + .map(drop) // ignore the useless return value } } @@ -350,7 +389,8 @@ pub fn seize(pid: Pid, options: Options) -> Result<()> { pid, ptr::null_mut(), options.bits() as *mut c_void, - ).map(drop) // ignore the useless return value + ) + .map(drop) // ignore the useless return value } } @@ -364,12 +404,8 @@ pub fn detach<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { None => ptr::null_mut(), }; unsafe { - ptrace_other( - Request::PTRACE_DETACH, - pid, - ptr::null_mut(), - data - ).map(drop) + ptrace_other(Request::PTRACE_DETACH, pid, ptr::null_mut(), data) + .map(drop) } } @@ -383,7 +419,8 @@ pub fn cont<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { None => ptr::null_mut(), }; unsafe { - ptrace_other(Request::PTRACE_CONT, pid, ptr::null_mut(), data).map(drop) // ignore the useless return value + ptrace_other(Request::PTRACE_CONT, pid, ptr::null_mut(), data).map(drop) + // ignore the useless return value } } @@ -394,7 +431,13 @@ pub fn cont<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { #[cfg_attr(docsrs, doc(cfg(all())))] pub fn interrupt(pid: Pid) -> Result<()> { unsafe { - ptrace_other(Request::PTRACE_INTERRUPT, pid, ptr::null_mut(), ptr::null_mut()).map(drop) + ptrace_other( + Request::PTRACE_INTERRUPT, + pid, + ptr::null_mut(), + ptr::null_mut(), + ) + .map(drop) } } @@ -403,7 +446,13 @@ pub fn interrupt(pid: Pid) -> Result<()> { /// This request is equivalent to `ptrace(PTRACE_CONT, ..., SIGKILL);` pub fn kill(pid: Pid) -> Result<()> { unsafe { - ptrace_other(Request::PTRACE_KILL, pid, ptr::null_mut(), ptr::null_mut()).map(drop) + ptrace_other( + Request::PTRACE_KILL, + pid, + ptr::null_mut(), + ptr::null_mut(), + ) + .map(drop) } } @@ -436,7 +485,8 @@ pub fn step<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { None => ptr::null_mut(), }; unsafe { - ptrace_other(Request::PTRACE_SINGLESTEP, pid, ptr::null_mut(), data).map(drop) + ptrace_other(Request::PTRACE_SINGLESTEP, pid, ptr::null_mut(), data) + .map(drop) } } @@ -446,7 +496,11 @@ pub fn step<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { /// Advances the execution by a single step or until the next syscall. /// In case the tracee is stopped at a syscall, the syscall will not be executed. /// Optionally, the signal specified by `sig` is delivered to the tracee upon continuation. -#[cfg(all(target_os = "linux", target_env = "gnu", any(target_arch = "x86", target_arch = "x86_64")))] +#[cfg(all( + target_os = "linux", + target_env = "gnu", + any(target_arch = "x86", target_arch = "x86_64") +))] pub fn sysemu_step<T: Into<Option<Signal>>>(pid: Pid, sig: T) -> Result<()> { let data = match sig.into() { Some(s) => s as i32 as *mut c_void, @@ -477,8 +531,8 @@ pub fn read(pid: Pid, addr: AddressType) -> Result<c_long> { pub unsafe fn write( pid: Pid, addr: AddressType, - data: *mut c_void) -> Result<()> -{ + data: *mut c_void, +) -> Result<()> { ptrace_other(Request::PTRACE_POKEDATA, pid, addr, data).map(drop) } @@ -498,7 +552,7 @@ pub fn read_user(pid: Pid, offset: AddressType) -> Result<c_long> { pub unsafe fn write_user( pid: Pid, offset: AddressType, - data: *mut c_void) -> Result<()> -{ + data: *mut c_void, +) -> Result<()> { ptrace_other(Request::PTRACE_POKEUSER, pid, offset, data).map(drop) } diff --git a/src/sys/ptrace/mod.rs b/src/sys/ptrace/mod.rs index 782c3040..2b121c0b 100644 --- a/src/sys/ptrace/mod.rs +++ b/src/sys/ptrace/mod.rs @@ -1,4 +1,4 @@ -///! Provides helpers for making ptrace system calls +///! Provides helpers for making ptrace system calls #[cfg(any(target_os = "android", target_os = "linux"))] mod linux; @@ -6,17 +6,20 @@ mod linux; #[cfg(any(target_os = "android", target_os = "linux"))] pub use self::linux::*; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] mod bsd; -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd" - ))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] pub use self::bsd::*; diff --git a/src/sys/quota.rs b/src/sys/quota.rs index f3b4c02d..b3c44ca7 100644 --- a/src/sys/quota.rs +++ b/src/sys/quota.rs @@ -12,11 +12,11 @@ //! dqblk.set_blocks_soft_limit(8000); //! quotactl_set(QuotaType::USRQUOTA, "/dev/sda1", 50, &dqblk, QuotaValidFlags::QIF_BLIMITS).unwrap(); //! ``` +use crate::errno::Errno; +use crate::{NixPath, Result}; +use libc::{self, c_char, c_int}; use std::default::Default; use std::{mem, ptr}; -use libc::{self, c_int, c_char}; -use crate::{Result, NixPath}; -use crate::errno::Errno; struct QuotaCmd(QuotaSubCmd, QuotaType); @@ -28,7 +28,7 @@ impl QuotaCmd { } // linux quota version >= 2 -libc_enum!{ +libc_enum! { #[repr(i32)] enum QuotaSubCmd { Q_SYNC, @@ -39,7 +39,7 @@ libc_enum!{ } } -libc_enum!{ +libc_enum! { /// The scope of the quota. #[repr(i32)] #[non_exhaustive] @@ -51,7 +51,7 @@ libc_enum!{ } } -libc_enum!{ +libc_enum! { /// The type of quota format to use. #[repr(i32)] #[non_exhaustive] @@ -120,7 +120,8 @@ impl Default for Dqblk { impl Dqblk { /// The absolute limit on disk quota blocks allocated. pub fn blocks_hard_limit(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_BLIMITS) { Some(self.0.dqb_bhardlimit) } else { @@ -135,7 +136,8 @@ impl Dqblk { /// Preferred limit on disk quota blocks pub fn blocks_soft_limit(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_BLIMITS) { Some(self.0.dqb_bsoftlimit) } else { @@ -150,7 +152,8 @@ impl Dqblk { /// Current occupied space (bytes). pub fn occupied_space(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_SPACE) { Some(self.0.dqb_curspace) } else { @@ -160,7 +163,8 @@ impl Dqblk { /// Maximum number of allocated inodes. pub fn inodes_hard_limit(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_ILIMITS) { Some(self.0.dqb_ihardlimit) } else { @@ -175,7 +179,8 @@ impl Dqblk { /// Preferred inode limit pub fn inodes_soft_limit(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_ILIMITS) { Some(self.0.dqb_isoftlimit) } else { @@ -190,7 +195,8 @@ impl Dqblk { /// Current number of allocated inodes. pub fn allocated_inodes(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_INODES) { Some(self.0.dqb_curinodes) } else { @@ -200,7 +206,8 @@ impl Dqblk { /// Time limit for excessive disk use. pub fn block_time_limit(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_BTIME) { Some(self.0.dqb_btime) } else { @@ -215,7 +222,8 @@ impl Dqblk { /// Time limit for excessive files. pub fn inode_time_limit(&self) -> Option<u64> { - let valid_fields = QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); + let valid_fields = + QuotaValidFlags::from_bits_truncate(self.0.dqb_valid); if valid_fields.contains(QuotaValidFlags::QIF_ITIME) { Some(self.0.dqb_itime) } else { @@ -229,11 +237,18 @@ impl Dqblk { } } -fn quotactl<P: ?Sized + NixPath>(cmd: QuotaCmd, special: Option<&P>, id: c_int, addr: *mut c_char) -> Result<()> { +fn quotactl<P: ?Sized + NixPath>( + cmd: QuotaCmd, + special: Option<&P>, + id: c_int, + addr: *mut c_char, +) -> Result<()> { unsafe { Errno::clear(); let res = match special { - Some(dev) => dev.with_nix_path(|path| libc::quotactl(cmd.as_int(), path.as_ptr(), id, addr)), + Some(dev) => dev.with_nix_path(|path| { + libc::quotactl(cmd.as_int(), path.as_ptr(), id, addr) + }), None => Ok(libc::quotactl(cmd.as_int(), ptr::null(), id, addr)), }?; @@ -242,36 +257,82 @@ fn quotactl<P: ?Sized + NixPath>(cmd: QuotaCmd, special: Option<&P>, id: c_int, } /// Turn on disk quotas for a block device. -pub fn quotactl_on<P: ?Sized + NixPath>(which: QuotaType, special: &P, format: QuotaFmt, quota_file: &P) -> Result<()> { +pub fn quotactl_on<P: ?Sized + NixPath>( + which: QuotaType, + special: &P, + format: QuotaFmt, + quota_file: &P, +) -> 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; - quotactl(QuotaCmd(QuotaSubCmd::Q_QUOTAON, which), Some(special), format as c_int, p) + quotactl( + QuotaCmd(QuotaSubCmd::Q_QUOTAON, which), + Some(special), + format as c_int, + p, + ) })? } /// Disable disk quotas for a block device. -pub fn quotactl_off<P: ?Sized + NixPath>(which: QuotaType, special: &P) -> Result<()> { - quotactl(QuotaCmd(QuotaSubCmd::Q_QUOTAOFF, which), Some(special), 0, ptr::null_mut()) +pub fn quotactl_off<P: ?Sized + NixPath>( + which: QuotaType, + special: &P, +) -> Result<()> { + quotactl( + QuotaCmd(QuotaSubCmd::Q_QUOTAOFF, which), + Some(special), + 0, + ptr::null_mut(), + ) } /// Update the on-disk copy of quota usages for a filesystem. /// /// If `special` is `None`, then all file systems with active quotas are sync'd. -pub fn quotactl_sync<P: ?Sized + NixPath>(which: QuotaType, special: Option<&P>) -> Result<()> { - quotactl(QuotaCmd(QuotaSubCmd::Q_SYNC, which), special, 0, ptr::null_mut()) +pub fn quotactl_sync<P: ?Sized + NixPath>( + which: QuotaType, + special: Option<&P>, +) -> Result<()> { + quotactl( + QuotaCmd(QuotaSubCmd::Q_SYNC, which), + special, + 0, + ptr::null_mut(), + ) } /// Get disk quota limits and current usage for the given user/group id. -pub fn quotactl_get<P: ?Sized + NixPath>(which: QuotaType, special: &P, id: c_int) -> Result<Dqblk> { +pub fn quotactl_get<P: ?Sized + NixPath>( + which: QuotaType, + special: &P, + id: c_int, +) -> Result<Dqblk> { let mut dqblk = mem::MaybeUninit::uninit(); - quotactl(QuotaCmd(QuotaSubCmd::Q_GETQUOTA, which), Some(special), id, dqblk.as_mut_ptr() as *mut c_char)?; - Ok(unsafe{ Dqblk(dqblk.assume_init())}) + quotactl( + QuotaCmd(QuotaSubCmd::Q_GETQUOTA, which), + Some(special), + id, + dqblk.as_mut_ptr() as *mut c_char, + )?; + Ok(unsafe { Dqblk(dqblk.assume_init()) }) } /// Configure quota values for the specified fields for a given user/group id. -pub fn quotactl_set<P: ?Sized + NixPath>(which: QuotaType, special: &P, id: c_int, dqblk: &Dqblk, fields: QuotaValidFlags) -> Result<()> { +pub fn quotactl_set<P: ?Sized + NixPath>( + which: QuotaType, + special: &P, + id: c_int, + dqblk: &Dqblk, + fields: QuotaValidFlags, +) -> Result<()> { let mut dqblk_copy = *dqblk; dqblk_copy.0.dqb_valid = fields.bits(); - quotactl(QuotaCmd(QuotaSubCmd::Q_SETQUOTA, which), Some(special), id, &mut dqblk_copy as *mut _ as *mut c_char) + quotactl( + QuotaCmd(QuotaSubCmd::Q_SETQUOTA, which), + Some(special), + id, + &mut dqblk_copy as *mut _ as *mut c_char, + ) } diff --git a/src/sys/reboot.rs b/src/sys/reboot.rs index 2a8009e4..02d98162 100644 --- a/src/sys/reboot.rs +++ b/src/sys/reboot.rs @@ -1,7 +1,7 @@ //! Reboot/shutdown or enable/disable Ctrl-Alt-Delete. -use crate::Result; use crate::errno::Errno; +use crate::Result; use std::convert::Infallible; use std::mem::drop; @@ -30,9 +30,7 @@ libc_enum! { /// Reboots or shuts down the system. pub fn reboot(how: RebootMode) -> Result<Infallible> { - unsafe { - libc::reboot(how as libc::c_int) - }; + unsafe { libc::reboot(how as libc::c_int) }; Err(Errno::last()) } @@ -45,8 +43,6 @@ pub fn set_cad_enabled(enable: bool) -> Result<()> { } else { libc::RB_DISABLE_CAD }; - let res = unsafe { - libc::reboot(cmd) - }; + let res = unsafe { libc::reboot(cmd) }; Errno::result(res).map(drop) } diff --git a/src/sys/resource.rs b/src/sys/resource.rs index 788444d8..89277377 100644 --- a/src/sys/resource.rs +++ b/src/sys/resource.rs @@ -245,7 +245,11 @@ pub fn getrlimit(resource: Resource) -> Result<(rlim_t, rlim_t)> { /// [`Resource`]: enum.Resource.html /// /// Note: `setrlimit` provides a safe wrapper to libc's `setrlimit`. -pub fn setrlimit(resource: Resource, soft_limit: rlim_t, hard_limit: rlim_t) -> Result<()> { +pub fn setrlimit( + resource: Resource, + soft_limit: rlim_t, + hard_limit: rlim_t, +) -> Result<()> { let new_rlim = rlimit { rlim_cur: soft_limit, rlim_max: hard_limit, @@ -427,7 +431,8 @@ mod test { // thing away. Replace the assert with test::black_box once stabilized. assert_eq!(numbers[100..200].iter().sum::<i32>(), 30_100); - let usage = getrusage(UsageWho::RUSAGE_SELF).expect("Failed to call getrusage for SELF"); + let usage = getrusage(UsageWho::RUSAGE_SELF) + .expect("Failed to call getrusage for SELF"); let rusage = usage.as_ref(); let user = usage.user_time(); diff --git a/src/sys/select.rs b/src/sys/select.rs index ab4f68f5..7a94cff8 100644 --- a/src/sys/select.rs +++ b/src/sys/select.rs @@ -1,14 +1,14 @@ //! Portably monitor a group of file descriptors for readiness. +use crate::errno::Errno; +use crate::sys::time::{TimeSpec, TimeVal}; +use crate::Result; +use libc::{self, c_int}; use std::convert::TryFrom; use std::iter::FusedIterator; use std::mem; use std::ops::Range; use std::os::unix::io::RawFd; use std::ptr::{null, null_mut}; -use libc::{self, c_int}; -use crate::Result; -use crate::errno::Errno; -use crate::sys::time::{TimeSpec, TimeVal}; pub use libc::FD_SETSIZE; @@ -173,11 +173,13 @@ impl<'a> FusedIterator for Fds<'a> {} /// [select(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/select.html) /// /// [`FdSet::highest`]: struct.FdSet.html#method.highest -pub fn select<'a, N, R, W, E, T>(nfds: N, +pub fn select<'a, N, R, W, E, T>( + nfds: N, readfds: R, writefds: W, errorfds: E, - timeout: T) -> Result<c_int> + timeout: T, +) -> Result<c_int> where N: Into<Option<c_int>>, R: Into<Option<&'a mut FdSet>>, @@ -191,23 +193,31 @@ where let timeout = timeout.into(); let nfds = nfds.into().unwrap_or_else(|| { - readfds.iter_mut() + readfds + .iter_mut() .chain(writefds.iter_mut()) .chain(errorfds.iter_mut()) .map(|set| set.highest().unwrap_or(-1)) .max() - .unwrap_or(-1) + 1 + .unwrap_or(-1) + + 1 }); - let readfds = readfds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let writefds = writefds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let errorfds = errorfds.map(|set| set as *mut _ as *mut libc::fd_set).unwrap_or(null_mut()); - let timeout = timeout.map(|tv| tv as *mut _ as *mut libc::timeval) + let readfds = readfds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let writefds = writefds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let errorfds = errorfds + .map(|set| set as *mut _ as *mut libc::fd_set) + .unwrap_or(null_mut()); + let timeout = timeout + .map(|tv| tv as *mut _ as *mut libc::timeval) .unwrap_or(null_mut()); - let res = unsafe { - libc::select(nfds, readfds, writefds, errorfds, timeout) - }; + let res = + unsafe { libc::select(nfds, readfds, writefds, errorfds, timeout) }; Errno::result(res) } @@ -292,9 +302,9 @@ where #[cfg(test)] mod tests { use super::*; - use std::os::unix::io::RawFd; use crate::sys::time::{TimeVal, TimeValLike}; - use crate::unistd::{write, pipe}; + use crate::unistd::{pipe, write}; + use std::os::unix::io::RawFd; #[test] fn fdset_insert() { @@ -383,11 +393,10 @@ mod tests { fd_set.insert(r2); let mut timeout = TimeVal::seconds(10); - assert_eq!(1, select(None, - &mut fd_set, - None, - None, - &mut timeout).unwrap()); + assert_eq!( + 1, + select(None, &mut fd_set, None, None, &mut timeout).unwrap() + ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); } @@ -403,11 +412,17 @@ mod tests { fd_set.insert(r2); let mut timeout = TimeVal::seconds(10); - assert_eq!(1, select(Some(fd_set.highest().unwrap() + 1), + assert_eq!( + 1, + select( + Some(fd_set.highest().unwrap() + 1), &mut fd_set, None, None, - &mut timeout).unwrap()); + &mut timeout + ) + .unwrap() + ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); } @@ -423,11 +438,17 @@ mod tests { fd_set.insert(r2); let mut timeout = TimeVal::seconds(10); - assert_eq!(1, select(::std::cmp::max(r1, r2) + 1, + assert_eq!( + 1, + select( + ::std::cmp::max(r1, r2) + 1, &mut fd_set, None, None, - &mut timeout).unwrap()); + &mut timeout + ) + .unwrap() + ); assert!(fd_set.contains(r1)); assert!(!fd_set.contains(r2)); } diff --git a/src/sys/sendfile.rs b/src/sys/sendfile.rs index 2ebcdf48..fb293a4e 100644 --- a/src/sys/sendfile.rs +++ b/src/sys/sendfile.rs @@ -6,8 +6,8 @@ use std::ptr; use libc::{self, off_t}; -use crate::Result; use crate::errno::Errno; +use crate::Result; /// Copy up to `count` bytes to `out_fd` from `in_fd` starting at `offset`. /// diff --git a/src/sys/signalfd.rs b/src/sys/signalfd.rs index 166bb9d2..095e5908 100644 --- a/src/sys/signalfd.rs +++ b/src/sys/signalfd.rs @@ -15,17 +15,16 @@ //! //! Please note that signal discarding is not specific to `signalfd`, but also happens with regular //! signal handlers. -use crate::unistd; -use crate::Result; use crate::errno::Errno; pub use crate::sys::signal::{self, SigSet}; +use crate::unistd; +use crate::Result; pub use libc::signalfd_siginfo as siginfo; -use std::os::unix::io::{RawFd, AsRawFd}; use std::mem; +use std::os::unix::io::{AsRawFd, RawFd}; - -libc_bitflags!{ +libc_bitflags! { pub struct SfdFlags: libc::c_int { SFD_NONBLOCK; SFD_CLOEXEC; @@ -49,7 +48,11 @@ pub const SIGNALFD_SIGINFO_SIZE: usize = mem::size_of::<siginfo>(); /// See [the signalfd man page for more information](https://man7.org/linux/man-pages/man2/signalfd.2.html) pub fn signalfd(fd: RawFd, mask: &SigSet, flags: SfdFlags) -> Result<RawFd> { unsafe { - Errno::result(libc::signalfd(fd as libc::c_int, mask.as_ref(), flags.bits())) + Errno::result(libc::signalfd( + fd as libc::c_int, + mask.as_ref(), + flags.bits(), + )) } } @@ -103,12 +106,13 @@ impl SignalFd { let size = mem::size_of_val(&buffer); let res = Errno::result(unsafe { libc::read(self.0, buffer.as_mut_ptr() as *mut libc::c_void, size) - }).map(|r| r as usize); + }) + .map(|r| r as usize); match res { Ok(x) if x == size => Ok(Some(unsafe { buffer.assume_init() })), Ok(_) => unreachable!("partial read on signalfd"), Err(Errno::EAGAIN) => Ok(None), - Err(error) => Err(error) + Err(error) => Err(error), } } } @@ -139,7 +143,6 @@ impl Iterator for SignalFd { } } - #[cfg(test)] mod tests { use super::*; @@ -163,7 +166,8 @@ mod tests { #[test] fn read_empty_signalfd() { let mask = SigSet::empty(); - let mut fd = SignalFd::with_flags(&mask, SfdFlags::SFD_NONBLOCK).unwrap(); + 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/addr.rs b/src/sys/socket/addr.rs index 07d68e1f..4a16eea9 100644 --- a/src/sys/socket/addr.rs +++ b/src/sys/socket/addr.rs @@ -1,47 +1,54 @@ +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd", + target_os = "haiku", + target_os = "fuchsia" +))] +#[cfg(feature = "net")] +pub use self::datalink::LinkAddr; +#[cfg(any(target_os = "android", target_os = "linux"))] +pub use self::vsock::VsockAddr; use super::sa_family_t; -use cfg_if::cfg_if; -use crate::{Result, NixPath}; use crate::errno::Errno; +#[cfg(any(target_os = "android", target_os = "linux"))] +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") +))] +use crate::sys::socket::addr::sys_control::SysControlAddr; +use crate::{NixPath, Result}; +use cfg_if::cfg_if; use memoffset::offset_of; -use std::{fmt, mem, net, ptr, slice}; use std::convert::TryInto; use std::ffi::OsStr; use std::hash::{Hash, Hasher}; -use std::path::Path; use std::os::unix::ffi::OsStrExt; -#[cfg(any(target_os = "android", target_os = "linux"))] -use crate::sys::socket::addr::netlink::NetlinkAddr; -#[cfg(any(target_os = "android", target_os = "linux"))] -use crate::sys::socket::addr::alg::AlgAddr; #[cfg(any(target_os = "ios", target_os = "macos"))] use std::os::unix::io::RawFd; -#[cfg(all(feature = "ioctl", any(target_os = "ios", target_os = "macos")))] -use crate::sys::socket::addr::sys_control::SysControlAddr; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd", - target_os = "haiku", - target_os = "fuchsia"))] -#[cfg(feature = "net")] -pub use self::datalink::LinkAddr; -#[cfg(any(target_os = "android", target_os = "linux"))] -pub use self::vsock::VsockAddr; +use std::path::Path; +use std::{fmt, mem, net, ptr, slice}; /// Convert a std::net::Ipv4Addr into the libc form. #[cfg(feature = "net")] pub(crate) fn ipv4addr_to_libc(addr: net::Ipv4Addr) -> libc::in_addr { let octets = addr.octets(); libc::in_addr { - s_addr: u32::to_be(((octets[0] as u32) << 24) | - ((octets[1] as u32) << 16) | - ((octets[2] as u32) << 8) | - (octets[3] as u32)) + s_addr: u32::to_be( + ((octets[0] as u32) << 24) + | ((octets[1] as u32) << 16) + | ((octets[2] as u32) << 8) + | (octets[3] as u32), + ), } } @@ -49,7 +56,7 @@ pub(crate) 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(), } } @@ -75,11 +82,13 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] Netlink = libc::AF_NETLINK, /// 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( + target_os = "android", + target_os = "linux", + target_os = "illumos", + target_os = "fuchsia", + target_os = "solaris" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Packet = libc::AF_PACKET, /// KEXT Controls and Notifications @@ -136,7 +145,7 @@ pub enum AddressFamily { #[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 + #[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, @@ -172,7 +181,7 @@ pub enum AddressFamily { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] Llc = libc::AF_LLC, - /// InfiniBand native addressing + /// InfiniBand native addressing #[cfg(all(target_os = "linux", not(target_env = "uclibc")))] #[cfg_attr(docsrs, doc(cfg(all())))] Ib = libc::AF_IB, @@ -189,10 +198,12 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] Tipc = libc::AF_TIPC, /// Bluetooth low-level socket protocol - #[cfg(not(any(target_os = "illumos", - target_os = "ios", - target_os = "macos", - target_os = "solaris")))] + #[cfg(not(any( + target_os = "illumos", + target_os = "ios", + target_os = "macos", + target_os = "solaris" + )))] #[cfg_attr(docsrs, doc(cfg(all())))] Bluetooth = libc::AF_BLUETOOTH, /// IUCV (inter-user communication vehicle) z/VM protocol for @@ -205,7 +216,11 @@ pub enum AddressFamily { #[cfg_attr(docsrs, doc(cfg(all())))] RxRpc = libc::AF_RXRPC, /// New "modular ISDN" driver interface protocol - #[cfg(not(any(target_os = "illumos", target_os = "solaris", target_os = "haiku")))] + #[cfg(not(any( + target_os = "illumos", + target_os = "solaris", + target_os = "haiku" + )))] #[cfg_attr(docsrs, doc(cfg(all())))] Isdn = libc::AF_ISDN, /// Nokia cellular modem IPC/RPC interface @@ -234,128 +249,156 @@ pub enum AddressFamily { #[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", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] ImpLink = libc::AF_IMPLINK, /// PUP protocols, e.g. BSP - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Pup = libc::AF_PUP, /// MIT CHAOS protocols - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + 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( + target_os = "ios", + target_os = "macos", + 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", - target_os = "netbsd", - target_os = "openbsd"))] + #[allow(missing_docs)] // Not documented anywhere that I can find + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Iso = libc::AF_ISO, /// Bell Labs virtual circuit switch ? - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Datakit = libc::AF_DATAKIT, /// CCITT protocols, X.25 etc - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Ccitt = libc::AF_CCITT, /// DEC Direct data link interface - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + 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(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[allow(missing_docs)] // Not documented anywhere that I can find + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Lat = libc::AF_LAT, /// NSC Hyperchannel - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Hylink = libc::AF_HYLINK, /// Link layer interface - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Link = libc::AF_LINK, /// connection-oriented IP, aka ST II - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Coip = libc::AF_COIP, /// Computer Network Technology - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg_attr(docsrs, doc(cfg(all())))] Cnt = libc::AF_CNT, /// Native ATM access - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + 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)) @@ -381,17 +424,19 @@ impl AddressFamily { libc::AF_SYSTEM => Some(AddressFamily::System), #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_PACKET => Some(AddressFamily::Packet), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "illumos", + target_os = "openbsd" + ))] libc::AF_LINK => Some(AddressFamily::Link), #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_VSOCK => Some(AddressFamily::Vsock), - _ => None + _ => None, } } } @@ -707,12 +752,13 @@ 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(target_os = "android", - target_os = "fuchsia", - target_os = "illumos", - target_os = "linux" + #[cfg(any( + target_os = "android", + target_os = "fuchsia", + target_os = "illumos", + target_os = "linux" ))] - sun_len: u8 + sun_len: u8, } // linux man page unix(7) says there are 3 kinds of unix socket: @@ -732,17 +778,21 @@ impl<'a> UnixAddrKind<'a> { /// Safety: sun & sun_len must be valid 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 = sun_len as usize - offset_of!(libc::sockaddr_un, sun_path); + let path_len = + sun_len as usize - offset_of!(libc::sockaddr_un, sun_path); if path_len == 0 { return Self::Unnamed; } #[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, path_len - 1); + let name = slice::from_raw_parts( + sun.sun_path.as_ptr().add(1) as *const u8, + path_len - 1, + ); return Self::Abstract(name); } - let pathname = slice::from_raw_parts(sun.sun_path.as_ptr() as *const u8, path_len); + let pathname = + slice::from_raw_parts(sun.sun_path.as_ptr() as *const u8, 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 @@ -751,7 +801,9 @@ impl<'a> UnixAddrKind<'a> { // getsockname() (the BSDs do not do that). So we need to filter // out any trailing NUL here, so sockaddrs can round-trip through // the kernel and still compare equal. - Self::Pathname(Path::new(OsStr::from_bytes(&pathname[0..pathname.len() - 1]))) + Self::Pathname(Path::new(OsStr::from_bytes( + &pathname[0..pathname.len() - 1], + ))) } else { Self::Pathname(Path::new(OsStr::from_bytes(pathname))) } @@ -761,38 +813,41 @@ impl<'a> UnixAddrKind<'a> { impl UnixAddr { /// Create a new sockaddr_un representing a filesystem path. pub fn new<P: ?Sized + NixPath>(path: &P) -> Result<UnixAddr> { - path.with_nix_path(|cstr| { - unsafe { - let mut ret = libc::sockaddr_un { - sun_family: AddressFamily::Unix as sa_family_t, - .. mem::zeroed() - }; - - let bytes = cstr.to_bytes(); + path.with_nix_path(|cstr| unsafe { + let mut ret = libc::sockaddr_un { + sun_family: AddressFamily::Unix as sa_family_t, + ..mem::zeroed() + }; - if bytes.len() >= ret.sun_path.len() { - return Err(Errno::ENAMETOOLONG); - } + let bytes = cstr.to_bytes(); - let sun_len = (bytes.len() + - offset_of!(libc::sockaddr_un, sun_path)).try_into() - .unwrap(); + if bytes.len() >= ret.sun_path.len() { + return Err(Errno::ENAMETOOLONG); + } - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] - { - ret.sun_len = sun_len; - } - ptr::copy_nonoverlapping(bytes.as_ptr(), - ret.sun_path.as_mut_ptr() as *mut u8, - bytes.len()); + let sun_len = (bytes.len() + + offset_of!(libc::sockaddr_un, sun_path)) + .try_into() + .unwrap(); - Ok(UnixAddr::from_raw_parts(ret, sun_len)) + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] + { + ret.sun_len = sun_len; } + ptr::copy_nonoverlapping( + bytes.as_ptr(), + ret.sun_path.as_mut_ptr() as *mut u8, + bytes.len(), + ); + + Ok(UnixAddr::from_raw_parts(ret, sun_len)) })? } @@ -808,22 +863,24 @@ impl UnixAddr { unsafe { let mut ret = libc::sockaddr_un { sun_family: AddressFamily::Unix as sa_family_t, - .. mem::zeroed() + ..mem::zeroed() }; if path.len() >= ret.sun_path.len() { return Err(Errno::ENAMETOOLONG); } - let sun_len = (path.len() + - 1 + - offset_of!(libc::sockaddr_un, sun_path)).try_into() - .unwrap(); + let sun_len = + (path.len() + 1 + offset_of!(libc::sockaddr_un, sun_path)) + .try_into() + .unwrap(); // Abstract addresses are represented by sun_path[0] == // 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, - path.len()); + ptr::copy_nonoverlapping( + path.as_ptr(), + ret.sun_path.as_mut_ptr().offset(1) as *mut u8, + path.len(), + ); Ok(UnixAddr::from_raw_parts(ret, sun_len)) } @@ -840,8 +897,11 @@ impl UnixAddr { /// - sun_len <= sockaddr_un.sun_path.len() - offset_of(sockaddr_un, sun_path) /// - if this is a unix addr with a pathname, sun.sun_path is a /// fs path, not necessarily nul-terminated. - pub(crate) unsafe fn from_raw_parts(sun: libc::sockaddr_un, sun_len: u8) -> UnixAddr { - cfg_if!{ + pub(crate) unsafe fn from_raw_parts( + sun: libc::sockaddr_un, + sun_len: u8, + ) -> UnixAddr { + cfg_if! { if #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "illumos", @@ -898,8 +958,8 @@ impl UnixAddr { &mut self.sun } - fn sun_len(&self)-> u8 { - cfg_if!{ + fn sun_len(&self) -> u8 { + cfg_if! { if #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "illumos", @@ -916,21 +976,26 @@ 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( + target_os = "android", + target_os = "fuchsia", + target_os = "illumos", + target_os = "linux" ))] fn len(&self) -> libc::socklen_t { self.sun_len.into() } - unsafe fn from_raw(addr: *const libc::sockaddr, len: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + len: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if let Some(l) = len { - if (l as usize) < offset_of!(libc::sockaddr_un, sun_path) || - l > u8::MAX as libc::socklen_t + if (l as usize) < offset_of!(libc::sockaddr_un, sun_path) + || l > u8::MAX as libc::socklen_t { return None; } @@ -940,7 +1005,7 @@ impl SockaddrLike for UnixAddr { } let mut su: libc::sockaddr_un = mem::zeroed(); let sup = &mut su as *mut libc::sockaddr_un as *mut u8; - cfg_if!{ + cfg_if! { if #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "illumos", @@ -957,7 +1022,10 @@ impl SockaddrLike for UnixAddr { Some(Self::from_raw_parts(su, su_len as u8)) } - fn size() -> libc::socklen_t where Self: Sized { + fn size() -> libc::socklen_t + where + Self: Sized, + { mem::size_of::<libc::sockaddr_un>() as libc::socklen_t } } @@ -1037,8 +1105,12 @@ pub trait SockaddrLike: private::SockaddrLikePriv { /// /// `addr` must be valid for the specific type of sockaddr. `len`, if /// present, must not exceed the length of valid data in `addr`. - unsafe fn from_raw(addr: *const libc::sockaddr, len: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized; + unsafe fn from_raw( + addr: *const libc::sockaddr, + len: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized; /// Return the address family of this socket /// @@ -1058,11 +1130,9 @@ pub trait SockaddrLike: private::SockaddrLikePriv { fn family(&self) -> Option<AddressFamily> { // Safe since all implementors have a sa_family field at the same // address, and they're all repr(C) - AddressFamily::from_i32( - unsafe { - (*(self as *const Self as *const libc::sockaddr)).sa_family as i32 - } - ) + AddressFamily::from_i32(unsafe { + (*(self as *const Self as *const libc::sockaddr)).sa_family as i32 + }) } cfg_if! { @@ -1101,7 +1171,10 @@ pub trait SockaddrLike: private::SockaddrLikePriv { } /// Return the available space in the structure - fn size() -> libc::socklen_t where Self: Sized { + fn size() -> libc::socklen_t + where + Self: Sized, + { mem::size_of::<Self>() as libc::socklen_t } } @@ -1121,8 +1194,12 @@ impl SockaddrLike for () { ptr::null() } - unsafe fn from_raw(_: *const libc::sockaddr, _: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + _: *const libc::sockaddr, + _: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { None } @@ -1156,20 +1233,22 @@ 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(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "haiku", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "haiku", + target_os = "openbsd" + ))] sin_len: Self::size() as u8, sin_family: AddressFamily::Inet as sa_family_t, sin_port: u16::to_be(port), sin_addr: libc::in_addr { - s_addr: u32::from_ne_bytes([a, b, c, d]) + s_addr: u32::from_ne_bytes([a, b, c, d]), }, - sin_zero: unsafe{mem::zeroed()} + sin_zero: unsafe { mem::zeroed() }, }) } @@ -1184,8 +1263,12 @@ impl SockaddrIn { impl private::SockaddrLikePriv for SockaddrIn {} #[cfg(feature = "net")] impl SockaddrLike for SockaddrIn { - unsafe fn from_raw(addr: *const libc::sockaddr, len: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + len: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if let Some(l) = len { if l != mem::size_of::<libc::sockaddr_in>() as libc::socklen_t { @@ -1211,28 +1294,37 @@ impl fmt::Display for SockaddrIn { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ne = u32::from_be(self.0.sin_addr.s_addr); let port = u16::from_be(self.0.sin_port); - write!(f, "{}.{}.{}.{}:{}", - ne >> 24, - (ne >> 16) & 0xFF, - (ne >> 8) & 0xFF, - ne & 0xFF, - port) + write!( + f, + "{}.{}.{}.{}:{}", + ne >> 24, + (ne >> 16) & 0xFF, + (ne >> 8) & 0xFF, + ne & 0xFF, + port + ) } } #[cfg(feature = "net")] impl From<net::SocketAddrV4> for SockaddrIn { fn from(addr: net::SocketAddrV4) -> Self { - Self(libc::sockaddr_in{ - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "haiku", target_os = "hermit", - target_os = "ios", target_os = "macos", - target_os = "netbsd", target_os = "openbsd"))] + Self(libc::sockaddr_in { + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "haiku", + target_os = "hermit", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] sin_len: mem::size_of::<libc::sockaddr_in>() as u8, sin_family: AddressFamily::Inet as sa_family_t, - sin_port: addr.port().to_be(), // network byte order + sin_port: addr.port().to_be(), // network byte order sin_addr: ipv4addr_to_libc(*addr.ip()), - .. unsafe { mem::zeroed() } + ..unsafe { mem::zeroed() } }) } } @@ -1242,7 +1334,7 @@ impl From<SockaddrIn> for net::SocketAddrV4 { fn from(addr: SockaddrIn) -> Self { net::SocketAddrV4::new( net::Ipv4Addr::from(addr.0.sin_addr.s_addr.to_ne_bytes()), - u16::from_be(addr.0.sin_port) + u16::from_be(addr.0.sin_port), ) } } @@ -1290,8 +1382,12 @@ impl SockaddrIn6 { impl private::SockaddrLikePriv for SockaddrIn6 {} #[cfg(feature = "net")] impl SockaddrLike for SockaddrIn6 { - unsafe fn from_raw(addr: *const libc::sockaddr, len: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + len: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if let Some(l) = len { if l != mem::size_of::<libc::sockaddr_in6>() as libc::socklen_t { @@ -1317,8 +1413,12 @@ impl fmt::Display for SockaddrIn6 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // These things are really hard to display properly. Easier to let std // do it. - let std = net::SocketAddrV6::new(self.ip(), self.port(), - self.flowinfo(), self.scope_id()); + let std = net::SocketAddrV6::new( + self.ip(), + self.port(), + self.flowinfo(), + self.scope_id(), + ); std.fmt(f) } } @@ -1326,19 +1426,25 @@ impl fmt::Display for SockaddrIn6 { #[cfg(feature = "net")] impl From<net::SocketAddrV6> for SockaddrIn6 { fn from(addr: net::SocketAddrV6) -> Self { - #[allow(clippy::needless_update)] // It isn't needless on Illumos - Self(libc::sockaddr_in6{ - #[cfg(any(target_os = "dragonfly", target_os = "freebsd", - target_os = "haiku", target_os = "hermit", - target_os = "ios", target_os = "macos", - target_os = "netbsd", target_os = "openbsd"))] + #[allow(clippy::needless_update)] // It isn't needless on Illumos + Self(libc::sockaddr_in6 { + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "haiku", + target_os = "hermit", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] sin6_len: mem::size_of::<libc::sockaddr_in6>() as u8, sin6_family: AddressFamily::Inet6 as sa_family_t, - sin6_port: addr.port().to_be(), // network byte order + sin6_port: addr.port().to_be(), // network byte order sin6_addr: ipv6addr_to_libc(addr.ip()), - sin6_flowinfo: addr.flowinfo(), // host byte order - sin6_scope_id: addr.scope_id(), // host byte order - .. unsafe { mem::zeroed() } + sin6_flowinfo: addr.flowinfo(), // host byte order + sin6_scope_id: addr.scope_id(), // host byte order + ..unsafe { mem::zeroed() } }) } } @@ -1350,7 +1456,7 @@ impl From<SockaddrIn6> for net::SocketAddrV6 { net::Ipv6Addr::from(addr.0.sin6_addr.s6_addr), u16::from_be(addr.0.sin6_port), u32::from_be(addr.0.sin6_flowinfo), - u32::from_be(addr.0.sin6_scope_id) + u32::from_be(addr.0.sin6_scope_id), ) } } @@ -1364,7 +1470,6 @@ impl std::str::FromStr for SockaddrIn6 { } } - /// A container for any sockaddr type /// /// Just like C's `sockaddr_storage`, this type is large enough to hold any type @@ -1394,7 +1499,10 @@ 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", + any(target_os = "ios", target_os = "macos") + ))] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] sctl: SysControlAddr, #[cfg(feature = "net")] @@ -1405,26 +1513,31 @@ pub union SockaddrStorage { su: UnixAddr, #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] - vsock: VsockAddr + vsock: VsockAddr, } impl private::SockaddrLikePriv for SockaddrStorage {} impl SockaddrLike for SockaddrStorage { - unsafe fn from_raw(addr: *const libc::sockaddr, l: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + l: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if addr.is_null() { return None; } if let Some(len) = l { let ulen = len as usize; - if ulen < offset_of!(libc::sockaddr, sa_data) || - ulen > mem::size_of::<libc::sockaddr_storage>() { + if ulen < offset_of!(libc::sockaddr, sa_data) + || ulen > mem::size_of::<libc::sockaddr_storage>() + { None - } else{ + } else { let mut ss: libc::sockaddr_storage = mem::zeroed(); let ssp = &mut ss as *mut libc::sockaddr_storage as *mut u8; ptr::copy(addr as *const u8, ssp, len as usize); - Some(Self{ss}) + Some(Self { ss }) } } else { // If length is not available and addr is of a fixed-length type, @@ -1432,43 +1545,56 @@ impl SockaddrLike for SockaddrStorage { // available, then there's nothing we can do. match (*addr).sa_family as i32 { #[cfg(any(target_os = "android", target_os = "linux"))] - libc::AF_ALG => AlgAddr::from_raw(addr, l) - .map(|alg| Self { alg}), + libc::AF_ALG => { + AlgAddr::from_raw(addr, l).map(|alg| Self { alg }) + } #[cfg(feature = "net")] - libc::AF_INET => SockaddrIn::from_raw(addr, l) - .map(|sin| Self{ sin}), + libc::AF_INET => { + SockaddrIn::from_raw(addr, l).map(|sin| Self { sin }) + } #[cfg(feature = "net")] - libc::AF_INET6 => SockaddrIn6::from_raw(addr, l) - .map(|sin6| Self{ sin6}), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "haiku", - target_os = "openbsd"))] + libc::AF_INET6 => { + SockaddrIn6::from_raw(addr, l).map(|sin6| Self { sin6 }) + } + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "haiku", + target_os = "openbsd" + ))] #[cfg(feature = "net")] - libc::AF_LINK => LinkAddr::from_raw(addr, l) - .map(|dl| Self{ dl}), + libc::AF_LINK => { + LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) + } #[cfg(any(target_os = "android", target_os = "linux"))] - libc::AF_NETLINK => NetlinkAddr::from_raw(addr, l) - .map(|nl| Self{ nl }), - #[cfg(any(target_os = "android", - target_os = "fuchsia", - target_os = "linux" + libc::AF_NETLINK => { + 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 => LinkAddr::from_raw(addr, l) - .map(|dl| Self{ dl}), - #[cfg(all(feature = "ioctl", - any(target_os = "ios", target_os = "macos")))] - libc::AF_SYSTEM => SysControlAddr::from_raw(addr, l) - .map(|sctl| Self {sctl}), + libc::AF_PACKET => { + LinkAddr::from_raw(addr, l).map(|dl| Self { dl }) + } + #[cfg(all( + feature = "ioctl", + any(target_os = "ios", target_os = "macos") + ))] + libc::AF_SYSTEM => { + SysControlAddr::from_raw(addr, l).map(|sctl| Self { sctl }) + } #[cfg(any(target_os = "android", target_os = "linux"))] - libc::AF_VSOCK => VsockAddr::from_raw(addr, l) - .map(|vsock| Self{vsock}), - _ => None + libc::AF_VSOCK => { + VsockAddr::from_raw(addr, l).map(|vsock| Self { vsock }) + } + _ => None, } } } @@ -1481,15 +1607,14 @@ macro_rules! accessors { $sockty:ty, $family:expr, $libc_ty:ty, - $field:ident) => - { + $field:ident) => { /// Safely and falliably downcast to an immutable reference pub fn $fname(&self) -> Option<&$sockty> { - if self.family() == Some($family) && - self.len() >= mem::size_of::<$libc_ty>() as libc::socklen_t + if self.family() == Some($family) + && self.len() >= mem::size_of::<$libc_ty>() as libc::socklen_t { // Safe because family and len are validated - Some(unsafe{&self.$field}) + Some(unsafe { &self.$field }) } else { None } @@ -1497,66 +1622,70 @@ macro_rules! accessors { /// Safely and falliably downcast to a mutable reference pub fn $fname_mut(&mut self) -> Option<&mut $sockty> { - if self.family() == Some($family) && - self.len() >= mem::size_of::<$libc_ty>() as libc::socklen_t + if self.family() == Some($family) + && self.len() >= mem::size_of::<$libc_ty>() as libc::socklen_t { // Safe because family and len are validated - Some(unsafe{&mut self.$field}) + Some(unsafe { &mut self.$field }) } else { None } } - } + }; } impl SockaddrStorage { #[cfg(any(target_os = "android", target_os = "linux"))] - accessors!{as_alg_addr, as_alg_addr_mut, AlgAddr, - AddressFamily::Alg, libc::sockaddr_alg, alg} + 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( + target_os = "android", + target_os = "fuchsia", + target_os = "linux" + ))] #[cfg(feature = "net")] - accessors!{ - as_link_addr, as_link_addr_mut, LinkAddr, - AddressFamily::Packet, libc::sockaddr_ll, dl} - - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + accessors! { + as_link_addr, as_link_addr_mut, LinkAddr, + AddressFamily::Packet, libc::sockaddr_ll, dl} + + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg(feature = "net")] - accessors!{ - as_link_addr, as_link_addr_mut, LinkAddr, - AddressFamily::Link, libc::sockaddr_dl, dl} + accessors! { + as_link_addr, as_link_addr_mut, LinkAddr, + AddressFamily::Link, libc::sockaddr_dl, dl} #[cfg(feature = "net")] - accessors!{ - as_sockaddr_in, as_sockaddr_in_mut, SockaddrIn, - AddressFamily::Inet, libc::sockaddr_in, sin} + accessors! { + as_sockaddr_in, as_sockaddr_in_mut, SockaddrIn, + AddressFamily::Inet, libc::sockaddr_in, sin} #[cfg(feature = "net")] - accessors!{ - as_sockaddr_in6, as_sockaddr_in6_mut, SockaddrIn6, - AddressFamily::Inet6, libc::sockaddr_in6, sin6} + accessors! { + as_sockaddr_in6, as_sockaddr_in6_mut, SockaddrIn6, + AddressFamily::Inet6, libc::sockaddr_in6, sin6} #[cfg(any(target_os = "android", target_os = "linux"))] - accessors!{as_netlink_addr, as_netlink_addr_mut, NetlinkAddr, - AddressFamily::Netlink, libc::sockaddr_nl, nl} + 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_attr(docsrs, doc(cfg(feature = "ioctl")))] - accessors!{as_sys_control_addr, as_sys_control_addr_mut, SysControlAddr, - AddressFamily::System, libc::sockaddr_ctl, sctl} + 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"))] #[cfg_attr(docsrs, doc(cfg(all())))] - accessors!{as_vsock_addr, as_vsock_addr_mut, VsockAddr, - AddressFamily::Vsock, libc::sockaddr_vm, vsock} + accessors! {as_vsock_addr, as_vsock_addr_mut, VsockAddr, + AddressFamily::Vsock, libc::sockaddr_vm, vsock} } impl fmt::Debug for SockaddrStorage { @@ -1564,7 +1693,7 @@ impl fmt::Debug for SockaddrStorage { f.debug_struct("SockaddrStorage") // Safe because sockaddr_storage has the least specific // field types - .field("ss", unsafe{&self.ss}) + .field("ss", unsafe { &self.ss }) .finish() } } @@ -1579,20 +1708,23 @@ impl fmt::Display for SockaddrStorage { 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", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + 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"))] libc::AF_NETLINK => self.nl.fmt(f), - #[cfg(any(target_os = "android", - target_os = "linux", - target_os = "fuchsia" + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "fuchsia" ))] #[cfg(feature = "net")] libc::AF_PACKET => self.dl.fmt(f), @@ -1602,7 +1734,7 @@ impl fmt::Display for SockaddrStorage { libc::AF_UNIX => self.su.fmt(f), #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_VSOCK => self.vsock.fmt(f), - _ => "<Address family unspecified>".fmt(f) + _ => "<Address family unspecified>".fmt(f), } } } @@ -1650,20 +1782,23 @@ impl Hash for SockaddrStorage { 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", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + 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"))] libc::AF_NETLINK => self.nl.hash(s), - #[cfg(any(target_os = "android", - target_os = "linux", - target_os = "fuchsia" + #[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "fuchsia" ))] #[cfg(feature = "net")] libc::AF_PACKET => self.dl.hash(s), @@ -1673,7 +1808,7 @@ impl Hash for SockaddrStorage { libc::AF_UNIX => self.su.hash(s), #[cfg(any(target_os = "android", target_os = "linux"))] libc::AF_VSOCK => self.vsock.hash(s), - _ => self.ss.hash(s) + _ => self.ss.hash(s), } } } @@ -1689,20 +1824,23 @@ 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(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + 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"))] (libc::AF_NETLINK, libc::AF_NETLINK) => self.nl == other.nl, - #[cfg(any(target_os = "android", - target_os = "fuchsia", - target_os = "linux" + #[cfg(any( + target_os = "android", + target_os = "fuchsia", + target_os = "linux" ))] #[cfg(feature = "net")] (libc::AF_PACKET, libc::AF_PACKET) => self.dl == other.dl, @@ -1740,7 +1878,7 @@ mod private { since = "0.24.0", note = "use SockaddrLike or SockaddrStorage instead" )] -#[allow(missing_docs)] // Since they're all deprecated anyway +#[allow(missing_docs)] // Since they're all deprecated anyway #[allow(deprecated)] #[non_exhaustive] pub enum SockAddr { @@ -1754,19 +1892,24 @@ pub enum SockAddr { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] Alg(AlgAddr), - #[cfg(all(feature = "ioctl", any(target_os = "ios", target_os = "macos")))] + #[cfg(all( + feature = "ioctl", + any(target_os = "ios", target_os = "macos") + ))] #[cfg_attr(docsrs, doc(cfg(feature = "ioctl")))] SysControl(SysControlAddr), /// Datalink address (MAC) - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg(feature = "net")] #[cfg_attr(docsrs, doc(cfg(feature = "net")))] Link(LinkAddr), @@ -1775,7 +1918,7 @@ pub enum SockAddr { Vsock(VsockAddr), } -#[allow(missing_docs)] // Since they're all deprecated anyway +#[allow(missing_docs)] // Since they're all deprecated anyway #[allow(deprecated)] impl SockAddr { feature! { @@ -1826,19 +1969,23 @@ impl SockAddr { SockAddr::Netlink(..) => AddressFamily::Netlink, #[cfg(any(target_os = "android", target_os = "linux"))] SockAddr::Alg(..) => AddressFamily::Alg, - #[cfg(all(feature = "ioctl", - any(target_os = "ios", target_os = "macos")))] + #[cfg(all( + feature = "ioctl", + any(target_os = "ios", target_os = "macos") + ))] SockAddr::SysControl(..) => AddressFamily::System, #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] SockAddr::Link(..) => AddressFamily::Packet, - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "illumos", + target_os = "openbsd" + ))] #[cfg(feature = "net")] SockAddr::Link(..) => AddressFamily::Link, #[cfg(any(target_os = "android", target_os = "linux"))] @@ -1862,7 +2009,9 @@ impl SockAddr { /// ensure that the pointer is valid. #[cfg(not(target_os = "fuchsia"))] #[cfg(feature = "net")] - pub(crate) unsafe fn from_libc_sockaddr(addr: *const libc::sockaddr) -> Option<SockAddr> { + pub(crate) unsafe fn from_libc_sockaddr( + addr: *const libc::sockaddr, + ) -> Option<SockAddr> { if addr.is_null() { None } else { @@ -1870,40 +2019,51 @@ impl SockAddr { Some(AddressFamily::Unix) => None, #[cfg(feature = "net")] Some(AddressFamily::Inet) => Some(SockAddr::Inet( - InetAddr::V4(ptr::read_unaligned(addr as *const _)))), + InetAddr::V4(ptr::read_unaligned(addr as *const _)), + )), #[cfg(feature = "net")] Some(AddressFamily::Inet6) => Some(SockAddr::Inet( - InetAddr::V6(ptr::read_unaligned(addr as *const _)))), + InetAddr::V6(ptr::read_unaligned(addr as *const _)), + )), #[cfg(any(target_os = "android", target_os = "linux"))] Some(AddressFamily::Netlink) => Some(SockAddr::Netlink( - NetlinkAddr(ptr::read_unaligned(addr as *const _)))), - #[cfg(all(feature = "ioctl", - any(target_os = "ios", target_os = "macos")))] + NetlinkAddr(ptr::read_unaligned(addr as *const _)), + )), + #[cfg(all( + feature = "ioctl", + any(target_os = "ios", target_os = "macos") + ))] Some(AddressFamily::System) => Some(SockAddr::SysControl( - SysControlAddr(ptr::read_unaligned(addr as *const _)))), + SysControlAddr(ptr::read_unaligned(addr as *const _)), + )), #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] - Some(AddressFamily::Packet) => Some(SockAddr::Link( - LinkAddr(ptr::read_unaligned(addr as *const _)))), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd"))] + Some(AddressFamily::Packet) => Some(SockAddr::Link(LinkAddr( + ptr::read_unaligned(addr as *const _), + ))), + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "illumos", + target_os = "openbsd" + ))] #[cfg(feature = "net")] Some(AddressFamily::Link) => { - let ether_addr = LinkAddr(ptr::read_unaligned(addr as *const _)); + let ether_addr = + LinkAddr(ptr::read_unaligned(addr as *const _)); if ether_addr.is_empty() { None } else { Some(SockAddr::Link(ether_addr)) } - }, + } #[cfg(any(target_os = "android", target_os = "linux"))] - Some(AddressFamily::Vsock) => Some(SockAddr::Vsock( - VsockAddr(ptr::read_unaligned(addr as *const _)))), + Some(AddressFamily::Vsock) => Some(SockAddr::Vsock(VsockAddr( + ptr::read_unaligned(addr as *const _), + ))), // Other address families are currently not supported and simply yield a None // entry instead of a proper conversion to a `SockAddr`. Some(_) | None => None, @@ -1924,24 +2084,27 @@ impl SockAddr { SockAddr::Inet(InetAddr::V4(ref addr)) => ( // This cast is always allowed in C unsafe { - &*(addr as *const libc::sockaddr_in as *const libc::sockaddr) + &*(addr as *const libc::sockaddr_in + as *const libc::sockaddr) }, - mem::size_of_val(addr) as libc::socklen_t + mem::size_of_val(addr) as libc::socklen_t, ), #[cfg(feature = "net")] SockAddr::Inet(InetAddr::V6(ref addr)) => ( // This cast is always allowed in C unsafe { - &*(addr as *const libc::sockaddr_in6 as *const libc::sockaddr) + &*(addr as *const libc::sockaddr_in6 + as *const libc::sockaddr) }, - mem::size_of_val(addr) as libc::socklen_t + mem::size_of_val(addr) as libc::socklen_t, ), SockAddr::Unix(ref unix_addr) => ( // This cast is always allowed in C unsafe { - &*(&unix_addr.sun as *const libc::sockaddr_un as *const libc::sockaddr) + &*(&unix_addr.sun as *const libc::sockaddr_un + as *const libc::sockaddr) }, - unix_addr.sun_len() as libc::socklen_t + unix_addr.sun_len() as libc::socklen_t, ), #[cfg(any(target_os = "android", target_os = "linux"))] SockAddr::Netlink(NetlinkAddr(ref sa)) => ( @@ -1949,7 +2112,7 @@ impl SockAddr { unsafe { &*(sa as *const libc::sockaddr_nl as *const libc::sockaddr) }, - mem::size_of_val(sa) as libc::socklen_t + mem::size_of_val(sa) as libc::socklen_t, ), #[cfg(any(target_os = "android", target_os = "linux"))] SockAddr::Alg(AlgAddr(ref sa)) => ( @@ -1957,41 +2120,46 @@ impl SockAddr { unsafe { &*(sa as *const libc::sockaddr_alg as *const libc::sockaddr) }, - mem::size_of_val(sa) as libc::socklen_t + mem::size_of_val(sa) as libc::socklen_t, ), - #[cfg(all(feature = "ioctl", - any(target_os = "ios", target_os = "macos")))] + #[cfg(all( + feature = "ioctl", + any(target_os = "ios", target_os = "macos") + ))] SockAddr::SysControl(SysControlAddr(ref sa)) => ( // This cast is always allowed in C unsafe { &*(sa as *const libc::sockaddr_ctl as *const libc::sockaddr) }, - mem::size_of_val(sa) as libc::socklen_t - + mem::size_of_val(sa) as libc::socklen_t, ), #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] SockAddr::Link(LinkAddr(ref addr)) => ( // This cast is always allowed in C unsafe { - &*(addr as *const libc::sockaddr_ll as *const libc::sockaddr) + &*(addr as *const libc::sockaddr_ll + as *const libc::sockaddr) }, - mem::size_of_val(addr) as libc::socklen_t + mem::size_of_val(addr) as libc::socklen_t, ), - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[cfg(feature = "net")] SockAddr::Link(LinkAddr(ref addr)) => ( // This cast is always allowed in C unsafe { - &*(addr as *const libc::sockaddr_dl as *const libc::sockaddr) + &*(addr as *const libc::sockaddr_dl + as *const libc::sockaddr) }, - mem::size_of_val(addr) as libc::socklen_t + mem::size_of_val(addr) as libc::socklen_t, ), #[cfg(any(target_os = "android", target_os = "linux"))] SockAddr::Vsock(VsockAddr(ref sa)) => ( @@ -1999,7 +2167,7 @@ impl SockAddr { unsafe { &*(sa as *const libc::sockaddr_vm as *const libc::sockaddr) }, - mem::size_of_val(sa) as libc::socklen_t + mem::size_of_val(sa) as libc::socklen_t, ), } } @@ -2016,18 +2184,22 @@ impl fmt::Display for SockAddr { SockAddr::Netlink(ref nl) => nl.fmt(f), #[cfg(any(target_os = "android", target_os = "linux"))] SockAddr::Alg(ref nl) => nl.fmt(f), - #[cfg(all(feature = "ioctl", - any(target_os = "ios", target_os = "macos")))] + #[cfg(all( + feature = "ioctl", + any(target_os = "ios", target_os = "macos") + ))] SockAddr::SysControl(ref sc) => sc.fmt(f), - #[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd"))] + #[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "illumos", + target_os = "openbsd" + ))] #[cfg(feature = "net")] SockAddr::Link(ref ether_addr) => ether_addr.fmt(f), #[cfg(any(target_os = "android", target_os = "linux"))] @@ -2044,9 +2216,10 @@ impl private::SockaddrLikePriv for SockAddr {} #[cfg(feature = "net")] #[allow(deprecated)] impl SockaddrLike for SockAddr { - unsafe fn from_raw(addr: *const libc::sockaddr, _len: Option<libc::socklen_t>) - -> Option<Self> - { + unsafe fn from_raw( + addr: *const libc::sockaddr, + _len: Option<libc::socklen_t>, + ) -> Option<Self> { Self::from_libc_sockaddr(addr) } } @@ -2054,10 +2227,10 @@ impl SockaddrLike for SockAddr { #[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; use libc::{sa_family_t, sockaddr_nl}; use std::{fmt, mem}; - use super::*; /// Address for the Linux kernel user interface device. /// @@ -2093,8 +2266,12 @@ pub mod netlink { impl private::SockaddrLikePriv for NetlinkAddr {} impl SockaddrLike for NetlinkAddr { - unsafe fn from_raw(addr: *const libc::sockaddr, len: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + len: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if let Some(l) = len { if l != mem::size_of::<libc::sockaddr_nl>() as libc::socklen_t { @@ -2124,11 +2301,11 @@ pub mod netlink { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub mod alg { - use libc::{AF_ALG, sockaddr_alg, c_char}; - use std::{fmt, mem, str}; - use std::hash::{Hash, Hasher}; - use std::ffi::CStr; use super::*; + use libc::{c_char, sockaddr_alg, AF_ALG}; + use std::ffi::CStr; + use std::hash::{Hash, Hasher}; + use std::{fmt, mem, str}; /// Socket address for the Linux kernel crypto API #[derive(Copy, Clone)] @@ -2137,11 +2314,16 @@ pub mod alg { impl private::SockaddrLikePriv for AlgAddr {} impl SockaddrLike for AlgAddr { - unsafe fn from_raw(addr: *const libc::sockaddr, l: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + l: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if let Some(l) = l { - if l != mem::size_of::<libc::sockaddr_alg>() as libc::socklen_t { + if l != mem::size_of::<libc::sockaddr_alg>() as libc::socklen_t + { return None; } } @@ -2162,8 +2344,19 @@ pub mod alg { impl PartialEq for AlgAddr { fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); - (inner.salg_family, &inner.salg_type[..], inner.salg_feat, inner.salg_mask, &inner.salg_name[..]) == - (other.salg_family, &other.salg_type[..], other.salg_feat, other.salg_mask, &other.salg_name[..]) + ( + inner.salg_family, + &inner.salg_type[..], + inner.salg_feat, + inner.salg_mask, + &inner.salg_name[..], + ) == ( + other.salg_family, + &other.salg_type[..], + other.salg_feat, + other.salg_mask, + &other.salg_name[..], + ) } } @@ -2172,7 +2365,14 @@ pub mod alg { impl Hash for AlgAddr { fn hash<H: Hasher>(&self, s: &mut H) { let inner = self.0; - (inner.salg_family, &inner.salg_type[..], inner.salg_feat, inner.salg_mask, &inner.salg_name[..]).hash(s); + ( + inner.salg_family, + &inner.salg_type[..], + inner.salg_feat, + inner.salg_mask, + &inner.salg_name[..], + ) + .hash(s); } } @@ -2181,29 +2381,37 @@ pub mod alg { pub fn new(alg_type: &str, alg_name: &str) -> AlgAddr { let mut addr: sockaddr_alg = unsafe { mem::zeroed() }; addr.salg_family = AF_ALG as u16; - addr.salg_type[..alg_type.len()].copy_from_slice(alg_type.to_string().as_bytes()); - addr.salg_name[..alg_name.len()].copy_from_slice(alg_name.to_string().as_bytes()); + addr.salg_type[..alg_type.len()] + .copy_from_slice(alg_type.to_string().as_bytes()); + addr.salg_name[..alg_name.len()] + .copy_from_slice(alg_name.to_string().as_bytes()); AlgAddr(addr) } - /// 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) } + unsafe { + CStr::from_ptr(self.0.salg_type.as_ptr() as *const c_char) + } } /// 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) } + unsafe { + CStr::from_ptr(self.0.salg_name.as_ptr() as *const c_char) + } } } impl fmt::Display for AlgAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "type: {} alg: {}", - self.alg_name().to_string_lossy(), - self.alg_type().to_string_lossy()) + write!( + f, + "type: {} alg: {}", + self.alg_name().to_string_lossy(), + self.alg_type().to_string_lossy() + ) } } @@ -2323,7 +2531,6 @@ pub mod sys_control { } } - #[cfg(any(target_os = "android", target_os = "linux", target_os = "fuchsia"))] #[cfg_attr(docsrs, doc(cfg(all())))] mod datalink { @@ -2418,14 +2625,16 @@ mod datalink { } } -#[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "illumos", - target_os = "netbsd", - target_os = "haiku", - target_os = "openbsd"))] +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "illumos", + target_os = "netbsd", + target_os = "haiku", + target_os = "openbsd" +))] #[cfg_attr(docsrs, doc(cfg(all())))] mod datalink { feature! { @@ -2543,11 +2752,11 @@ mod datalink { #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg_attr(docsrs, doc(cfg(all())))] pub mod vsock { + use super::*; use crate::sys::socket::addr::AddressFamily; use libc::{sa_family_t, sockaddr_vm}; - use std::{fmt, mem}; use std::hash::{Hash, Hasher}; - use super::*; + use std::{fmt, mem}; /// Socket address for VMWare VSockets protocol /// @@ -2560,8 +2769,12 @@ pub mod vsock { impl private::SockaddrLikePriv for VsockAddr {} impl SockaddrLike for VsockAddr { - unsafe fn from_raw(addr: *const libc::sockaddr, len: Option<libc::socklen_t>) - -> Option<Self> where Self: Sized + unsafe fn from_raw( + addr: *const libc::sockaddr, + len: Option<libc::socklen_t>, + ) -> Option<Self> + where + Self: Sized, { if let Some(l) = len { if l != mem::size_of::<libc::sockaddr_vm>() as libc::socklen_t { @@ -2584,8 +2797,8 @@ pub mod vsock { impl PartialEq for VsockAddr { fn eq(&self, other: &Self) -> bool { let (inner, other) = (self.0, other.0); - (inner.svm_family, inner.svm_cid, inner.svm_port) == - (other.svm_family, other.svm_cid, other.svm_port) + (inner.svm_family, inner.svm_cid, inner.svm_port) + == (other.svm_family, other.svm_cid, other.svm_port) } } @@ -2655,33 +2868,39 @@ mod tests { fn test_ipv6addr_to_libc() { let s = std::net::Ipv6Addr::new(1, 2, 3, 4, 5, 6, 7, 8); let l = ipv6addr_to_libc(&s); - assert_eq!(l.s6_addr, [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8]); + assert_eq!( + l.s6_addr, + [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8] + ); } } mod link { #![allow(clippy::cast_ptr_alignment)] - use super::*; - #[cfg(any(target_os = "ios", - target_os = "macos", - target_os = "illumos" - ))] + #[cfg(any( + target_os = "ios", + target_os = "macos", + target_os = "illumos" + ))] use super::super::super::socklen_t; + use super::*; /// Don't panic when trying to display an empty datalink address - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ))] #[test] fn test_datalink_display() { use super::super::LinkAddr; use std::mem; - let la = LinkAddr(libc::sockaddr_dl{ + let la = LinkAddr(libc::sockaddr_dl { sdl_len: 56, sdl_family: 18, sdl_index: 5, @@ -2689,67 +2908,75 @@ mod tests { sdl_nlen: 3, sdl_alen: 0, sdl_slen: 0, - .. unsafe{mem::zeroed()} + ..unsafe { mem::zeroed() } }); format!("{}", la); } #[cfg(all( - any(target_os = "android", - target_os = "fuchsia", - target_os = "linux"), - target_endian = "little" + any( + target_os = "android", + target_os = "fuchsia", + target_os = "linux" + ), + target_endian = "little" ))] #[test] fn linux_loopback() { #[repr(align(2))] struct Raw([u8; 20]); - let bytes = Raw([17u8, 0, 0, 0, 1, 0, 0, 0, 4, 3, 0, 6, 1, 2, 3, 4, 5, 6, 0, 0]); + 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 len = None; - let sock_addr = unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); + let sock_addr = + unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); assert_eq!(sock_addr.family(), Some(AddressFamily::Packet)); match sock_addr.as_link_addr() { Some(dl) => assert_eq!(dl.addr(), Some([1, 2, 3, 4, 5, 6])), - None => panic!("Can't unwrap sockaddr storage") + None => panic!("Can't unwrap sockaddr storage"), } } - #[cfg(any(target_os = "ios", - target_os = "macos" - ))] + #[cfg(any(target_os = "ios", target_os = "macos"))] #[test] fn macos_loopback() { - let bytes = [20i8, 18, 1, 0, 24, 3, 0, 0, 108, 111, 48, 0, 0, 0, 0, 0]; + 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 len = Some(bytes.len() as socklen_t); - let sock_addr = unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); + let sock_addr = + unsafe { SockaddrStorage::from_raw(sa, len) }.unwrap(); assert_eq!(sock_addr.family(), Some(AddressFamily::Link)); match sock_addr.as_link_addr() { Some(dl) => { assert!(dl.addr().is_none()); - }, - None => panic!("Can't unwrap sockaddr storage") + } + None => panic!("Can't unwrap sockaddr storage"), } } - #[cfg(any(target_os = "ios", - target_os = "macos" - ))] + #[cfg(any(target_os = "ios", target_os = "macos"))] #[test] fn macos_tap() { - let bytes = [20i8, 18, 7, 0, 6, 3, 6, 0, 101, 110, 48, 24, 101, -112, -35, 76, -80]; + let bytes = [ + 20i8, 18, 7, 0, 6, 3, 6, 0, 101, 110, 48, 24, 101, -112, -35, + 76, -80, + ]; let ptr = bytes.as_ptr(); let sa = ptr as *const libc::sockaddr; let len = Some(bytes.len() as socklen_t); - let sock_addr = unsafe { SockaddrStorage::from_raw(sa, len).unwrap() }; + let sock_addr = + unsafe { SockaddrStorage::from_raw(sa, len).unwrap() }; assert_eq!(sock_addr.family(), Some(AddressFamily::Link)); match sock_addr.as_link_addr() { - Some(dl) => assert_eq!(dl.addr(), - Some([24u8, 101, 144, 221, 76, 176])), - None => panic!("Can't unwrap sockaddr storage") + Some(dl) => { + assert_eq!(dl.addr(), Some([24u8, 101, 144, 221, 76, 176])) + } + None => panic!("Can't unwrap sockaddr storage"), } } @@ -2768,27 +2995,32 @@ mod tests { assert_eq!(sock_addr.family().unwrap(), AddressFamily::Link); - assert_eq!(sock_addr.as_link_addr().unwrap().addr(), - Some([24u8, 101, 144, 221, 76, 176])); + assert_eq!( + sock_addr.as_link_addr().unwrap().addr(), + Some([24u8, 101, 144, 221, 76, 176]) + ); } #[test] fn size() { - #[cfg(any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "illumos", - target_os = "openbsd", - target_os = "haiku"))] + #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "illumos", + target_os = "openbsd", + target_os = "haiku" + ))] let l = mem::size_of::<libc::sockaddr_dl>(); #[cfg(any( - target_os = "android", - target_os = "fuchsia", - target_os = "linux"))] + target_os = "android", + target_os = "fuchsia", + target_os = "linux" + ))] let l = mem::size_of::<libc::sockaddr_ll>(); - assert_eq!( LinkAddr::size() as usize, l); + assert_eq!(LinkAddr::size() as usize, l); } } @@ -2805,8 +3037,10 @@ mod tests { #[test] fn size() { - assert_eq!(mem::size_of::<libc::sockaddr_in>(), - SockaddrIn::size() as usize); + assert_eq!( + mem::size_of::<libc::sockaddr_in>(), + SockaddrIn::size() as usize + ); } } @@ -2823,8 +3057,10 @@ mod tests { #[test] fn size() { - assert_eq!(mem::size_of::<libc::sockaddr_in6>(), - SockaddrIn6::size() as usize); + assert_eq!( + mem::size_of::<libc::sockaddr_in6>(), + SockaddrIn6::size() as usize + ); } } @@ -2837,15 +3073,21 @@ mod tests { let name = String::from("nix\0abstract\0test"); let addr = UnixAddr::new_abstract(name.as_bytes()).unwrap(); - let sun_path1 = unsafe { &(*addr.as_ptr()).sun_path[..addr.path_len()] }; - let sun_path2 = [0, 110, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, 116, 101, 115, 116]; + let sun_path1 = + unsafe { &(*addr.as_ptr()).sun_path[..addr.path_len()] }; + let sun_path2 = [ + 0, 110, 105, 120, 0, 97, 98, 115, 116, 114, 97, 99, 116, 0, + 116, 101, 115, 116, + ]; assert_eq!(sun_path1, sun_path2); } #[test] fn size() { - assert_eq!(mem::size_of::<libc::sockaddr_un>(), - UnixAddr::size() as usize); + assert_eq!( + mem::size_of::<libc::sockaddr_un>(), + UnixAddr::size() as usize + ); } } } diff --git a/src/sys/socket/sockopt.rs b/src/sys/socket/sockopt.rs index 90111ec5..e9f26333 100644 --- a/src/sys/socket/sockopt.rs +++ b/src/sys/socket/sockopt.rs @@ -1,18 +1,15 @@ //! Socket options as used by `setsockopt` and `getsockopt`. -use cfg_if::cfg_if; use super::{GetSockOpt, SetSockOpt}; -use crate::Result; use crate::errno::Errno; use crate::sys::time::TimeVal; +use crate::Result; +use cfg_if::cfg_if; use libc::{self, c_int, c_void, socklen_t}; -use std::mem::{ - self, - MaybeUninit -}; -use std::os::unix::io::RawFd; 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::RawFd; // Constants // TCP_CA_NAME_MAX isn't defined in user space include files @@ -51,14 +48,18 @@ macro_rules! setsockopt_impl { unsafe { let setter: $setter = Set::new(val); - let res = libc::setsockopt(fd, $level, $flag, - setter.ffi_ptr(), - setter.ffi_len()); + let res = libc::setsockopt( + fd, + $level, + $flag, + setter.ffi_ptr(), + setter.ffi_len(), + ); Errno::result(res).map(drop) } } } - } + }; } /// Helper for implementing `GetSockOpt` for a given socket option. See @@ -92,16 +93,20 @@ macro_rules! getsockopt_impl { unsafe { let mut getter: $getter = Get::uninit(); - let res = libc::getsockopt(fd, $level, $flag, - getter.ffi_ptr(), - getter.ffi_len()); + let res = libc::getsockopt( + fd, + $level, + $flag, + getter.ffi_ptr(), + getter.ffi_len(), + ); Errno::result(res)?; Ok(getter.assume_init()) } } } - } + }; } /// Helper to generate the sockopt accessors. See @@ -248,13 +253,22 @@ macro_rules! sockopt_impl { sockopt_impl!( /// Enables local address reuse - ReuseAddr, Both, libc::SOL_SOCKET, libc::SO_REUSEADDR, bool + ReuseAddr, + Both, + libc::SOL_SOCKET, + libc::SO_REUSEADDR, + bool ); #[cfg(not(any(target_os = "illumos", target_os = "solaris")))] sockopt_impl!( /// Permits multiple AF_INET or AF_INET6 sockets to be bound to an /// identical socket address. - ReusePort, Both, libc::SOL_SOCKET, libc::SO_REUSEPORT, bool); + ReusePort, + Both, + libc::SOL_SOCKET, + libc::SO_REUSEPORT, + bool +); #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] @@ -265,24 +279,42 @@ sockopt_impl!( /// send a stream of mouse events which receive no replies, this /// packetization may cause significant delays. The boolean option /// TCP_NODELAY defeats this algorithm. - TcpNoDelay, Both, libc::IPPROTO_TCP, libc::TCP_NODELAY, bool); + TcpNoDelay, + Both, + libc::IPPROTO_TCP, + libc::TCP_NODELAY, + bool +); sockopt_impl!( /// When enabled, a close(2) or shutdown(2) will not return until all /// queued messages for the socket have been successfully sent or the /// linger timeout has been reached. - Linger, Both, libc::SOL_SOCKET, libc::SO_LINGER, libc::linger); + Linger, + Both, + libc::SOL_SOCKET, + libc::SO_LINGER, + libc::linger +); #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Join a multicast group - IpAddMembership, SetOnly, libc::IPPROTO_IP, libc::IP_ADD_MEMBERSHIP, - super::IpMembershipRequest); + IpAddMembership, + SetOnly, + libc::IPPROTO_IP, + libc::IP_ADD_MEMBERSHIP, + super::IpMembershipRequest +); #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Leave a multicast group. - IpDropMembership, SetOnly, libc::IPPROTO_IP, libc::IP_DROP_MEMBERSHIP, - super::IpMembershipRequest); + IpDropMembership, + SetOnly, + libc::IPPROTO_IP, + libc::IP_DROP_MEMBERSHIP, + super::IpMembershipRequest +); cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { #[cfg(feature = "net")] @@ -322,74 +354,145 @@ sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Set or read the time-to-live value of outgoing multicast packets for /// this socket. - IpMulticastTtl, Both, libc::IPPROTO_IP, libc::IP_MULTICAST_TTL, u8); + IpMulticastTtl, + Both, + libc::IPPROTO_IP, + libc::IP_MULTICAST_TTL, + u8 +); #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Set or read a boolean integer argument that determines whether sent /// multicast packets should be looped back to the local sockets. - IpMulticastLoop, Both, libc::IPPROTO_IP, libc::IP_MULTICAST_LOOP, bool); + IpMulticastLoop, + Both, + libc::IPPROTO_IP, + libc::IP_MULTICAST_LOOP, + bool +); #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// If enabled, this boolean option allows binding to an IP address that /// is nonlocal or does not (yet) exist. - IpFreebind, Both, libc::IPPROTO_IP, libc::IP_FREEBIND, bool); + IpFreebind, + Both, + libc::IPPROTO_IP, + libc::IP_FREEBIND, + bool +); sockopt_impl!( /// Specify the receiving timeout until reporting an error. - ReceiveTimeout, Both, libc::SOL_SOCKET, libc::SO_RCVTIMEO, TimeVal); + ReceiveTimeout, + Both, + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + TimeVal +); sockopt_impl!( /// Specify the sending timeout until reporting an error. - SendTimeout, Both, libc::SOL_SOCKET, libc::SO_SNDTIMEO, TimeVal); + SendTimeout, + Both, + libc::SOL_SOCKET, + libc::SO_SNDTIMEO, + TimeVal +); sockopt_impl!( /// Set or get the broadcast flag. - Broadcast, Both, libc::SOL_SOCKET, libc::SO_BROADCAST, bool); + Broadcast, + Both, + libc::SOL_SOCKET, + libc::SO_BROADCAST, + bool +); sockopt_impl!( /// If this option is enabled, out-of-band data is directly placed into /// the receive data stream. - OobInline, Both, libc::SOL_SOCKET, libc::SO_OOBINLINE, bool); + OobInline, + Both, + libc::SOL_SOCKET, + libc::SO_OOBINLINE, + bool +); sockopt_impl!( /// Get and clear the pending socket error. - SocketError, GetOnly, libc::SOL_SOCKET, libc::SO_ERROR, i32); + SocketError, + GetOnly, + libc::SOL_SOCKET, + libc::SO_ERROR, + i32 +); sockopt_impl!( /// Set or get the don't route flag. - DontRoute, Both, libc::SOL_SOCKET, libc::SO_DONTROUTE, bool); + DontRoute, + Both, + libc::SOL_SOCKET, + libc::SO_DONTROUTE, + bool +); sockopt_impl!( /// Enable sending of keep-alive messages on connection-oriented sockets. - KeepAlive, Both, libc::SOL_SOCKET, libc::SO_KEEPALIVE, bool); + KeepAlive, + Both, + libc::SOL_SOCKET, + libc::SO_KEEPALIVE, + bool +); #[cfg(any( - target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "ios" + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "ios" ))] sockopt_impl!( /// Get the credentials of the peer process of a connected unix domain /// socket. - LocalPeerCred, GetOnly, 0, libc::LOCAL_PEERCRED, super::XuCred); + LocalPeerCred, + GetOnly, + 0, + libc::LOCAL_PEERCRED, + super::XuCred +); #[cfg(any(target_os = "android", target_os = "linux"))] sockopt_impl!( /// Return the credentials of the foreign process connected to this socket. - PeerCredentials, GetOnly, libc::SOL_SOCKET, libc::SO_PEERCRED, super::UnixCredentials); -#[cfg(any(target_os = "ios", - target_os = "macos"))] + PeerCredentials, + GetOnly, + libc::SOL_SOCKET, + libc::SO_PEERCRED, + super::UnixCredentials +); +#[cfg(any(target_os = "ios", target_os = "macos"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Specify the amount of time, in seconds, that the connection must be idle /// before keepalive probes (if enabled) are sent. - TcpKeepAlive, Both, libc::IPPROTO_TCP, libc::TCP_KEEPALIVE, u32); -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux"))] + TcpKeepAlive, + Both, + libc::IPPROTO_TCP, + libc::TCP_KEEPALIVE, + u32 +); +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux" +))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The time (in seconds) the connection needs to remain idle before TCP /// starts sending keepalive probes - TcpKeepIdle, Both, libc::IPPROTO_TCP, libc::TCP_KEEPIDLE, u32); + TcpKeepIdle, + Both, + libc::IPPROTO_TCP, + libc::TCP_KEEPIDLE, + u32 +); cfg_if! { if #[cfg(any(target_os = "android", target_os = "linux"))] { sockopt_impl!( @@ -407,20 +510,33 @@ sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The maximum number of keepalive probes TCP should send before /// dropping the connection. - TcpKeepCount, Both, libc::IPPROTO_TCP, libc::TCP_KEEPCNT, u32); -#[cfg(any(target_os = "android", - target_os = "fuchsia", - target_os = "linux"))] + TcpKeepCount, + Both, + libc::IPPROTO_TCP, + libc::TCP_KEEPCNT, + u32 +); +#[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] sockopt_impl!( #[allow(missing_docs)] // Not documented by Linux! - TcpRepair, Both, libc::IPPROTO_TCP, libc::TCP_REPAIR, u32); + TcpRepair, + Both, + libc::IPPROTO_TCP, + libc::TCP_REPAIR, + u32 +); #[cfg(not(any(target_os = "openbsd", target_os = "haiku")))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The time (in seconds) between individual keepalive probes. - TcpKeepInterval, Both, libc::IPPROTO_TCP, libc::TCP_KEEPINTVL, u32); + TcpKeepInterval, + Both, + libc::IPPROTO_TCP, + libc::TCP_KEEPINTVL, + u32 +); #[cfg(any(target_os = "fuchsia", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( @@ -428,98 +544,193 @@ sockopt_impl!( /// Specifies the maximum amount of time in milliseconds that transmitted /// data may remain unacknowledged before TCP will forcibly close the /// corresponding connection - TcpUserTimeout, Both, libc::IPPROTO_TCP, libc::TCP_USER_TIMEOUT, u32); + TcpUserTimeout, + Both, + libc::IPPROTO_TCP, + libc::TCP_USER_TIMEOUT, + u32 +); sockopt_impl!( /// Sets or gets the maximum socket receive buffer in bytes. - RcvBuf, Both, libc::SOL_SOCKET, libc::SO_RCVBUF, usize); + RcvBuf, + Both, + libc::SOL_SOCKET, + libc::SO_RCVBUF, + usize +); sockopt_impl!( /// Sets or gets the maximum socket send buffer in bytes. - SndBuf, Both, libc::SOL_SOCKET, libc::SO_SNDBUF, usize); + SndBuf, + Both, + libc::SOL_SOCKET, + libc::SO_SNDBUF, + usize +); #[cfg(any(target_os = "android", target_os = "linux"))] 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 /// overridden. - RcvBufForce, SetOnly, libc::SOL_SOCKET, libc::SO_RCVBUFFORCE, usize); + RcvBufForce, + SetOnly, + libc::SOL_SOCKET, + libc::SO_RCVBUFFORCE, + usize +); #[cfg(any(target_os = "android", target_os = "linux"))] 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 /// overridden. - SndBufForce, SetOnly, libc::SOL_SOCKET, libc::SO_SNDBUFFORCE, usize); + SndBufForce, + SetOnly, + libc::SOL_SOCKET, + libc::SO_SNDBUFFORCE, + usize +); sockopt_impl!( /// Gets the socket type as an integer. - SockType, GetOnly, libc::SOL_SOCKET, libc::SO_TYPE, super::SockType); + SockType, + GetOnly, + libc::SOL_SOCKET, + libc::SO_TYPE, + super::SockType +); sockopt_impl!( /// Returns a value indicating whether or not this socket has been marked to /// accept connections with `listen(2)`. - AcceptConn, GetOnly, libc::SOL_SOCKET, libc::SO_ACCEPTCONN, bool); + AcceptConn, + GetOnly, + libc::SOL_SOCKET, + libc::SO_ACCEPTCONN, + bool +); #[cfg(any(target_os = "android", target_os = "linux"))] sockopt_impl!( /// Bind this socket to a particular device like “eth0”. - BindToDevice, Both, libc::SOL_SOCKET, libc::SO_BINDTODEVICE, OsString<[u8; libc::IFNAMSIZ]>); + BindToDevice, + Both, + libc::SOL_SOCKET, + libc::SO_BINDTODEVICE, + OsString<[u8; libc::IFNAMSIZ]> +); #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] #[allow(missing_docs)] // Not documented by Linux! - OriginalDst, GetOnly, libc::SOL_IP, libc::SO_ORIGINAL_DST, libc::sockaddr_in); + OriginalDst, + GetOnly, + libc::SOL_IP, + libc::SO_ORIGINAL_DST, + libc::sockaddr_in +); #[cfg(any(target_os = "android", target_os = "linux"))] sockopt_impl!( #[allow(missing_docs)] // Not documented by Linux! - Ip6tOriginalDst, GetOnly, libc::SOL_IPV6, libc::IP6T_SO_ORIGINAL_DST, libc::sockaddr_in6); + Ip6tOriginalDst, + GetOnly, + libc::SOL_IPV6, + libc::IP6T_SO_ORIGINAL_DST, + libc::sockaddr_in6 +); #[cfg(any(target_os = "linux"))] sockopt_impl!( /// Specifies exact type of timestamping information collected by the kernel /// [Further reading](https://www.kernel.org/doc/html/latest/networking/timestamping.html) - Timestamping, Both, libc::SOL_SOCKET, libc::SO_TIMESTAMPING, super::TimestampingFlag); + Timestamping, + Both, + libc::SOL_SOCKET, + libc::SO_TIMESTAMPING, + super::TimestampingFlag +); #[cfg(not(target_os = "haiku"))] sockopt_impl!( /// Enable or disable the receiving of the `SO_TIMESTAMP` control message. - ReceiveTimestamp, Both, libc::SOL_SOCKET, libc::SO_TIMESTAMP, bool); + ReceiveTimestamp, + Both, + libc::SOL_SOCKET, + libc::SO_TIMESTAMP, + bool +); #[cfg(all(target_os = "linux"))] sockopt_impl!( /// Enable or disable the receiving of the `SO_TIMESTAMPNS` control message. - ReceiveTimestampns, Both, libc::SOL_SOCKET, libc::SO_TIMESTAMPNS, bool); + ReceiveTimestampns, + Both, + libc::SOL_SOCKET, + libc::SO_TIMESTAMPNS, + bool +); #[cfg(any(target_os = "android", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Setting this boolean option enables transparent proxying on this socket. - IpTransparent, Both, libc::SOL_IP, libc::IP_TRANSPARENT, bool); + IpTransparent, + Both, + libc::SOL_IP, + libc::IP_TRANSPARENT, + bool +); #[cfg(target_os = "openbsd")] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Allows the socket to be bound to addresses which are not local to the /// machine, so it can be used to make a transparent proxy. - BindAny, Both, libc::SOL_SOCKET, libc::SO_BINDANY, bool); + BindAny, + Both, + libc::SOL_SOCKET, + libc::SO_BINDANY, + bool +); #[cfg(target_os = "freebsd")] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Can `bind(2)` to any address, even one not bound to any available /// network interface in the system. - BindAny, Both, libc::IPPROTO_IP, libc::IP_BINDANY, bool); + BindAny, + Both, + libc::IPPROTO_IP, + libc::IP_BINDANY, + bool +); #[cfg(target_os = "linux")] sockopt_impl!( /// Set the mark for each packet sent through this socket (similar to the /// netfilter MARK target but socket-based). - Mark, Both, libc::SOL_SOCKET, libc::SO_MARK, u32); + Mark, + Both, + libc::SOL_SOCKET, + libc::SO_MARK, + u32 +); #[cfg(any(target_os = "android", target_os = "linux"))] sockopt_impl!( /// Enable or disable the receiving of the `SCM_CREDENTIALS` control /// message. - PassCred, Both, libc::SOL_SOCKET, libc::SO_PASSCRED, bool); + PassCred, + Both, + libc::SOL_SOCKET, + libc::SO_PASSCRED, + bool +); #[cfg(any(target_os = "freebsd", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// This option allows the caller to set the TCP congestion control /// algorithm to be used, on a per-socket basis. - TcpCongestion, Both, libc::IPPROTO_TCP, libc::TCP_CONGESTION, OsString<[u8; TCP_CA_NAME_MAX]>); + TcpCongestion, + Both, + libc::IPPROTO_TCP, + libc::TCP_CONGESTION, + OsString<[u8; TCP_CA_NAME_MAX]> +); #[cfg(any( target_os = "android", target_os = "ios", @@ -532,7 +743,12 @@ sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Pass an `IP_PKTINFO` ancillary message that contains a pktinfo /// structure that supplies some information about the incoming packet. - Ipv4PacketInfo, Both, libc::IPPROTO_IP, libc::IP_PKTINFO, bool); + Ipv4PacketInfo, + Both, + libc::IPPROTO_IP, + libc::IP_PKTINFO, + bool +); #[cfg(any( target_os = "android", target_os = "freebsd", @@ -547,7 +763,12 @@ sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// Set delivery of the `IPV6_PKTINFO` control message on incoming /// datagrams. - Ipv6RecvPacketInfo, Both, libc::IPPROTO_IPV6, libc::IPV6_RECVPKTINFO, bool); + Ipv6RecvPacketInfo, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_RECVPKTINFO, + bool +); #[cfg(any( target_os = "freebsd", target_os = "ios", @@ -560,7 +781,12 @@ sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The `recvmsg(2)` call returns a `struct sockaddr_dl` corresponding to /// the interface on which the packet was received. - Ipv4RecvIf, Both, libc::IPPROTO_IP, libc::IP_RECVIF, bool); + Ipv4RecvIf, + Both, + libc::IPPROTO_IP, + libc::IP_RECVIF, + bool +); #[cfg(any( target_os = "freebsd", target_os = "ios", @@ -573,72 +799,137 @@ sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The `recvmsg(2)` call will return the destination IP address for a UDP /// datagram. - Ipv4RecvDstAddr, Both, libc::IPPROTO_IP, libc::IP_RECVDSTADDR, bool); + Ipv4RecvDstAddr, + Both, + libc::IPPROTO_IP, + libc::IP_RECVDSTADDR, + bool +); #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The `recvmsg(2)` call will return the destination IP address for a UDP /// datagram. - Ipv4OrigDstAddr, Both, libc::IPPROTO_IP, libc::IP_ORIGDSTADDR, bool); + Ipv4OrigDstAddr, + Both, + libc::IPPROTO_IP, + libc::IP_ORIGDSTADDR, + bool +); #[cfg(target_os = "linux")] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] #[allow(missing_docs)] // Not documented by Linux! - UdpGsoSegment, Both, libc::SOL_UDP, libc::UDP_SEGMENT, libc::c_int); + UdpGsoSegment, + Both, + libc::SOL_UDP, + libc::UDP_SEGMENT, + libc::c_int +); #[cfg(target_os = "linux")] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] #[allow(missing_docs)] // Not documented by Linux! - UdpGroSegment, Both, libc::IPPROTO_UDP, libc::UDP_GRO, bool); + UdpGroSegment, + Both, + libc::IPPROTO_UDP, + libc::UDP_GRO, + bool +); #[cfg(target_os = "linux")] sockopt_impl!( /// Configures the behavior of time-based transmission of packets, for use /// with the `TxTime` control message. - TxTime, Both, libc::SOL_SOCKET, libc::SO_TXTIME, libc::sock_txtime); + TxTime, + Both, + libc::SOL_SOCKET, + libc::SO_TXTIME, + libc::sock_txtime +); #[cfg(any(target_os = "android", target_os = "fuchsia", target_os = "linux"))] 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 /// the socket since its creation. - RxqOvfl, Both, libc::SOL_SOCKET, libc::SO_RXQ_OVFL, libc::c_int); + RxqOvfl, + Both, + libc::SOL_SOCKET, + libc::SO_RXQ_OVFL, + libc::c_int +); #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The socket is restricted to sending and receiving IPv6 packets only. - Ipv6V6Only, Both, libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, bool); + Ipv6V6Only, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_V6ONLY, + bool +); #[cfg(any(target_os = "android", target_os = "linux"))] sockopt_impl!( /// Enable extended reliable error message passing. - Ipv4RecvErr, Both, libc::IPPROTO_IP, libc::IP_RECVERR, bool); + Ipv4RecvErr, + Both, + libc::IPPROTO_IP, + libc::IP_RECVERR, + bool +); #[cfg(any(target_os = "android", target_os = "linux"))] sockopt_impl!( /// Control receiving of asynchronous error options. - Ipv6RecvErr, Both, libc::IPPROTO_IPV6, libc::IPV6_RECVERR, bool); + Ipv6RecvErr, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_RECVERR, + bool +); #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] sockopt_impl!( /// Set or retrieve the current time-to-live field that is used in every /// packet sent from this socket. - Ipv4Ttl, Both, libc::IPPROTO_IP, libc::IP_TTL, libc::c_int); + Ipv4Ttl, + Both, + libc::IPPROTO_IP, + libc::IP_TTL, + libc::c_int +); #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] sockopt_impl!( /// Set the unicast hop limit for the socket. - Ipv6Ttl, Both, libc::IPPROTO_IPV6, libc::IPV6_UNICAST_HOPS, libc::c_int); + Ipv6Ttl, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_UNICAST_HOPS, + libc::c_int +); #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux"))] #[cfg(feature = "net")] sockopt_impl!( #[cfg_attr(docsrs, doc(cfg(feature = "net")))] /// The `recvmsg(2)` call will return the destination IP address for a UDP /// datagram. - Ipv6OrigDstAddr, Both, libc::IPPROTO_IPV6, libc::IPV6_ORIGDSTADDR, bool); + Ipv6OrigDstAddr, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_ORIGDSTADDR, + bool +); #[cfg(any(target_os = "ios", target_os = "macos"))] sockopt_impl!( /// Set "don't fragment packet" flag on the IP packet. - IpDontFrag, Both, libc::IPPROTO_IP, libc::IP_DONTFRAG, bool); + IpDontFrag, + Both, + libc::IPPROTO_IP, + libc::IP_DONTFRAG, + bool +); #[cfg(any( target_os = "android", target_os = "ios", @@ -647,7 +938,12 @@ sockopt_impl!( ))] sockopt_impl!( /// Set "don't fragment packet" flag on the IPv6 packet. - Ipv6DontFrag, Both, libc::IPPROTO_IPV6, libc::IPV6_DONTFRAG, bool); + Ipv6DontFrag, + Both, + libc::IPPROTO_IPV6, + libc::IPV6_DONTFRAG, + bool +); #[allow(missing_docs)] // Not documented by Linux! @@ -663,11 +959,13 @@ impl SetSockOpt for AlgSetAeadAuthSize { fn set(&self, fd: RawFd, val: &usize) -> Result<()> { unsafe { - let res = libc::setsockopt(fd, - libc::SOL_ALG, - libc::ALG_SET_AEAD_AUTHSIZE, - ::std::ptr::null(), - *val as libc::socklen_t); + let res = libc::setsockopt( + fd, + libc::SOL_ALG, + libc::ALG_SET_AEAD_AUTHSIZE, + ::std::ptr::null(), + *val as libc::socklen_t, + ); Errno::result(res).map(drop) } } @@ -687,16 +985,21 @@ impl<T> Default for AlgSetKey<T> { } #[cfg(any(target_os = "android", target_os = "linux"))] -impl<T> SetSockOpt for AlgSetKey<T> where T: AsRef<[u8]> + Clone { +impl<T> SetSockOpt for AlgSetKey<T> +where + T: AsRef<[u8]> + Clone, +{ type Val = T; fn set(&self, fd: RawFd, val: &T) -> Result<()> { unsafe { - let res = libc::setsockopt(fd, - libc::SOL_ALG, - libc::ALG_SET_KEY, - val.as_ref().as_ptr() as *const _, - val.as_ref().len() as libc::socklen_t); + let res = libc::setsockopt( + fd, + libc::SOL_ALG, + libc::ALG_SET_KEY, + val.as_ref().as_ptr() as *const _, + val.as_ref().len() as libc::socklen_t, + ); Errno::result(res).map(drop) } } @@ -757,7 +1060,11 @@ impl<T> Get<T> for GetStruct<T> { } unsafe fn assume_init(self) -> T { - assert_eq!(self.len as usize, mem::size_of::<T>(), "invalid getsockopt implementation"); + assert_eq!( + self.len as usize, + mem::size_of::<T>(), + "invalid getsockopt implementation" + ); self.val.assume_init() } } @@ -804,7 +1111,11 @@ impl Get<bool> for GetBool { } unsafe fn assume_init(self) -> bool { - assert_eq!(self.len as usize, mem::size_of::<c_int>(), "invalid getsockopt implementation"); + assert_eq!( + self.len as usize, + mem::size_of::<c_int>(), + "invalid getsockopt implementation" + ); self.val.assume_init() != 0 } } @@ -816,7 +1127,9 @@ struct SetBool { impl<'a> Set<'a, bool> for SetBool { fn new(val: &'a bool) -> SetBool { - SetBool { val: i32::from(*val) } + SetBool { + val: i32::from(*val), + } } fn ffi_ptr(&self) -> *const c_void { @@ -851,7 +1164,11 @@ impl Get<u8> for GetU8 { } unsafe fn assume_init(self) -> u8 { - assert_eq!(self.len as usize, mem::size_of::<u8>(), "invalid getsockopt implementation"); + assert_eq!( + self.len as usize, + mem::size_of::<u8>(), + "invalid getsockopt implementation" + ); self.val.assume_init() } } @@ -898,7 +1215,11 @@ impl Get<usize> for GetUsize { } unsafe fn assume_init(self) -> usize { - assert_eq!(self.len as usize, mem::size_of::<c_int>(), "invalid getsockopt implementation"); + assert_eq!( + self.len as usize, + mem::size_of::<c_int>(), + "invalid getsockopt implementation" + ); self.val.assume_init() as usize } } @@ -958,7 +1279,9 @@ struct SetOsString<'a> { impl<'a> Set<'a, OsString> for SetOsString<'a> { fn new(val: &'a OsString) -> SetOsString { - SetOsString { val: val.as_os_str() } + SetOsString { + val: val.as_os_str(), + } } fn ffi_ptr(&self) -> *const c_void { @@ -970,7 +1293,6 @@ impl<'a> Set<'a, OsString> for SetOsString<'a> { } } - #[cfg(test)] mod test { #[cfg(any(target_os = "android", target_os = "linux"))] @@ -978,7 +1300,13 @@ mod 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, 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); @@ -990,7 +1318,13 @@ mod test { use super::super::*; use crate::unistd::close; - let (a, b) = socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::empty()).unwrap(); + 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); close(a).unwrap(); @@ -1002,20 +1336,31 @@ mod test { use super::super::*; use crate::unistd::close; - let s = socket(AddressFamily::Inet, SockType::Datagram, SockFlag::empty(), None).unwrap(); + 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); close(s).unwrap(); } - #[cfg(any(target_os = "freebsd", - target_os = "linux"))] + #[cfg(any(target_os = "freebsd", target_os = "linux"))] #[test] fn can_get_listen_on_tcp_socket() { use super::super::*; use crate::unistd::close; - let s = socket(AddressFamily::Inet, SockType::Stream, SockFlag::empty(), None).unwrap(); + 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(); @@ -1023,5 +1368,4 @@ mod test { assert!(s_listening2); close(s).unwrap(); } - } diff --git a/src/sys/stat.rs b/src/sys/stat.rs index 8b7627d5..94be4107 100644 --- a/src/sys/stat.rs +++ b/src/sys/stat.rs @@ -1,4 +1,3 @@ -pub use libc::{dev_t, mode_t}; #[cfg(any(target_os = "macos", target_os = "ios", target_os = "openbsd"))] pub use libc::c_uint; #[cfg(any( @@ -8,13 +7,14 @@ pub use libc::c_uint; ))] pub use libc::c_ulong; pub use libc::stat as FileStat; +pub use libc::{dev_t, mode_t}; -use crate::{Result, NixPath, errno::Errno}; #[cfg(not(target_os = "redox"))] -use crate::fcntl::{AtFlags, at_rawfd}; +use crate::fcntl::{at_rawfd, AtFlags}; +use crate::sys::time::{TimeSpec, TimeVal}; +use crate::{errno::Errno, NixPath, Result}; use std::mem; use std::os::unix::io::RawFd; -use crate::sys::time::{TimeSpec, TimeVal}; libc_bitflags!( /// "File type" flags for `mknod` and related functions. @@ -51,7 +51,7 @@ libc_bitflags! { } } -#[cfg(any(target_os = "macos", target_os = "ios", target_os="openbsd"))] +#[cfg(any(target_os = "macos", target_os = "ios", target_os = "openbsd"))] pub type type_of_file_flag = c_uint; #[cfg(any( target_os = "netbsd", @@ -156,7 +156,12 @@ libc_bitflags! { } /// Create a special or ordinary file, by pathname. -pub fn mknod<P: ?Sized + NixPath>(path: &P, kind: SFlag, perm: Mode, dev: dev_t) -> Result<()> { +pub fn mknod<P: ?Sized + NixPath>( + path: &P, + kind: SFlag, + perm: Mode, + dev: dev_t, +) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { libc::mknod(cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev) })?; @@ -165,7 +170,12 @@ pub fn mknod<P: ?Sized + NixPath>(path: &P, kind: SFlag, perm: Mode, dev: dev_t) } /// 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( + target_os = "ios", + target_os = "macos", + target_os = "redox", + target_os = "haiku" +)))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn mknodat<P: ?Sized + NixPath>( dirfd: RawFd, @@ -175,7 +185,12 @@ pub fn mknodat<P: ?Sized + NixPath>( dev: dev_t, ) -> Result<()> { let res = path.with_nix_path(|cstr| unsafe { - libc::mknodat(dirfd, cstr.as_ptr(), kind.bits | perm.bits() as mode_t, dev) + libc::mknodat( + dirfd, + cstr.as_ptr(), + kind.bits | perm.bits() as mode_t, + dev, + ) })?; Errno::result(res).map(drop) @@ -184,24 +199,22 @@ pub fn mknodat<P: ?Sized + NixPath>( #[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) + ((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) + ((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) | - ((minor & 0xffff_ff00) << 12) | - (minor & 0x0000_00ff) + ((major & 0xffff_f000) << 32) + | ((major & 0x0000_0fff) << 8) + | ((minor & 0xffff_ff00) << 12) + | (minor & 0x0000_00ff) } pub fn umask(mode: Mode) -> Mode { @@ -211,28 +224,24 @@ pub fn umask(mode: Mode) -> Mode { pub fn stat<P: ?Sized + NixPath>(path: &P) -> Result<FileStat> { let mut dst = mem::MaybeUninit::uninit(); - let res = path.with_nix_path(|cstr| { - unsafe { - libc::stat(cstr.as_ptr(), dst.as_mut_ptr()) - } + let res = path.with_nix_path(|cstr| unsafe { + libc::stat(cstr.as_ptr(), dst.as_mut_ptr()) })?; Errno::result(res)?; - Ok(unsafe{dst.assume_init()}) + Ok(unsafe { dst.assume_init() }) } pub fn lstat<P: ?Sized + NixPath>(path: &P) -> Result<FileStat> { let mut dst = mem::MaybeUninit::uninit(); - let res = path.with_nix_path(|cstr| { - unsafe { - libc::lstat(cstr.as_ptr(), dst.as_mut_ptr()) - } + let res = path.with_nix_path(|cstr| unsafe { + libc::lstat(cstr.as_ptr(), dst.as_mut_ptr()) })?; Errno::result(res)?; - Ok(unsafe{dst.assume_init()}) + Ok(unsafe { dst.assume_init() }) } pub fn fstat(fd: RawFd) -> Result<FileStat> { @@ -241,20 +250,29 @@ pub fn fstat(fd: RawFd) -> Result<FileStat> { Errno::result(res)?; - Ok(unsafe{dst.assume_init()}) + Ok(unsafe { dst.assume_init() }) } #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] -pub fn fstatat<P: ?Sized + NixPath>(dirfd: RawFd, pathname: &P, f: AtFlags) -> Result<FileStat> { +pub fn fstatat<P: ?Sized + NixPath>( + dirfd: RawFd, + pathname: &P, + f: AtFlags, +) -> Result<FileStat> { let mut dst = mem::MaybeUninit::uninit(); - let res = pathname.with_nix_path(|cstr| { - unsafe { libc::fstatat(dirfd, cstr.as_ptr(), dst.as_mut_ptr(), f.bits() as libc::c_int) } + let res = pathname.with_nix_path(|cstr| unsafe { + libc::fstatat( + dirfd, + cstr.as_ptr(), + dst.as_mut_ptr(), + f.bits() as libc::c_int, + ) })?; Errno::result(res)?; - Ok(unsafe{dst.assume_init()}) + Ok(unsafe { dst.assume_init() }) } /// Change the file permission bits of the file specified by a file descriptor. @@ -299,11 +317,10 @@ pub fn fchmodat<P: ?Sized + NixPath>( mode: Mode, flag: FchmodatFlags, ) -> Result<()> { - let atflag = - match flag { - FchmodatFlags::FollowSymlink => AtFlags::empty(), - FchmodatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, - }; + let atflag = match flag { + FchmodatFlags::FollowSymlink => AtFlags::empty(), + FchmodatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, + }; let res = path.with_nix_path(|cstr| unsafe { libc::fchmodat( at_rawfd(dirfd), @@ -326,7 +343,11 @@ pub fn fchmodat<P: ?Sized + NixPath>( /// # References /// /// [utimes(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/utimes.html). -pub fn utimes<P: ?Sized + NixPath>(path: &P, atime: &TimeVal, mtime: &TimeVal) -> Result<()> { +pub fn utimes<P: ?Sized + NixPath>( + path: &P, + atime: &TimeVal, + mtime: &TimeVal, +) -> Result<()> { let times: [libc::timeval; 2] = [*atime.as_ref(), *mtime.as_ref()]; let res = path.with_nix_path(|cstr| unsafe { libc::utimes(cstr.as_ptr(), ×[0]) @@ -345,14 +366,20 @@ pub fn utimes<P: ?Sized + NixPath>(path: &P, atime: &TimeVal, mtime: &TimeVal) - /// # References /// /// [lutimes(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/lutimes.html). -#[cfg(any(target_os = "linux", - target_os = "haiku", - target_os = "ios", - target_os = "macos", - target_os = "freebsd", - target_os = "netbsd"))] +#[cfg(any( + target_os = "linux", + target_os = "haiku", + target_os = "ios", + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd" +))] #[cfg_attr(docsrs, doc(cfg(all())))] -pub fn lutimes<P: ?Sized + NixPath>(path: &P, atime: &TimeVal, mtime: &TimeVal) -> Result<()> { +pub fn lutimes<P: ?Sized + NixPath>( + path: &P, + atime: &TimeVal, + mtime: &TimeVal, +) -> Result<()> { let times: [libc::timeval; 2] = [*atime.as_ref(), *mtime.as_ref()]; let res = path.with_nix_path(|cstr| unsafe { libc::lutimes(cstr.as_ptr(), ×[0]) @@ -405,13 +432,12 @@ pub fn utimensat<P: ?Sized + NixPath>( path: &P, atime: &TimeSpec, mtime: &TimeSpec, - flag: UtimensatFlags + flag: UtimensatFlags, ) -> Result<()> { - let atflag = - match flag { - UtimensatFlags::FollowSymlink => AtFlags::empty(), - UtimensatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, - }; + let atflag = match flag { + UtimensatFlags::FollowSymlink => AtFlags::empty(), + UtimensatFlags::NoFollowSymlink => AtFlags::AT_SYMLINK_NOFOLLOW, + }; let times: [libc::timespec; 2] = [*atime.as_ref(), *mtime.as_ref()]; let res = path.with_nix_path(|cstr| unsafe { libc::utimensat( @@ -427,9 +453,13 @@ pub fn utimensat<P: ?Sized + NixPath>( #[cfg(not(target_os = "redox"))] #[cfg_attr(docsrs, doc(cfg(all())))] -pub fn mkdirat<P: ?Sized + NixPath>(fd: RawFd, path: &P, mode: Mode) -> Result<()> { - let res = path.with_nix_path(|cstr| { - unsafe { libc::mkdirat(fd, cstr.as_ptr(), mode.bits() as mode_t) } +pub fn mkdirat<P: ?Sized + NixPath>( + fd: RawFd, + path: &P, + mode: Mode, +) -> Result<()> { + let res = path.with_nix_path(|cstr| unsafe { + libc::mkdirat(fd, cstr.as_ptr(), mode.bits() as mode_t) })?; Errno::result(res).map(drop) diff --git a/src/sys/statfs.rs b/src/sys/statfs.rs index 9c28bc21..9be8ca66 100644 --- a/src/sys/statfs.rs +++ b/src/sys/statfs.rs @@ -1,25 +1,28 @@ //! Get filesystem statistics, non-portably //! //! See [`statvfs`](crate::sys::statvfs) for a portable alternative. +#[cfg(not(any(target_os = "linux", target_os = "android")))] +use std::ffi::CStr; use std::fmt::{self, Debug}; use std::mem; use std::os::unix::io::AsRawFd; -#[cfg(not(any(target_os = "linux", target_os = "android")))] -use std::ffi::CStr; use cfg_if::cfg_if; -use crate::{NixPath, Result, errno::Errno}; -#[cfg(all(feature = "mount", - any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd") +#[cfg(all( + feature = "mount", + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) ))] use crate::mount::MntFlags; #[cfg(target_os = "linux")] use crate::sys::statvfs::FsFlags; +use crate::{errno::Errno, NixPath, Result}; /// Identifies a mounted file system #[cfg(target_os = "android")] @@ -65,7 +68,14 @@ type fs_type_t = libc::c_uint; type fs_type_t = libc::c_ulong; #[cfg(all(target_os = "linux", target_env = "uclibc"))] type fs_type_t = libc::c_int; -#[cfg(all(target_os = "linux", not(any(target_arch = "s390x", target_env = "musl", target_env = "uclibc"))))] +#[cfg(all( + target_os = "linux", + not(any( + target_arch = "s390x", + target_env = "musl", + target_env = "uclibc" + )) +))] type fs_type_t = libc::__fsword_t; /// Describes the file system type as known by the operating system. @@ -74,7 +84,10 @@ 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", not(any(target_arch = "s390x", target_env = "musl"))), + all( + target_os = "linux", + not(any(target_arch = "s390x", target_env = "musl")) + ), ))] #[derive(Eq, Copy, Clone, PartialEq, Debug)] pub struct FsType(pub fs_type_t); @@ -83,31 +96,38 @@ pub struct FsType(pub fs_type_t); // can't very well document them here. #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const ADFS_SUPER_MAGIC: FsType = FsType(libc::ADFS_SUPER_MAGIC as fs_type_t); +pub const ADFS_SUPER_MAGIC: FsType = + FsType(libc::ADFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const AFFS_SUPER_MAGIC: FsType = FsType(libc::AFFS_SUPER_MAGIC as fs_type_t); +pub const AFFS_SUPER_MAGIC: FsType = + FsType(libc::AFFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "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"))] #[allow(missing_docs)] -pub const AUTOFS_SUPER_MAGIC: FsType = FsType(libc::AUTOFS_SUPER_MAGIC as fs_type_t); +pub const AUTOFS_SUPER_MAGIC: FsType = + FsType(libc::AUTOFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "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"))] #[allow(missing_docs)] -pub const BTRFS_SUPER_MAGIC: FsType = FsType(libc::BTRFS_SUPER_MAGIC as fs_type_t); +pub const BTRFS_SUPER_MAGIC: FsType = + FsType(libc::BTRFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const CGROUP2_SUPER_MAGIC: FsType = FsType(libc::CGROUP2_SUPER_MAGIC as fs_type_t); +pub const CGROUP2_SUPER_MAGIC: FsType = + FsType(libc::CGROUP2_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const CGROUP_SUPER_MAGIC: FsType = FsType(libc::CGROUP_SUPER_MAGIC as fs_type_t); +pub const CGROUP_SUPER_MAGIC: FsType = + FsType(libc::CGROUP_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const CODA_SUPER_MAGIC: FsType = FsType(libc::CODA_SUPER_MAGIC as fs_type_t); +pub const CODA_SUPER_MAGIC: FsType = + FsType(libc::CODA_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const CRAMFS_MAGIC: FsType = FsType(libc::CRAMFS_MAGIC as fs_type_t); @@ -116,64 +136,82 @@ pub const CRAMFS_MAGIC: FsType = FsType(libc::CRAMFS_MAGIC as fs_type_t); pub const DEBUGFS_MAGIC: FsType = FsType(libc::DEBUGFS_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const DEVPTS_SUPER_MAGIC: FsType = FsType(libc::DEVPTS_SUPER_MAGIC as fs_type_t); +pub const DEVPTS_SUPER_MAGIC: FsType = + FsType(libc::DEVPTS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const ECRYPTFS_SUPER_MAGIC: FsType = FsType(libc::ECRYPTFS_SUPER_MAGIC as fs_type_t); +pub const ECRYPTFS_SUPER_MAGIC: FsType = + FsType(libc::ECRYPTFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "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"))] #[allow(missing_docs)] -pub const EXT2_SUPER_MAGIC: FsType = FsType(libc::EXT2_SUPER_MAGIC as fs_type_t); +pub const EXT2_SUPER_MAGIC: FsType = + FsType(libc::EXT2_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const EXT3_SUPER_MAGIC: FsType = FsType(libc::EXT3_SUPER_MAGIC as fs_type_t); +pub const EXT3_SUPER_MAGIC: FsType = + FsType(libc::EXT3_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const EXT4_SUPER_MAGIC: FsType = FsType(libc::EXT4_SUPER_MAGIC as fs_type_t); +pub const EXT4_SUPER_MAGIC: FsType = + FsType(libc::EXT4_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const F2FS_SUPER_MAGIC: FsType = FsType(libc::F2FS_SUPER_MAGIC as fs_type_t); +pub const F2FS_SUPER_MAGIC: FsType = + FsType(libc::F2FS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const FUSE_SUPER_MAGIC: FsType = FsType(libc::FUSE_SUPER_MAGIC as fs_type_t); +pub const FUSE_SUPER_MAGIC: FsType = + FsType(libc::FUSE_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const FUTEXFS_SUPER_MAGIC: FsType = FsType(libc::FUTEXFS_SUPER_MAGIC as fs_type_t); +pub const FUTEXFS_SUPER_MAGIC: FsType = + FsType(libc::FUTEXFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const HOSTFS_SUPER_MAGIC: FsType = FsType(libc::HOSTFS_SUPER_MAGIC as fs_type_t); +pub const HOSTFS_SUPER_MAGIC: FsType = + FsType(libc::HOSTFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const HPFS_SUPER_MAGIC: FsType = FsType(libc::HPFS_SUPER_MAGIC as fs_type_t); +pub const HPFS_SUPER_MAGIC: FsType = + FsType(libc::HPFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "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"))] #[allow(missing_docs)] -pub const ISOFS_SUPER_MAGIC: FsType = FsType(libc::ISOFS_SUPER_MAGIC as fs_type_t); +pub const ISOFS_SUPER_MAGIC: FsType = + FsType(libc::ISOFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const JFFS2_SUPER_MAGIC: FsType = FsType(libc::JFFS2_SUPER_MAGIC as fs_type_t); +pub const JFFS2_SUPER_MAGIC: FsType = + FsType(libc::JFFS2_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const MINIX2_SUPER_MAGIC2: FsType = FsType(libc::MINIX2_SUPER_MAGIC2 as fs_type_t); +pub const MINIX2_SUPER_MAGIC2: FsType = + FsType(libc::MINIX2_SUPER_MAGIC2 as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const MINIX2_SUPER_MAGIC: FsType = FsType(libc::MINIX2_SUPER_MAGIC as fs_type_t); +pub const MINIX2_SUPER_MAGIC: FsType = + FsType(libc::MINIX2_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const MINIX3_SUPER_MAGIC: FsType = FsType(libc::MINIX3_SUPER_MAGIC as fs_type_t); +pub const MINIX3_SUPER_MAGIC: FsType = + FsType(libc::MINIX3_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const MINIX_SUPER_MAGIC2: FsType = FsType(libc::MINIX_SUPER_MAGIC2 as fs_type_t); +pub const MINIX_SUPER_MAGIC2: FsType = + FsType(libc::MINIX_SUPER_MAGIC2 as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const MINIX_SUPER_MAGIC: FsType = FsType(libc::MINIX_SUPER_MAGIC as fs_type_t); +pub const MINIX_SUPER_MAGIC: FsType = + FsType(libc::MINIX_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const MSDOS_SUPER_MAGIC: FsType = FsType(libc::MSDOS_SUPER_MAGIC as fs_type_t); +pub const MSDOS_SUPER_MAGIC: FsType = + FsType(libc::MSDOS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const NCP_SUPER_MAGIC: FsType = FsType(libc::NCP_SUPER_MAGIC as fs_type_t); @@ -182,34 +220,44 @@ pub const NCP_SUPER_MAGIC: FsType = FsType(libc::NCP_SUPER_MAGIC as fs_type_t); pub const NFS_SUPER_MAGIC: FsType = FsType(libc::NFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const NILFS_SUPER_MAGIC: FsType = FsType(libc::NILFS_SUPER_MAGIC as fs_type_t); +pub const NILFS_SUPER_MAGIC: FsType = + FsType(libc::NILFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const OCFS2_SUPER_MAGIC: FsType = FsType(libc::OCFS2_SUPER_MAGIC as fs_type_t); +pub const OCFS2_SUPER_MAGIC: FsType = + FsType(libc::OCFS2_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const OPENPROM_SUPER_MAGIC: FsType = FsType(libc::OPENPROM_SUPER_MAGIC as fs_type_t); +pub const OPENPROM_SUPER_MAGIC: FsType = + FsType(libc::OPENPROM_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const OVERLAYFS_SUPER_MAGIC: FsType = FsType(libc::OVERLAYFS_SUPER_MAGIC as fs_type_t); +pub const OVERLAYFS_SUPER_MAGIC: FsType = + FsType(libc::OVERLAYFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const PROC_SUPER_MAGIC: FsType = FsType(libc::PROC_SUPER_MAGIC as fs_type_t); +pub const PROC_SUPER_MAGIC: FsType = + FsType(libc::PROC_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const QNX4_SUPER_MAGIC: FsType = FsType(libc::QNX4_SUPER_MAGIC as fs_type_t); +pub const QNX4_SUPER_MAGIC: FsType = + FsType(libc::QNX4_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const QNX6_SUPER_MAGIC: FsType = FsType(libc::QNX6_SUPER_MAGIC as fs_type_t); +pub const QNX6_SUPER_MAGIC: FsType = + FsType(libc::QNX6_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const RDTGROUP_SUPER_MAGIC: FsType = FsType(libc::RDTGROUP_SUPER_MAGIC as fs_type_t); +pub const RDTGROUP_SUPER_MAGIC: FsType = + FsType(libc::RDTGROUP_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const REISERFS_SUPER_MAGIC: FsType = FsType(libc::REISERFS_SUPER_MAGIC as fs_type_t); +pub const REISERFS_SUPER_MAGIC: FsType = + FsType(libc::REISERFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const SECURITYFS_MAGIC: FsType = FsType(libc::SECURITYFS_MAGIC as fs_type_t); +pub const SECURITYFS_MAGIC: FsType = + FsType(libc::SECURITYFS_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] pub const SELINUX_MAGIC: FsType = FsType(libc::SELINUX_MAGIC as fs_type_t); @@ -233,14 +281,19 @@ pub const TRACEFS_MAGIC: FsType = FsType(libc::TRACEFS_MAGIC as fs_type_t); pub const UDF_SUPER_MAGIC: FsType = FsType(libc::UDF_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const USBDEVICE_SUPER_MAGIC: FsType = FsType(libc::USBDEVICE_SUPER_MAGIC as fs_type_t); +pub const USBDEVICE_SUPER_MAGIC: FsType = + FsType(libc::USBDEVICE_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "android"))] #[allow(missing_docs)] -pub const XENFS_SUPER_MAGIC: FsType = FsType(libc::XENFS_SUPER_MAGIC as fs_type_t); +pub const XENFS_SUPER_MAGIC: FsType = + FsType(libc::XENFS_SUPER_MAGIC as fs_type_t); #[cfg(any(target_os = "linux", target_os = "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( + any(target_os = "linux", target_os = "android"), + not(target_env = "musl") +))] #[allow(missing_docs)] pub const XFS_SUPER_MAGIC: FsType = FsType(libc::XFS_SUPER_MAGIC as fs_type_t); @@ -297,7 +350,14 @@ impl Statfs { } /// Optimal transfer block size - #[cfg(all(target_os = "linux", not(any(target_arch = "s390x", target_env = "musl", target_env = "uclibc"))))] + #[cfg(all( + target_os = "linux", + not(any( + target_arch = "s390x", + target_env = "musl", + target_env = "uclibc" + )) + ))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn optimal_transfer_size(&self) -> libc::__fsword_t { self.0.f_bsize @@ -357,7 +417,14 @@ 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", not(any(target_arch = "s390x", target_env = "musl", target_env = "uclibc"))))] + #[cfg(all( + target_os = "linux", + not(any( + target_arch = "s390x", + target_env = "musl", + target_env = "uclibc" + )) + ))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn block_size(&self) -> libc::__fsword_t { self.0.f_bsize @@ -385,15 +452,18 @@ impl Statfs { } /// Get the mount flags - #[cfg(all(feature = "mount", - any(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd") + #[cfg(all( + feature = "mount", + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) ))] #[cfg_attr(docsrs, doc(cfg(all())))] - #[allow(clippy::unnecessary_cast)] // Not unnecessary on all arches + #[allow(clippy::unnecessary_cast)] // Not unnecessary on all arches pub fn flags(&self) -> MntFlags { MntFlags::from_bits_truncate(self.0.f_flags as i32) } @@ -436,7 +506,14 @@ impl Statfs { } /// Maximum length of filenames - #[cfg(all(target_os = "linux", not(any(target_arch = "s390x", target_env = "musl", target_env = "uclibc"))))] + #[cfg(all( + target_os = "linux", + not(any( + target_arch = "s390x", + target_env = "musl", + target_env = "uclibc" + )) + ))] #[cfg_attr(docsrs, doc(cfg(all())))] pub fn maximum_name_length(&self) -> libc::__fsword_t { self.0.f_namelen @@ -622,16 +699,18 @@ 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(target_os = "dragonfly", - target_os = "freebsd", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd") + #[cfg(all( + feature = "mount", + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ) ))] ds.field("flags", &self.flags()); ds.finish() - } } @@ -646,7 +725,9 @@ impl Debug for Statfs { pub fn statfs<P: ?Sized + NixPath>(path: &P) -> Result<Statfs> { unsafe { let mut stat = mem::MaybeUninit::<type_of_statfs>::uninit(); - let res = path.with_nix_path(|path| LIBC_STATFS(path.as_ptr(), stat.as_mut_ptr()))?; + let res = path.with_nix_path(|path| { + LIBC_STATFS(path.as_ptr(), stat.as_mut_ptr()) + })?; Errno::result(res).map(|_| Statfs(stat.assume_init())) } } diff --git a/src/sys/statvfs.rs b/src/sys/statvfs.rs index 38b1fdcc..8de369f4 100644 --- a/src/sys/statvfs.rs +++ b/src/sys/statvfs.rs @@ -7,7 +7,7 @@ use std::os::unix::io::AsRawFd; use libc::{self, c_ulong}; -use crate::{Result, NixPath, errno::Errno}; +use crate::{errno::Errno, NixPath, Result}; #[cfg(not(target_os = "redox"))] libc_bitflags!( @@ -130,7 +130,6 @@ impl Statvfs { pub fn name_max(&self) -> c_ulong { self.0.f_namemax } - } /// Return a `Statvfs` object with information about the `path` @@ -138,9 +137,9 @@ pub fn statvfs<P: ?Sized + NixPath>(path: &P) -> Result<Statvfs> { unsafe { Errno::clear(); let mut stat = mem::MaybeUninit::<libc::statvfs>::uninit(); - let res = path.with_nix_path(|path| + let res = path.with_nix_path(|path| { libc::statvfs(path.as_ptr(), stat.as_mut_ptr()) - )?; + })?; Errno::result(res).map(|_| Statvfs(stat.assume_init())) } @@ -158,8 +157,8 @@ pub fn fstatvfs<T: AsRawFd>(fd: &T) -> Result<Statvfs> { #[cfg(test)] mod test { - use std::fs::File; use crate::sys::statvfs::*; + use std::fs::File; #[test] fn statvfs_call() { diff --git a/src/sys/termios.rs b/src/sys/termios.rs index 4ff4e674..fba2cd82 100644 --- a/src/sys/termios.rs +++ b/src/sys/termios.rs @@ -85,12 +85,28 @@ //! //! On non-BSDs, `cfgetispeed()` and `cfgetospeed()` both return a `BaudRate`: //! -#![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd"), - doc = " ```rust,ignore")] -#![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust")] +#![cfg_attr( + any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ), + doc = " ```rust,ignore" +)] +#![cfg_attr( + not(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + )), + doc = " ```rust" +)] //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfgetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -102,12 +118,28 @@ //! //! But on the BSDs, `cfgetispeed()` and `cfgetospeed()` both return `u32`s: //! -#![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd"), - doc = " ```rust")] -#![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust,ignore")] +#![cfg_attr( + any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ), + doc = " ```rust" +)] +#![cfg_attr( + not(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + )), + doc = " ```rust,ignore" +)] //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfgetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -119,12 +151,28 @@ //! //! It's trivial to convert from a `BaudRate` to a `u32` on BSDs: //! -#![cfg_attr(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd"), - doc = " ```rust")] -#![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust,ignore")] +#![cfg_attr( + any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ), + doc = " ```rust" +)] +#![cfg_attr( + not(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + )), + doc = " ```rust,ignore" +)] //! # use nix::sys::termios::{BaudRate, cfgetispeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -137,12 +185,28 @@ //! 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", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd"), - doc = " ```rust")] -#![cfg_attr(not(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", - target_os = "macos", target_os = "netbsd", target_os = "openbsd")), - doc = " ```rust,ignore")] +#![cfg_attr( + any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + ), + doc = " ```rust" +)] +#![cfg_attr( + not(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" + )), + doc = " ```rust,ignore" +)] //! # use nix::sys::termios::{cfsetispeed, cfsetospeed, cfsetspeed, Termios}; //! # fn main() { //! # let mut t: Termios = unsafe { std::mem::zeroed() }; @@ -151,9 +215,9 @@ //! cfsetspeed(&mut t, 9600u32); //! # } //! ``` -use cfg_if::cfg_if; -use crate::Result; use crate::errno::Errno; +use crate::Result; +use cfg_if::cfg_if; use libc::{self, c_int, tcflag_t}; use std::cell::{Ref, RefCell}; use std::convert::From; @@ -182,10 +246,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(any(target_os = "linux", target_os = "android",))] pub line_discipline: libc::cc_t, /// Line discipline (see `termios.c_line` documentation) #[cfg(target_os = "haiku")] @@ -287,7 +348,7 @@ impl From<Termios> for libc::termios { } } -libc_enum!{ +libc_enum! { /// Baud rates supported by the system. /// /// For the BSDs, arbitrary baud rates can be specified by using `u32`s directly instead of this @@ -402,12 +463,14 @@ libc_enum!{ impl TryFrom<libc::speed_t> } -#[cfg(any(target_os = "freebsd", - target_os = "dragonfly", - target_os = "ios", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "freebsd", + target_os = "dragonfly", + target_os = "ios", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] impl From<BaudRate> for u32 { fn from(b: BaudRate) -> u32 { b as u32 @@ -421,7 +484,6 @@ impl From<BaudRate> for u8 { } } - // TODO: Add TCSASOFT, which will require treating this as a bitfield. libc_enum! { /// Specify when a port configuration change should occur. @@ -538,21 +600,26 @@ libc_enum! { } } -#[cfg(any(all(target_os = "linux", target_arch = "sparc64"), - target_os = "illumos", target_os = "solaris"))] +#[cfg(any( + all(target_os = "linux", target_arch = "sparc64"), + target_os = "illumos", + target_os = "solaris" +))] impl SpecialCharacterIndices { pub const VMIN: SpecialCharacterIndices = SpecialCharacterIndices::VEOF; pub const VTIME: SpecialCharacterIndices = SpecialCharacterIndices::VEOL; } pub use libc::NCCS; -#[cfg(any(target_os = "android", - target_os = "dragonfly", - target_os = "freebsd", - target_os = "linux", - target_os = "macos", - target_os = "netbsd", - target_os = "openbsd"))] +#[cfg(any( + target_os = "android", + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd" +))] #[cfg_attr(docsrs, doc(cfg(all())))] pub use libc::_POSIX_VDISABLE; @@ -922,7 +989,7 @@ libc_bitflags! { } } -cfg_if!{ +cfg_if! { if #[cfg(any(target_os = "freebsd", target_os = "dragonfly", target_os = "ios", @@ -1094,7 +1161,10 @@ pub fn tcgetattr(fd: RawFd) -> Result<Termios> { /// *any* of the parameters were successfully set, not only if all were set successfully. pub fn tcsetattr(fd: RawFd, actions: SetArg, termios: &Termios) -> Result<()> { let inner_termios = termios.get_libc_termios(); - Errno::result(unsafe { libc::tcsetattr(fd, actions as c_int, &*inner_termios) }).map(drop) + Errno::result(unsafe { + libc::tcsetattr(fd, actions as c_int, &*inner_termios) + }) + .map(drop) } /// Block until all output data is written (see diff --git a/src/sys/timer.rs b/src/sys/timer.rs index dac5e9b5..e1a34051 100644 --- a/src/sys/timer.rs +++ b/src/sys/timer.rs @@ -72,7 +72,8 @@ impl Timer { /// of the signal and its handler are defined by the passed `sigevent`. #[doc(alias("timer_create"))] pub fn new(clockid: ClockId, mut sigevent: SigEvent) -> Result<Self> { - let mut timer_id: mem::MaybeUninit<libc::timer_t> = mem::MaybeUninit::uninit(); + let mut timer_id: mem::MaybeUninit<libc::timer_t> = + mem::MaybeUninit::uninit(); Errno::result(unsafe { libc::timer_create( clockid.as_raw(), @@ -124,7 +125,11 @@ impl Timer { /// Note: Setting a one shot alarm with a 0s TimeSpec disable the alarm /// altogether. #[doc(alias("timer_settime"))] - pub fn set(&mut self, expiration: Expiration, flags: TimerSetTimeFlags) -> Result<()> { + pub fn set( + &mut self, + expiration: Expiration, + flags: TimerSetTimeFlags, + ) -> Result<()> { let timerspec: TimerSpec = expiration.into(); Errno::result(unsafe { libc::timer_settime( @@ -141,7 +146,10 @@ impl Timer { #[doc(alias("timer_gettime"))] pub fn get(&self) -> Result<Option<Expiration>> { let mut timerspec = TimerSpec::none(); - Errno::result(unsafe { libc::timer_gettime(self.0, timerspec.as_mut()) }).map(|_| { + Errno::result(unsafe { + libc::timer_gettime(self.0, timerspec.as_mut()) + }) + .map(|_| { if timerspec.as_ref().it_interval.tv_sec == 0 && timerspec.as_ref().it_interval.tv_nsec == 0 && timerspec.as_ref().it_value.tv_sec == 0 diff --git a/src/sys/timerfd.rs b/src/sys/timerfd.rs index b57d33c3..a35fc927 100644 --- a/src/sys/timerfd.rs +++ b/src/sys/timerfd.rs @@ -94,8 +94,10 @@ impl TimerFd { /// NONBLOCK). The underlying fd will be closed on drop. #[doc(alias("timerfd_create"))] pub fn new(clockid: ClockId, flags: TimerFlags) -> Result<Self> { - Errno::result(unsafe { libc::timerfd_create(clockid as i32, flags.bits()) }) - .map(|fd| Self { fd }) + Errno::result(unsafe { + libc::timerfd_create(clockid as i32, flags.bits()) + }) + .map(|fd| Self { fd }) } /// Sets a new alarm on the timer. @@ -135,7 +137,11 @@ impl TimerFd { /// Note: Setting a one shot alarm with a 0s TimeSpec disables the alarm /// altogether. #[doc(alias("timerfd_settime"))] - pub fn set(&self, expiration: Expiration, flags: TimerSetTimeFlags) -> Result<()> { + pub fn set( + &self, + expiration: Expiration, + flags: TimerSetTimeFlags, + ) -> Result<()> { let timerspec: TimerSpec = expiration.into(); Errno::result(unsafe { libc::timerfd_settime( @@ -152,7 +158,10 @@ impl TimerFd { #[doc(alias("timerfd_gettime"))] pub fn get(&self) -> Result<Option<Expiration>> { let mut timerspec = TimerSpec::none(); - Errno::result(unsafe { libc::timerfd_gettime(self.fd, timerspec.as_mut()) }).map(|_| { + Errno::result(unsafe { + libc::timerfd_gettime(self.fd, timerspec.as_mut()) + }) + .map(|_| { if timerspec.as_ref().it_interval.tv_sec == 0 && timerspec.as_ref().it_interval.tv_nsec == 0 && timerspec.as_ref().it_value.tv_sec == 0 diff --git a/src/sys/uio.rs b/src/sys/uio.rs index 7cddb372..b31c3068 100644 --- a/src/sys/uio.rs +++ b/src/sys/uio.rs @@ -1,8 +1,8 @@ //! Vectored I/O -use crate::Result; use crate::errno::Errno; -use libc::{self, c_int, c_void, size_t, off_t}; +use crate::Result; +use libc::{self, c_int, c_void, off_t, size_t}; use std::io::{IoSlice, IoSliceMut}; use std::marker::PhantomData; use std::os::unix::io::RawFd; @@ -12,13 +12,15 @@ use std::os::unix::io::RawFd; /// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.html) pub fn writev(fd: RawFd, iov: &[IoSlice<'_>]) -> Result<usize> { // SAFETY: to quote the documentation for `IoSlice`: - // - // [IoSlice] is semantically a wrapper around a &[u8], but is + // + // [IoSlice] is semantically a wrapper around a &[u8], but is // guaranteed to be ABI compatible with the iovec type on Unix // platforms. // // Because it is ABI compatible, a pointer cast here is valid - let res = unsafe { libc::writev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; + let res = unsafe { + libc::writev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) + }; Errno::result(res).map(|r| r as usize) } @@ -28,7 +30,9 @@ pub fn writev(fd: RawFd, iov: &[IoSlice<'_>]) -> Result<usize> { /// See also [readv(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/readv.html) pub fn readv(fd: RawFd, iov: &mut [IoSliceMut<'_>]) -> Result<usize> { // SAFETY: same as in writev(), IoSliceMut is ABI-compatible with iovec - let res = unsafe { libc::readv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) }; + let res = unsafe { + libc::readv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int) + }; Errno::result(res).map(|r| r as usize) } @@ -41,15 +45,18 @@ pub fn readv(fd: RawFd, iov: &mut [IoSliceMut<'_>]) -> Result<usize> { /// 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: RawFd, iov: &[IoSlice<'_>], - offset: off_t) -> Result<usize> { - +pub fn pwritev(fd: RawFd, iov: &[IoSlice<'_>], offset: off_t) -> Result<usize> { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t // SAFETY: same as in writev() let res = unsafe { - libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) + libc::pwritev( + fd, + iov.as_ptr() as *const libc::iovec, + iov.len() as c_int, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -64,14 +71,22 @@ pub fn pwritev(fd: RawFd, iov: &[IoSlice<'_>], /// 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())))] -pub fn preadv(fd: RawFd, iov: &mut [IoSliceMut<'_>], - offset: off_t) -> Result<usize> { +pub fn preadv( + fd: RawFd, + iov: &mut [IoSliceMut<'_>], + offset: off_t, +) -> Result<usize> { #[cfg(target_env = "uclibc")] let offset = offset as libc::off64_t; // uclibc doesn't use off_t // SAFETY: same as in readv() let res = unsafe { - libc::preadv(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset) + libc::preadv( + fd, + iov.as_ptr() as *const libc::iovec, + iov.len() as c_int, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -83,8 +98,12 @@ pub fn preadv(fd: RawFd, iov: &mut [IoSliceMut<'_>], // TODO: move to unistd pub fn pwrite(fd: RawFd, buf: &[u8], offset: off_t) -> Result<usize> { let res = unsafe { - libc::pwrite(fd, buf.as_ptr() as *const c_void, buf.len() as size_t, - offset) + libc::pwrite( + fd, + buf.as_ptr() as *const c_void, + buf.len() as size_t, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -94,10 +113,14 @@ pub fn pwrite(fd: RawFd, buf: &[u8], offset: off_t) -> Result<usize> { /// /// See also [pread(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pread.html) // TODO: move to unistd -pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result<usize>{ +pub fn pread(fd: RawFd, buf: &mut [u8], offset: off_t) -> Result<usize> { let res = unsafe { - libc::pread(fd, buf.as_mut_ptr() as *mut c_void, buf.len() as size_t, - offset) + libc::pread( + fd, + buf.as_mut_ptr() as *mut c_void, + buf.len() as size_t, + offset, + ) }; Errno::result(res).map(|r| r as usize) @@ -151,9 +174,7 @@ impl<T> IoVec<T> { use std::slice; unsafe { - slice::from_raw_parts( - self.0.iov_base as *const u8, - self.0.iov_len) + slice::from_raw_parts(self.0.iov_base as *const u8, self.0.iov_len) } } } @@ -161,30 +182,30 @@ impl<T> IoVec<T> { #[allow(deprecated)] impl<'a> IoVec<&'a [u8]> { /// Create an `IoVec` from a Rust slice. - #[deprecated( - since = "0.24.0", - note = "Use `IoSlice::new` instead" - )] + #[deprecated(since = "0.24.0", note = "Use `IoSlice::new` instead")] pub fn from_slice(buf: &'a [u8]) -> IoVec<&'a [u8]> { - IoVec(libc::iovec { - iov_base: buf.as_ptr() as *mut c_void, - iov_len: buf.len() as size_t, - }, PhantomData) + IoVec( + libc::iovec { + iov_base: buf.as_ptr() as *mut c_void, + iov_len: buf.len() as size_t, + }, + PhantomData, + ) } } #[allow(deprecated)] impl<'a> IoVec<&'a mut [u8]> { /// Create an `IoVec` from a mutable Rust slice. - #[deprecated( - since = "0.24.0", - note = "Use `IoSliceMut::new` instead" - )] + #[deprecated(since = "0.24.0", note = "Use `IoSliceMut::new` instead")] pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> { - IoVec(libc::iovec { - iov_base: buf.as_ptr() as *mut c_void, - iov_len: buf.len() as size_t, - }, PhantomData) + IoVec( + libc::iovec { + iov_base: buf.as_ptr() as *mut c_void, + iov_len: buf.len() as size_t, + }, + PhantomData, + ) } } diff --git a/src/sys/utsname.rs b/src/sys/utsname.rs index 0448cb29..b48ed9f4 100644 --- a/src/sys/utsname.rs +++ b/src/sys/utsname.rs @@ -1,9 +1,9 @@ //! Get system identification +use crate::{Errno, Result}; +use libc::c_char; +use std::ffi::OsStr; use std::mem; use std::os::unix::ffi::OsStrExt; -use std::ffi::OsStr; -use libc::c_char; -use crate::{Errno, Result}; /// Describes the running system. Return type of [`uname`]. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] @@ -53,10 +53,12 @@ pub fn uname() -> Result<UtsName> { } fn cast_and_trim(slice: &[c_char]) -> &OsStr { - let length = slice.iter().position(|&byte| byte == 0).unwrap_or(slice.len()); - let bytes = unsafe { - std::slice::from_raw_parts(slice.as_ptr().cast(), length) - }; + let length = slice + .iter() + .position(|&byte| byte == 0) + .unwrap_or(slice.len()); + let bytes = + unsafe { std::slice::from_raw_parts(slice.as_ptr().cast(), length) }; OsStr::from_bytes(bytes) } diff --git a/src/sys/wait.rs b/src/sys/wait.rs index 5fb2075f..b6524e86 100644 --- a/src/sys/wait.rs +++ b/src/sys/wait.rs @@ -135,7 +135,9 @@ impl WaitStatus { pub fn pid(&self) -> Option<Pid> { use self::WaitStatus::*; match *self { - Exited(p, _) | Signaled(p, _, _) | Stopped(p, _) | Continued(p) => Some(p), + Exited(p, _) | Signaled(p, _, _) | Stopped(p, _) | Continued(p) => { + Some(p) + } StillAlive => None, #[cfg(any(target_os = "android", target_os = "linux"))] PtraceEvent(p, _, _) | PtraceSyscall(p) => Some(p), @@ -274,7 +276,9 @@ impl WaitStatus { Signal::try_from(si_status)?, siginfo.si_code == libc::CLD_DUMPED, ), - libc::CLD_STOPPED => WaitStatus::Stopped(pid, Signal::try_from(si_status)?), + libc::CLD_STOPPED => { + WaitStatus::Stopped(pid, Signal::try_from(si_status)?) + } libc::CLD_CONTINUED => WaitStatus::Continued(pid), #[cfg(any(target_os = "android", target_os = "linux"))] libc::CLD_TRAPPED => { @@ -298,7 +302,10 @@ impl WaitStatus { /// Wait for a process to change status /// /// See also [waitpid(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html) -pub fn waitpid<P: Into<Option<Pid>>>(pid: P, options: Option<WaitPidFlag>) -> Result<WaitStatus> { +pub fn waitpid<P: Into<Option<Pid>>>( + pid: P, + options: Option<WaitPidFlag>, +) -> Result<WaitStatus> { use self::WaitStatus::*; let mut status: i32 = 0; diff --git a/src/time.rs b/src/time.rs index 6a385b90..2e03c46c 100644 --- a/src/time.rs +++ b/src/time.rs @@ -85,7 +85,8 @@ impl ClockId { target_os = "linux" ))] #[cfg_attr(docsrs, doc(cfg(all())))] - pub const CLOCK_BOOTTIME_ALARM: ClockId = ClockId(libc::CLOCK_BOOTTIME_ALARM); + 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", @@ -94,13 +95,16 @@ impl ClockId { target_os = "linux" ))] #[cfg_attr(docsrs, doc(cfg(all())))] - pub const CLOCK_MONOTONIC_COARSE: ClockId = ClockId(libc::CLOCK_MONOTONIC_COARSE); + 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); + 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); + pub const CLOCK_MONOTONIC_PRECISE: ClockId = + ClockId(libc::CLOCK_MONOTONIC_PRECISE); #[cfg(any( target_os = "android", target_os = "emscripten", @@ -121,7 +125,8 @@ impl ClockId { target_os = "linux" ))] #[cfg_attr(docsrs, doc(cfg(all())))] - pub const CLOCK_PROCESS_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_PROCESS_CPUTIME_ID); + 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); @@ -133,7 +138,8 @@ impl ClockId { target_os = "linux" ))] #[cfg_attr(docsrs, doc(cfg(all())))] - pub const CLOCK_REALTIME_ALARM: ClockId = ClockId(libc::CLOCK_REALTIME_ALARM); + pub const CLOCK_REALTIME_ALARM: ClockId = + ClockId(libc::CLOCK_REALTIME_ALARM); #[cfg(any( target_os = "android", target_os = "emscripten", @@ -141,13 +147,15 @@ impl ClockId { target_os = "linux" ))] #[cfg_attr(docsrs, doc(cfg(all())))] - pub const CLOCK_REALTIME_COARSE: ClockId = ClockId(libc::CLOCK_REALTIME_COARSE); + 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); + 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); @@ -177,7 +185,8 @@ impl ClockId { target_os = "linux" ))] #[cfg_attr(docsrs, doc(cfg(all())))] - pub const CLOCK_THREAD_CPUTIME_ID: ClockId = ClockId(libc::CLOCK_THREAD_CPUTIME_ID); + 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); @@ -186,7 +195,8 @@ impl ClockId { 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); + 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 +226,8 @@ impl std::fmt::Display for ClockId { #[cfg_attr(docsrs, doc(cfg(all())))] pub fn clock_getres(clock_id: ClockId) -> Result<TimeSpec> { let mut c_time: MaybeUninit<libc::timespec> = MaybeUninit::uninit(); - let ret = unsafe { libc::clock_getres(clock_id.as_raw(), c_time.as_mut_ptr()) }; + let ret = + unsafe { libc::clock_getres(clock_id.as_raw(), c_time.as_mut_ptr()) }; Errno::result(ret)?; let res = unsafe { c_time.assume_init() }; Ok(TimeSpec::from(res)) @@ -226,7 +237,8 @@ pub fn clock_getres(clock_id: ClockId) -> Result<TimeSpec> { /// [clock_gettime(2)](https://pubs.opengroup.org/onlinepubs/7908799/xsh/clock_gettime.html)). pub fn clock_gettime(clock_id: ClockId) -> Result<TimeSpec> { let mut c_time: MaybeUninit<libc::timespec> = MaybeUninit::uninit(); - let ret = unsafe { libc::clock_gettime(clock_id.as_raw(), c_time.as_mut_ptr()) }; + let ret = + unsafe { libc::clock_gettime(clock_id.as_raw(), c_time.as_mut_ptr()) }; Errno::result(ret)?; let res = unsafe { c_time.assume_init() }; Ok(TimeSpec::from(res)) @@ -242,7 +254,8 @@ pub fn clock_gettime(clock_id: ClockId) -> Result<TimeSpec> { )))] #[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()) }; + let ret = + unsafe { libc::clock_settime(clock_id.as_raw(), timespec.as_ref()) }; Errno::result(ret).map(drop) } @@ -259,7 +272,8 @@ pub fn clock_settime(clock_id: ClockId, timespec: TimeSpec) -> Result<()> { #[cfg_attr(docsrs, doc(cfg(feature = "process")))] pub fn clock_getcpuclockid(pid: Pid) -> Result<ClockId> { let mut clk_id: MaybeUninit<libc::clockid_t> = MaybeUninit::uninit(); - let ret = unsafe { libc::clock_getcpuclockid(pid.into(), clk_id.as_mut_ptr()) }; + let ret = + unsafe { libc::clock_getcpuclockid(pid.into(), clk_id.as_mut_ptr()) }; if ret == 0 { let res = unsafe { clk_id.assume_init() }; Ok(ClockId::from(res)) diff --git a/src/ucontext.rs b/src/ucontext.rs index f2338bd4..b2a39f76 100644 --- a/src/ucontext.rs +++ b/src/ucontext.rs @@ -1,10 +1,10 @@ #[cfg(not(target_env = "musl"))] -use crate::Result; -#[cfg(not(target_env = "musl"))] use crate::errno::Errno; +use crate::sys::signal::SigSet; +#[cfg(not(target_env = "musl"))] +use crate::Result; #[cfg(not(target_env = "musl"))] use std::mem; -use crate::sys::signal::SigSet; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct UContext { @@ -17,7 +17,9 @@ impl UContext { let mut context = mem::MaybeUninit::<libc::ucontext_t>::uninit(); let res = unsafe { libc::getcontext(context.as_mut_ptr()) }; Errno::result(res).map(|_| unsafe { - UContext { context: context.assume_init()} + UContext { + context: context.assume_init(), + } }) } @@ -31,13 +33,15 @@ impl UContext { pub fn sigmask_mut(&mut self) -> &mut SigSet { unsafe { - &mut *(&mut self.context.uc_sigmask as *mut libc::sigset_t as *mut SigSet) + &mut *(&mut self.context.uc_sigmask as *mut libc::sigset_t + as *mut SigSet) } } pub fn sigmask(&self) -> &SigSet { unsafe { - &*(&self.context.uc_sigmask as *const libc::sigset_t as *const SigSet) + &*(&self.context.uc_sigmask as *const libc::sigset_t + as *const SigSet) } } } |