From ab3088139a7a48d0b40a8204e2519f38c167811b Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Tue, 26 Nov 2024 09:43:01 -0800 Subject: [PATCH] Format with rustfmt 1.8.0-nightly --- src/unix/apple/macos/component/arm.rs | 7 +- src/unix/apple/macos/ffi.rs | 66 ++++-- src/unix/apple/macos/process.rs | 2 +- src/unix/apple/network.rs | 46 +++- src/unix/apple/system.rs | 5 +- src/unix/freebsd/disk.rs | 50 +++-- src/unix/freebsd/ffi.rs | 2 +- src/unix/freebsd/network.rs | 4 +- src/unix/freebsd/process.rs | 2 +- src/unix/freebsd/system.rs | 3 +- src/unix/linux/disk.rs | 107 +++++---- src/unix/linux/network.rs | 9 +- src/unix/linux/process.rs | 9 +- src/unix/linux/system.rs | 40 ++-- src/unknown/system.rs | 5 +- src/windows/component.rs | 12 +- src/windows/cpu.rs | 9 +- src/windows/network.rs | 8 +- src/windows/process.rs | 2 +- src/windows/sid.rs | 308 +++++++++++++------------- src/windows/system.rs | 4 +- 21 files changed, 418 insertions(+), 282 deletions(-) diff --git a/src/unix/apple/macos/component/arm.rs b/src/unix/apple/macos/component/arm.rs index b06ffaf02..6923e98ce 100644 --- a/src/unix/apple/macos/component/arm.rs +++ b/src/unix/apple/macos/component/arm.rs @@ -111,7 +111,8 @@ impl ComponentsInner { None => continue, }; - let name_ptr = CFStringGetCStringPtr(name.inner() as *const _, kCFStringEncodingUTF8); + let name_ptr = + CFStringGetCStringPtr(name.inner() as *const _, kCFStringEncodingUTF8); if name_ptr.is_null() { continue; } @@ -135,8 +136,8 @@ pub(crate) struct ComponentInner { critical: Option, } -unsafe impl Send for ComponentInner{} -unsafe impl Sync for ComponentInner{} +unsafe impl Send for ComponentInner {} +unsafe impl Sync for ComponentInner {} impl ComponentInner { pub(crate) fn new( diff --git a/src/unix/apple/macos/ffi.rs b/src/unix/apple/macos/ffi.rs index d62339be4..974dc11b6 100644 --- a/src/unix/apple/macos/ffi.rs +++ b/src/unix/apple/macos/ffi.rs @@ -1,19 +1,25 @@ // Take a look at the license at the top of the repository in the LICENSE file. -#[cfg(any(feature = "system", feature = "disk"))] -use core_foundation_sys::base::CFAllocatorRef; #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] use core_foundation_sys::base::mach_port_t; #[cfg(any(feature = "system", feature = "disk"))] +use core_foundation_sys::base::CFAllocatorRef; +#[cfg(any(feature = "system", feature = "disk"))] use core_foundation_sys::dictionary::CFDictionaryRef; #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] use core_foundation_sys::dictionary::CFMutableDictionaryRef; #[cfg(any(feature = "system", feature = "disk"))] @@ -23,7 +29,10 @@ use libc::c_char; #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] use libc::kern_return_t; @@ -32,7 +41,10 @@ use libc::kern_return_t; #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] #[allow(non_camel_case_types)] pub type io_object_t = mach_port_t; @@ -40,7 +52,10 @@ pub type io_object_t = mach_port_t; #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] #[allow(non_camel_case_types)] pub type io_iterator_t = io_object_t; @@ -85,7 +100,10 @@ cfg_if! { #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] pub const kIOMasterPortDefault: mach_port_t = 0; @@ -93,7 +111,10 @@ pub const kIOMasterPortDefault: mach_port_t = 0; #[cfg(any( feature = "system", feature = "disk", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] #[link(name = "IOKit", kind = "framework")] extern "C" { @@ -104,7 +125,10 @@ extern "C" { ) -> kern_return_t; #[cfg(any( feature = "system", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] pub fn IOServiceMatching(a: *const c_char) -> CFMutableDictionaryRef; @@ -134,15 +158,15 @@ extern "C" { #[cfg(feature = "system")] pub fn IORegistryEntryGetName(entry: io_registry_entry_t, name: io_name_t) -> kern_return_t; #[cfg(feature = "disk")] - pub fn IOObjectConformsTo( - object: io_object_t, - className: *const c_char, - ) -> libc::boolean_t; + pub fn IOObjectConformsTo(object: io_object_t, className: *const c_char) -> libc::boolean_t; } #[cfg(any( feature = "system", - all(feature = "component", any(target_arch = "x86", target_arch = "x86_64")), + all( + feature = "component", + any(target_arch = "x86", target_arch = "x86_64") + ), ))] pub const KIO_RETURN_SUCCESS: i32 = 0; @@ -249,7 +273,11 @@ mod io_service {} ))] pub use io_service::*; -#[cfg(all(feature = "component", not(feature = "apple-sandbox"), target_arch = "aarch64"))] +#[cfg(all( + feature = "component", + not(feature = "apple-sandbox"), + target_arch = "aarch64" +))] mod io_service { use std::ptr::null; @@ -368,5 +396,9 @@ mod io_service { } } -#[cfg(all(feature = "component", not(feature = "apple-sandbox"), target_arch = "aarch64"))] +#[cfg(all( + feature = "component", + not(feature = "apple-sandbox"), + target_arch = "aarch64" +))] pub use io_service::*; diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs index e39694299..933fd2163 100644 --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -228,7 +228,7 @@ impl ProcessInner { } pub(crate) fn switch_updated(&mut self) -> bool { - std::mem::replace(&mut self.updated, false) + std::mem::replace(&mut self.updated, false) } } diff --git a/src/unix/apple/network.rs b/src/unix/apple/network.rs index 642642a92..802cde412 100644 --- a/src/unix/apple/network.rs +++ b/src/unix/apple/network.rs @@ -1,9 +1,12 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use libc::{self, c_char, c_int, c_uint, if_data64, if_msghdr2, sysctl, CTL_NET, IFNAMSIZ, NET_RT_IFLIST2, PF_ROUTE, RTM_IFINFO2}; +use libc::{ + self, c_char, c_int, c_uint, if_data64, if_msghdr2, sysctl, CTL_NET, IFNAMSIZ, NET_RT_IFLIST2, + PF_ROUTE, RTM_IFINFO2, +}; use std::collections::{hash_map, HashMap}; -use std::mem::{MaybeUninit, size_of}; +use std::mem::{size_of, MaybeUninit}; use std::ptr::null_mut; use crate::network::refresh_networks_addresses; @@ -38,11 +41,27 @@ fn update_network_data(inner: &mut NetworkDataInner, data: &if_data64) { update_field(&mut inner.old_out, &mut inner.current_out, data.ifi_obytes); update_field(&mut inner.old_in, &mut inner.current_in, data.ifi_ibytes); - update_field(&mut inner.old_packets_out, &mut inner.packets_out, data.ifi_opackets); - update_field(&mut inner.old_packets_in, &mut inner.packets_in, data.ifi_ipackets); - - update_field(&mut inner.old_errors_in, &mut inner.errors_in, data.ifi_ierrors); - update_field(&mut inner.old_errors_out, &mut inner.errors_out, data.ifi_oerrors); + update_field( + &mut inner.old_packets_out, + &mut inner.packets_out, + data.ifi_opackets, + ); + update_field( + &mut inner.old_packets_in, + &mut inner.packets_in, + data.ifi_ipackets, + ); + + update_field( + &mut inner.old_errors_in, + &mut inner.errors_in, + data.ifi_ierrors, + ); + update_field( + &mut inner.old_errors_out, + &mut inner.errors_out, + data.ifi_oerrors, + ); } pub(crate) struct NetworksInner { @@ -83,7 +102,7 @@ impl NetworksInner { NETLINK_GENERIC, IFMIB_IFDATA, 0, - IFDATA_GENERAL + IFDATA_GENERAL, ]; let mut len = 0; @@ -146,7 +165,14 @@ impl NetworksInner { let mut mib_data: MaybeUninit = MaybeUninit::uninit(); mib2[4] = (*if2m).ifm_index as _; - let ret = sysctl(mib2.as_mut_ptr(), mib2.len() as _, mib_data.as_mut_ptr() as *mut _, &mut size_of::(), null_mut(), 0); + let ret = sysctl( + mib2.as_mut_ptr(), + mib2.len() as _, + mib_data.as_mut_ptr() as *mut _, + &mut size_of::(), + null_mut(), + 0, + ); match self.interfaces.entry(name) { hash_map::Entry::Occupied(mut e) => { @@ -198,7 +224,7 @@ impl NetworksInner { packets_out = data.ifi_opackets; errors_in = data.ifi_ierrors; errors_out = data.ifi_oerrors; - } + } e.insert(NetworkData { inner: NetworkDataInner { diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs index d70ef228a..f13fe8554 100644 --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -5,7 +5,10 @@ use crate::sys::cpu::*; use crate::sys::process::*; use crate::sys::utils::{get_sys_value, get_sys_value_by_name}; -use crate::{Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessesToUpdate, ProcessRefreshKind}; +use crate::{ + Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessRefreshKind, + ProcessesToUpdate, +}; #[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] use std::cell::UnsafeCell; diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs index ec841603e..dff7cafec 100644 --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -5,24 +5,18 @@ use std::ffi::{OsStr, OsString}; use std::marker::PhantomData; use std::os::unix::ffi::OsStringExt; use std::path::{Path, PathBuf}; -use std::ptr::{NonNull, null_mut}; +use std::ptr::{null_mut, NonNull}; use std::sync::OnceLock; use libc::c_void; -use crate::{Disk, DiskKind, DiskUsage}; use super::ffi::{ - devstat, - devstat_getversion, - geom_stats_open, - geom_stats_snapshot_get, - geom_stats_snapshot_next, - geom_stats_snapshot_reset, - geom_stats_snapshot_free, - DEVSTAT_READ, + devstat, devstat_getversion, geom_stats_open, geom_stats_snapshot_free, + geom_stats_snapshot_get, geom_stats_snapshot_next, geom_stats_snapshot_reset, DEVSTAT_READ, DEVSTAT_WRITE, }; use super::utils::{c_buf_to_utf8_str, get_sys_value_str_by_name}; +use crate::{Disk, DiskKind, DiskUsage}; #[derive(Debug)] pub(crate) struct DiskInner { @@ -97,7 +91,9 @@ impl crate::DisksInner { } pub(crate) fn refresh_list(&mut self) { - unsafe { get_all_list(&mut self.disks, true); } + unsafe { + get_all_list(&mut self.disks, true); + } } pub(crate) fn list(&self) -> &[Disk] { @@ -109,7 +105,9 @@ impl crate::DisksInner { } pub(crate) fn refresh(&mut self) { - unsafe { get_all_list(&mut self.disks, false); } + unsafe { + get_all_list(&mut self.disks, false); + } } } @@ -200,16 +198,26 @@ unsafe fn initialize_geom() -> Result<(), ()> { unsafe fn refresh_disk_io(disks: &mut [T]) { static GEOM_STATS: OnceLock> = OnceLock::new(); - if GEOM_STATS.get_or_init(|| unsafe { initialize_geom() }).is_err() { + if GEOM_STATS + .get_or_init(|| unsafe { initialize_geom() }) + .is_err() + { return; } - let Some(mut snap) = GeomSnapshot::new() else { return }; + let Some(mut snap) = GeomSnapshot::new() else { + return; + }; for device in snap.iter() { let device = device.devstat.as_ref(); - let Some(device_name) = c_buf_to_utf8_str(&device.device_name) else { continue }; + let Some(device_name) = c_buf_to_utf8_str(&device.device_name) else { + continue; + }; let dev_stat_name = format!("{device_name}{}", device.unit_number); - for disk in disks.iter_mut().filter(|d| d.dev_id().is_some_and(|id| *id == dev_stat_name)) { + for disk in disks + .iter_mut() + .filter(|d| d.dev_id().is_some_and(|id| *id == dev_stat_name)) + { disk.update_old(); *disk.get_read() = device.bytes[DEVSTAT_READ]; *disk.get_written() = device.bytes[DEVSTAT_WRITE]; @@ -256,7 +264,9 @@ unsafe fn refresh_disk_io(disks: &mut [T]) { fn get_disks_mapping() -> HashMap { let mut disk_mapping = HashMap::new(); - let Some(mapping) = get_sys_value_str_by_name(b"kern.geom.conftxt\0") else { return disk_mapping }; + let Some(mapping) = get_sys_value_str_by_name(b"kern.geom.conftxt\0") else { + return disk_mapping; + }; let mut last_id = String::new(); @@ -357,8 +367,8 @@ pub unsafe fn get_all_list(container: &mut Vec, add_new_disks: bool) { let dev_mount_point = c_buf_to_utf8_str(&fs_info.f_mntfromname).unwrap_or(""); // USB keys and CDs are removable. - let is_removable = - [b"USB", b"usb"].iter().any(|b| *b == &fs_type[..]) || fs_type.starts_with(b"/dev/cd"); + let is_removable = [b"USB", b"usb"].iter().any(|b| *b == &fs_type[..]) + || fs_type.starts_with(b"/dev/cd"); container.push(Disk { inner: DiskInner { @@ -478,7 +488,7 @@ impl<'a> Iterator for GeomSnapshotIter<'a> { type Item = Devstat<'a>; fn next(&mut self) -> Option { - let raw = unsafe { geom_stats_snapshot_next(self.0.0.as_mut()) }; + let raw = unsafe { geom_stats_snapshot_next(self.0 .0.as_mut()) }; NonNull::new(raw).map(|devstat| Devstat { devstat, phantom: PhantomData, diff --git a/src/unix/freebsd/ffi.rs b/src/unix/freebsd/ffi.rs index 305ea8d43..dde1a356e 100644 --- a/src/unix/freebsd/ffi.rs +++ b/src/unix/freebsd/ffi.rs @@ -2,7 +2,7 @@ #![allow(non_camel_case_types)] -use libc::{c_char, c_int, c_uint, c_void, bintime, kvm_t}; +use libc::{bintime, c_char, c_int, c_uint, c_void, kvm_t}; // definitions come from: // https://github.com/freebsd/freebsd-src/blob/main/lib/libdevstat/devstat.h diff --git a/src/unix/freebsd/network.rs b/src/unix/freebsd/network.rs index 68ebcd7aa..fa5ae5af0 100644 --- a/src/unix/freebsd/network.rs +++ b/src/unix/freebsd/network.rs @@ -92,7 +92,9 @@ impl NetworksInner { old_and_new!(interface, ifi_opackets, old_ifi_opackets, data); old_and_new!(interface, ifi_ierrors, old_ifi_ierrors, data); old_and_new!(interface, ifi_oerrors, old_ifi_oerrors, data); - if interface.mtu != mtu { interface.mtu = mtu } + if interface.mtu != mtu { + interface.mtu = mtu + } interface.updated = true; } hash_map::Entry::Vacant(e) => { diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs index ac946e70b..d5b9612ef 100644 --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -180,7 +180,7 @@ impl ProcessInner { } pub(crate) fn switch_updated(&mut self) -> bool { - std::mem::replace(&mut self.updated, false) + std::mem::replace(&mut self.updated, false) } } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs index 74ba25c78..32d2b7ff3 100644 --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -1,7 +1,8 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::{ - Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessesToUpdate, ProcessInner, ProcessRefreshKind, + Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessInner, + ProcessRefreshKind, ProcessesToUpdate, }; use std::cell::UnsafeCell; diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs index 7e2a0156c..8d1d41fe9 100644 --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -88,9 +88,13 @@ impl DiskInner { } fn efficient_refresh(&mut self, procfs_disk_stats: &HashMap) -> bool { - let Some((read_bytes, written_bytes)) = procfs_disk_stats - .get(&self.actual_device_name) - .map(|stat| (stat.sectors_read * SECTOR_SIZE, stat.sectors_written * SECTOR_SIZE)) + let Some((read_bytes, written_bytes)) = + procfs_disk_stats.get(&self.actual_device_name).map(|stat| { + ( + stat.sectors_read * SECTOR_SIZE, + stat.sectors_written * SECTOR_SIZE, + ) + }) else { sysinfo_debug!("Failed to update disk i/o stats"); return false; @@ -207,7 +211,12 @@ fn new_disk( let (read_bytes, written_bytes) = procfs_disk_stats .get(&actual_device_name) - .map(|stat| (stat.sectors_read * SECTOR_SIZE, stat.sectors_written * SECTOR_SIZE)) + .map(|stat| { + ( + stat.sectors_read * SECTOR_SIZE, + stat.sectors_written * SECTOR_SIZE, + ) + }) .unwrap_or_default(); Some(Disk { @@ -425,10 +434,13 @@ impl DiskStat { let sectors_read = iter.nth(2).and_then(|v| u64::from_str(v).ok())?; // 10th field let sectors_written = iter.nth(3).and_then(|v| u64::from_str(v).ok())?; - Some((name, Self { - sectors_read, - sectors_written, - })) + Some(( + name, + Self { + sectors_read, + sectors_written, + }, + )) } } @@ -461,7 +473,7 @@ fn disk_stats_inner(content: &str) -> HashMap { #[cfg(test)] mod test { - use super::{DiskStat, disk_stats_inner}; + use super::{disk_stats_inner, DiskStat}; use std::collections::HashMap; #[test] @@ -479,35 +491,56 @@ mod test { let data = disk_stats_inner(file_content); let expected_data: HashMap = HashMap::from([ - ("nvme0n1".to_string(), DiskStat { - sectors_read: 38943220, - sectors_written: 462375378, - }), - ("nvme0n1p1".to_string(), DiskStat { - sectors_read: 15468, - sectors_written: 2, - }), - ("nvme0n1p2".to_string(), DiskStat { - sectors_read: 11626, - sectors_written: 616, - }), - ("nvme0n1p3".to_string(), DiskStat { - sectors_read: 38910302, - sectors_written: 462374760, - }), - ("dm-0".to_string(),DiskStat { - sectors_read: 38909056, - sectors_written: 462374760, - }), - ("zram0".to_string(), DiskStat { - sectors_read: 20984, - sectors_written: 2082088, - }), + ( + "nvme0n1".to_string(), + DiskStat { + sectors_read: 38943220, + sectors_written: 462375378, + }, + ), + ( + "nvme0n1p1".to_string(), + DiskStat { + sectors_read: 15468, + sectors_written: 2, + }, + ), + ( + "nvme0n1p2".to_string(), + DiskStat { + sectors_read: 11626, + sectors_written: 616, + }, + ), + ( + "nvme0n1p3".to_string(), + DiskStat { + sectors_read: 38910302, + sectors_written: 462374760, + }, + ), + ( + "dm-0".to_string(), + DiskStat { + sectors_read: 38909056, + sectors_written: 462374760, + }, + ), + ( + "zram0".to_string(), + DiskStat { + sectors_read: 20984, + sectors_written: 2082088, + }, + ), // This one ensures that we read the correct fields. - ("bla".to_string(), DiskStat { - sectors_read: 6, - sectors_written: 10, - }), + ( + "bla".to_string(), + DiskStat { + sectors_read: 6, + sectors_written: 10, + }, + ), ]); assert_eq!(data, expected_data); diff --git a/src/unix/linux/network.rs b/src/unix/linux/network.rs index 907402246..70613df4b 100644 --- a/src/unix/linux/network.rs +++ b/src/unix/linux/network.rs @@ -79,7 +79,9 @@ fn refresh_networks_list_from_sysfs( old_and_new!(interface, tx_errors, old_tx_errors); // old_and_new!(e, rx_compressed, old_rx_compressed); // old_and_new!(e, tx_compressed, old_tx_compressed); - if interface.mtu != mtu { interface.mtu = mtu } + if interface.mtu != mtu { + interface.mtu = mtu + } interface.updated = true; } hash_map::Entry::Vacant(e) => { @@ -228,7 +230,9 @@ impl NetworkDataInner { // ); let mtu_path = &Path::new("/sys/class/net/").join(path); let mtu = read(mtu_path, "mtu", data); - if self.mtu != mtu { self.mtu = mtu } + if self.mtu != mtu { + self.mtu = mtu + } } pub(crate) fn received(&self) -> u64 { @@ -290,7 +294,6 @@ impl NetworkDataInner { pub(crate) fn mtu(&self) -> u64 { self.mtu } - } #[cfg(test)] diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs index c7c2307be..e14e8427e 100644 --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -18,7 +18,8 @@ use crate::sys::utils::{ get_all_data_from_file, get_all_utf8_data, realpath, PathHandler, PathPush, }; use crate::{ - DiskUsage, Gid, Pid, Process, ProcessesToUpdate, ProcessRefreshKind, ProcessStatus, Signal, ThreadKind, Uid, + DiskUsage, Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, ProcessesToUpdate, Signal, + ThreadKind, Uid, }; use crate::sys::system::remaining_files; @@ -280,7 +281,7 @@ impl ProcessInner { } pub(crate) fn switch_updated(&mut self) -> bool { - std::mem::replace(&mut self.updated, false) + std::mem::replace(&mut self.updated, false) } } @@ -763,8 +764,8 @@ pub(crate) fn refresh_procs( Ok(d) => d, Err(_err) => { sysinfo_debug!("Failed to read folder {path:?}: {_err:?}"); - return 0 - }, + return 0; + } }; let proc_list = Wrap(UnsafeCell::new(proc_list)); diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs index fbe89e593..c696119c0 100644 --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -3,7 +3,10 @@ use crate::sys::cpu::{get_physical_core_count, CpusWrapper}; use crate::sys::process::{compute_cpu_usage, refresh_procs}; use crate::sys::utils::{get_all_utf8_data, to_u64}; -use crate::{Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessesToUpdate, ProcessRefreshKind}; +use crate::{ + Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessRefreshKind, + ProcessesToUpdate, +}; use libc::{self, c_char, sysconf, _SC_CLK_TCK, _SC_HOST_NAME_MAX, _SC_PAGESIZE}; @@ -177,7 +180,8 @@ impl SystemInner { if !refresh_kind.cpu() { return; } - self.cpus.refresh_if_needed(true, CpuRefreshKind::new().with_cpu_usage()); + self.cpus + .refresh_if_needed(true, CpuRefreshKind::new().with_cpu_usage()); if self.cpus.is_empty() { sysinfo_debug!("cannot compute processes CPU usage: no CPU found..."); @@ -525,19 +529,17 @@ where fn read_table_key(filename: &str, target_key: &str, colsep: char) -> Option { if let Ok(content) = get_all_utf8_data(filename, 16_635) { - return content - .split('\n') - .find_map(|line| { - let mut split = line.split(colsep); - let key = split.next()?; - if key != target_key { - return None; - } + return content.split('\n').find_map(|line| { + let mut split = line.split(colsep); + let key = split.next()?; + if key != target_key { + return None; + } - let value = split.next()?; - let value0 = value.trim_start().split(' ').next()?; - u64::from_str(value0).ok() - }); + let value = split.next()?; + let value0 = value.trim_start().split(' ').next()?; + u64::from_str(value0).ok() + }); } None @@ -553,13 +555,13 @@ impl crate::CGroupLimits { // cgroups v2 read_u64("/sys/fs/cgroup/memory.current"), read_u64("/sys/fs/cgroup/memory.max"), - read_table_key("/sys/fs/cgroup/memory.stat", "anon", ' ') + read_table_key("/sys/fs/cgroup/memory.stat", "anon", ' '), ) { let mut limits = Self { total_memory: sys.mem_total, free_memory: sys.mem_free, free_swap: sys.swap_free, - rss: mem_rss + rss: mem_rss, }; limits.total_memory = min(mem_max, sys.mem_total); @@ -574,13 +576,13 @@ impl crate::CGroupLimits { // cgroups v1 read_u64("/sys/fs/cgroup/memory/memory.usage_in_bytes"), read_u64("/sys/fs/cgroup/memory/memory.limit_in_bytes"), - read_table_key("/sys/fs/cgroup/memory/memory.stat", "total_rss", ' ') + read_table_key("/sys/fs/cgroup/memory/memory.stat", "total_rss", ' '), ) { let mut limits = Self { total_memory: sys.mem_total, free_memory: sys.mem_free, free_swap: sys.swap_free, - rss: mem_rss + rss: mem_rss, }; limits.total_memory = min(mem_max, sys.mem_total); @@ -689,9 +691,9 @@ mod test { use super::get_system_info_android; #[cfg(not(target_os = "android"))] use super::get_system_info_linux; - use super::InfoType; use super::read_table; use super::read_table_key; + use super::InfoType; use std::collections::HashMap; use std::io::Write; use tempfile::NamedTempFile; diff --git a/src/unknown/system.rs b/src/unknown/system.rs index c5a81fa82..a6162e2b8 100644 --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -1,6 +1,9 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::{Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessesToUpdate, ProcessRefreshKind}; +use crate::{ + Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessRefreshKind, + ProcessesToUpdate, +}; use std::collections::HashMap; use std::time::Duration; diff --git a/src/windows/component.rs b/src/windows/component.rs index b11a19526..38d43faed 100644 --- a/src/windows/component.rs +++ b/src/windows/component.rs @@ -162,7 +162,9 @@ unsafe fn initialize_security() -> Result<(), ()> { None, EOAC_NONE, None, - ).is_err() { + ) + .is_err() + { sysinfo_debug!("Failed to initialize security"); Err(()) } else { @@ -173,8 +175,12 @@ unsafe fn initialize_security() -> Result<(), ()> { impl Connection { #[allow(clippy::unnecessary_wraps)] fn new() -> Option { - if CONNECTION.with(|x| *x.get_or_init(|| unsafe { initialize_connection() })).is_err() - || SECURITY.get_or_init(|| unsafe { initialize_security() }).is_err() + if CONNECTION + .with(|x| *x.get_or_init(|| unsafe { initialize_connection() })) + .is_err() + || SECURITY + .get_or_init(|| unsafe { initialize_security() }) + .is_err() { return None; } diff --git a/src/windows/cpu.rs b/src/windows/cpu.rs index e84f1b429..861c252c7 100644 --- a/src/windows/cpu.rs +++ b/src/windows/cpu.rs @@ -170,7 +170,14 @@ impl Query { let mut query = 0; unsafe { if force_reload { - PdhEnumObjectsA(PCSTR::null(), PCSTR::null(), PSTR::null(), &mut 0, PERF_DETAIL_NOVICE, TRUE); + PdhEnumObjectsA( + PCSTR::null(), + PCSTR::null(), + PSTR::null(), + &mut 0, + PERF_DETAIL_NOVICE, + TRUE, + ); } if PdhOpenQueryA(PCSTR::null(), 0, &mut query) == ERROR_SUCCESS.0 { let q = InternalQuery { diff --git a/src/windows/network.rs b/src/windows/network.rs index cd059aa7f..c6bc574c1 100644 --- a/src/windows/network.rs +++ b/src/windows/network.rs @@ -116,7 +116,9 @@ impl NetworksInner { ); old_and_new!(interface, errors_in, old_errors_in, ptr.InErrors); old_and_new!(interface, errors_out, old_errors_out, ptr.OutErrors); - if interface.mtu != mtu { interface.mtu = mtu } + if interface.mtu != mtu { + interface.mtu = mtu + } interface.updated = true; } hash_map::Entry::Vacant(e) => { @@ -183,7 +185,9 @@ impl NetworksInner { ); old_and_new!(interface, errors_in, old_errors_in, entry.InErrors); old_and_new!(interface, errors_out, old_errors_out, entry.OutErrors); - if interface.mtu != entry.Mtu as u64 { interface.mtu = entry.Mtu as u64 } + if interface.mtu != entry.Mtu as u64 { + interface.mtu = entry.Mtu as u64 + } } } } diff --git a/src/windows/process.rs b/src/windows/process.rs index e881906b0..373d00e49 100644 --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -445,7 +445,7 @@ impl ProcessInner { } pub(crate) fn switch_updated(&mut self) -> bool { - std::mem::replace(&mut self.updated, false) + std::mem::replace(&mut self.updated, false) } } diff --git a/src/windows/sid.rs b/src/windows/sid.rs index 85c5b4b45..5dc474ab6 100644 --- a/src/windows/sid.rs +++ b/src/windows/sid.rs @@ -1,154 +1,154 @@ -// Take a look at the license at the top of the repository in the LICENSE file. - -use std::{fmt::Display, str::FromStr}; - -use windows::core::{PCWSTR, PWSTR}; -use windows::Win32::Foundation::{LocalFree, ERROR_INSUFFICIENT_BUFFER, HLOCAL, PSID}; -use windows::Win32::Security::Authorization::{ConvertSidToStringSidW, ConvertStringSidToSidW}; -use windows::Win32::Security::{ - CopySid, GetLengthSid, IsValidSid, LookupAccountSidW, SidTypeUnknown, -}; - -use crate::sys::utils::to_utf8_str; - -#[doc = include_str!("../../md_doc/sid.md")] -#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Sid { - sid: Vec, -} - -impl Sid { - /// Creates an `Sid` by making a copy of the given raw SID. - pub(crate) unsafe fn from_psid(psid: PSID) -> Option { - if psid.is_invalid() { - return None; - } - - if !IsValidSid(psid).as_bool() { - return None; - } - - let length = GetLengthSid(psid); - - let mut sid = vec![0; length as usize]; - - if CopySid(length, PSID(sid.as_mut_ptr().cast()), psid).is_err() { - sysinfo_debug!("CopySid failed: {:?}", std::io::Error::last_os_error()); - return None; - } - - // We are making assumptions about the SID internal structure, - // and these only hold if the revision is 1 - // https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid - // Namely: - // 1. SIDs can be compared directly (memcmp). - // 2. Following from this, to hash a SID we can just hash its bytes. - // These are the basis for deriving PartialEq, Eq, and Hash. - // And since we also need PartialOrd and Ord, we might as well derive them - // too. The default implementation will be consistent with Eq, - // and we don't care about the actual order, just that there is one. - // So it should all work out. - // Why bother with this? Because it makes the implementation that - // much simpler :) - assert_eq!(sid[0], 1, "Expected SID revision to be 1"); - - Some(Self { sid }) - } - - /// Retrieves the account name of this SID. - pub(crate) fn account_name(&self) -> Option { - unsafe { - let mut name_len = 0; - let mut domain_len = 0; - let mut name_use = SidTypeUnknown; - - let sid = PSID((self.sid.as_ptr() as *mut u8).cast()); - if let Err(err) = LookupAccountSidW( - PCWSTR::null(), - sid, - PWSTR::null(), - &mut name_len, - PWSTR::null(), - &mut domain_len, - &mut name_use, - ) { - if err.code() != ERROR_INSUFFICIENT_BUFFER.to_hresult() { - sysinfo_debug!("LookupAccountSidW failed: {:?}", err); - return None; - } - } - - let mut name = vec![0; name_len as usize]; - - // Reset length to 0 since we're still passing a NULL pointer - // for the domain. - domain_len = 0; - - if LookupAccountSidW( - PCWSTR::null(), - sid, - PWSTR::from_raw(name.as_mut_ptr()), - &mut name_len, - PWSTR::null(), - &mut domain_len, - &mut name_use, - ) - .is_err() - { - sysinfo_debug!( - "LookupAccountSidW failed: {:?}", - std::io::Error::last_os_error() - ); - return None; - } - - Some(to_utf8_str(PWSTR::from_raw(name.as_mut_ptr()))) - } - } -} - -impl Display for Sid { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - unsafe fn convert_sid_to_string_sid(sid: PSID) -> Option { - let mut string_sid = PWSTR::null(); - if let Err(_err) = ConvertSidToStringSidW(sid, &mut string_sid) { - sysinfo_debug!("ConvertSidToStringSidW failed: {:?}", _err); - return None; - } - let result = to_utf8_str(string_sid); - let _err = LocalFree(HLOCAL(string_sid.0 as _)); - Some(result) - } - - let string_sid = - unsafe { convert_sid_to_string_sid(PSID((self.sid.as_ptr() as *mut u8).cast())) }; - let string_sid = string_sid.ok_or(std::fmt::Error)?; - - write!(f, "{string_sid}") - } -} - -impl FromStr for Sid { - type Err = String; - - fn from_str(s: &str) -> Result { - unsafe { - let mut string_sid: Vec = s.encode_utf16().collect(); - string_sid.push(0); - - let mut psid = PSID::default(); - if let Err(err) = - ConvertStringSidToSidW(PCWSTR::from_raw(string_sid.as_ptr()), &mut psid) - { - return Err(format!("ConvertStringSidToSidW failed: {:?}", err)); - } - let sid = Self::from_psid(psid); - let _err = LocalFree(HLOCAL(psid.0 as _)); - - // Unwrapping because ConvertStringSidToSidW should've performed - // all the necessary validations. If it returned an invalid SID, - // we better fail fast. - Ok(sid.unwrap()) - } - } -} +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::{fmt::Display, str::FromStr}; + +use windows::core::{PCWSTR, PWSTR}; +use windows::Win32::Foundation::{LocalFree, ERROR_INSUFFICIENT_BUFFER, HLOCAL, PSID}; +use windows::Win32::Security::Authorization::{ConvertSidToStringSidW, ConvertStringSidToSidW}; +use windows::Win32::Security::{ + CopySid, GetLengthSid, IsValidSid, LookupAccountSidW, SidTypeUnknown, +}; + +use crate::sys::utils::to_utf8_str; + +#[doc = include_str!("../../md_doc/sid.md")] +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Sid { + sid: Vec, +} + +impl Sid { + /// Creates an `Sid` by making a copy of the given raw SID. + pub(crate) unsafe fn from_psid(psid: PSID) -> Option { + if psid.is_invalid() { + return None; + } + + if !IsValidSid(psid).as_bool() { + return None; + } + + let length = GetLengthSid(psid); + + let mut sid = vec![0; length as usize]; + + if CopySid(length, PSID(sid.as_mut_ptr().cast()), psid).is_err() { + sysinfo_debug!("CopySid failed: {:?}", std::io::Error::last_os_error()); + return None; + } + + // We are making assumptions about the SID internal structure, + // and these only hold if the revision is 1 + // https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-sid + // Namely: + // 1. SIDs can be compared directly (memcmp). + // 2. Following from this, to hash a SID we can just hash its bytes. + // These are the basis for deriving PartialEq, Eq, and Hash. + // And since we also need PartialOrd and Ord, we might as well derive them + // too. The default implementation will be consistent with Eq, + // and we don't care about the actual order, just that there is one. + // So it should all work out. + // Why bother with this? Because it makes the implementation that + // much simpler :) + assert_eq!(sid[0], 1, "Expected SID revision to be 1"); + + Some(Self { sid }) + } + + /// Retrieves the account name of this SID. + pub(crate) fn account_name(&self) -> Option { + unsafe { + let mut name_len = 0; + let mut domain_len = 0; + let mut name_use = SidTypeUnknown; + + let sid = PSID((self.sid.as_ptr() as *mut u8).cast()); + if let Err(err) = LookupAccountSidW( + PCWSTR::null(), + sid, + PWSTR::null(), + &mut name_len, + PWSTR::null(), + &mut domain_len, + &mut name_use, + ) { + if err.code() != ERROR_INSUFFICIENT_BUFFER.to_hresult() { + sysinfo_debug!("LookupAccountSidW failed: {:?}", err); + return None; + } + } + + let mut name = vec![0; name_len as usize]; + + // Reset length to 0 since we're still passing a NULL pointer + // for the domain. + domain_len = 0; + + if LookupAccountSidW( + PCWSTR::null(), + sid, + PWSTR::from_raw(name.as_mut_ptr()), + &mut name_len, + PWSTR::null(), + &mut domain_len, + &mut name_use, + ) + .is_err() + { + sysinfo_debug!( + "LookupAccountSidW failed: {:?}", + std::io::Error::last_os_error() + ); + return None; + } + + Some(to_utf8_str(PWSTR::from_raw(name.as_mut_ptr()))) + } + } +} + +impl Display for Sid { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + unsafe fn convert_sid_to_string_sid(sid: PSID) -> Option { + let mut string_sid = PWSTR::null(); + if let Err(_err) = ConvertSidToStringSidW(sid, &mut string_sid) { + sysinfo_debug!("ConvertSidToStringSidW failed: {:?}", _err); + return None; + } + let result = to_utf8_str(string_sid); + let _err = LocalFree(HLOCAL(string_sid.0 as _)); + Some(result) + } + + let string_sid = + unsafe { convert_sid_to_string_sid(PSID((self.sid.as_ptr() as *mut u8).cast())) }; + let string_sid = string_sid.ok_or(std::fmt::Error)?; + + write!(f, "{string_sid}") + } +} + +impl FromStr for Sid { + type Err = String; + + fn from_str(s: &str) -> Result { + unsafe { + let mut string_sid: Vec = s.encode_utf16().collect(); + string_sid.push(0); + + let mut psid = PSID::default(); + if let Err(err) = + ConvertStringSidToSidW(PCWSTR::from_raw(string_sid.as_ptr()), &mut psid) + { + return Err(format!("ConvertStringSidToSidW failed: {:?}", err)); + } + let sid = Self::from_psid(psid); + let _err = LocalFree(HLOCAL(psid.0 as _)); + + // Unwrapping because ConvertStringSidToSidW should've performed + // all the necessary validations. If it returned an invalid SID, + // we better fail fast. + Ok(sid.unwrap()) + } + } +} diff --git a/src/windows/system.rs b/src/windows/system.rs index 0492de7b2..71a358cc8 100644 --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -1,6 +1,8 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::{Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, ProcessesToUpdate, ProcessRefreshKind}; +use crate::{ + Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, ProcessRefreshKind, ProcessesToUpdate, +}; use crate::sys::cpu::*; use crate::{Process, ProcessInner};