created_at
stringlengths
20
20
test_patch
stringlengths
226
26.3k
issue_numbers
listlengths
1
1
instance_id
stringlengths
26
28
repo
stringclasses
1 value
patch
stringlengths
441
162k
base_commit
stringlengths
40
40
problem_statement
stringlengths
24
3.57k
version
stringlengths
3
4
pull_number
int64
51
1.41k
hints_text
stringlengths
0
9.55k
environment_setup_commit
stringlengths
40
40
2021-01-05T21:40:46Z
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -57,7 +57,7 @@ jobs: - { os: 'ubuntu-latest', target: 'arm-unknown-linux-gnueabihf', cross: true } - { os: 'ubuntu-latest', target: 'arm-unknown-linux-musleabihf', cross: true } toolchain: - - "1.42.0" # minimum supported rust version + - "1.45.0" # minimum supported rust version - stable - beta - nightly diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -88,7 +88,7 @@ jobs: - macos-latest - windows-latest toolchain: - - "1.42.0" # minimum supported rust version + - "1.45.0" # minimum supported rust version - stable - beta - nightly diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -209,6 +209,19 @@ mod test { let s = ::System::new_all(); assert!(s.get_users().len() >= MIN_USERS); } + + #[test] + fn check_system_info() { + // We don't want to test on unknown systems. + if MIN_USERS > 0 { + let s = ::System::new(); + assert!(!s.get_name().expect("Failed to get system name").is_empty()); + assert!(!s + .get_version() + .expect("Failed to get system version") + .is_empty()); + } + } } // Used to check that System is Send and Sync.
[ "187" ]
GuillaumeGomez__sysinfo-385
GuillaumeGomez/sysinfo
diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -503,6 +503,14 @@ impl SystemExt for System { fn get_users(&self) -> &[User] { &self.users } + + fn get_name(&self) -> Option<String> { + get_system_info("NAME=") + } + + fn get_version(&self) -> Option<String> { + get_system_info("VERSION_ID=") + } } impl Default for System { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -734,6 +742,19 @@ fn get_exe_name(p: &Process) -> String { .unwrap_or_else(String::new) } +fn get_system_info(info: &str) -> Option<String> { + let buf = BufReader::new(File::open("/etc/os-release").ok()?); + + for line in buf.lines() { + if let Ok(line) = line { + if let Some(stripped) = line.strip_prefix(info) { + return Some(stripped.replace("\"", "")); + } + } + } + None +} + fn _get_process_data( path: &Path, proc_list: &mut Process, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -410,6 +410,14 @@ impl SystemExt for System { fn get_boot_time(&self) -> u64 { self.boot_time } + + fn get_name(&self) -> Option<String> { + get_system_info(libc::KERN_OSTYPE, Some("Darwin")) + } + + fn get_version(&self) -> Option<String> { + get_system_info(libc::KERN_OSRELEASE, None) + } } impl Default for System { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -492,3 +500,28 @@ pub(crate) unsafe fn get_sys_value( 0, ) == 0 } + +fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> { + let len = 256; + let mut mib: [c_int; 2] = [libc::CTL_KERN, value]; + let mut buf: Vec<u8> = Vec::with_capacity(len); + let mut size = len; + if unsafe { + libc::sysctl( + mib.as_mut_ptr(), + 2, + buf.as_mut_ptr() as _, + &mut size, + ::std::ptr::null_mut(), + 0, + ) + } == -1 + { + default.map(|s| s.to_owned()) + } else { + unsafe { + buf.set_len(size); + } + String::from_utf8(buf).ok() + } +} diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -934,6 +934,30 @@ pub trait SystemExt: Sized + Debug + Default { /// ); /// ``` fn get_load_average(&self) -> LoadAvg; + + /// Returns the system name. + /// + /// **Important**: this information is computed every time this function is called. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new(); + /// println!("OS: {:?}", s.get_name()); + /// ``` + fn get_name(&self) -> Option<String>; + + /// Returns the system version. + /// + /// **Important**: this information is computed every time this function is called. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new(); + /// println!("OS version: {:?}", s.get_version()); + /// ``` + fn get_version(&self) -> Option<String>; } /// Getting volume of received and transmitted data. diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -139,6 +139,14 @@ impl SystemExt for System { fn get_users(&self) -> &[User] { &[] } + + fn get_name(&self) -> Option<String> { + None + } + + fn get_version(&self) -> Option<String> { + None + } } impl Default for System { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -11,7 +11,7 @@ use sys::users::get_users; use std::cell::UnsafeCell; use std::collections::HashMap; -use std::mem::{size_of, zeroed}; +use std::mem::{size_of, zeroed, MaybeUninit}; use std::time::SystemTime; use LoadAvg; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -32,13 +32,13 @@ use ntapi::ntexapi::{ NtQuerySystemInformation, SystemProcessInformation, SYSTEM_PROCESS_INFORMATION, }; use rayon::prelude::*; -use winapi::shared::minwindef::FALSE; +use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::{PVOID, ULONG}; use winapi::shared::ntstatus::STATUS_INFO_LENGTH_MISMATCH; use winapi::um::minwinbase::STILL_ACTIVE; use winapi::um::processthreadsapi::GetExitCodeProcess; -use winapi::um::sysinfoapi::{GetTickCount64, GlobalMemoryStatusEx, MEMORYSTATUSEX}; -use winapi::um::winnt::HANDLE; +use winapi::um::sysinfoapi::{GetTickCount64, GetVersionExW, GlobalMemoryStatusEx, MEMORYSTATUSEX}; +use winapi::um::winnt::{HANDLE, OSVERSIONINFOW}; /// Struct containing the system's information. pub struct System { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -386,6 +386,14 @@ impl SystemExt for System { fn get_load_average(&self) -> LoadAvg { get_load_average() } + + fn get_name(&self) -> Option<String> { + Some("Windows".to_owned()) + } + + fn get_version(&self) -> Option<String> { + get_system_version() + } } impl Default for System { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -440,3 +448,16 @@ pub(crate) fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: String::from_utf16_lossy(slice) } } + +fn get_system_version() -> Option<String> { + let mut info: OSVERSIONINFOW = unsafe { MaybeUninit::zeroed().assume_init() }; + info.dwOSVersionInfoSize = size_of::<OSVERSIONINFOW>() as _; + if unsafe { GetVersionExW(&mut info) } == TRUE { + Some(format!( + "{}.{}.{}", + info.dwMajorVersion, info.dwMinorVersion, info.dwBuildNumber + )) + } else { + None + } +}
5341d2e5229a5d81a6acf1bb1f0d43bb15d8e48c
Add system version and/or OS name
0.15
385
The [`whoami` crate](https://crates.io/crates/whoami) has been really useful for this. It offers: * `whoami::platform()` - a serialisable enum for platform, such as `Linux`, `MacOS`, `Windows `, etc * `whoami::os()` - a string representation of the OS version, such as `Mac OS X 10.15.3 19D76` I tend to prefer implementing things myself as it allows me to discover how things work. It also allows me to control my dependency tree to prevent it getting too big as I want this crate to remain as small as possible in term of compilation time. I'll take a look to the crate though and might ask the owner a few questions. :) Thanks a lot for bringing it to my attention!
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
2020-12-27T22:17:38Z
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -101,7 +101,13 @@ jobs: toolchain: ${{ matrix.toolchain }} override: true - - name: Execute tests + - name: Execute tests (not mac) run: cargo test + if: matrix.os != 'macos-latest' + env: + RUST_BACKTRACE: full + - name: Execute tests (mac) + run: cargo test -- --test-threads 1 + if: matrix.os == 'macos-latest' env: RUST_BACKTRACE: full diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -81,6 +81,7 @@ cfg_if! { if #[cfg(any(target_os = "macos", target_os = "ios"))] { mod mac; use mac as sys; + extern crate core_foundation; #[cfg(test)] const MIN_USERS: usize = 1;
[ "375" ]
GuillaumeGomez__sysinfo-377
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -14,7 +14,7 @@ build = "build.rs" [dependencies] cfg-if = "0.1" -rayon = "^1.0" +rayon = "^1.5" doc-comment = "0.3" once_cell = "1.0" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,12 @@ ntapi = "0.3" [target.'cfg(not(any(target_os = "unknown", target_arch = "wasm32")))'.dependencies] libc = "0.2" +[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] +core-foundation = "0.9" + +[target.'cfg(any(target_os = "macos", target_os = "ios"))'.build-dependencies] +cc = "1.0" + [lib] name = "sysinfo" crate_type = ["rlib", "cdylib"] diff --git a/build.rs b/build.rs --- a/build.rs +++ b/build.rs @@ -1,7 +1,14 @@ +#[cfg(any(target_os = "macos", target_os = "ios"))] +extern crate cc; + +#[cfg(any(target_os = "macos", target_os = "ios"))] fn main() { - if std::env::var("TARGET").unwrap().contains("-apple") { - println!("cargo:rustc-link-lib=framework=IOKit"); - println!("cargo:rustc-link-lib=framework=CoreFoundation"); - // println!("cargo:rustc-link-lib=framework=OpenDirectory"); - } + cc::Build::new().file("src/mac/disk.m").compile("disk"); + println!("cargo:rustc-link-lib=framework=IOKit"); + println!("cargo:rustc-link-lib=framework=CoreFoundation"); + println!("cargo:rustc-link-lib=framework=Foundation"); + println!("cargo:rustc-link-lib=framework=DiskArbitration"); } + +#[cfg(not(any(target_os = "macos", target_os = "ios")))] +fn main() {} diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -253,6 +253,8 @@ pub enum DiskType { HDD, /// SSD type. SSD, + /// Removable disk. + Removable, /// Unknown type. Unknown(isize), } diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -57,7 +57,10 @@ impl fmt::Debug for Disk { fmt, "Disk({:?})[FS: {:?}][Type: {:?}] mounted on {:?}: {}/{} B", self.get_name(), - self.get_file_system(), + self.get_file_system() + .iter() + .map(|c| *c as char) + .collect::<Vec<_>>(), self.get_type(), self.get_mount_point(), self.get_available_space(), diff --git /dev/null b/src/mac/disk.m new file mode 100644 --- /dev/null +++ b/src/mac/disk.m @@ -0,0 +1,6 @@ +#import <AppKit/AppKit.h> +#import <Foundation/NSFileManager.h> + +CFArrayRef macos_get_disks() { + return (__bridge CFArrayRef)[[NSFileManager defaultManager] mountedVolumeURLsIncludingResourceValuesForKeys:nil options:0]; +} diff --git a/src/mac/disk.rs b/src/mac/disk.rs --- a/src/mac/disk.rs +++ b/src/mac/disk.rs @@ -4,17 +4,18 @@ // Copyright (c) 2017 Guillaume Gomez // -use utils; +use sys::utils; +use utils::to_cpath; use DiskExt; use DiskType; -use libc::{c_char, c_void, statfs}; -use std::collections::HashMap; +use core_foundation::boolean as cfb; +use core_foundation::string as cfs; +use core_foundation::url::{CFURLGetFileSystemRepresentation, CFURLRef}; +use libc::{c_char, c_void, statfs, strlen, PATH_MAX}; use std::ffi::{OsStr, OsString}; -use std::fs; use std::mem; -use std::mem::MaybeUninit; -use std::os::unix::ffi::OsStringExt; +use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::ptr; use sys::ffi; diff --git a/src/mac/disk.rs b/src/mac/disk.rs --- a/src/mac/disk.rs +++ b/src/mac/disk.rs @@ -57,7 +58,7 @@ impl DiskExt for Disk { fn refresh(&mut self) -> bool { unsafe { let mut stat: statfs = mem::zeroed(); - let mount_point_cpath = utils::to_cpath(&self.mount_point); + let mount_point_cpath = to_cpath(&self.mount_point); if statfs(mount_point_cpath.as_ptr() as *const i8, &mut stat) == 0 { self.available_space = u64::from(stat.f_bsize) * stat.f_bavail; true diff --git a/src/mac/disk.rs b/src/mac/disk.rs --- a/src/mac/disk.rs +++ b/src/mac/disk.rs @@ -68,115 +69,116 @@ impl DiskExt for Disk { } } -static DISK_TYPES: once_cell::sync::Lazy<HashMap<OsString, DiskType>> = - once_cell::sync::Lazy::new(get_disk_types); - -fn get_disk_types() -> HashMap<OsString, DiskType> { - let mut master_port: ffi::mach_port_t = 0; - let mut media_iterator: ffi::io_iterator_t = 0; - let mut ret = HashMap::with_capacity(1); - - unsafe { - ffi::IOMasterPort(ffi::MACH_PORT_NULL, &mut master_port); - - let matching_dictionary = ffi::IOServiceMatching(b"IOMedia\0".as_ptr() as *const i8); - let result = ffi::IOServiceGetMatchingServices( - master_port, - matching_dictionary, - &mut media_iterator, - ); - if result != ffi::KERN_SUCCESS as i32 { - sysinfo_debug!("Error: IOServiceGetMatchingServices() = {}", result); - return ret; - } - - loop { - let next_media = ffi::IOIteratorNext(media_iterator); - if next_media == 0 { - break; - } - let mut props = MaybeUninit::<ffi::CFMutableDictionaryRef>::uninit(); - let result = ffi::IORegistryEntryCreateCFProperties( - next_media, - props.as_mut_ptr(), - ffi::kCFAllocatorDefault, - 0, - ); - let props = props.assume_init(); - if result == ffi::KERN_SUCCESS as i32 && check_value(props, b"Whole\0") { - let mut name: ffi::io_name_t = mem::zeroed(); - if ffi::IORegistryEntryGetName(next_media, name.as_mut_ptr() as *mut c_char) - == ffi::KERN_SUCCESS as i32 - { - ret.insert( - make_name(&name), - if check_value(props, b"RAID\0") { - DiskType::Unknown(-1) - } else { - DiskType::SSD - }, - ); - } - ffi::CFRelease(props as *mut _); - } - ffi::IOObjectRelease(next_media); - } - ffi::IOObjectRelease(media_iterator); +unsafe fn to_path(url: CFURLRef) -> Option<PathBuf> { + let mut buf = [0u8; PATH_MAX as usize]; + let result = + CFURLGetFileSystemRepresentation(url, true as u8, buf.as_mut_ptr(), buf.len() as _); + if result == false as u8 { + return None; } - ret + let len = strlen(buf.as_ptr() as *const c_char); + let path = OsStr::from_bytes(&buf[0..len]); + Some(PathBuf::from(path)) } -fn make_name(v: &[u8]) -> OsString { - for (pos, x) in v.iter().enumerate() { - if *x == 0 { - return OsStringExt::from_vec(v[0..pos].to_vec()); - } +pub(crate) fn get_disks(session: ffi::DASessionRef) -> Vec<Disk> { + if session.is_null() { + return Vec::new(); } - OsStringExt::from_vec(v.to_vec()) -} - -pub(crate) fn get_disks() -> Vec<Disk> { - match fs::read_dir("/Volumes") { - Ok(d) => d - .flat_map(|x| { - if let Ok(ref entry) = x { - let mount_point = utils::realpath(&entry.path()); - if mount_point.as_os_str().is_empty() { - None + let arr = unsafe { ffi::macos_get_disks() }; + if arr.is_null() { + return Vec::new(); + } + let mut disks = Vec::new(); + for i in 0..unsafe { ffi::CFArrayGetCount(arr) } { + let url = unsafe { ffi::CFArrayGetValueAtIndex(arr, i) } as CFURLRef; + if url.is_null() { + continue; + } + if let Some(mount_point) = unsafe { to_path(url) } { + unsafe { + let disk = ffi::DADiskCreateFromVolumePath(ffi::kCFAllocatorDefault, session, url); + let dict = ffi::DADiskCopyDescription(disk); + if !dict.is_null() { + // Keeping this around in case one might want the list of the available + // keys in "dict". + // ::core_foundation::base::CFShow(dict as _); + let name = match get_str_value(dict, b"DAMediaName\0").map(OsString::from) { + Some(n) => n, + None => continue, + }; + let removable = get_bool_value(dict, b"DAMediaRemovable\0").unwrap_or(false); + let ejectable = get_bool_value(dict, b"DAMediaEjectable\0").unwrap_or(false); + // This is very hackish but still better than nothing... + let type_ = if let Some(model) = get_str_value(dict, b"DADeviceModel\0") { + if model.contains("SSD") { + DiskType::SSD + } else if removable || ejectable { + DiskType::Removable + } else { + // We just assume by default that this is a HDD + DiskType::HDD + } + } else if removable || ejectable { + DiskType::Removable } else { - let name = entry.path().file_name()?.to_owned(); - let type_ = DISK_TYPES - .get(&name) - .cloned() - .unwrap_or(DiskType::Unknown(-2)); - new_disk(name, &mount_point, type_) + DiskType::Unknown(-1) + }; + + if let Some(disk) = new_disk(name, mount_point, type_) { + disks.push(disk); } - } else { - None + ffi::CFRelease(dict as *const c_void); } - }) - .collect(), - _ => Vec::new(), + } + } } + unsafe { + ffi::CFRelease(arr as *const c_void); + } + disks } -unsafe fn check_value(dict: ffi::CFMutableDictionaryRef, key: &[u8]) -> bool { +unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( + dict: ffi::CFDictionaryRef, + key: &[u8], + callback: F, +) -> Option<T> { let key = ffi::CFStringCreateWithCStringNoCopy( ptr::null_mut(), key.as_ptr() as *const c_char, ffi::kCFStringEncodingMacRoman, ffi::kCFAllocatorNull as *mut c_void, ); - let ret = ffi::CFDictionaryContainsKey(dict as ffi::CFDictionaryRef, key as *const c_void) != 0 - && *(ffi::CFDictionaryGetValue(dict as ffi::CFDictionaryRef, key as *const c_void) - as *const ffi::Boolean) - != 0; + let mut value = ::std::ptr::null(); + let ret = if ffi::CFDictionaryGetValueIfPresent(dict, key as _, &mut value) != 0 { + callback(value) + } else { + None + }; ffi::CFRelease(key as *const c_void); ret } -fn new_disk(name: OsString, mount_point: &Path, type_: DiskType) -> Option<Disk> { - let mount_point_cpath = utils::to_cpath(mount_point); +unsafe fn get_str_value(dict: ffi::CFDictionaryRef, key: &[u8]) -> Option<String> { + get_dict_value(dict, key, |v| { + let v = v as cfs::CFStringRef; + let len = cfs::CFStringGetLength(v); + utils::cstr_to_rust_with_size( + cfs::CFStringGetCStringPtr(v, cfs::kCFStringEncodingUTF8), + Some(len as _), + ) + }) +} + +unsafe fn get_bool_value(dict: ffi::CFDictionaryRef, key: &[u8]) -> Option<bool> { + get_dict_value(dict, key, |v| { + Some(v as cfb::CFBooleanRef == cfb::kCFBooleanTrue) + }) +} + +fn new_disk(name: OsString, mount_point: PathBuf, type_: DiskType) -> Option<Disk> { + let mount_point_cpath = to_cpath(&mount_point); let mut total_space = 0; let mut available_space = 0; let mut file_system = None; diff --git a/src/mac/disk.rs b/src/mac/disk.rs --- a/src/mac/disk.rs +++ b/src/mac/disk.rs @@ -202,7 +204,7 @@ fn new_disk(name: OsString, mount_point: &Path, type_: DiskType) -> Option<Disk> type_, name, file_system: file_system.unwrap_or_else(|| b"<Unknown>".to_vec()), - mount_point: mount_point.to_owned(), + mount_point, total_space, available_space, }) diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -4,7 +4,8 @@ // Copyright (c) 2015 Guillaume Gomez // -use libc::{c_char, c_int, c_uchar, c_uint, c_ushort, c_void, size_t}; +use core_foundation::url::CFURLRef; +use libc::{c_char, c_int, c_long, c_uchar, c_uint, c_ushort, c_void, size_t}; extern "C" { // #[no_mangle] diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -51,15 +52,20 @@ extern "C" { outputStruct: *mut KeyData_t, outputStructCnt: *mut size_t, ) -> i32; - pub fn IORegistryEntryCreateCFProperties( - entry: io_registry_entry_t, - properties: *mut CFMutableDictionaryRef, - allocator: CFAllocatorRef, - options: IOOptionBits, - ) -> kern_return_t; - pub fn CFDictionaryContainsKey(d: CFDictionaryRef, key: *const c_void) -> Boolean; - pub fn CFDictionaryGetValue(d: CFDictionaryRef, key: *const c_void) -> *const c_void; - pub fn IORegistryEntryGetName(entry: io_registry_entry_t, name: *mut c_char) -> kern_return_t; + // pub fn IORegistryEntryCreateCFProperties( + // entry: io_registry_entry_t, + // properties: *mut CFMutableDictionaryRef, + // allocator: CFAllocatorRef, + // options: IOOptionBits, + // ) -> kern_return_t; + pub fn CFDictionaryGetValueIfPresent( + d: CFDictionaryRef, + key: *const c_void, + value: *mut *const c_void, + ) -> Boolean; + // pub fn CFDictionaryContainsKey(d: CFDictionaryRef, key: *const c_void) -> Boolean; + // pub fn CFDictionaryGetValue(d: CFDictionaryRef, key: *const c_void) -> *const c_void; + // pub fn IORegistryEntryGetName(entry: io_registry_entry_t, name: *mut c_char) -> kern_return_t; pub fn CFRelease(cf: CFTypeRef); pub fn CFStringCreateWithCStringNoCopy( alloc: *mut c_void, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -93,8 +99,8 @@ extern "C" { // maxResults: CFIndex, // error: *mut CFErrorRef, // ) -> ODQueryRef; - // pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; - // pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; + pub fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; + pub fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; // pub fn ODRecordGetRecordName(record: ODRecordRef) -> CFStringRef; pub fn mach_absolute_time() -> u64; diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -120,6 +126,19 @@ extern "C" { // pub fn proc_pidpath(pid: i32, buf: *mut i8, bufsize: u32) -> i32; // pub fn proc_name(pid: i32, buf: *mut i8, bufsize: u32) -> i32; pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> kern_return_t; + pub fn DASessionCreate(allocator: CFAllocatorRef) -> DASessionRef; + // pub fn NSFileManagerMountedVolumeURLsIncludingResourceValuesForKeys( + // propertyKeys: *mut c_void, + // options: usize, + // ) -> CFArrayRef; + pub fn macos_get_disks() -> CFArrayRef; + pub fn DADiskCreateFromVolumePath( + allocator: CFAllocatorRef, + session: DASessionRef, + path: CFURLRef, + ) -> DADiskRef; + // pub fn DADiskGetBSDName(disk: DADiskRef) -> *const c_char; + pub fn DADiskCopyDescription(disk: DADiskRef) -> CFMutableDictionaryRef; } // TODO: waiting for https://github.com/rust-lang/libc/pull/678 diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -264,19 +283,32 @@ pub struct __ODQuery { __private: c_void, } +#[cfg_attr(feature = "debug", derive(Debug))] +#[repr(C)] +pub struct __NSArray { + __private: c_void, +} +#[repr(C)] +pub struct __DADisk(c_void); +#[repr(C)] +pub struct __DASession(c_void); + pub type CFAllocatorRef = *const __CFAllocator; pub type CFMutableDictionaryRef = *mut __CFDictionary; pub type CFDictionaryRef = *const __CFDictionary; -#[allow(non_camel_case_types)] -pub type io_name_t = [u8; 128]; -#[allow(non_camel_case_types)] -pub type io_registry_entry_t = io_object_t; +// #[allow(non_camel_case_types)] +// pub type io_name_t = [u8; 128]; +// #[allow(non_camel_case_types)] +// pub type io_registry_entry_t = io_object_t; pub type CFTypeRef = *const c_void; pub type CFStringRef = *const __CFString; +// pub type NSArray = *const __NSArray; +pub type DADiskRef = *const __DADisk; +pub type DASessionRef = *const __DASession; // pub type ODNodeRef = *const __ODNode; // pub type ODSessionRef = *const __ODSession; // pub type CFErrorRef = *const __CFError; -// pub type CFArrayRef = *const __CFArray; +pub type CFArrayRef = *const __CFArray; // pub type ODRecordRef = *const __ODRecord; // pub type ODQueryRef = *const __ODQuery; diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -309,12 +341,15 @@ pub type boolean_t = c_uint; #[allow(non_camel_case_types)] pub type kern_return_t = c_int; pub type Boolean = c_uchar; -pub type IOOptionBits = u32; +// pub type IOOptionBits = u32; pub type CFStringEncoding = u32; // pub type ODRecordType = CFStringRef; // pub type ODAttributeType = CFStringRef; // pub type ODMatchType = u32; -// pub type CFIndex = c_long; +pub type CFIndex = c_long; +#[repr(C)] +pub struct __CFBoolean(c_void); +// pub type CFBooleanRef = *const __CFBoolean; /*#[repr(C)] pub struct task_thread_times_info { diff --git a/src/mac/mod.rs b/src/mac/mod.rs --- a/src/mac/mod.rs +++ b/src/mac/mod.rs @@ -12,6 +12,7 @@ pub mod process; pub mod processor; pub mod system; pub mod users; +mod utils; pub use self::component::Component; pub use self::disk::Disk; diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -22,6 +22,12 @@ use libc::{self, c_int, c_void, size_t, sysconf, _SC_PAGESIZE}; use rayon::prelude::*; +// We need to wrap `DASessionRef` to be sure `System` remains Send+Sync. +struct SessionWrap(ffi::DASessionRef); + +unsafe impl Send for SessionWrap {} +unsafe impl Sync for SessionWrap {} + /// Structs containing system's information. pub struct System { process_list: HashMap<Pid, Process>, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -40,6 +46,9 @@ pub struct System { port: ffi::mach_port_t, users: Vec<User>, boot_time: u64, + // Used to get disk information, to be more specific, it's needed by the + // DADiskCreateFromVolumePath function. + session: SessionWrap, } impl Drop for System { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -49,6 +58,11 @@ impl Drop for System { ffi::IOServiceClose(conn); } } + if !self.session.0.is_null() { + unsafe { + ffi::CFRelease(self.session.0 as _); + } + } } } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -118,6 +132,7 @@ impl SystemExt for System { port, users: Vec::new(), boot_time: boot_time(), + session: SessionWrap(::std::ptr::null_mut()), }; s.refresh_specifics(refreshes); s diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -285,7 +300,10 @@ impl SystemExt for System { } fn refresh_disks_list(&mut self) { - self.disks = crate::mac::disk::get_disks(); + if self.session.0.is_null() { + self.session.0 = unsafe { ffi::DASessionCreate(ffi::kCFAllocatorDefault) }; + } + self.disks = crate::mac::disk::get_disks(self.session.0); } fn refresh_users_list(&mut self) { diff --git a/src/mac/users.rs b/src/mac/users.rs --- a/src/mac/users.rs +++ b/src/mac/users.rs @@ -7,20 +7,7 @@ use crate::User; use libc::{c_char, endpwent, getgrgid, getgrouplist, getpwent, gid_t, setpwent, strlen}; - -fn cstr_to_rust(c: *const c_char) -> Option<String> { - let mut s = Vec::new(); - let mut i = 0; - loop { - let value = unsafe { *c.offset(i) } as u8; - if value == 0 { - break; - } - s.push(value); - i += 1; - } - String::from_utf8(s).ok() -} +use sys::utils; fn get_user_groups(name: *const c_char, group_id: gid_t) -> Vec<String> { let mut add = 0; diff --git a/src/mac/users.rs b/src/mac/users.rs --- a/src/mac/users.rs +++ b/src/mac/users.rs @@ -42,7 +29,7 @@ fn get_user_groups(name: *const c_char, group_id: gid_t) -> Vec<String> { if group.is_null() { return None; } - cstr_to_rust(unsafe { (*group).gr_name }) + utils::cstr_to_rust(unsafe { (*group).gr_name }) }) .collect(); } diff --git a/src/mac/users.rs b/src/mac/users.rs --- a/src/mac/users.rs +++ b/src/mac/users.rs @@ -78,7 +65,7 @@ where continue; } let groups = get_user_groups(unsafe { (*pw).pw_name }, unsafe { (*pw).pw_gid }); - if let Some(name) = cstr_to_rust(unsafe { (*pw).pw_name }) { + if let Some(name) = utils::cstr_to_rust(unsafe { (*pw).pw_name }) { users.push(User { name, groups }); } } diff --git /dev/null b/src/mac/utils.rs new file mode 100644 --- /dev/null +++ b/src/mac/utils.rs @@ -0,0 +1,31 @@ +// +// Sysinfo +// +// Copyright (c) 2020 Guillaume Gomez +// + +use libc::c_char; + +pub fn cstr_to_rust(c: *const c_char) -> Option<String> { + cstr_to_rust_with_size(c, None) +} + +pub fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> Option<String> { + if c.is_null() { + return None; + } + let mut s = match size { + Some(len) => Vec::with_capacity(len), + None => Vec::new(), + }; + let mut i = 0; + loop { + let value = unsafe { *c.offset(i) } as u8; + if value == 0 { + break; + } + s.push(value); + i += 1; + } + String::from_utf8(s).ok() +} diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -4,50 +4,50 @@ // Copyright (c) 2017 Guillaume Gomez // -#[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] -use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] use std::ffi::OsStr; #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] -use std::fs; -#[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] use std::os::unix::ffi::OsStrExt; #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] -use std::path::{Path, PathBuf}; +use std::path::Path; use Pid; #[allow(clippy::useless_conversion)] -#[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] -pub fn realpath(original: &Path) -> PathBuf { +#[cfg(not(any( + target_os = "windows", + target_os = "unknown", + target_arch = "wasm32", + target_os = "macos", + target_os = "ios" +)))] +pub fn realpath(original: &Path) -> ::std::path::PathBuf { + use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; + use std::fs; use std::mem::MaybeUninit; + use std::path::PathBuf; fn and(x: u32, y: u32) -> u32 { x & y } - if let Some(original_str) = original.to_str() { - let ori = Path::new(original_str); - - // Right now lstat on windows doesn't work quite well - if cfg!(windows) { - return PathBuf::from(ori); - } - let result = PathBuf::from(original); - let mut result_s = result.to_str().unwrap_or("").as_bytes().to_vec(); - result_s.push(0); - let mut buf = MaybeUninit::<stat>::uninit(); - let res = unsafe { lstat(result_s.as_ptr() as *const c_char, buf.as_mut_ptr()) }; - let buf = unsafe { buf.assume_init() }; - if res < 0 || and(buf.st_mode.into(), S_IFMT.into()) != S_IFLNK.into() { - PathBuf::new() - } else { - match fs::read_link(&result) { - Ok(f) => f, - Err(_) => PathBuf::new(), - } - } - } else { + // let ori = Path::new(original.to_str().unwrap()); + // Right now lstat on windows doesn't work quite well + // if cfg!(windows) { + // return PathBuf::from(ori); + // } + let result = PathBuf::from(original); + let mut result_s = result.to_str().unwrap_or("").as_bytes().to_vec(); + result_s.push(0); + let mut buf = MaybeUninit::<stat>::uninit(); + let res = unsafe { lstat(result_s.as_ptr() as *const c_char, buf.as_mut_ptr()) }; + let buf = unsafe { buf.assume_init() }; + if res < 0 || and(buf.st_mode.into(), S_IFMT.into()) != S_IFLNK.into() { PathBuf::new() + } else { + match fs::read_link(&result) { + Ok(f) => f, + Err(_) => PathBuf::new(), + } } }
2a2e91cf8cd9319b1dbaa8fb3af889743a06519c
get_disks() doesn't return all mounted disks on Mac OS I've just started learning Rust. I'm on a 2013 MacBook Air running macOS Sierra and rustc 1.48.0 I modified the sysinfo example to just print out the disks in the system. My boot disk is an external USB 3.0 SSD. (The internal SSD has been missing since I got the laptop.) Running the code with just the boot disk reports just the boot disk. Attaching my USB 3.0 HD with several partitions including Mac, FAT, and NTFS; still only the boot disk is listed. I added more refresh_* calls but it made no difference. Code: ``` use sysinfo::SystemExt; fn main() { let mut system = sysinfo::System::new_all(); // First we update all information of our system struct. system.refresh_all(); // And then all disks' information: for disk in system.get_disks() { println!("{:?}", disk); } } ``` Output: ``` > Executing task: cargo run --package disklist --bin disklist < Compiling disklist v0.1.0 (/Users/hippietrail/disklist) Finished dev [unoptimized + debuginfo] target(s) in 2.32s Running `target/debug/disklist` ``` **UPDATE** It turns out I had my .toml set up to use version "0.3" of sysinfo, which I must've got from Googling. I changed it to "0.15" to get the latest version. Instead of fixing the problem it now prints out nothing at all. Not even my boot disk is listed. **UPDATE 2** It looks like I had code that was still using System::new() from the 0.3 example so I changed it to System::new_all() to match the 0.15 version. Now on my Mac the boot disk shows up again but neither of two different USB hard drives, nor any of their partitions. On my Windows 10 machine there's a different problem. The internal SSDs show up and the external USB HDs that don't show up on the Mac do show up, **but** my SDHC card does not show up.
0.15
377
That's intriguing. I'll need to check what's going there. > That's intriguing. I'll need to check what's going there. Thanks Guillaume. I updated the report by fixing a problem in the code that was mixing 0.3 and 0.15 versions of the example code and tested under Windows 10, which has a different problem. In utils.rs lines 41 & 42 ... ``` if res < 0 || and(buf.st_mode.into(), S_IFMT.into()) != S_IFLNK.into() { PathBuf::new() ``` It seems you are only considering an entry in /Volumes to be a mountpoint if it is a symlink. On my system my boot drive is a symlink but the other drives are directories. So unless this check is here for a specific reason not apparent to me it seems to be wrong to filter out non-symlinks. I only have my own Mac to check that so if you're telling me that it works in your case, then we can simply remove this check. My friend has also checked it on his Mac and confirms: I have a usb drive, a network drive and a timemachine snapshot ... can see only one softlink Testing with a USB key is a good idea! I'll give it a try. It seems that on Mac a USB key is treated identically to USB hard drive or SSD but on Windows USB hard drives and SSDs are included but USB keys are rejected. Technically a separate bug but as the crate currently doesn't list any external drives on Mac I won't open a new issue yet. So a good example why I didn't take into account folders. On my computer I have in my `/Volumes`: ``` lrwxr-xr-x 1 root wheel 1 Jul 11 19:14 Macintosh HD -> / drwxr-xr-x 3 root wheel 96 Jul 11 13:43 Recovery drwxr-xr-x 10 imperio staff 408 Sep 7 2019 Steam ``` Obviously, `Recovery` and `Steam` aren't hard drives. Now something interesting happens with USB drives: ``` drwxrwxrwx@ 1 imperio staff 16384 Dec 11 20:47 Untitled drwxrwxrwx@ 1 imperio staff 16384 Aug 26 12:43 key ``` As you can see, there is a `@` at the end, so I need to check how to get this info. So after spending quite some time on this, the only thing I could find for the moment was `getFileSystemInfoForPath`, but I wasn't able to use it in rust because I can't find the C symbol which would allow me to use it. The code I added to try it out is (you'll need to uncomment a few things in `mac/ffi.rs` too: `CFStringGetCharactersPtr`, `CFArrayGetCount`, `CFArrayGetValueAtIndex`, `CFStringRef`, `CFArrayRef`, `CFIndex`): ```rust #[repr(C)] pub struct NSWorkspace { __private: c_void, } extern "C" { fn NSWorkspaceSharedWorkspace() -> *mut NSWorkspace; fn NSWorkspaceMountedLocalVolumePaths(ws: *mut NSWorkspace) -> *mut c_void; fn getFileSystemInfoForPath( ws: *mut NSWorkspace, path: ffi::CFStringRef, isRemovable: *mut ffi::Boolean, isWritable: *mut ffi::Boolean, isUnmountable: *mut ffi::Boolean, description: ffi::CFStringRef, type_: ffi::CFStringRef, ) -> ffi::Boolean; } pub(crate) fn get_disks() -> Vec<Disk> { unsafe { let ws = NSWorkspaceSharedWorkspace(); let vols = NSWorkspaceMountedLocalVolumePaths(ws); for x in 0..ffi::CFArrayGetCount(vols as _) { let path = ffi::CFArrayGetValueAtIndex(vols as _, x); let mut isRemovable = 0; let mut isWritable = 0; let mut isUnmountable = 0; let description = ffi::CFStringCreateWithCStringNoCopy( ws, ptr::null_mut(), [0].as_ptr() as *const c_char, ffi::kCFStringEncodingMacRoman, ffi::kCFAllocatorNull as *mut c_void, ); let res = getFileSystemInfoForPath(path as _, &mut isRemovable, &mut isWritable, &mut isUnmountable, description, ::std::ptr::null_mut()); if res == 0 { continue; } let tmp = std::ffi::CStr::from_ptr(ffi::CFStringGetCharactersPtr(path as _) as _); let tmp_d = std::ffi::CStr::from_ptr(ffi::CFStringGetCharactersPtr(description)as _); println!("==> {:?} {:?} w: {:?} r: {:?} u: {:?}", tmp.to_str().unwrap(), tmp_d.to_str().unwrap(), isWritable, isRemovable, isUnmountable); } } vec![] } ``` If anyone is interested into trying to fix more things... The `@` means there are extended attributes. You can see them by doing for example `ls -l@` ``` drwxrwxrwx@ 1 hippietrail staff 131072 1 Jan 1980 Backup Plus com.apple.FinderInfo 32 drwxrwxrwx@ 1 hippietrail staff 16384 12 Dec 08:58 CRUZERFAT8 com.apple.filesystems.msdosfs.volume_id 4 lrwxr-xr-x 1 root wheel 1 10 Dec 18:08 Mac USB SSD -> / drwxrwxrwx@ 1 hippietrail staff 32768 11 Dec 20:47 SANDISKµ16 com.apple.filesystems.msdosfs.volume_id 4 ``` The first is a hard drive with one MS partition, the second is a USB stick, the third is my boot drive, and the last is a microSD card attached via a USB adapter. Except for the boot drive, they are all connected via a $5 USB 2 hub. The SD card and the USB stick are not partitioned. So the only pattern I can see is that unpartitioned drive with MS filesystems get `com.apple.filesystems.msdosfs.volume_id` and partitioned ones get `com.apple.FinderInfo`. I'm starting to think that `/Volumes/` is not the right place to start. The nodeJS module "drivelist" uses a different approach. [You can see its Objective C code here.](https://github.com/balena-io-modules/drivelist/blob/master/src/darwin/list.mm) I have to admit that so far I'm not very good at reading mscOS API code or Objective C though. It uses the [Disk Arbitration system](https://developer.apple.com/library/archive/documentation/DriversKernelHardware/Conceptual/DiskArbitrationProgGuide/Introduction/Introduction.html). Another way to fool the current code is to make a random symlink in the `/Volumes` directory: `sudo ln -s ~ /Volumes/a-link` Current `get_disks()` on Mac will consider you to have a disk named `a-link` mounted at `/Users/yourusername` Here's some proof of concept code I managed to get working in very terrible Swift. It doesn't seem to have false positives or false negatives for anything that might be in `/Volumes` and it should hopefully filter hd/ssd vs usb stick/sdcard to match the Windows code. ``` import Cocoa import DiskArbitration if let session = DASessionCreate(kCFAllocatorDefault) { let mountedVolumeURLs = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: nil)! for volumeURL in mountedVolumeURLs { if let disk = DADiskCreateFromVolumePath(kCFAllocatorDefault, session, volumeURL as CFURL), let bsdName = DADiskGetBSDName(disk) { let bsdString = String(cString : bsdName) print(volumeURL.path, bsdString) if let descDict = DADiskCopyDescription(disk) as? [String: CFTypeRef] { let removable : Bool, ejectable : Bool if let val = descDict["DAMediaRemovable"] as? Bool { removable = val if let val = descDict["DAMediaEjectable"] as? Bool { ejectable = val var type = "" type += removable || ejectable ? "USB stick, SD card, etc" ? "hard drive, SSD, etc"; type += " (" type += removable ? "" : "not " type += "removable" type += ", " type += ejectable ? "" : "not " type += "ejectable" type += ")" print(" ", type) } } } print("\n") } } } ``` > Another way to fool the current code is to make a random symlink in the `/Volumes` directory: > > `sudo ln -s ~ /Volumes/a-link` > > Current `get_disks()` on Mac will consider you to have a disk named `a-link` mounted at `/Users/yourusername` We definitely shouldn't do that, I'll try to find another way. ;)
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
2020-10-02T14:52:22Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -104,3 +104,25 @@ fn test_process_disk_usage() { p.disk_usage().written_bytes ); } + +#[test] +fn cpu_usage_is_not_nan() { + let mut system = sysinfo::System::new(); + system.refresh_processes(); + + let first_pids = system.get_processes() + .iter() + .take(10) + .map(|(&pid, _)| pid) + .collect::<Vec<_>>(); + let mut checked = 0; + + first_pids.into_iter().for_each(|pid| { + system.refresh_process(pid); + if let Some(p) = system.get_process(pid) { + assert!(!p.cpu_usage().is_nan()); + checked += 1; + } + }); + assert!(checked > 0); +}
[ "366" ]
GuillaumeGomez__sysinfo-367
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sysinfo" -version = "0.15.2" +version = "0.15.3" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] description = "Library to get system information such as processes, processors, disks, components and networks" diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -377,7 +377,7 @@ impl SystemExt for System { if found && !self.processors.is_empty() { self.refresh_processors(Some(1)); let (new, old) = get_raw_times(&self.global_processor); - let total_time = (if old > new { 1 } else { new - old }) as f32; + let total_time = (if old >= new { 1 } else { new - old }) as f32; if let Some(p) = self.process_list.tasks.get_mut(&pid) { compute_cpu_usage(p, self.processors.len() as u64, total_time); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -739,9 +739,10 @@ pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64, now: ULARGE &mut fuser as *mut FILETIME as *mut c_void, size_of::<FILETIME>(), ); + let old = check_sub(*now.QuadPart(), p.old_cpu); p.cpu_usage = (check_sub(*sys.QuadPart(), p.old_sys_cpu) as f32 + check_sub(*user.QuadPart(), p.old_user_cpu) as f32) - / check_sub(*now.QuadPart(), p.old_cpu) as f32 + / if old == 0 { 1 } else { old } as f32 / nb_processors as f32 * 100.; p.old_cpu = *now.QuadPart();
f57031a38b0d527958a58605682c52e262f3f017
Process cpu_usage() returns NaN in some cases Hello, I'm using `sysinfo` on version `0.15.2` on Linux mint 19. `cargo -V` outputs `cargo 1.46.0 (149022b1d 2020-07-17)`. `rustc -V` outputs `rustc 1.46.0 (04488afe3 2020-08-24)`. When `system.refresh_process(pid)` is called too often, the cpu_usage() of this process becomes NaN (or sometimes inf). I have tried to understand where is this comes from, and I think that the bug is in `system.rs`, in the function `refresh_process` (line 380): ``` let total_time = (if old > new { 1 } else { new - old }) as f32; ``` If by any chance `new == old`, then `total_time` would be zero. `total_time` is then sent as an argument to `compute_cpu_usage`, which uses it in the denominator. The code to reproduce: ``` fn main() { let mut system: System = System::new(); system.refresh_processes(); let first_5_pids: Vec<Pid> = system.get_processes() .iter() .take(5) .map(|(pid, _)| *pid as Pid) .collect::<Vec<Pid>>(); first_5_pids.iter().for_each(|pid| { system.refresh_process(*pid as Pid); let proc = system.get_process(*pid as Pid).unwrap(); println!("pid: {}, cpu: {}", proc.pid(), proc.cpu_usage()); }); } ``` the output is as follows: ``` pid: 673, cpu: 0 pid: 1736, cpu: NaN pid: 58, cpu: NaN pid: 684, cpu: NaN pid: 52, cpu: NaN ```
0.15
367
This is indeed where the bug is coming from. However, I'm not too aware on how to compare floats and check if they're equal. If you have any directions, it'd be awesome! (You can also send a PR if you want to go faster :wink: ). I appreciate the quick reply :) there are some crates that handle this, like [float_cmp](https://docs.rs/float-cmp/0.8.0/float_cmp/). Alternatively, you can use `round()` or something like that. I don't know if I will have the time to send a PR though. Best regards I'd rather not add a dependency for such a specific case. I can always add a precision level to perform the comparison though. I think the best practice is to `abs` the 2 floats, `abs` the difference and check if its smaller than `std::f64:: EPSILON` for example
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
2020-06-01T11:28:42Z
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -92,7 +92,7 @@ cfg_if! { #[cfg(test)] const MIN_USERS: usize = 1; - } else if #[cfg(unix)] { + } else if #[cfg(any(target_os = "linux", target_os = "android"))] { mod linux; use linux as sys;
[ "319" ]
GuillaumeGomez__sysinfo-322
GuillaumeGomez/sysinfo
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -151,7 +151,7 @@ mod utils; /// let s = System::new_all(); /// ``` pub fn set_open_files_limit(mut _new_limit: isize) -> bool { - #[cfg(all(not(target_os = "macos"), unix))] + #[cfg(any(target_os = "linux", target_os = "android"))] { if _new_limit < 0 { _new_limit = 0; diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -170,7 +170,7 @@ pub fn set_open_files_limit(mut _new_limit: isize) -> bool { false } } - #[cfg(any(not(unix), target_os = "macos"))] + #[cfg(all(not(target_os = "linux"), not(target_os = "android")))] { false }
98fb1e1d4fc5187b9701464ebd6674245879bea0
Fails on FreeBSD: cannot find value `CLOCK_BOOTTIME` in crate `libc` ``` error[E0425]: cannot find value `CLOCK_BOOTTIME` in crate `libc` --> /wrkdirs/usr/ports/shells/starship/work/starship-0.41.3/cargo-crates/sysinfo-0.14.2/src/linux/system.rs:121:43 | 121 | if unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut up) } == 0 { | ^^^^^^^^^^^^^^ help: a constant with a similar name exists: `CLOCK_REALTIME` | ::: /wrkdirs/usr/ports/shells/starship/work/starship-0.41.3/cargo-crates/libc-0.2.70/src/unix/bsd/freebsdlike/freebsd/mod.rs:423:1 | 423 | pub const CLOCK_REALTIME: ::clockid_t = 0; | ------------------------------------------ similarly named constant `CLOCK_REALTIME` defined here error: aborting due to previous error ``` Needed for https://starship.rs/
0.14
322
I'm surprised that FreeBSD is considered as a unix target... I'm sorry but I have no machine with a FreeBSD installed. So I have two leads to solve this issue: 1. Understand which condition failed, allowing FreeBSD to use unix code. 2. Fix the code directly by using the matching constant on FreeBSD. Practically every OS that isn't Windows is covered by `cfg(unix)` - all the BSDs, Solaris and friends, Fuchsia, Redox, etc. Your Linux support should be behind `cfg(target_os = "linux")`, because it has basically zero hope of running anywhere else - one missing constant is the tip of the iceberg. A shame I didn't realize it sooner... I'm just worried now about android and raspberry targets...
98fb1e1d4fc5187b9701464ebd6674245879bea0
2020-04-15T13:12:29Z
diff --git a/src/linux/disk.rs b/src/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/linux/disk.rs @@ -148,3 +72,156 @@ impl DiskExt for Disk { } } } + +fn new_disk(name: &OsStr, mount_point: &Path, file_system: &[u8]) -> Disk { + let mount_point_cpath = utils::to_cpath(mount_point); + let type_ = find_type_for_name(name); + let mut total = 0; + let mut available = 0; + unsafe { + let mut stat: statvfs = mem::zeroed(); + if statvfs(mount_point_cpath.as_ptr() as *const _, &mut stat) == 0 { + total = cast!(stat.f_bsize) * cast!(stat.f_blocks); + available = cast!(stat.f_bsize) * cast!(stat.f_bavail); + } + } + Disk { + type_, + name: name.to_owned(), + file_system: file_system.to_owned(), + mount_point: mount_point.to_owned(), + total_space: cast!(total), + available_space: cast!(available), + } +} + +fn find_type_for_name(name: &OsStr) -> DiskType { + // The format of devices are as follows: + // - name_path is symbolic link in the case of /dev/mapper/ + // and /dev/root, and the target is corresponding device under + // /sys/block/ + // - In the case of /dev/sd, the format is /dev/sd[a-z][1-9], + // corresponding to /sys/block/sd[a-z] + // - In the case of /dev/nvme, the format is /dev/nvme[0-9]n[0-9]p[0-9], + // corresponding to /sys/block/nvme[0-9]n[0-9] + // - In the case of /dev/mmcblk, the format is /dev/mmcblk[0-9]p[0-9], + // corresponding to /sys/block/mmcblk[0-9] + let name_path = name.to_str().unwrap_or_default(); + let real_path = fs::canonicalize(name_path).unwrap_or(PathBuf::from(name_path)); + let mut real_path = real_path.to_str().unwrap_or_default(); + if name_path.starts_with("/dev/mapper/") { + // Recursively solve, for example /dev/dm-0 + return find_type_for_name(OsStr::new(&real_path)); + } else if name_path.starts_with("/dev/sd") { + // Turn "sda1" into "sda" + real_path = real_path.trim_start_matches("/dev/"); + real_path = real_path.trim_end_matches(|c| c >= '0' && c <= '9'); + } else if name_path.starts_with("/dev/nvme") { + // Turn "nvme0n1p1" into "nvme0n1" + real_path = real_path.trim_start_matches("/dev/"); + real_path = real_path.trim_end_matches(|c| c >= '0' && c <= '9'); + real_path = real_path.trim_end_matches(|c| c == 'p'); + } else if name_path.starts_with("/dev/root") { + // Recursively solve, for example /dev/mmcblk0p1 + return find_type_for_name(OsStr::new(&real_path)); + } else if name_path.starts_with("/dev/mmcblk") { + // Turn "mmcblk0p1" into "mmcblk0" + real_path = real_path.trim_start_matches("/dev/"); + real_path = real_path.trim_end_matches(|c| c >= '0' && c <= '9'); + real_path = real_path.trim_end_matches(|c| c == 'p'); + } else { + // Default case: remove /dev/ and expects the name presents under /sys/block/ + // For example, /dev/dm-0 to dm-0 + real_path = real_path.trim_start_matches("/dev/"); + } + + let trimmed: &OsStr = OsStrExt::from_bytes(real_path.as_bytes()); + + let path = Path::new("/sys/block/") + .to_owned() + .join(trimmed) + .join("queue/rotational"); + // Normally, this file only contains '0' or '1' but just in case, we get 8 bytes... + let rotational_int = get_all_data(path, 8).unwrap_or_default().trim().parse(); + DiskType::from(rotational_int.unwrap_or(-1)) +} + +fn get_all_disks_inner(content: &str) -> Vec<Disk> { + content + .lines() + .map(|line| { + let line = line.trim_start(); + // mounts format + // http://man7.org/linux/man-pages/man5/fstab.5.html + // fs_spec<tab>fs_file<tab>fs_vfstype<tab>other fields + let mut fields = line.split_whitespace(); + let fs_spec = fields.next().unwrap_or(""); + let fs_file = fields.next().unwrap_or(""); + let fs_vfstype = fields.next().unwrap_or(""); + (fs_spec, fs_file, fs_vfstype) + }) + .filter(|(fs_spec, fs_file, fs_vfstype)| { + // Check if fs_vfstype is one of our 'ignored' file systems. + let filtered = match *fs_vfstype { + "sysfs" | // pseudo file system for kernel objects + "proc" | // another pseudo file system + "tmpfs" | + "cgroup" | + "cgroup2" | + "pstore" | // https://www.kernel.org/doc/Documentation/ABI/testing/pstore + "squashfs" | // squashfs is a compressed read-only file system (for snaps) + "rpc_pipefs" | // The pipefs pseudo file system service + "iso9660" => true, // optical media + _ => false, + }; + + if filtered || + fs_file.starts_with("/sys") || // check if fs_file is an 'ignored' mount point + fs_file.starts_with("/proc") || + fs_file.starts_with("/run") || + fs_spec.starts_with("sunrpc") + { + false + } else { + true + } + }) + .map(|(fs_spec, fs_file, fs_vfstype)| { + new_disk(fs_spec.as_ref(), Path::new(fs_file), fs_vfstype.as_bytes()) + }) + .collect() +} + +pub fn get_all_disks() -> Vec<Disk> { + get_all_disks_inner(&get_all_data("/proc/mounts", 16_385).unwrap_or_default()) +} + +#[test] +fn check_all_disks() { + let disks = get_all_disks_inner(r#"tmpfs /proc tmpfs rw,seclabel,relatime 0 0 +proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0 +systemd-1 /proc/sys/fs/binfmt_misc autofs rw,relatime,fd=29,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=17771 0 0 +tmpfs /sys tmpfs rw,seclabel,relatime 0 0 +sysfs /sys sysfs rw,seclabel,nosuid,nodev,noexec,relatime 0 0 +securityfs /sys/kernel/security securityfs rw,nosuid,nodev,noexec,relatime 0 0 +cgroup2 /sys/fs/cgroup cgroup2 rw,seclabel,nosuid,nodev,noexec,relatime,nsdelegate 0 0 +pstore /sys/fs/pstore pstore rw,seclabel,nosuid,nodev,noexec,relatime 0 0 +none /sys/fs/bpf bpf rw,nosuid,nodev,noexec,relatime,mode=700 0 0 +configfs /sys/kernel/config configfs rw,nosuid,nodev,noexec,relatime 0 0 +selinuxfs /sys/fs/selinux selinuxfs rw,relatime 0 0 +debugfs /sys/kernel/debug debugfs rw,seclabel,nosuid,nodev,noexec,relatime 0 0 +tmpfs /dev/shm tmpfs rw,seclabel,relatime 0 0 +devpts /dev/pts devpts rw,seclabel,relatime,gid=5,mode=620,ptmxmode=666 0 0 +tmpfs /sys/fs/selinux tmpfs rw,seclabel,relatime 0 0 +/dev/vda2 /proc/filesystems xfs rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota 0 0 +"#); + assert_eq!(disks.len(), 1); + assert_eq!(disks[0], Disk { + type_: DiskType::Unknown(-1), + name: OsString::from("devpts"), + file_system: vec![100, 101, 118, 112, 116, 115], + mount_point: PathBuf::from("/dev/pts"), + total_space: 0, + available_space: 0, + }); +} diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -866,55 +866,6 @@ pub fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<Str get_all_data_from_file(&mut file, size) } -fn get_all_disks() -> Vec<Disk> { - let content = get_all_data("/proc/mounts", 16_385).unwrap_or_default(); - - content - .lines() - .map(|line| { - let line = line.trim_start(); - // mounts format - // http://man7.org/linux/man-pages/man5/fstab.5.html - // fs_spec<tab>fs_file<tab>fs_vfstype<tab>other fields - let mut fields = line.split_whitespace(); - let fs_spec = fields.next().unwrap_or(""); - let fs_file = fields.next().unwrap_or(""); - let fs_vfstype = fields.next().unwrap_or(""); - (fs_spec, fs_file, fs_vfstype) - }) - .filter(|(fs_spec, fs_file, fs_vfstype)| { - // Check if fs_vfstype is one of our 'ignored' file systems. - let filtered = match *fs_vfstype { - "sysfs" | // pseudo file system for kernel objects - "proc" | // another pseudo file system - "tmpfs" | - "cgroup" | - "cgroup2" | - "pstore" | // https://www.kernel.org/doc/Documentation/ABI/testing/pstore - "squashfs" | // squashfs is a compressed read-only file system (for snaps) - "rpc_pipefs" | // The pipefs pseudo file system service - "iso9660" => true, // optical media - _ => false, - }; - - if filtered || - fs_file.starts_with("/sys") || // check if fs_file is an 'ignored' mount point - fs_file.starts_with("/proc") || - fs_file.starts_with("/run") || - fs_file.starts_with("/dev") || - fs_spec.starts_with("sunrpc") - { - false - } else { - true - } - }) - .map(|(fs_spec, fs_file, fs_vfstype)| { - disk::new(fs_spec.as_ref(), Path::new(fs_file), fs_vfstype.as_bytes()) - }) - .collect() -} - fn get_uptime() -> u64 { let content = get_all_data("/proc/uptime", 50).unwrap_or_default(); u64::from_str_radix(content.split('.').next().unwrap_or_else(|| "0"), 10).unwrap_or_else(|_| 0)
[ "300" ]
GuillaumeGomez__sysinfo-302
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sysinfo" -version = "0.13.2" +version = "0.13.3" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] description = "Library to get system information such as processes, processors, disks, components and networks" diff --git a/src/linux/disk.rs b/src/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/linux/disk.rs @@ -16,90 +16,14 @@ use std::mem; use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; -fn find_type_for_name(name: &OsStr) -> DiskType { - /* - The format of devices are as follows: - - name_path is symbolic link in the case of /dev/mapper/ - and /dev/root, and the target is corresponding device under - /sys/block/ - - In the case of /dev/sd, the format is /dev/sd[a-z][1-9], - corresponding to /sys/block/sd[a-z] - - In the case of /dev/nvme, the format is /dev/nvme[0-9]n[0-9]p[0-9], - corresponding to /sys/block/nvme[0-9]n[0-9] - - In the case of /dev/mmcblk, the format is /dev/mmcblk[0-9]p[0-9], - corresponding to /sys/block/mmcblk[0-9] - */ - let name_path = name.to_str().unwrap_or_default(); - let real_path = fs::canonicalize(name_path).unwrap_or(PathBuf::from(name_path)); - let mut real_path = real_path.to_str().unwrap_or_default(); - if name_path.starts_with("/dev/mapper/") { - /* Recursively solve, for example /dev/dm-0 */ - return find_type_for_name(OsStr::new(&real_path)); - } else if name_path.starts_with("/dev/sd") { - /* Turn "sda1" into "sda" */ - real_path = real_path.trim_start_matches("/dev/"); - real_path = real_path.trim_end_matches(|c| c >= '0' && c <= '9'); - } else if name_path.starts_with("/dev/nvme") { - /* Turn "nvme0n1p1" into "nvme0n1" */ - real_path = real_path.trim_start_matches("/dev/"); - real_path = real_path.trim_end_matches(|c| c >= '0' && c <= '9'); - real_path = real_path.trim_end_matches(|c| c == 'p'); - } else if name_path.starts_with("/dev/root") { - /* Recursively solve, for example /dev/mmcblk0p1 */ - return find_type_for_name(OsStr::new(&real_path)); - } else if name_path.starts_with("/dev/mmcblk") { - /* Turn "mmcblk0p1" into "mmcblk0" */ - real_path = real_path.trim_start_matches("/dev/"); - real_path = real_path.trim_end_matches(|c| c >= '0' && c <= '9'); - real_path = real_path.trim_end_matches(|c| c == 'p'); - } else { - /* - Default case: remove /dev/ and expects the name presents under /sys/block/ - For example, /dev/dm-0 to dm-0 - */ - real_path = real_path.trim_start_matches("/dev/"); - } - - let trimmed: &OsStr = OsStrExt::from_bytes(real_path.as_bytes()); - - let path = Path::new("/sys/block/") - .to_owned() - .join(trimmed) - .join("queue/rotational"); - // Normally, this file only contains '0' or '1' but just in case, we get 8 bytes... - let rotational_int = get_all_data(path, 8).unwrap_or_default().trim().parse(); - DiskType::from(rotational_int.unwrap_or(-1)) -} - macro_rules! cast { ($x:expr) => { u64::from($x) }; } -pub fn new(name: &OsStr, mount_point: &Path, file_system: &[u8]) -> Disk { - let mount_point_cpath = utils::to_cpath(mount_point); - let type_ = find_type_for_name(name); - let mut total = 0; - let mut available = 0; - unsafe { - let mut stat: statvfs = mem::zeroed(); - if statvfs(mount_point_cpath.as_ptr() as *const _, &mut stat) == 0 { - total = cast!(stat.f_bsize) * cast!(stat.f_blocks); - available = cast!(stat.f_bsize) * cast!(stat.f_bavail); - } - } - Disk { - type_, - name: name.to_owned(), - file_system: file_system.to_owned(), - mount_point: mount_point.to_owned(), - total_space: cast!(total), - available_space: cast!(available), - } -} - /// Struct containing a disk information. +#[derive(PartialEq)] pub struct Disk { type_: DiskType, name: OsString, diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -371,7 +371,7 @@ impl SystemExt for System { } fn refresh_disks_list(&mut self) { - self.disks = get_all_disks(); + self.disks = disk::get_all_disks(); } fn refresh_users_list(&mut self) {
a6228731cb3464cfc72c3475b2ab0e10448262a0
test_disks fail in Fedora buildsystem ```rust ---- test_disks stdout ---- thread 'test_disks' panicked at 'assertion failed: s.get_disks().len() > 0', tests/disk_list.rs:14:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: test_disks test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out ``` Let me know if you need more info.
0.13
302
You didn't have this issue before I assume? On 0.12.0 no, but now I upgraded to 0.13.2 and have it :) I suspect #297, which is weird considering that it was supposed to handle more disk kinds... Can you show what your `/proc/mounts` file contains please? ``` tmpfs /proc tmpfs rw,seclabel,relatime 0 0 proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0 systemd-1 /proc/sys/fs/binfmt_misc autofs rw,relatime,fd=29,pgrp=1,timeout=0,minproto=5,maxproto=5,direct,pipe_ino=17771 0 0 tmpfs /sys tmpfs rw,seclabel,relatime 0 0 sysfs /sys sysfs rw,seclabel,nosuid,nodev,noexec,relatime 0 0 securityfs /sys/kernel/security securityfs rw,nosuid,nodev,noexec,relatime 0 0 cgroup2 /sys/fs/cgroup cgroup2 rw,seclabel,nosuid,nodev,noexec,relatime,nsdelegate 0 0 pstore /sys/fs/pstore pstore rw,seclabel,nosuid,nodev,noexec,relatime 0 0 none /sys/fs/bpf bpf rw,nosuid,nodev,noexec,relatime,mode=700 0 0 configfs /sys/kernel/config configfs rw,nosuid,nodev,noexec,relatime 0 0 selinuxfs /sys/fs/selinux selinuxfs rw,relatime 0 0 debugfs /sys/kernel/debug debugfs rw,seclabel,nosuid,nodev,noexec,relatime 0 0 tmpfs /dev/shm tmpfs rw,seclabel,relatime 0 0 devpts /dev/pts devpts rw,seclabel,relatime,gid=5,mode=620,ptmxmode=666 0 0 tmpfs /sys/fs/selinux tmpfs rw,seclabel,relatime 0 0 /dev/vda2 /proc/filesystems xfs rw,seclabel,relatime,attr2,inode64,logbufs=8,logbsize=32k,noquota 0 0 ``` Thanks! I'll use it to add a test on linux disks.
a6228731cb3464cfc72c3475b2ab0e10448262a0
2020-03-19T10:58:00Z
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -316,3 +316,18 @@ mod test { assert!(s.get_users().len() >= MIN_USERS); } } + +// Used to check that System is Send and Sync. +#[cfg(doctest)] +doc_comment!( + " +``` +fn is_send<T: Send>() {} +is_send::<sysinfo::System>(); +``` + +``` +fn is_sync<T: Sync>() {} +is_sync::<sysinfo::System>(); +```" +); diff --git /dev/null b/tests/send_sync.rs new file mode 100644 --- /dev/null +++ b/tests/send_sync.rs @@ -0,0 +1,16 @@ +// +// Sysinfo +// +// Copyright (c) 2020 Guillaume Gomez +// + +extern crate sysinfo; + +#[test] +fn test_send_sync() { + fn is_send<T: Send>() {} + fn is_sync<T: Sync>() {} + + is_send::<sysinfo::System>(); + is_sync::<sysinfo::System>(); +}
[ "282" ]
GuillaumeGomez__sysinfo-283
GuillaumeGomez/sysinfo
diff --git a/src/unknown/component.rs b/src/unknown/component.rs --- a/src/unknown/component.rs +++ b/src/unknown/component.rs @@ -26,6 +26,5 @@ impl ComponentExt for Component { "" } - fn refresh(&mut self) { - } + fn refresh(&mut self) {} } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -9,9 +9,9 @@ use sys::process::*; use sys::processor::*; use sys::Disk; use sys::Networks; +use LoadAvg; use Pid; use User; -use LoadAvg; use {RefreshKind, SystemExt}; use std::collections::HashMap; diff --git a/src/windows/component.rs b/src/windows/component.rs --- a/src/windows/component.rs +++ b/src/windows/component.rs @@ -159,6 +159,9 @@ struct Connection { enumerator: Option<Enumerator>, } +unsafe impl Send for Connection {} +unsafe impl Sync for Connection {} + impl Connection { fn new() -> Option<Connection> { // "Funnily", this function returns ok, false or "this function has already been called".
90049ce2c712284ee93379e4e5f9c03da41b9ee2
`System` implements `Send` on Linux, but not on Windows As the title says, the `System` struct implements `Send` on Linux, but not on Windows. Take a look at the implemented traits: https://docs.rs/sysinfo/0.11.7/x86_64-pc-windows-msvc/sysinfo/struct.System.html https://docs.rs/sysinfo/0.11.7/sysinfo/struct.System.html
0.11
283
It shouldn't implement `Send` on any platform. Sending a PR.
90049ce2c712284ee93379e4e5f9c03da41b9ee2
2020-02-10T21:08:36Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -6,12 +6,12 @@ extern crate sysinfo; +#[cfg(not(windows))] +use sysinfo::ProcessExt; +use sysinfo::SystemExt; + #[test] fn test_process() { - #[cfg(not(windows))] - use sysinfo::ProcessExt; - use sysinfo::SystemExt; - let mut s = sysinfo::System::new(); assert_eq!(s.get_processes().len(), 0); s.refresh_processes(); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -22,3 +22,15 @@ fn test_process() { .values() .any(|p| p.exe().to_str().unwrap_or_else(|| "").len() != 0)); } + +#[test] +fn test_process_refresh() { + let mut s = sysinfo::System::new(); + assert_eq!(s.get_processes().len(), 0); + s.refresh_process(sysinfo::get_current_pid().expect("failed to get current pid")); + assert_eq!( + s.get_process(sysinfo::get_current_pid().expect("failed to get current pid")) + .is_some(), + true + ); +}
[ "261" ]
GuillaumeGomez__sysinfo-262
GuillaumeGomez/sysinfo
diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -538,7 +538,7 @@ pub trait SystemExt: Sized { fn refresh_processes(&mut self); /// Refresh *only* the process corresponding to `pid`. Returns `false` if the process doesn't - /// exist or isn't listed. + /// exist. If it isn't listed yet, it'll be added. /// /// ```no_run /// use sysinfo::{System, SystemExt}; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -5,9 +5,10 @@ // use std::fmt::{self, Debug, Formatter}; -use std::mem::{size_of, zeroed}; +use std::mem::{size_of, zeroed, MaybeUninit}; use std::ops::Deref; use std::path::{Path, PathBuf}; +use std::ptr::null_mut; use std::str; use libc::{c_uint, c_void, memcpy}; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -15,6 +16,9 @@ use libc::{c_uint, c_void, memcpy}; use Pid; use ProcessExt; +use ntapi::ntpsapi::{ + NtQueryInformationProcess, ProcessBasicInformation, PROCESS_BASIC_INFORMATION, +}; use winapi::shared::minwindef::{DWORD, FALSE, FILETIME, MAX_PATH /*, TRUE, USHORT*/}; use winapi::um::handleapi::CloseHandle; use winapi::um::processthreadsapi::{GetProcessTimes, OpenProcess, TerminateProcess}; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -130,7 +134,7 @@ unsafe fn get_h_mod(process_handler: HANDLE, h_mod: &mut *mut c_void) -> bool { EnumProcessModulesEx( process_handler, h_mod as *mut *mut c_void as _, - ::std::mem::size_of::<DWORD>() as DWORD, + size_of::<DWORD>() as DWORD, &mut cb_needed, LIST_MODULES_ALL, ) != 0 diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -157,6 +161,37 @@ unsafe fn get_exe(process_handler: HANDLE, h_mod: *mut c_void) -> PathBuf { } impl Process { + #[allow(clippy::uninit_assumed_init)] + pub(crate) fn new_from_pid(pid: Pid) -> Option<Process> { + let process_handler = unsafe { OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid as _) }; + if process_handler.is_null() { + return None; + } + let mut info: PROCESS_BASIC_INFORMATION = unsafe { MaybeUninit::uninit().assume_init() }; + if unsafe { + NtQueryInformationProcess( + process_handler, + ProcessBasicInformation, + &mut info as *mut _ as *mut _, + size_of::<PROCESS_BASIC_INFORMATION>() as _, + null_mut(), + ) + } != 0 + { + unsafe { CloseHandle(process_handler) }; + return None; + } + Some(Process::new_with_handle( + pid, + if info.InheritedFromUniqueProcessId as usize != 0 { + Some(info.InheritedFromUniqueProcessId as usize) + } else { + None + }, + process_handler, + )) + } + pub(crate) fn new_full( pid: Pid, parent: Option<Pid>, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -164,39 +199,37 @@ impl Process { virtual_memory: u64, name: String, ) -> Process { - if let Some(process_handler) = get_process_handler(pid) { - unsafe { - let mut h_mod = ::std::ptr::null_mut(); - get_h_mod(process_handler, &mut h_mod); - let environ = get_proc_env(process_handler, pid as u32, &name); - - let exe = get_exe(process_handler, h_mod); - let mut root = exe.clone(); - root.pop(); - Process { - handle: HandleWrapper(process_handler), - name, - pid, - parent, - cmd: get_cmd_line(pid), - environ, - exe, - cwd: PathBuf::new(), - root, - status: ProcessStatus::Run, - memory, - virtual_memory, - cpu_usage: 0., - old_cpu: 0, - old_sys_cpu: 0, - old_user_cpu: 0, - start_time: get_start_time(process_handler), - updated: true, - } + if let Some(handle) = get_process_handler(pid) { + let mut h_mod = null_mut(); + unsafe { get_h_mod(handle, &mut h_mod) }; + let environ = unsafe { get_proc_env(handle, pid as u32, &name) }; + + let exe = unsafe { get_exe(handle, h_mod) }; + let mut root = exe.clone(); + root.pop(); + Process { + handle: HandleWrapper(handle), + name, + pid, + parent, + cmd: get_cmd_line(pid), + environ, + exe, + cwd: PathBuf::new(), + root, + status: ProcessStatus::Run, + memory, + virtual_memory, + cpu_usage: 0., + old_cpu: 0, + old_sys_cpu: 0, + old_user_cpu: 0, + start_time: unsafe { get_start_time(handle) }, + updated: true, } } else { Process { - handle: HandleWrapper(::std::ptr::null_mut()), + handle: HandleWrapper(null_mut()), name, pid, parent, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -217,6 +250,43 @@ impl Process { } } } + + fn new_with_handle(pid: Pid, parent: Option<Pid>, process_handler: HANDLE) -> Process { + let mut h_mod = null_mut(); + + unsafe { + let name = if get_h_mod(process_handler, &mut h_mod) { + get_process_name(process_handler, h_mod) + } else { + String::new() + }; + let environ = get_proc_env(process_handler, pid as u32, &name); + + let exe = get_exe(process_handler, h_mod); + let mut root = exe.clone(); + root.pop(); + Process { + handle: HandleWrapper(process_handler), + name, + pid, + parent, + cmd: get_cmd_line(pid), + environ, + exe, + cwd: PathBuf::new(), + root, + status: ProcessStatus::Run, + memory: 0, + virtual_memory: 0, + cpu_usage: 0., + old_cpu: 0, + old_sys_cpu: 0, + old_user_cpu: 0, + start_time: get_start_time(process_handler), + updated: true, + } + } + } } // TODO: it's possible to get environment variables like it's done in diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -227,43 +297,10 @@ impl Process { impl ProcessExt for Process { fn new(pid: Pid, parent: Option<Pid>, _: u64) -> Process { if let Some(process_handler) = get_process_handler(pid) { - let mut h_mod = ::std::ptr::null_mut(); - - unsafe { - let name = if get_h_mod(process_handler, &mut h_mod) { - get_process_name(process_handler, h_mod) - } else { - String::new() - }; - let environ = get_proc_env(process_handler, pid as u32, &name); - - let exe = get_exe(process_handler, h_mod); - let mut root = exe.clone(); - root.pop(); - Process { - handle: HandleWrapper(process_handler), - name, - pid, - parent, - cmd: get_cmd_line(pid), - environ, - exe, - cwd: PathBuf::new(), - root, - status: ProcessStatus::Run, - memory: 0, - virtual_memory: 0, - cpu_usage: 0., - old_cpu: 0, - old_sys_cpu: 0, - old_user_cpu: 0, - start_time: get_start_time(process_handler), - updated: true, - } - } + Process::new_with_handle(pid, parent, process_handler) } else { Process { - handle: HandleWrapper(::std::ptr::null_mut()), + handle: HandleWrapper(null_mut()), name: String::new(), pid, parent, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -396,41 +433,6 @@ unsafe fn get_start_time(handle: HANDLE) -> u64 { tmp / 10_000_000 - 11_644_473_600 } -/*pub unsafe fn get_parent_process_id(pid: Pid) -> Option<Pid> { - use winapi::um::tlhelp32::{ - CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS, - }; - - let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); - let mut entry: PROCESSENTRY32 = zeroed(); - entry.dwSize = size_of::<PROCESSENTRY32>() as u32; - let mut not_the_end = Process32First(snapshot, &mut entry); - while not_the_end != 0 { - if pid == entry.th32ProcessID as usize { - // TODO: if some day I have the motivation to add threads: - // ListProcessThreads(entry.th32ProcessID); - CloseHandle(snapshot); - return Some(entry.th32ParentProcessID as usize); - } - not_the_end = Process32Next(snapshot, &mut entry); - } - CloseHandle(snapshot); - None -}*/ - -/*fn run_wmi(args: &[&str]) -> Option<String> { - use std::process::Command; - - if let Ok(out) = Command::new("wmic") - .args(args) - .output() { - if out.status.success() { - return Some(String::from_utf8_lossy(&out.stdout).into_owned()); - } - } - None -}*/ - fn get_cmd_line(_pid: Pid) -> Vec<String> { /*let where_req = format!("ProcessId={}", pid); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -482,7 +484,7 @@ unsafe fn get_proc_env(_handle: HANDLE, _pid: u32, _name: &str) -> Vec<String> { context.MxCsr as usize as *mut winapi::c_void, x.as_mut_ptr() as *mut winapi::c_void, x.len() as u64, - ::std::ptr::null_mut()) != 0 { + null_mut()) != 0 { for y in x { print!("{}", y as char); } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -176,11 +176,19 @@ impl SystemExt for System { } fn refresh_process(&mut self, pid: Pid) -> bool { - if refresh_existing_process(self, pid, true) == false { - self.process_list.remove(&pid); - false - } else { + if self.process_list.contains_key(&pid) { + if refresh_existing_process(self, pid, true) == false { + self.process_list.remove(&pid); + return false; + } true + } else if let Some(mut p) = Process::new_from_pid(pid) { + let system_time = get_system_computation_time(); + compute_cpu_usage(&mut p, self.processors.len() as u64, system_time); + self.process_list.insert(pid, p); + true + } else { + false } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -389,7 +397,7 @@ fn refresh_existing_process(s: &mut System, pid: Pid, compute_cpu: bool) -> bool } } -fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: usize) -> String { +pub(crate) fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: usize) -> String { let name = &process.ImageName; if name.Buffer.is_null() { match process_id {
d7bfc1e62c91c5f34e9e444bb083fa67716f3051
Different behavior on window for refresh_process Hi, I have a use case where I just ran a new child process, and then I call system.refresh_process(pid), and try to get the process info. Things work fine on linux and mac, however on windows, the process is not found. I suspect windows does not add a new process with refresh_process Amir
0.11
262
Great catch and thanks for the precise report! I'll check what's going on.
90049ce2c712284ee93379e4e5f9c03da41b9ee2
2020-01-26T22:19:43Z
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Support the following platforms: * Linux * Raspberry * Android - * Mac OSX + * macOS * Windows It also compiles for Android but never been tested on it. diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -94,17 +94,19 @@ Here are the current results: <details> ```text -test bench_new ... bench: 10,437,759 ns/iter (+/- 531,424) -test bench_refresh_all ... bench: 2,658,946 ns/iter (+/- 189,612) -test bench_refresh_cpu ... bench: 13,429 ns/iter (+/- 537) -test bench_refresh_disk_lists ... bench: 50,688 ns/iter (+/- 8,032) -test bench_refresh_disks ... bench: 2,582 ns/iter (+/- 226) -test bench_refresh_memory ... bench: 12,015 ns/iter (+/- 537) -test bench_refresh_network ... bench: 23,661 ns/iter (+/- 617) -test bench_refresh_process ... bench: 56,157 ns/iter (+/- 2,445) -test bench_refresh_processes ... bench: 2,486,534 ns/iter (+/- 121,187) -test bench_refresh_system ... bench: 53,739 ns/iter (+/- 6,793) -test bench_refresh_temperatures ... bench: 25,770 ns/iter (+/- 1,164) +test bench_new ... bench: 375,774 ns/iter (+/- 7,119) +test bench_new_all ... bench: 10,308,642 ns/iter (+/- 422,803) +test bench_refresh_all ... bench: 2,824,911 ns/iter (+/- 169,153) +test bench_refresh_cpu ... bench: 13,630 ns/iter (+/- 702) +test bench_refresh_disks ... bench: 2,558 ns/iter (+/- 14) +test bench_refresh_disks_lists ... bench: 51,737 ns/iter (+/- 5,712) +test bench_refresh_memory ... bench: 12,006 ns/iter (+/- 277) +test bench_refresh_networks ... bench: 223,858 ns/iter (+/- 28,537) +test bench_refresh_networks_list ... bench: 232,934 ns/iter (+/- 34,344) +test bench_refresh_process ... bench: 78,925 ns/iter (+/- 12,421) +test bench_refresh_processes ... bench: 2,235,119 ns/iter (+/- 137,403) +test bench_refresh_system ... bench: 52,832 ns/iter (+/- 6,704) +test bench_refresh_temperatures ... bench: 25,079 ns/iter (+/- 2,258) ``` </details> diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -113,36 +115,40 @@ test bench_refresh_temperatures ... bench: 25,770 ns/iter (+/- 1,164) <details> ```text -test bench_new ... bench: 61,548,071 ns/iter (+/- 196,093,742) -test bench_refresh_all ... bench: 2,541,951 ns/iter (+/- 482,285) -test bench_refresh_cpu ... bench: 460 ns/iter (+/- 478) -test bench_refresh_disk_lists ... bench: 152,940 ns/iter (+/- 8,330) -test bench_refresh_disks ... bench: 55,597 ns/iter (+/- 9,629) -test bench_refresh_memory ... bench: 2,130 ns/iter (+/- 486) -test bench_refresh_network ... bench: 212 ns/iter (+/- 216) -test bench_refresh_process ... bench: 38 ns/iter (+/- 33) -test bench_refresh_processes ... bench: 2,175,034 ns/iter (+/- 315,585) -test bench_refresh_system ... bench: 2,508 ns/iter (+/- 224) -test bench_refresh_temperatures ... bench: 1 ns/iter (+/- 0) +test bench_new ... bench: 14,738,570 ns/iter (+/- 586,107) +test bench_new_all ... bench: 27,132,490 ns/iter (+/- 1,292,307) +test bench_refresh_all ... bench: 3,075,022 ns/iter (+/- 110,711) +test bench_refresh_cpu ... bench: 392 ns/iter (+/- 30) +test bench_refresh_disks ... bench: 41,778 ns/iter (+/- 954) +test bench_refresh_disks_lists ... bench: 113,942 ns/iter (+/- 4,240) +test bench_refresh_memory ... bench: 578 ns/iter (+/- 41) +test bench_refresh_networks ... bench: 38,178 ns/iter (+/- 3,718) +test bench_refresh_networks_list ... bench: 668,390 ns/iter (+/- 30,642) +test bench_refresh_process ... bench: 745 ns/iter (+/- 62) +test bench_refresh_processes ... bench: 1,179,581 ns/iter (+/- 188,119) +test bench_refresh_system ... bench: 1,230,542 ns/iter (+/- 64,231) +test bench_refresh_temperatures ... bench: 1,231,260 ns/iter (+/- 111,274) ``` </details> -**OSX** +**macOS** <details> ```text -test bench_new ... bench: 4,713,851 ns/iter (+/- 1,080,986) -test bench_refresh_all ... bench: 1,639,098 ns/iter (+/- 191,147) -test bench_refresh_cpu ... bench: 10,651 ns/iter (+/- 1,635) -test bench_refresh_disk_lists ... bench: 29,327 ns/iter (+/- 3,104) -test bench_refresh_disks ... bench: 942 ns/iter (+/- 79) -test bench_refresh_memory ... bench: 3,417 ns/iter (+/- 654) -test bench_refresh_network ... bench: 34,497 ns/iter (+/- 2,681) -test bench_refresh_process ... bench: 4,272 ns/iter (+/- 549) -test bench_refresh_processes ... bench: 782,977 ns/iter (+/- 30,958) -test bench_refresh_system ... bench: 336,008 ns/iter (+/- 43,015) -test bench_refresh_temperatures ... bench: 294,323 ns/iter (+/- 41,612) +test bench_new ... bench: 54,862 ns/iter (+/- 6,528) +test bench_new_all ... bench: 4,989,120 ns/iter (+/- 1,001,529) +test bench_refresh_all ... bench: 1,924,596 ns/iter (+/- 341,209) +test bench_refresh_cpu ... bench: 10,521 ns/iter (+/- 1,623) +test bench_refresh_disks ... bench: 945 ns/iter (+/- 95) +test bench_refresh_disks_lists ... bench: 29,315 ns/iter (+/- 3,076) +test bench_refresh_memory ... bench: 3,275 ns/iter (+/- 143) +test bench_refresh_networks ... bench: 200,670 ns/iter (+/- 28,674) +test bench_refresh_networks_list ... bench: 200,263 ns/iter (+/- 31,473) +test bench_refresh_process ... bench: 4,009 ns/iter (+/- 584) +test bench_refresh_processes ... bench: 790,834 ns/iter (+/- 61,236) +test bench_refresh_system ... bench: 335,144 ns/iter (+/- 35,713) +test bench_refresh_temperatures ... bench: 298,823 ns/iter (+/- 77,589) ``` </details> diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -4,6 +4,7 @@ extern crate sysinfo; extern crate test; use sysinfo::SystemExt; +use sysinfo::get_current_pid; #[bench] fn bench_new(b: &mut test::Bencher) { diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -12,9 +13,16 @@ fn bench_new(b: &mut test::Bencher) { }); } +#[bench] +fn bench_new_all(b: &mut test::Bencher) { + b.iter(|| { + sysinfo::System::new_all(); + }); +} + #[bench] fn bench_refresh_all(b: &mut test::Bencher) { - let mut s = sysinfo::System::new(); + let mut s = sysinfo::System::new_all(); b.iter(move || { s.refresh_all(); diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -23,7 +31,7 @@ fn bench_refresh_all(b: &mut test::Bencher) { #[bench] fn bench_refresh_system(b: &mut test::Bencher) { - let mut s = sysinfo::System::new(); + let mut s = sysinfo::System::new_all(); s.refresh_system(); b.iter(move || { diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -35,6 +43,7 @@ fn bench_refresh_system(b: &mut test::Bencher) { fn bench_refresh_processes(b: &mut test::Bencher) { let mut s = sysinfo::System::new(); + s.refresh_processes(); // to load the whole processes list a first time. b.iter(move || { s.refresh_processes(); }); diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -45,7 +54,8 @@ fn bench_refresh_process(b: &mut test::Bencher) { let mut s = sysinfo::System::new(); s.refresh_all(); - let pid = *s.get_process_list().iter().take(1).next().unwrap().0; + // to be sure it'll exist for at least as long as we run + let pid = get_current_pid().expect("failed to get current pid"); b.iter(move || { s.refresh_process(pid); }); diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -53,7 +63,7 @@ fn bench_refresh_process(b: &mut test::Bencher) { #[bench] fn bench_refresh_disks(b: &mut test::Bencher) { - let mut s = sysinfo::System::new(); + let mut s = sysinfo::System::new_all(); b.iter(move || { s.refresh_disks(); diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -61,20 +71,29 @@ fn bench_refresh_disks(b: &mut test::Bencher) { } #[bench] -fn bench_refresh_disk_lists(b: &mut test::Bencher) { +fn bench_refresh_disks_lists(b: &mut test::Bencher) { let mut s = sysinfo::System::new(); b.iter(move || { - s.refresh_disk_list(); + s.refresh_disks_list(); }); } #[bench] -fn bench_refresh_network(b: &mut test::Bencher) { +fn bench_refresh_networks(b: &mut test::Bencher) { + let mut s = sysinfo::System::new_all(); + + b.iter(move || { + s.refresh_networks(); + }); +} + +#[bench] +fn bench_refresh_networks_list(b: &mut test::Bencher) { let mut s = sysinfo::System::new(); b.iter(move || { - s.refresh_network(); + s.refresh_networks_list(); }); } diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -98,7 +117,7 @@ fn bench_refresh_cpu(b: &mut test::Bencher) { #[bench] fn bench_refresh_temperatures(b: &mut test::Bencher) { - let mut s = sysinfo::System::new(); + let mut s = sysinfo::System::new_all(); b.iter(move || { s.refresh_temperatures(); diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -205,9 +209,21 @@ pub enum Signal { Sys = 31, } +/// A struct represents system load average value. +#[repr(C)] +#[derive(Default, Debug, Clone)] +pub struct LoadAvg { + /// Average load within one minute. + pub one: f64, + /// Average load within five minutes. + pub five: f64, + /// Average load within fifteen minutes. + pub fifteen: f64, +} + #[cfg(test)] mod test { - use traits::{ProcessExt, SystemExt}; + use super::*; #[test] fn check_memory_usage() { diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -25,7 +25,12 @@ mod tests { #[test] fn test_refresh_process() { let mut sys = System::new(); - assert!(sys.refresh_process(utils::get_current_pid().expect("failed to get current pid"))); + assert!(sys.get_process_list().is_empty(), "no process should be listed!"); + sys.refresh_processes(); + assert!( + sys.refresh_process(utils::get_current_pid().expect("failed to get current pid")), + "process not listed", + ); } #[test] diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -8,7 +8,9 @@ extern crate sysinfo; #[test] fn test_process() { - use sysinfo::{ProcessExt, SystemExt}; + #[cfg(not(windows))] + use sysinfo::ProcessExt; + use sysinfo::SystemExt; let mut s = sysinfo::System::new(); s.refresh_processes();
[ "215" ]
GuillaumeGomez__sysinfo-245
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -16,17 +16,15 @@ build = "build.rs" cfg-if = "0.1" rayon = "^1.0" doc-comment = "0.3" +once_cell = "1.0" [target.'cfg(windows)'.dependencies] -winapi = { version = "0.3", features = ["fileapi", "handleapi", "ioapiset", "minwindef", "pdh", "psapi", "synchapi", "sysinfoapi", "winbase", "winerror", "winioctl", "winnt", "oleauto", "wbemcli", "rpcdce", "combaseapi", "objidl", "objbase"] } +winapi = { version = "0.3", features = ["fileapi", "handleapi", "ifdef", "ioapiset", "minwindef", "pdh", "psapi", "synchapi", "sysinfoapi", "winbase", "winerror", "winioctl", "winnt", "oleauto", "wbemcli", "rpcdce", "combaseapi", "objidl", "objbase", "powerbase", "netioapi"] } ntapi = "0.3" [target.'cfg(not(any(target_os = "unknown", target_arch = "wasm32")))'.dependencies] libc = "0.2" -[target.'cfg(unix)'.dependencies] -once_cell = "1.0" - [lib] name = "sysinfo" crate_type = ["rlib", "cdylib"] diff --git a/examples/src/simple.c b/examples/src/simple.c --- a/examples/src/simple.c +++ b/examples/src/simple.c @@ -63,19 +63,19 @@ bool process_loop(pid_t pid, CProcess process, void *data) { int main() { CSystem system = sysinfo_init(); sysinfo_refresh_all(system); - printf("total memory: %ld\n", sysinfo_get_total_memory(system)); - printf("free memory: %ld\n", sysinfo_get_free_memory(system)); - printf("used memory: %ld\n", sysinfo_get_used_memory(system)); - printf("total swap: %ld\n", sysinfo_get_total_swap(system)); - printf("free swap: %ld\n", sysinfo_get_free_swap(system)); - printf("used swap: %ld\n", sysinfo_get_used_swap(system)); - printf("network income: %ld\n", sysinfo_get_network_income(system)); - printf("network outcome: %ld\n", sysinfo_get_network_outcome(system)); + printf("total memory: %ld\n", sysinfo_get_total_memory(system)); + printf("free memory: %ld\n", sysinfo_get_free_memory(system)); + printf("used memory: %ld\n", sysinfo_get_used_memory(system)); + printf("total swap: %ld\n", sysinfo_get_total_swap(system)); + printf("free swap: %ld\n", sysinfo_get_free_swap(system)); + printf("used swap: %ld\n", sysinfo_get_used_swap(system)); + printf("networks income: %ld\n", sysinfo_get_networks_income(system)); + printf("networks outcome: %ld\n", sysinfo_get_networks_outcome(system)); unsigned int len = 0, i = 0; float *procs = NULL; sysinfo_get_processors_usage(system, &len, &procs); while (i < len) { - printf("Processor #%d usage: %f\n", i, procs[i]); + printf("Processor #%d usage: %f%%\n", i, procs[i]); i += 1; } free(procs); diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -1,43 +1,126 @@ -// +// // Sysinfo -// +// // Copyright (c) 2017 Guillaume Gomez // #![crate_type = "bin"] - #![allow(unused_must_use, non_upper_case_globals)] extern crate sysinfo; -use sysinfo::{NetworkExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt}; -use sysinfo::Signal::*; use std::io::{self, BufRead, Write}; use std::str::FromStr; +use sysinfo::Signal::*; +use sysinfo::{NetworkExt, NetworksExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt}; -const signals: [Signal; 31] = [Hangup, Interrupt, Quit, Illegal, Trap, Abort, Bus, - FloatingPointException, Kill, User1, Segv, User2, Pipe, Alarm, - Term, Stklft, Child, Continue, Stop, TSTP, TTIN, TTOU, Urgent, - XCPU, XFSZ, VirtualAlarm, Profiling, Winch, IO, Power, Sys]; +const signals: [Signal; 31] = [ + Hangup, + Interrupt, + Quit, + Illegal, + Trap, + Abort, + Bus, + FloatingPointException, + Kill, + User1, + Segv, + User2, + Pipe, + Alarm, + Term, + Stklft, + Child, + Continue, + Stop, + TSTP, + TTIN, + TTOU, + Urgent, + XCPU, + XFSZ, + VirtualAlarm, + Profiling, + Winch, + IO, + Power, + Sys, +]; fn print_help() { writeln!(&mut io::stdout(), "== Help menu =="); writeln!(&mut io::stdout(), "help : show this menu"); - writeln!(&mut io::stdout(), "signals : show the available signals"); - writeln!(&mut io::stdout(), "refresh : reloads all processes' information"); - writeln!(&mut io::stdout(), "refresh [pid] : reloads corresponding process' information"); - writeln!(&mut io::stdout(), "refresh_disks : reloads only disks' information"); - writeln!(&mut io::stdout(), "show [pid | name] : show information of the given process \ - corresponding to [pid | name]"); - writeln!(&mut io::stdout(), "kill [pid] [signal]: send [signal] to the process with this \ - [pid]. 0 < [signal] < 32"); - writeln!(&mut io::stdout(), "proc : Displays proc state"); - writeln!(&mut io::stdout(), "memory : Displays memory state"); - writeln!(&mut io::stdout(), "temperature : Displays components' temperature"); - writeln!(&mut io::stdout(), "disks : Displays disks' information"); - writeln!(&mut io::stdout(), "network : Displays network' information"); - writeln!(&mut io::stdout(), "all : Displays all process name and pid"); - writeln!(&mut io::stdout(), "uptime : Displays system uptime"); + writeln!( + &mut io::stdout(), + "signals : show the available signals" + ); + writeln!( + &mut io::stdout(), + "refresh : reloads all processes' information" + ); + writeln!( + &mut io::stdout(), + "refresh [pid] : reloads corresponding process' information" + ); + writeln!( + &mut io::stdout(), + "refresh_disks : reloads only disks' information" + ); + writeln!( + &mut io::stdout(), + "show [pid | name] : show information of the given process \ + corresponding to [pid | name]" + ); + writeln!( + &mut io::stdout(), + "kill [pid] [signal]: send [signal] to the process with this \ + [pid]. 0 < [signal] < 32" + ); + writeln!( + &mut io::stdout(), + "procd : Displays processors state" + ); + writeln!( + &mut io::stdout(), + "memory : Displays memory state" + ); + writeln!( + &mut io::stdout(), + "temperature : Displays components' temperature" + ); + writeln!( + &mut io::stdout(), + "disks : Displays disks' information" + ); + writeln!( + &mut io::stdout(), + "network : Displays network' information" + ); + writeln!( + &mut io::stdout(), + "all : Displays all process name and pid" + ); + writeln!( + &mut io::stdout(), + "uptime : Displays system uptime" + ); + writeln!( + &mut io::stdout(), + "vendor_id : Displays processor vendor id" + ); + writeln!( + &mut io::stdout(), + "brand : Displays processor brand" + ); + writeln!( + &mut io::stdout(), + "load_avg : Displays system load average" + ); + writeln!( + &mut io::stdout(), + "frequency : Displays processor frequency" + ); writeln!(&mut io::stdout(), "quit : exit the program"); } diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -46,7 +129,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { "help" => print_help(), "refresh_disks" => { writeln!(&mut io::stdout(), "Refreshing disk list..."); - sys.refresh_disk_list(); + sys.refresh_disks_list(); writeln!(&mut io::stdout(), "Done."); } "signals" => { diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -57,32 +140,91 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { nb += 1; } } - "proc" => { - // Note: you should refresh a few times before using this, so that usage statistics can be ascertained + "procs" => { + // Note: you should refresh a few times before using this, so that usage statistics + // can be ascertained let procs = sys.get_processor_list(); - writeln!(&mut io::stdout(), "total process usage: {}%", procs[0].get_cpu_usage()); + writeln!( + &mut io::stdout(), + "total process usage: {}%", + procs[0].get_cpu_usage() + ); for proc_ in procs.iter().skip(1) { writeln!(&mut io::stdout(), "{:?}", proc_); } } "memory" => { - writeln!(&mut io::stdout(), "total memory: {} KiB", sys.get_total_memory()); - writeln!(&mut io::stdout(), "used memory : {} KiB", sys.get_used_memory()); - writeln!(&mut io::stdout(), "total swap : {} KiB", sys.get_total_swap()); - writeln!(&mut io::stdout(), "used swap : {} KiB", sys.get_used_swap()); + writeln!( + &mut io::stdout(), + "total memory: {} KiB", + sys.get_total_memory() + ); + writeln!( + &mut io::stdout(), + "used memory : {} KiB", + sys.get_used_memory() + ); + writeln!( + &mut io::stdout(), + "total swap : {} KiB", + sys.get_total_swap() + ); + writeln!( + &mut io::stdout(), + "used swap : {} KiB", + sys.get_used_swap() + ); } "quit" | "exit" => return true, "all" => { for (pid, proc_) in sys.get_process_list() { - writeln!(&mut io::stdout(), "{}:{} status={:?}", pid, proc_.name(), proc_.status()); + writeln!( + &mut io::stdout(), + "{}:{} status={:?}", + pid, + proc_.name(), + proc_.status() + ); } } + "frequency" => { + let procs = sys.get_processor_list(); + // On windows, the first processor is the "all processors", so not interesting in here. + writeln!( + &mut io::stdout(), + "{} MHz", + procs[if procs.len() > 1 { 1 } else { 0 }].get_frequency() + ); + } + "vendor_id" => { + writeln!( + &mut io::stdout(), + "vendor ID: {}", + sys.get_processor_list()[0].get_vendor_id() + ); + } + "brand" => { + writeln!( + &mut io::stdout(), + "brand: {}", + sys.get_processor_list()[0].get_brand() + ); + } + "load_avg" => { + let load_avg = sys.get_load_average(); + writeln!(&mut io::stdout(), "one minute : {}%", load_avg.one); + writeln!(&mut io::stdout(), "five minutes : {}%", load_avg.five); + writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen); + } e if e.starts_with("show ") => { - let tmp : Vec<&str> = e.split(' ').collect(); + let tmp: Vec<&str> = e.split(' ').collect(); if tmp.len() != 2 { - writeln!(&mut io::stdout(), "show command takes a pid or a name in parameter!"); + writeln!( + &mut io::stdout(), + "show command takes a pid or a name in parameter!" + ); writeln!(&mut io::stdout(), "example: show 1254"); } else if let Ok(pid) = Pid::from_str(tmp[1]) { match sys.get_process(pid) { diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -103,33 +245,52 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { } } "network" => { - writeln!(&mut io::stdout(), "input data : {} B", sys.get_network().get_income()); - writeln!(&mut io::stdout(), "output data: {} B", sys.get_network().get_outcome()); + for (interface_name, data) in sys.get_networks().iter() { + writeln!( + &mut io::stdout(), + "{}:\n input data (new / total): {} / {} B\n output data (new / total): {} / {} B", + interface_name, + data.get_income(), + data.get_total_income(), + data.get_outcome(), + data.get_total_outcome(), + ); + } } "show" => { - writeln!(&mut io::stdout(), "'show' command expects a pid number or a process name"); + writeln!( + &mut io::stdout(), + "'show' command expects a pid number or a process name" + ); } e if e.starts_with("kill ") => { - let tmp : Vec<&str> = e.split(' ').collect(); + let tmp: Vec<&str> = e.split(' ').collect(); if tmp.len() != 3 { - writeln!(&mut io::stdout(), - "kill command takes the pid and a signal number in parameter !"); + writeln!( + &mut io::stdout(), + "kill command takes the pid and a signal number in parameter !" + ); writeln!(&mut io::stdout(), "example: kill 1254 9"); } else { let pid = Pid::from_str(tmp[1]).unwrap(); let signal = i32::from_str(tmp[2]).unwrap(); if signal < 1 || signal > 31 { - writeln!(&mut io::stdout(), - "Signal must be between 0 and 32 ! See the signals list with the \ - signals command"); + writeln!( + &mut io::stdout(), + "Signal must be between 0 and 32 ! See the signals list with the \ + signals command" + ); } else { match sys.get_process(pid) { Some(p) => { - writeln!(&mut io::stdout(), "kill: {}", - p.kill(*signals.get(signal as usize - 1).unwrap())); - }, + writeln!( + &mut io::stdout(), + "kill: {}", + p.kill(*signals.get(signal as usize - 1).unwrap()) + ); + } None => { writeln!(&mut io::stdout(), "pid not found"); } diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -149,11 +310,13 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { let hours = uptime / 3600; uptime -= hours * 3600; let minutes = uptime / 60; - writeln!(&mut io::stdout(), - "{} days {} hours {} minutes", - days, - hours, - minutes); + writeln!( + &mut io::stdout(), + "{} days {} hours {} minutes", + days, + hours, + minutes + ); } x if x.starts_with("refresh") => { if x == "refresh" { diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -162,25 +325,40 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { writeln!(&mut io::stdout(), "Done."); } else if x.starts_with("refresh ") { writeln!(&mut io::stdout(), "Getting process' information..."); - if let Some(pid) = x.split(' ').filter_map(|pid| pid.parse().ok()).take(1).next() { + if let Some(pid) = x + .split(' ') + .filter_map(|pid| pid.parse().ok()) + .take(1) + .next() + { if sys.refresh_process(pid) { writeln!(&mut io::stdout(), "Process `{}` updated successfully", pid); } else { - writeln!(&mut io::stdout(), "Process `{}` couldn't be updated...", pid); + writeln!( + &mut io::stdout(), + "Process `{}` couldn't be updated...", + pid + ); } } else { writeln!(&mut io::stdout(), "Invalid [pid] received..."); } } else { - writeln!(&mut io::stdout(), - "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \ - list.", x); + writeln!( + &mut io::stdout(), + "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \ + list.", + x + ); } } e => { - writeln!(&mut io::stdout(), - "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \ - list.", e); + writeln!( + &mut io::stdout(), + "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \ + list.", + e + ); } } false diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -188,7 +366,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { fn main() { println!("Getting processes' information..."); - let mut t = System::new(); + let mut t = System::new_all(); println!("Done."); let t_stin = io::stdin(); let mut stin = t_stin.lock(); diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -201,6 +379,12 @@ fn main() { io::stdout().flush(); stin.read_line(&mut input); + if input.is_empty() { + // The string is empty, meaning there is no '\n', meaning + // that the user used CTRL+D so we can just quit! + println!("\nLeaving, bye!"); + break; + } if (&input as &str).ends_with('\n') { input.pop(); } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -7,7 +7,7 @@ use libc::{self, c_char, c_float, c_uint, c_void, pid_t, size_t}; use std::borrow::BorrowMut; use std::ffi::CString; -use {NetworkExt, Process, ProcessExt, ProcessorExt, System, SystemExt}; +use {NetworkExt, NetworksExt, Process, ProcessExt, ProcessorExt, System, SystemExt}; /// Equivalent of `System` struct. pub type CSystem = *mut c_void; diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -131,14 +131,14 @@ pub extern "C" fn sysinfo_refresh_disks(system: CSystem) { Box::into_raw(system); } -/// Equivalent of `System::refresh_disk_list()`. +/// Equivalent of `System::refresh_disks_list()`. #[no_mangle] -pub extern "C" fn sysinfo_refresh_disk_list(system: CSystem) { +pub extern "C" fn sysinfo_refresh_disks_list(system: CSystem) { assert!(!system.is_null()); let mut system: Box<System> = unsafe { Box::from_raw(system as *mut System) }; { let system: &mut System = system.borrow_mut(); - system.refresh_disk_list(); + system.refresh_disks_list(); } Box::into_raw(system); } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -203,22 +203,30 @@ pub extern "C" fn sysinfo_get_used_swap(system: CSystem) -> size_t { ret } -/// Equivalent of `system::get_network().get_income()`. +/// Equivalent of +/// `system::get_networks().iter().fold(0, |acc, (_, data)| acc + data.get_income() as size_t)`. #[no_mangle] -pub extern "C" fn sysinfo_get_network_income(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_get_networks_income(system: CSystem) -> size_t { assert!(!system.is_null()); let system: Box<System> = unsafe { Box::from_raw(system as *mut System) }; - let ret = system.get_network().get_income() as size_t; + let ret = system + .get_networks() + .iter() + .fold(0, |acc, (_, data)| acc + data.get_income() as size_t); Box::into_raw(system); ret } -/// Equivalent of `system::get_network().get_outcome()`. +/// Equivalent of +/// `system::get_networks().iter().fold(0, |acc, (_, data)| acc + data.get_outcome() as size_t)`. #[no_mangle] -pub extern "C" fn sysinfo_get_network_outcome(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_get_networks_outcome(system: CSystem) -> size_t { assert!(!system.is_null()); let system: Box<System> = unsafe { Box::from_raw(system as *mut System) }; - let ret = system.get_network().get_outcome() as size_t; + let ret = system + .get_networks() + .iter() + .fold(0, |acc, (_, data)| acc + data.get_outcome() as size_t); Box::into_raw(system); ret } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -4,6 +4,10 @@ // Copyright (c) 2015 Guillaume Gomez // +use NetworkData; +use Networks; +use NetworksExt; + /// Trait to have a common fallback for the `Pid` type. pub trait AsU32 { /// Allows to convert `Pid` into `u32`. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -105,16 +109,17 @@ assert_eq!(r.", stringify!($name), "(), false); /// use sysinfo::{RefreshKind, System, SystemExt}; /// /// // We want everything except disks. -/// let mut system = System::new_with_specifics(RefreshKind::everything().without_disk_list()); +/// let mut system = System::new_with_specifics(RefreshKind::everything().without_disks_list()); /// /// assert_eq!(system.get_disks().len(), 0); /// assert!(system.get_process_list().len() > 0); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct RefreshKind { - network: bool, + networks: bool, + networks_list: bool, processes: bool, - disk_list: bool, + disks_list: bool, disks: bool, memory: bool, cpu: bool, diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -131,9 +136,10 @@ impl RefreshKind { /// /// let r = RefreshKind::new(); /// - /// assert_eq!(r.network(), false); + /// assert_eq!(r.networks(), false); + /// assert_eq!(r.networks_list(), false); /// assert_eq!(r.processes(), false); - /// assert_eq!(r.disk_list(), false); + /// assert_eq!(r.disks_list(), false); /// assert_eq!(r.disks(), false); /// assert_eq!(r.memory(), false); /// assert_eq!(r.cpu(), false); diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -141,10 +147,11 @@ impl RefreshKind { /// ``` pub fn new() -> RefreshKind { RefreshKind { - network: false, + networks: false, + networks_list: false, processes: false, disks: false, - disk_list: false, + disks_list: false, memory: false, cpu: false, temperatures: false, diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -160,9 +167,10 @@ impl RefreshKind { /// /// let r = RefreshKind::everything(); /// - /// assert_eq!(r.network(), true); + /// assert_eq!(r.networks(), true); + /// assert_eq!(r.networks_list(), true); /// assert_eq!(r.processes(), true); - /// assert_eq!(r.disk_list(), true); + /// assert_eq!(r.disks_list(), true); /// assert_eq!(r.disks(), true); /// assert_eq!(r.memory(), true); /// assert_eq!(r.cpu(), true); diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -170,21 +178,51 @@ impl RefreshKind { /// ``` pub fn everything() -> RefreshKind { RefreshKind { - network: true, + networks: true, + networks_list: true, processes: true, disks: true, - disk_list: true, + disks_list: true, memory: true, cpu: true, temperatures: true, } } - impl_get_set!(network, with_network, without_network); + impl_get_set!(networks, with_networks, without_networks); + impl_get_set!(networks_list, with_networks_list, without_networks_list); impl_get_set!(processes, with_processes, without_processes); impl_get_set!(disks, with_disks, without_disks); - impl_get_set!(disk_list, with_disk_list, without_disk_list); + impl_get_set!(disks_list, with_disks_list, without_disks_list); impl_get_set!(memory, with_memory, without_memory); impl_get_set!(cpu, with_cpu, without_cpu); impl_get_set!(temperatures, with_temperatures, without_temperatures); } + +/// Iterator over network interfaces. +pub struct NetworksIter<'a> { + inner: std::collections::hash_map::Iter<'a, String, NetworkData>, +} + +impl<'a> NetworksIter<'a> { + pub(crate) fn new(v: std::collections::hash_map::Iter<'a, String, NetworkData>) -> Self { + NetworksIter { inner: v } + } +} + +impl<'a> Iterator for NetworksIter<'a> { + type Item = (&'a String, &'a NetworkData); + + fn next(&mut self) -> Option<Self::Item> { + self.inner.next() + } +} + +impl<'a> IntoIterator for &'a Networks { + type Item = (&'a String, &'a NetworkData); + type IntoIter = NetworksIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} diff --git a/src/linux/mod.rs b/src/linux/mod.rs --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -13,7 +13,7 @@ pub mod system; pub use self::component::Component; pub use self::disk::{Disk, DiskType}; -pub use self::network::NetworkData; +pub use self::network::{NetworkData, Networks}; pub use self::process::{Process, ProcessStatus}; pub use self::processor::Processor; pub use self::system::System; diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -5,79 +5,220 @@ // use std::fs::File; -use std::io::{Error, ErrorKind, Read}; +use std::io::Read; +use std::path::Path; +use std::collections::HashMap; use NetworkExt; +use NetworksExt; +use NetworksIter; -/// Contains network information. +/// Network interfaces. +/// +/// ```no_run +/// use sysinfo::{NetworksExt, System, SystemExt}; +/// +/// let s = System::new_all(); +/// let networks = s.get_networks(); +/// ``` #[derive(Debug)] -pub struct NetworkData { - old_in: u64, - old_out: u64, - current_in: u64, - current_out: u64, +pub struct Networks { + interfaces: HashMap<String, NetworkData>, } -impl NetworkExt for NetworkData { - fn get_income(&self) -> u64 { - self.current_in - self.old_in - } +macro_rules! old_and_new { + ($ty_:expr, $name:ident, $old:ident) => {{ + $ty_.$old = $ty_.$name; + $ty_.$name = $name; + }}; + ($ty_:expr, $name:ident, $old:ident, $path:expr) => {{ + let _tmp = $path; + $ty_.$old = $ty_.$name; + $ty_.$name = _tmp; + }}; +} - fn get_outcome(&self) -> u64 { - self.current_out - self.old_out +fn read<P: AsRef<Path>>(parent: P, path: &str, data: &mut Vec<u8>) -> usize { + if let Ok(mut f) = File::open(parent.as_ref().join(path)) { + if let Ok(size) = f.read(data) { + let mut i = 0; + let mut ret = 0; + + while i < size && i < data.len() && data[i] >= b'0' && data[i] <= b'9' { + ret *= 10; + ret += (data[i] - b'0') as usize; + i += 1; + } + return ret; + } } + 0 } -pub fn new() -> NetworkData { - NetworkData { - old_in: 0, - old_out: 0, - current_in: 0, - current_out: 0, +impl Networks { + pub(crate) fn new() -> Self { + Networks { + interfaces: HashMap::new(), + } } } -fn read_things() -> Result<(u64, u64), Error> { - fn read_interface_stat(iface: &str, typ: &str) -> Result<u64, Error> { - let mut file = File::open(format!("/sys/class/net/{}/statistics/{}_bytes", iface, typ))?; - let mut content = String::with_capacity(20); - file.read_to_string(&mut content)?; - content - .trim() - .parse() - .map_err(|_| Error::new(ErrorKind::Other, "Failed to parse network stat")) +impl NetworksExt for Networks { + fn iter<'a>(&'a self) -> NetworksIter<'a> { + NetworksIter::new(self.interfaces.iter()) } - let default_interface = { - let mut file = File::open("/proc/net/route")?; - let mut content = String::with_capacity(800); - file.read_to_string(&mut content)?; - content - .lines() - .filter(|l| { - l.split_whitespace() - .nth(2) - .map(|l| l != "00000000") - .unwrap_or(false) - }) - .last() - .and_then(|l| l.split_whitespace().nth(0)) - .ok_or_else(|| Error::new(ErrorKind::Other, "Default device not found"))? - .to_owned() - }; - - Ok(( - read_interface_stat(&default_interface, "rx")?, - read_interface_stat(&default_interface, "tx")?, - )) + fn refresh(&mut self) { + let mut v = vec![0; 30]; + + for (interface_name, data) in self.interfaces.iter_mut() { + data.update(interface_name, &mut v); + } + } + + fn refresh_networks_list(&mut self) { + if let Ok(dir) = std::fs::read_dir("/sys/class/net/") { + let mut data = vec![0; 30]; + for entry in dir { + if let Ok(entry) = entry { + let parent = &entry.path().join("statistics"); + let entry = match entry.file_name().into_string() { + Ok(entry) => entry, + Err(_) => continue, + }; + let rx_bytes = read(parent, "rx_bytes", &mut data); + let tx_bytes = read(parent, "tx_bytes", &mut data); + let rx_packets = read(parent, "rx_packets", &mut data); + let tx_packets = read(parent, "tx_packets", &mut data); + let rx_errors = read(parent, "rx_errors", &mut data); + let tx_errors = read(parent, "tx_errors", &mut data); + // let rx_compressed = read(parent, "rx_compressed", &mut data); + // let tx_compressed = read(parent, "tx_compressed", &mut data); + let interface = self.interfaces.entry(entry).or_insert_with(|| NetworkData { + rx_bytes, + old_rx_bytes: rx_bytes, + tx_bytes, + old_tx_bytes: tx_bytes, + rx_packets, + old_rx_packets: rx_packets, + tx_packets, + old_tx_packets: tx_packets, + rx_errors, + old_rx_errors: rx_errors, + tx_errors, + old_tx_errors: tx_errors, + // rx_compressed, + // old_rx_compressed: rx_compressed, + // tx_compressed, + // old_tx_compressed: tx_compressed, + }); + old_and_new!(interface, rx_bytes, old_rx_bytes); + old_and_new!(interface, tx_bytes, old_tx_bytes); + old_and_new!(interface, rx_packets, old_rx_packets); + old_and_new!(interface, tx_packets, old_tx_packets); + old_and_new!(interface, rx_errors, old_rx_errors); + old_and_new!(interface, tx_errors, old_tx_errors); + // old_and_new!(interface, rx_compressed, old_rx_compressed); + // old_and_new!(interface, tx_compressed, old_tx_compressed); + } + } + } + } } -pub fn update_network(n: &mut NetworkData) { - if let Ok((new_in, new_out)) = read_things() { - n.old_in = n.current_in; - n.old_out = n.current_out; - n.current_in = new_in; - n.current_out = new_out; +/// Contains network information. +#[derive(Debug)] +pub struct NetworkData { + /// Total number of bytes received over interface. + rx_bytes: usize, + old_rx_bytes: usize, + /// Total number of bytes transmitted over interface. + tx_bytes: usize, + old_tx_bytes: usize, + /// Total number of packets received. + rx_packets: usize, + old_rx_packets: usize, + /// Total number of packets transmitted. + tx_packets: usize, + old_tx_packets: usize, + /// Shows the total number of packets received with error. This includes + /// too-long-frames errors, ring-buffer overflow errors, CRC errors, + /// frame alignment errors, fifo overruns, and missed packets. + rx_errors: usize, + old_rx_errors: usize, + /// similar to `rx_errors` + tx_errors: usize, + old_tx_errors: usize, + // /// Indicates the number of compressed packets received by this + // /// network device. This value might only be relevant for interfaces + // /// that support packet compression (e.g: PPP). + // rx_compressed: usize, + // old_rx_compressed: usize, + // /// Indicates the number of transmitted compressed packets. Note + // /// this might only be relevant for devices that support + // /// compression (e.g: PPP). + // tx_compressed: usize, + // old_tx_compressed: usize, +} + +impl NetworkData { + fn update(&mut self, path: &str, data: &mut Vec<u8>) { + let path = &Path::new("/sys/class/net/").join(path).join("statistics"); + old_and_new!(self, rx_bytes, old_rx_bytes, read(path, "rx_bytes", data)); + old_and_new!(self, tx_bytes, old_tx_bytes, read(path, "tx_bytes", data)); + old_and_new!( + self, + rx_packets, + old_rx_packets, + read(path, "rx_packets", data) + ); + old_and_new!( + self, + tx_packets, + old_tx_packets, + read(path, "tx_packets", data) + ); + old_and_new!( + self, + rx_errors, + old_rx_errors, + read(path, "rx_errors", data) + ); + old_and_new!( + self, + tx_errors, + old_tx_errors, + read(path, "tx_errors", data) + ); + // old_and_new!( + // self, + // rx_compressed, + // old_rx_compressed, + // read(path, "rx_compressed", data) + // ); + // old_and_new!( + // self, + // tx_compressed, + // old_tx_compressed, + // read(path, "tx_compressed", data) + // ); + } +} + +impl NetworkExt for NetworkData { + fn get_income(&self) -> u64 { + self.rx_bytes as u64 - self.old_rx_bytes as u64 + } + + fn get_outcome(&self) -> u64 { + self.tx_bytes as u64 - self.old_tx_bytes as u64 + } + + fn get_total_income(&self) -> u64 { + self.rx_bytes as u64 + } + + fn get_total_outcome(&self) -> u64 { + self.rx_bytes as u64 } - // TODO: maybe handle error here? } diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -6,6 +6,9 @@ #![allow(clippy::too_many_arguments)] +use std::fs::File; +use std::io::Read; + use ProcessorExt; /// Struct containing values to compute a CPU usage. diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -125,22 +128,13 @@ pub struct Processor { cpu_usage: f32, total_time: u64, old_total_time: u64, + frequency: u64, + vendor_id: String, + brand: String, } impl Processor { - #[allow(dead_code)] - fn new() -> Processor { - Processor { - name: String::new(), - old_values: CpuValues::new(), - new_values: CpuValues::new(), - cpu_usage: 0f32, - total_time: 0, - old_total_time: 0, - } - } - - fn new_with_values( + pub(crate) fn new_with_values( name: &str, user: u64, nice: u64, diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -152,6 +146,9 @@ impl Processor { steal: u64, guest: u64, guest_nice: u64, + frequency: u64, + vendor_id: String, + brand: String, ) -> Processor { Processor { name: name.to_owned(), diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -162,10 +159,13 @@ impl Processor { cpu_usage: 0f32, total_time: 0, old_total_time: 0, + frequency, + vendor_id, + brand, } } - fn set( + pub(crate) fn set( &mut self, user: u64, nice: u64, diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -208,44 +208,74 @@ impl ProcessorExt for Processor { fn get_name(&self) -> &str { &self.name } -} -pub fn new_processor( - name: &str, - user: u64, - nice: u64, - system: u64, - idle: u64, - iowait: u64, - irq: u64, - softirq: u64, - steal: u64, - guest: u64, - guest_nice: u64, -) -> Processor { - Processor::new_with_values( - name, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice, - ) -} + /// Returns the CPU frequency in MHz. + fn get_frequency(&self) -> u64 { + self.frequency + } -pub fn set_processor( - p: &mut Processor, - user: u64, - nice: u64, - system: u64, - idle: u64, - iowait: u64, - irq: u64, - softirq: u64, - steal: u64, - guest: u64, - guest_nice: u64, -) { - p.set( - user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice, - ) + fn get_vendor_id(&self) -> &str { + &self.vendor_id + } + + fn get_brand(&self) -> &str { + &self.brand + } } pub fn get_raw_times(p: &Processor) -> (u64, u64) { (p.new_values.total_time(), p.old_values.total_time()) } + +pub fn get_cpu_frequency() -> u64 { + // /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_cur_freq + let mut s = String::new(); + if let Err(_) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) { + return 0; + } + + let find_cpu_mhz = s.split('\n').find(|line| { + line.starts_with("cpu MHz\t") + || line.starts_with("BogoMIPS") + || line.starts_with("clock\t") + || line.starts_with("bogomips per cpu") + }); + + find_cpu_mhz + .and_then(|line| line.split(':').last()) + .and_then(|val| val.replace("MHz", "").trim().parse::<f64>().ok()) + .map(|speed| speed as u64) + .unwrap_or_default() +} + +/// Returns the brand/vendor string for the first CPU (which should be the same for all CPUs). +pub fn get_vendor_id_and_brand() -> (String, String) { + let mut s = String::new(); + if let Err(_) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) { + return (String::new(), String::new()); + } + + fn get_value(s: &str) -> String { + s.split(':') + .last() + .map(|x| x.trim().to_owned()) + .unwrap_or_default() + } + + let mut vendor_id = None; + let mut brand = None; + + for it in s.split('\n') { + if it.starts_with("vendor_id\t") { + vendor_id = Some(get_value(it)); + } else if it.starts_with("model name\t") { + brand = Some(get_value(it)); + } else { + continue; + } + if brand.is_some() && vendor_id.is_some() { + break; + } + } + (vendor_id.unwrap_or_default(), brand.unwrap_or_default()) +} diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -6,11 +6,12 @@ use sys::component::{self, Component}; use sys::disk; -use sys::network; use sys::process::*; use sys::processor::*; -use sys::Disk; -use sys::NetworkData; + +use Disk; +use LoadAvg; +use Networks; use Pid; use {DiskExt, ProcessExt, RefreshKind, SystemExt}; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -106,7 +107,7 @@ pub struct System { page_size_kb: u64, temperatures: Vec<Component>, disks: Vec<Disk>, - network: NetworkData, + networks: Networks, uptime: u64, } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -132,12 +133,64 @@ impl System { } fn refresh_processors(&mut self, limit: Option<u32>) { + fn get_callbacks( + first: bool, + ) -> Box<dyn Fn(&mut dyn Iterator<Item = &[u8]>, &mut Vec<Processor>, &mut usize)> { + if first { + let frequency = get_cpu_frequency(); + let (vendor_id, brand) = get_vendor_id_and_brand(); + Box::new( + move |parts: &mut dyn Iterator<Item = &[u8]>, + processors: &mut Vec<Processor>, + _| { + processors.push(Processor::new_with_values( + to_str!(parts.next().unwrap_or(&[])), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + frequency, + vendor_id.clone(), + brand.clone(), + )); + }, + ) + } else { + Box::new( + |parts: &mut dyn Iterator<Item = &[u8]>, + processors: &mut Vec<Processor>, + i: &mut usize| { + parts.next(); // we don't want the name again + processors[*i].set( + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + parts.next().map(|v| to_u64(v)).unwrap_or(0), + ); + *i += 1; + }, + ) + } + } if let Ok(f) = File::open("/proc/stat") { let buf = BufReader::new(f); let mut i = 0; let first = self.processors.is_empty(); let mut it = buf.split(b'\n'); let mut count = 0; + let callback = get_callbacks(first); while let Some(Ok(line)) = it.next() { if &line[..3] != b"cpu" { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -146,37 +199,7 @@ impl System { count += 1; let mut parts = line.split(|x| *x == b' ').filter(|s| !s.is_empty()); - if first { - self.processors.push(new_processor( - to_str!(parts.next().unwrap_or(&[])), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - )); - } else { - parts.next(); // we don't want the name again - set_processor( - &mut self.processors[i], - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - parts.next().map(|v| to_u64(v)).unwrap_or(0), - ); - i += 1; - } + callback(&mut parts, &mut self.processors, &mut i); if let Some(limit) = limit { if count >= limit { break; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -199,7 +222,7 @@ impl SystemExt for System { page_size_kb: unsafe { sysconf(_SC_PAGESIZE) as u64 / 1024 }, temperatures: component::get_components(), disks: Vec::with_capacity(2), - network: network::new(), + networks: Networks::new(), uptime: get_uptime(), }; s.refresh_specifics(refreshes); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -287,14 +310,10 @@ impl SystemExt for System { } } - fn refresh_disk_list(&mut self) { + fn refresh_disks_list(&mut self) { self.disks = get_all_disks(); } - fn refresh_network(&mut self) { - network::update_network(&mut self.network); - } - // COMMON PART // // Need to be moved into a "common" file to avoid duplication. diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -307,8 +326,12 @@ impl SystemExt for System { self.process_list.tasks.get(&pid) } - fn get_network(&self) -> &NetworkData { - &self.network + fn get_networks(&self) -> &Networks { + &self.networks + } + + fn get_networks_mut(&mut self) -> &mut Networks { + &mut self.networks } fn get_processor_list(&self) -> &[Processor] { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -351,6 +374,24 @@ impl SystemExt for System { fn get_uptime(&self) -> u64 { self.uptime } + + fn get_load_average(&self) -> LoadAvg { + let mut s = String::new(); + if let Err(_) = File::open("/proc/loadavg").and_then(|mut f| f.read_to_string(&mut s)) { + return LoadAvg::default(); + } + let loads = s + .trim() + .split(' ') + .take(3) + .map(|val| val.parse::<f64>().unwrap()) + .collect::<Vec<f64>>(); + LoadAvg { + one: loads[0], + five: loads[1], + fifteen: loads[2], + } + } } impl Default for System { diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -82,6 +82,14 @@ extern "C" { //pub fn host_statistics(host_priv: u32, flavor: u32, host_info: *mut c_void, // host_count: *const u32) -> u32; pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> kern_return_t; + pub fn sysctlbyname( + name: *const c_char, + oldp: *mut c_void, + oldlenp: *mut usize, + newp: *mut c_void, + newlen: usize, + ) -> kern_return_t; + pub fn getloadavg(loads: *const f64, size: c_int); // pub fn proc_pidpath(pid: i32, buf: *mut i8, bufsize: u32) -> i32; // pub fn proc_name(pid: i32, buf: *mut i8, bufsize: u32) -> i32; diff --git a/src/mac/mod.rs b/src/mac/mod.rs --- a/src/mac/mod.rs +++ b/src/mac/mod.rs @@ -14,7 +14,7 @@ pub mod system; pub use self::component::Component; pub use self::disk::{Disk, DiskType}; -pub use self::network::NetworkData; +pub use self::network::{NetworkData, Networks}; pub use self::process::{Process, ProcessStatus}; pub use self::processor::Processor; pub use self::system::System; diff --git a/src/mac/network.rs b/src/mac/network.rs --- a/src/mac/network.rs +++ b/src/mac/network.rs @@ -5,17 +5,126 @@ // use libc::{self, c_char, CTL_NET, NET_RT_IFLIST2, PF_ROUTE, RTM_IFINFO2}; + +use std::collections::HashMap; use std::ptr::null_mut; use sys::ffi; use NetworkExt; +use NetworksExt; +use NetworksIter; + +/// Network interfaces. +/// +/// ```no_run +/// use sysinfo::{NetworksExt, System, SystemExt}; +/// +/// let s = System::new_all(); +/// let networks = s.get_networks(); +/// ``` +pub struct Networks { + interfaces: HashMap<String, NetworkData>, +} + +impl Networks { + pub(crate) fn new() -> Self { + Networks { + interfaces: HashMap::new(), + } + } + + #[allow(clippy::cast_ptr_alignment)] + fn update_networks(&mut self) { + let mib = &mut [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]; + let mut len = 0; + if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, null_mut(), &mut len, null_mut(), 0) } < 0 { + // TODO: might be nice to put an error in here... + return; + } + let mut buf = Vec::with_capacity(len); + unsafe { + buf.set_len(len); + if libc::sysctl( + mib.as_mut_ptr(), + 6, + buf.as_mut_ptr(), + &mut len, + null_mut(), + 0, + ) < 0 + { + // TODO: might be nice to put an error in here... + return; + } + } + let buf = buf.as_ptr() as *const c_char; + let lim = unsafe { buf.add(len) }; + let mut next = buf; + while next < lim { + unsafe { + let ifm = next as *const libc::if_msghdr; + next = next.offset((*ifm).ifm_msglen as isize); + if (*ifm).ifm_type == RTM_IFINFO2 as u8 { + // The interface (line description) name stored at ifname will be returned in + // the default coded character set identifier (CCSID) currently in effect for + // the job. If this is not a single byte CCSID, then storage greater than + // IFNAMSIZ (16) bytes may be needed. 22 bytes is large enough for all CCSIDs. + let mut name = vec![0u8; libc::IFNAMSIZ + 6]; + + let if2m: *const ffi::if_msghdr2 = ifm as *const ffi::if_msghdr2; + let pname = + libc::if_indextoname((*if2m).ifm_index as _, name.as_mut_ptr() as _); + if pname.is_null() { + continue; + } + name.set_len(libc::strlen(pname)); + let name = String::from_utf8_unchecked(name); + let ibytes = (*if2m).ifm_data.ifi_ibytes; + let obytes = (*if2m).ifm_data.ifi_obytes; + let interface = self.interfaces.entry(name).or_insert_with(|| NetworkData { + old_in: ibytes, + current_in: ibytes, + old_out: obytes, + current_out: obytes, + updated: true, + }); + interface.old_in = interface.current_in; + interface.current_in = ibytes; + interface.old_out = interface.current_out; + interface.current_out = obytes; + interface.updated = true; + } + } + } + } +} + +impl NetworksExt for Networks { + fn iter<'a>(&'a self) -> NetworksIter<'a> { + NetworksIter::new(self.interfaces.iter()) + } + + fn refresh_networks_list(&mut self) { + for (_, data) in self.interfaces.iter_mut() { + data.updated = false; + } + self.update_networks(); + self.interfaces.retain(|_, data| data.updated); + } + + fn refresh(&mut self) { + self.update_networks(); + } +} /// Contains network information. +#[derive(PartialEq, Eq)] pub struct NetworkData { old_in: u64, old_out: u64, current_in: u64, current_out: u64, + updated: bool, } impl NetworkExt for NetworkData { diff --git a/src/mac/network.rs b/src/mac/network.rs --- a/src/mac/network.rs +++ b/src/mac/network.rs @@ -26,67 +135,12 @@ impl NetworkExt for NetworkData { fn get_outcome(&self) -> u64 { self.current_out - self.old_out } -} -pub fn new() -> NetworkData { - NetworkData { - old_in: 0, - old_out: 0, - current_in: 0, - current_out: 0, + fn get_total_income(&self) -> u64 { + self.current_in } -} -#[allow(clippy::cast_ptr_alignment)] -pub fn update_network(n: &mut NetworkData) { - let mib = &mut [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]; - let mut len = 0; - if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, null_mut(), &mut len, null_mut(), 0) } < 0 { - // TODO: might be nice to put an error in here... - return; - } - let mut buf = Vec::with_capacity(len); - unsafe { - buf.set_len(len); - if libc::sysctl( - mib.as_mut_ptr(), - 6, - buf.as_mut_ptr(), - &mut len, - null_mut(), - 0, - ) < 0 - { - // TODO: might be nice to put an error in here... - return; - } - } - let buf = buf.as_ptr() as *const c_char; - let lim = unsafe { buf.add(len) }; - let mut next = buf; - let mut totalibytes = 0u64; - let mut totalobytes = 0u64; - while next < lim { - unsafe { - let ifm = next as *const libc::if_msghdr; - next = next.offset((*ifm).ifm_msglen as isize); - if (*ifm).ifm_type == RTM_IFINFO2 as u8 { - let if2m: *const ffi::if_msghdr2 = ifm as *const ffi::if_msghdr2; - totalibytes += (*if2m).ifm_data.ifi_ibytes; - totalobytes += (*if2m).ifm_data.ifi_obytes; - } - } + fn get_total_outcome(&self) -> u64 { + self.current_out } - n.old_in = if n.current_in > totalibytes { - 0 - } else { - n.current_in - }; - n.current_in = totalibytes; - n.old_out = if n.current_out > totalibytes { - 0 - } else { - n.current_out - }; - n.current_out = totalobytes; } diff --git a/src/mac/process.rs b/src/mac/process.rs --- a/src/mac/process.rs +++ b/src/mac/process.rs @@ -152,11 +152,7 @@ pub struct Process { } impl Process { - pub(crate) fn new_empty( - pid: Pid, - exe: PathBuf, - name: String, - ) -> Process { + pub(crate) fn new_empty(pid: Pid, exe: PathBuf, name: String) -> Process { Process { name, pid, diff --git a/src/mac/process.rs b/src/mac/process.rs --- a/src/mac/process.rs +++ b/src/mac/process.rs @@ -435,7 +431,11 @@ pub(crate) fn update_process( ) != mem::size_of::<libc::proc_bsdinfo>() as _ { let mut buffer: Vec<u8> = Vec::with_capacity(ffi::PROC_PIDPATHINFO_MAXSIZE as _); - match ffi::proc_pidpath(pid, buffer.as_mut_ptr() as *mut _, ffi::PROC_PIDPATHINFO_MAXSIZE) { + match ffi::proc_pidpath( + pid, + buffer.as_mut_ptr() as *mut _, + ffi::PROC_PIDPATHINFO_MAXSIZE, + ) { x if x > 0 => { buffer.set_len(x as _); let tmp = String::from_utf8_unchecked(buffer); diff --git a/src/mac/processor.rs b/src/mac/processor.rs --- a/src/mac/processor.rs +++ b/src/mac/processor.rs @@ -4,6 +4,7 @@ // Copyright (c) 2015 Guillaume Gomez // +use libc::c_char; use std::ops::Deref; use std::sync::Arc; use sys::ffi; diff --git a/src/mac/processor.rs b/src/mac/processor.rs --- a/src/mac/processor.rs +++ b/src/mac/processor.rs @@ -54,16 +55,41 @@ pub struct Processor { name: String, cpu_usage: f32, processor_data: Arc<ProcessorData>, + frequency: u64, + vendor_id: String, + brand: String, } impl Processor { - fn new(name: String, processor_data: Arc<ProcessorData>) -> Processor { + pub(crate) fn new( + name: String, + processor_data: Arc<ProcessorData>, + frequency: u64, + vendor_id: String, + brand: String, + ) -> Processor { Processor { name, cpu_usage: 0f32, processor_data, + frequency, + vendor_id, + brand, } } + + pub(crate) fn set_cpu_usage(&mut self, cpu_usage: f32) { + self.cpu_usage = cpu_usage; + } + + pub(crate) fn update(&mut self, cpu_usage: f32, processor_data: Arc<ProcessorData>) { + self.cpu_usage = cpu_usage; + self.processor_data = processor_data; + } + + pub(crate) fn get_data(&self) -> Arc<ProcessorData> { + Arc::clone(&self.processor_data) + } } impl ProcessorExt for Processor { diff --git a/src/mac/processor.rs b/src/mac/processor.rs --- a/src/mac/processor.rs +++ b/src/mac/processor.rs @@ -74,25 +100,75 @@ impl ProcessorExt for Processor { fn get_name(&self) -> &str { &self.name } -} -pub fn set_cpu_usage(p: &mut Processor, usage: f32) { - p.cpu_usage = usage; -} + /// Returns the processor frequency in MHz. + fn get_frequency(&self) -> u64 { + self.frequency + } -pub fn create_proc(name: String, processor_data: Arc<ProcessorData>) -> Processor { - Processor::new(name, processor_data) + fn get_vendor_id(&self) -> &str { + &self.vendor_id + } + + fn get_brand(&self) -> &str { + &self.brand + } } -pub fn update_proc(p: &mut Processor, cpu_usage: f32, processor_data: Arc<ProcessorData>) { - p.cpu_usage = cpu_usage; - p.processor_data = processor_data; +pub fn get_cpu_frequency() -> u64 { + let mut speed: u64 = 0; + let mut len = std::mem::size_of::<u64>(); + unsafe { + ffi::sysctlbyname( + b"hw.cpufrequency\0".as_ptr() as *const c_char, + &mut speed as *mut _ as _, + &mut len, + std::ptr::null_mut(), + 0, + ); + } + speed /= 1000000; + speed } -pub fn set_cpu_proc(p: &mut Processor, cpu_usage: f32) { - p.cpu_usage = cpu_usage; +fn get_sysctl_str(s: &[u8]) -> String { + let mut len = 0; + + unsafe { + ffi::sysctlbyname( + s.as_ptr() as *const c_char, + std::ptr::null_mut(), + &mut len, + std::ptr::null_mut(), + 0, + ); + } + if len < 1 { + return String::new(); + } + let mut buf = Vec::with_capacity(len); + unsafe { + ffi::sysctlbyname( + s.as_ptr() as *const c_char, + buf.as_mut_ptr() as _, + &mut len, + std::ptr::null_mut(), + 0, + ); + } + if len > 0 { + unsafe { + buf.set_len(len); + } + String::from_utf8(buf).unwrap_or_else(|_| String::new()) + } else { + String::new() + } } -pub fn get_processor_data(p: &Processor) -> Arc<ProcessorData> { - Arc::clone(&p.processor_data) +pub fn get_vendor_id_and_brand() -> (String, String) { + ( + get_sysctl_str(b"machdep.cpu.brand_string\0"), + get_sysctl_str(b"machdep.cpu.vendor\0"), + ) } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -7,17 +7,16 @@ use sys::component::Component; use sys::disk::Disk; use sys::ffi; -use sys::network::{self, NetworkData}; +use sys::network::Networks; use sys::process::*; use sys::processor::*; -use {DiskExt, Pid, ProcessExt, ProcessorExt, RefreshKind, SystemExt}; +use {DiskExt, LoadAvg, Pid, ProcessExt, ProcessorExt, RefreshKind, SystemExt}; use std::cell::UnsafeCell; use std::collections::HashMap; use std::mem; use std::sync::Arc; -use sys::processor; use libc::{self, c_int, c_void, size_t, sysconf, _SC_PAGESIZE}; diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -35,7 +34,7 @@ pub struct System { temperatures: Vec<Component>, connection: Option<ffi::io_connect_t>, disks: Vec<Disk>, - network: NetworkData, + networks: Networks, uptime: u64, port: ffi::mach_port_t, } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -83,7 +82,7 @@ impl SystemExt for System { temperatures: Vec::with_capacity(2), connection: get_io_service_connection(), disks: Vec::with_capacity(1), - network: network::new(), + networks: Networks::new(), uptime: get_uptime(), port: unsafe { ffi::mach_host_self() }, }; diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -183,6 +182,8 @@ impl SystemExt for System { if self.processors.is_empty() { let mut num_cpu = 0; + let (vendor_id, brand) = get_vendor_id_and_brand(); + let frequency = get_cpu_frequency(); if !get_sys_value( ffi::CTL_HW, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -194,9 +195,12 @@ impl SystemExt for System { num_cpu = 1; } - self.processors.push(processor::create_proc( + self.processors.push(Processor::new( "0".to_owned(), Arc::new(ProcessorData::new(::std::ptr::null_mut(), 0)), + frequency, + vendor_id.clone(), + brand.clone(), )); if ffi::host_processor_info( self.port, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -208,8 +212,13 @@ impl SystemExt for System { { let proc_data = Arc::new(ProcessorData::new(cpu_info, num_cpu_info)); for i in 0..num_cpu { - let mut p = - processor::create_proc(format!("{}", i + 1), Arc::clone(&proc_data)); + let mut p = Processor::new( + format!("{}", i + 1), + Arc::clone(&proc_data), + frequency, + vendor_id.clone(), + brand.clone(), + ); let in_use = *cpu_info.offset( (ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_USER as isize, ) + *cpu_info.offset( diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -221,7 +230,7 @@ impl SystemExt for System { + *cpu_info.offset( (ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_IDLE as isize, ); - processor::set_cpu_proc(&mut p, in_use as f32 / total as f32); + p.set_cpu_usage(in_use as f32 / total as f32); self.processors.push(p); } } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -236,7 +245,7 @@ impl SystemExt for System { let mut pourcent = 0f32; let proc_data = Arc::new(ProcessorData::new(cpu_info, num_cpu_info)); for (i, proc_) in self.processors.iter_mut().skip(1).enumerate() { - let old_proc_data = &*processor::get_processor_data(proc_); + let old_proc_data = &*proc_.get_data(); let in_use = (*cpu_info.offset( (ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_USER as isize, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -257,27 +266,19 @@ impl SystemExt for System { ) - *old_proc_data.cpu_info.offset( (ffi::CPU_STATE_MAX * i) as isize + ffi::CPU_STATE_IDLE as isize, )); - processor::update_proc( - proc_, - in_use as f32 / total as f32, - Arc::clone(&proc_data), - ); + proc_.update(in_use as f32 / total as f32, Arc::clone(&proc_data)); pourcent += proc_.get_cpu_usage(); } if self.processors.len() > 1 { let len = self.processors.len() - 1; if let Some(p) = self.processors.get_mut(0) { - processor::set_cpu_usage(p, pourcent / len as f32); + p.set_cpu_usage(pourcent / len as f32); } } } } } - fn refresh_network(&mut self) { - network::update_network(&mut self.network); - } - fn refresh_processes(&mut self) { let count = unsafe { ffi::proc_listallpids(::std::ptr::null_mut(), 0) }; if count < 1 { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -288,15 +289,9 @@ impl SystemExt for System { let entries: Vec<Process> = { let wrap = &Wrap(UnsafeCell::new(&mut self.process_list)); pids.par_iter() - .flat_map(|pid| { - match update_process( - wrap, - *pid, - arg_max as size_t, - ) { - Ok(x) => x, - Err(_) => None, - } + .flat_map(|pid| match update_process(wrap, *pid, arg_max as size_t) { + Ok(x) => x, + Err(_) => None, }) .collect() }; diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -311,11 +306,7 @@ impl SystemExt for System { let arg_max = get_arg_max(); match { let wrap = Wrap(UnsafeCell::new(&mut self.process_list)); - update_process( - &wrap, - pid, - arg_max as size_t, - ) + update_process(&wrap, pid, arg_max as size_t) } { Ok(Some(p)) => { self.process_list.insert(p.pid(), p); diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -332,7 +323,7 @@ impl SystemExt for System { } } - fn refresh_disk_list(&mut self) { + fn refresh_disks_list(&mut self) { self.disks = crate::mac::disk::get_disks(); } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -352,8 +343,12 @@ impl SystemExt for System { &self.processors[..] } - fn get_network(&self) -> &NetworkData { - &self.network + fn get_networks(&self) -> &Networks { + &self.networks + } + + fn get_networks_mut(&mut self) -> &mut Networks { + &mut self.networks } fn get_total_memory(&self) -> u64 { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -392,6 +387,18 @@ impl SystemExt for System { fn get_uptime(&self) -> u64 { self.uptime } + + fn get_load_average(&self) -> LoadAvg { + let loads = vec![0f64; 3]; + unsafe { + ffi::getloadavg(loads.as_ptr() as *const f64, 3); + } + LoadAvg { + one: loads[0], + five: loads[1], + fifteen: loads[2], + } + } } impl Default for System { diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -78,9 +78,13 @@ cfg_if! { } } -pub use common::{AsU32, Pid, RefreshKind}; -pub use sys::{Component, Disk, DiskType, NetworkData, Process, ProcessStatus, Processor, System}; -pub use traits::{ComponentExt, DiskExt, NetworkExt, ProcessExt, ProcessorExt, SystemExt}; +pub use common::{AsU32, NetworksIter, Pid, RefreshKind}; +pub use sys::{ + Component, Disk, DiskType, NetworkData, Networks, Process, ProcessStatus, Processor, System, +}; +pub use traits::{ + ComponentExt, DiskExt, NetworkExt, NetworksExt, ProcessExt, ProcessorExt, SystemExt, +}; #[cfg(feature = "c-interface")] pub use c_interface::*; diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -102,26 +106,26 @@ mod utils; /// a maximum number of files open equivalent to half of the system limit. /// /// The problem is that some users might need all the available file descriptors so we need to -/// allow them to change this limit. Reducing +/// allow them to change this limit. Reducing /// /// Note that if you set a limit bigger than the system limit, the system limit will be set. /// /// Returns `true` if the new value has been set. -pub fn set_open_files_limit(mut new_limit: isize) -> bool { +pub fn set_open_files_limit(mut _new_limit: isize) -> bool { #[cfg(all(not(target_os = "macos"), unix))] { - if new_limit < 0 { - new_limit = 0; + if _new_limit < 0 { + _new_limit = 0; } let max = sys::system::get_max_nb_fds(); - if new_limit > max { - new_limit = max; + if _new_limit > max { + _new_limit = max; } return if let Ok(ref mut x) = unsafe { sys::system::REMAINING_FILES.lock() } { // If files are already open, to be sure that the number won't be bigger when those // files are closed, we subtract the current number of opened files to the new limit. let diff = max - **x; - **x = new_limit - diff; + **x = _new_limit - diff; true } else { false diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -4,7 +4,9 @@ // Copyright (c) 2017 Guillaume Gomez // -use sys::{Component, Disk, DiskType, NetworkData, Process, Processor}; +use sys::{Component, Disk, DiskType, Networks, Process, Processor}; +use LoadAvg; +use NetworksIter; use Pid; use ProcessStatus; use RefreshKind; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -14,26 +16,90 @@ use std::ffi::OsStr; use std::path::Path; /// Contains all the methods of the `Disk` struct. +/// +/// ```no_run +/// use sysinfo::{DiskExt, System, SystemExt}; +/// +/// let s = System::new(); +/// for disk in s.get_disks() { +/// println!("{:?}: {:?}", disk.get_name(), disk.get_type()); +/// } +/// ``` pub trait DiskExt { /// Returns the disk type. + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for disk in s.get_disks() { + /// println!("{:?}", disk.get_type()); + /// } + /// ``` fn get_type(&self) -> DiskType; /// Returns the disk name. + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for disk in s.get_disks() { + /// println!("{:?}", disk.get_name()); + /// } + /// ``` fn get_name(&self) -> &OsStr; /// Returns the file system used on this disk (so for example: `EXT4`, `NTFS`, etc...). + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for disk in s.get_disks() { + /// println!("{:?}", disk.get_file_system()); + /// } + /// ``` fn get_file_system(&self) -> &[u8]; /// Returns the mount point of the disk (`/` for example). + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for disk in s.get_disks() { + /// println!("{:?}", disk.get_mount_point()); + /// } + /// ``` fn get_mount_point(&self) -> &Path; /// Returns the total disk size, in bytes. + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for disk in s.get_disks() { + /// println!("{}", disk.get_total_space()); + /// } + /// ``` fn get_total_space(&self) -> u64; /// Returns the available disk size, in bytes. + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for disk in s.get_disks() { + /// println!("{}", disk.get_available_space()); + /// } + /// ``` fn get_available_space(&self) -> u64; /// Update the disk' information. + #[doc(hidden)] fn update(&mut self) -> bool; } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -42,56 +108,183 @@ pub trait ProcessExt { /// Create a new process only containing the given information. /// /// On windows, the `start_time` argument is ignored. + #[doc(hidden)] fn new(pid: Pid, parent: Option<Pid>, start_time: u64) -> Self; /// Sends the given `signal` to the process. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, Signal, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// process.kill(Signal::Kill); + /// } + /// ``` fn kill(&self, signal: ::Signal) -> bool; /// Returns the name of the process. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.name()); + /// } + /// ``` fn name(&self) -> &str; /// Returns the command line. // /// // /// On Windows, this is always a one element vector. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{:?}", process.cmd()); + /// } + /// ``` fn cmd(&self) -> &[String]; /// Returns the path to the process. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.exe().display()); + /// } + /// ``` fn exe(&self) -> &Path; /// Returns the pid of the process. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.pid()); + /// } + /// ``` fn pid(&self) -> Pid; /// Returns the environment of the process. /// - /// Always empty on Windows except for current process. + /// Always empty on Windows, except for current process. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{:?}", process.environ()); + /// } + /// ``` fn environ(&self) -> &[String]; /// Returns the current working directory. /// /// Always empty on Windows. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.cwd().display()); + /// } + /// ``` fn cwd(&self) -> &Path; /// Returns the path of the root directory. /// /// Always empty on Windows. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.root().display()); + /// } + /// ``` fn root(&self) -> &Path; /// Returns the memory usage (in KiB). + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{} KiB", process.memory()); + /// } + /// ``` fn memory(&self) -> u64; /// Returns the virtual memory usage (in KiB). + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{} KiB", process.virtual_memory()); + /// } + /// ``` fn virtual_memory(&self) -> u64; /// Returns the parent pid. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{:?}", process.parent()); + /// } + /// ``` fn parent(&self) -> Option<Pid>; /// Returns the status of the processus. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{:?}", process.status()); + /// } + /// ``` fn status(&self) -> ProcessStatus; /// Returns the time of process launch (in seconds). + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.start_time()); + /// } + /// ``` fn start_time(&self) -> u64; - /// Returns the total CPU usage. + /// Returns the total CPU usage (in %). + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}%", process.cpu_usage()); + /// } + /// ``` fn cpu_usage(&self) -> f32; } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -101,24 +294,93 @@ pub trait ProcessorExt { /// /// Note: You'll need to refresh it at least twice at first if you want to have a /// non-zero value. + /// + /// ```no_run + /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for processor in s.get_processor_list() { + /// println!("{}%", processor.get_cpu_usage()); + /// } + /// ``` fn get_cpu_usage(&self) -> f32; /// Returns this processor's name. + /// + /// ```no_run + /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for processor in s.get_processor_list() { + /// println!("{}", processor.get_name()); + /// } + /// ``` fn get_name(&self) -> &str; + + /// Returns the processor's vendor id. + /// + /// ```no_run + /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for processor in s.get_processor_list() { + /// println!("{}", processor.get_vendor_id()); + /// } + /// ``` + fn get_vendor_id(&self) -> &str; + + /// Returns the processor's brand. + /// + /// ```no_run + /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for processor in s.get_processor_list() { + /// println!("{}", processor.get_brand()); + /// } + /// ``` + fn get_brand(&self) -> &str; + + /// Returns the processor's frequency. + /// + /// ```no_run + /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// + /// let s = System::new(); + /// for processor in s.get_processor_list() { + /// println!("{}", processor.get_frequency()); + /// } + /// ``` + fn get_frequency(&self) -> u64; } /// Contains all the methods of the [`System`] type. pub trait SystemExt: Sized { - /// Creates a new [`System`] instance. It only contains the disks' list and the processes list - /// at this stage. Use the [`refresh_all`] method to update its internal information (or any of - /// the `refresh_` method). + /// Creates a new [`System`] instance with nothing loaded. Use the [`refresh_all`] method to + /// update its internal information (or any of the `refresh_` method). /// /// [`refresh_all`]: #method.refresh_all + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new(); + /// ``` fn new() -> Self { - let mut s = Self::new_with_specifics(RefreshKind::new()); - s.refresh_disk_list(); - s.refresh_all(); - s + Self::new_with_specifics(RefreshKind::new()) + } + + /// Creates a new [`System`] instance with everything loaded. + /// + /// It is an equivalent of `SystemExt::new_with_specifics(RefreshKind::everything())`. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// ``` + fn new_all() -> Self { + Self::new_with_specifics(RefreshKind::everything()) } /// Creates a new [`System`] instance and refresh the data corresponding to the diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -130,14 +392,14 @@ pub trait SystemExt: Sized { /// use sysinfo::{RefreshKind, System, SystemExt}; /// /// // We want everything except disks. - /// let mut system = System::new_with_specifics(RefreshKind::everything().without_disk_list()); + /// let mut system = System::new_with_specifics(RefreshKind::everything().without_disks_list()); /// /// assert_eq!(system.get_disks().len(), 0); /// assert!(system.get_process_list().len() > 0); /// /// // If you want the disks list afterwards, just call the corresponding - /// // "refresh_disk_list": - /// system.refresh_disk_list(); + /// // "refresh_disks_list": + /// system.refresh_disks_list(); /// let disks = system.get_disks(); /// ``` fn new_with_specifics(refreshes: RefreshKind) -> Self; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -150,10 +412,10 @@ pub trait SystemExt: Sized { /// ``` /// use sysinfo::{RefreshKind, System, SystemExt}; /// - /// let mut s = System::new(); + /// let mut s = System::new_all(); /// - /// // Let's just update network data and processes: - /// s.refresh_specifics(RefreshKind::new().with_network().with_processes()); + /// // Let's just update networks and processes: + /// s.refresh_specifics(RefreshKind::new().with_networks().with_processes()); /// ``` fn refresh_specifics(&mut self, refreshes: RefreshKind) { if refreshes.memory() { diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -165,14 +427,17 @@ pub trait SystemExt: Sized { if refreshes.temperatures() { self.refresh_temperatures(); } - if refreshes.network() { - self.refresh_network(); + if refreshes.networks_list() { + self.refresh_networks_list(); + } + if refreshes.networks() { + self.refresh_networks(); } if refreshes.processes() { self.refresh_processes(); } - if refreshes.disk_list() { - self.refresh_disk_list(); + if refreshes.disks_list() { + self.refresh_disks_list(); } if refreshes.disks() { self.refresh_disks(); diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -187,6 +452,13 @@ pub trait SystemExt: Sized { /// [`refresh_memory`]: SystemExt::refresh_memory /// [`refresh_cpu`]: SystemExt::refresh_memory /// [`refresh_temperatures`]: SystemExt::refresh_temperatures + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_system(); + /// ``` fn refresh_system(&mut self) { self.refresh_memory(); self.refresh_cpu(); diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -194,45 +466,172 @@ pub trait SystemExt: Sized { } /// Refresh RAM and SWAP usage. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_memory(); + /// ``` fn refresh_memory(&mut self); /// Refresh CPU usage. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_cpu(); + /// ``` fn refresh_cpu(&mut self); /// Refresh components' temperature. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_temperatures(); + /// ``` fn refresh_temperatures(&mut self); /// Get all processes and update their information. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_processes(); + /// ``` fn refresh_processes(&mut self); /// Refresh *only* the process corresponding to `pid`. Returns `false` if the process doesn't - /// exist. + /// exist or isn't listed. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_process(1337); + /// ``` fn refresh_process(&mut self, pid: Pid) -> bool; /// Refreshes the listed disks' information. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_disks(); + /// ``` fn refresh_disks(&mut self); /// The disk list will be emptied then completely recomputed. - fn refresh_disk_list(&mut self); + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_disks_list(); + /// ``` + fn refresh_disks_list(&mut self); - /// Refresh data network. - fn refresh_network(&mut self); + /// Refresh networks data. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_networks(); + /// ``` + /// + /// It is a shortcut for: + /// + /// ```no_run + /// use sysinfo::{NetworksExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let networks = s.get_networks_mut(); + /// networks.refresh(); + /// ``` + fn refresh_networks(&mut self) { + self.get_networks_mut().refresh(); + } + + /// The network list will be emptied then completely recomputed. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_networks_list(); + /// ``` + /// + /// This is a shortcut for: + /// + /// ```no_run + /// use sysinfo::{NetworksExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let networks = s.get_networks_mut(); + /// networks.refresh_networks_list(); + /// ``` + fn refresh_networks_list(&mut self) { + self.get_networks_mut().refresh_networks_list(); + } - /// Refreshes all system, processes and disks information. + /// Refreshes all system, processes, disks and network interfaces information. + /// + /// Please note that it doesn't recompute disks list, components list nor network interfaces + /// list. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// s.refresh_all(); + /// ``` fn refresh_all(&mut self) { self.refresh_system(); self.refresh_processes(); self.refresh_disks(); - self.refresh_network(); + self.refresh_networks(); } /// Returns the process list. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for (pid, process) in s.get_process_list() { + /// println!("{} {}", pid, process.name()); + /// } + /// ``` fn get_process_list(&self) -> &HashMap<Pid, Process>; /// Returns the process corresponding to the given pid or `None` if no such process exists. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// if let Some(process) = s.get_process(1337) { + /// println!("{}", process.name()); + /// } + /// ``` fn get_process(&self, pid: Pid) -> Option<&Process>; /// Returns a list of process containing the given `name`. + /// + /// ```no_run + /// use sysinfo::{ProcessExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for process in s.get_process_by_name("htop") { + /// println!("{} {}", process.pid(), process.name()); + /// } + /// ``` fn get_process_by_name(&self, name: &str) -> Vec<&Process> { let mut ret = vec![]; for val in self.get_process_list().values() { diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -244,56 +643,292 @@ pub trait SystemExt: Sized { } /// The first processor in the array is the "main" one (aka the addition of all the others). + /// + /// ```no_run + /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for processor in s.get_processor_list() { + /// println!("{}%", processor.get_cpu_usage()); + /// } + /// ``` fn get_processor_list(&self) -> &[Processor]; /// Returns total RAM size in KiB. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{} KiB", s.get_total_memory()); + /// ``` fn get_total_memory(&self) -> u64; /// Returns free RAM size in KiB. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{} KiB", s.get_free_memory()); + /// ``` fn get_free_memory(&self) -> u64; /// Returns used RAM size in KiB. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{} KiB", s.get_used_memory()); + /// ``` fn get_used_memory(&self) -> u64; /// Returns SWAP size in KiB. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{} KiB", s.get_total_swap()); + /// ``` fn get_total_swap(&self) -> u64; /// Returns free SWAP size in KiB. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{} KiB", s.get_free_swap()); + /// ``` fn get_free_swap(&self) -> u64; /// Returns used SWAP size in KiB. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{} KiB", s.get_used_swap()); + /// ``` fn get_used_swap(&self) -> u64; /// Returns components list. + /// + /// ```no_run + /// use sysinfo::{ComponentExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for component in s.get_components_list() { + /// println!("{}: {}°C", component.get_label(), component.get_temperature()); + /// } + /// ``` fn get_components_list(&self) -> &[Component]; /// Returns disks' list. + /// + /// ```no_run + /// use sysinfo::{DiskExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for disk in s.get_disks() { + /// println!("{:?}", disk.get_name()); + /// } + /// ``` fn get_disks(&self) -> &[Disk]; - /// Returns network data. - fn get_network(&self) -> &NetworkData; + /// Returns network interfaces. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// let networks = s.get_networks(); + /// for (interface_name, data) in networks { + /// println!("[{}] in: {}, out: {}", interface_name, data.get_income(), data.get_outcome()); + /// } + /// ``` + fn get_networks(&self) -> &Networks; + + /// Returns a mutable access to network interfaces. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let networks = s.get_networks_mut(); + /// networks.refresh_networks_list(); + /// ``` + fn get_networks_mut(&mut self) -> &mut Networks; /// Returns system uptime. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// println!("{}", s.get_uptime()); + /// ``` fn get_uptime(&self) -> u64; + + /// Returns the system load average value. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new_all(); + /// let load_avg = s.get_load_average(); + /// println!( + /// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%", + /// load_avg.one, + /// load_avg.five, + /// load_avg.fifteen, + /// ); + /// ``` + fn get_load_average(&self) -> LoadAvg; } /// Getting volume of incoming and outgoing data. pub trait NetworkExt { - /// Returns the number of incoming bytes. + /// Returns the number of incoming bytes since the last refresh. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// let networks = s.get_networks(); + /// for (interface_name, network) in networks { + /// println!("in: {} B", network.get_income()); + /// } + /// ``` fn get_income(&self) -> u64; - /// Returns the number of outgoing bytes. + /// Returns the number of outgoing bytes since the last refresh. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// let networks = s.get_networks(); + /// for (interface_name, network) in networks { + /// println!("in: {} B", network.get_outcome()); + /// } + /// ``` fn get_outcome(&self) -> u64; + + /// Returns the total number of incoming bytes. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// let networks = s.get_networks(); + /// for (interface_name, network) in networks { + /// println!("in: {} B", network.get_total_income()); + /// } + /// ``` + fn get_total_income(&self) -> u64; + + /// Returns the total number of outgoing bytes. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// let networks = s.get_networks(); + /// for (interface_name, network) in networks { + /// println!("in: {} B", network.get_total_outcome()); + /// } + /// ``` + fn get_total_outcome(&self) -> u64; +} + +/// Interacting with network interfaces. +pub trait NetworksExt { + /// Returns an iterator over the network interfaces. + /// + /// ```no_run + /// use sysinfo::{NetworkExt, NetworksExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// let networks = s.get_networks(); + /// for (interface_name, network) in networks { + /// println!("in: {} B", network.get_income()); + /// } + /// ``` + fn iter(&self) -> NetworksIter; + + /// Refreshes the network interfaces list. + /// + /// ```no_run + /// use sysinfo::{NetworksExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let networks = s.get_networks_mut(); + /// networks.refresh_networks_list(); + /// ``` + fn refresh_networks_list(&mut self); + + /// Refreshes the network interfaces' content. + /// + /// ```no_run + /// use sysinfo::{NetworksExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let networks = s.get_networks_mut(); + /// networks.refresh(); + /// ``` + fn refresh(&mut self); } /// Getting a component temperature information. pub trait ComponentExt { /// Returns the component's temperature (in celsius degree). + /// + /// ```no_run + /// use sysinfo::{ComponentExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for component in s.get_components_list() { + /// println!("{}°C", component.get_temperature()); + /// } + /// ``` fn get_temperature(&self) -> f32; + /// Returns the maximum temperature of this component. + /// + /// ```no_run + /// use sysinfo::{ComponentExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for component in s.get_components_list() { + /// println!("{}°C", component.get_max()); + /// } + /// ``` fn get_max(&self) -> f32; + /// Returns the highest temperature before the computer halts. + /// + /// ```no_run + /// use sysinfo::{ComponentExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for component in s.get_components_list() { + /// println!("{:?}°C", component.get_critical()); + /// } + /// ``` fn get_critical(&self) -> Option<f32>; + /// Returns component's label. + /// + /// ```no_run + /// use sysinfo::{ComponentExt, System, SystemExt}; + /// + /// let s = System::new_all(); + /// for component in s.get_components_list() { + /// println!("{}", component.get_label()); + /// } + /// ``` fn get_label(&self) -> &str; } diff --git a/src/unknown/mod.rs b/src/unknown/mod.rs --- a/src/unknown/mod.rs +++ b/src/unknown/mod.rs @@ -13,7 +13,7 @@ pub mod system; pub use self::component::Component; pub use self::disk::{Disk, DiskType}; -pub use self::network::NetworkData; +pub use self::network::{Networks, NetworkData}; pub use self::process::{Process, ProcessStatus}; pub use self::processor::Processor; pub use self::system::System; diff --git a/src/unknown/network.rs b/src/unknown/network.rs --- a/src/unknown/network.rs +++ b/src/unknown/network.rs @@ -4,7 +4,41 @@ // Copyright (c) 2017 Guillaume Gomez // +use std::collections::HashMap; + use NetworkExt; +use NetworksExt; +use NetworksIter; + +/// Network interfaces. +/// +/// ```no_run +/// use sysinfo::{NetworksExt, System, SystemExt}; +/// +/// let s = System::new_all(); +/// let networks = s.get_networks(); +/// ``` +pub struct Networks { + interfaces: HashMap<String, NetworkData>, +} + +impl Networks { + pub(crate) fn new() -> Networks { + Networks { + interfaces: HashMap::new(), + } + } +} + +impl NetworksExt for Networks { + fn iter<'a>(&'a self) -> NetworksIter<'a> { + NetworksIter::new(self.interfaces.iter()) + } + + fn refresh_networks_list(&mut self) {} + + fn refresh(&mut self) {} +} /// Contains network information. #[derive(Debug)] diff --git a/src/unknown/network.rs b/src/unknown/network.rs --- a/src/unknown/network.rs +++ b/src/unknown/network.rs @@ -18,4 +52,12 @@ impl NetworkExt for NetworkData { fn get_outcome(&self) -> u64 { 0 } + + fn get_total_income(&self) -> u64 { + 0 + } + + fn get_total_outcome(&self) -> u64 { + 0 + } } diff --git a/src/unknown/processor.rs b/src/unknown/processor.rs --- a/src/unknown/processor.rs +++ b/src/unknown/processor.rs @@ -4,6 +4,9 @@ // Copyright (c) 2015 Guillaume Gomez // +use std::default::Default; + +use LoadAvg; use ProcessorExt; /// Dummy struct that represents a processor. diff --git a/src/unknown/processor.rs b/src/unknown/processor.rs --- a/src/unknown/processor.rs +++ b/src/unknown/processor.rs @@ -17,4 +20,16 @@ impl ProcessorExt for Processor { fn get_name(&self) -> &str { "" } + + fn get_frequency(&self) -> u64 { + 0 + } + + fn get_vendor_id(&self) -> &str { + "" + } + + fn get_brand(&self) -> &str { + "" + } } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -8,7 +8,7 @@ use sys::component::Component; use sys::process::*; use sys::processor::*; use sys::Disk; -use sys::NetworkData; +use sys::Networks; use Pid; use {RefreshKind, SystemExt}; diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -18,14 +18,14 @@ use std::collections::HashMap; #[derive(Debug)] pub struct System { processes_list: HashMap<Pid, Process>, - network: NetworkData, + networks: Networks, } impl SystemExt for System { fn new_with_specifics(_: RefreshKind) -> System { System { processes_list: Default::default(), - network: NetworkData, + networks: Networks::new(), } } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -43,7 +43,7 @@ impl SystemExt for System { fn refresh_disks(&mut self) {} - fn refresh_disk_list(&mut self) {} + fn refresh_disks_list(&mut self) {} fn refresh_network(&mut self) {} diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -59,8 +59,12 @@ impl SystemExt for System { None } - fn get_network(&self) -> &NetworkData { - &self.network + fn get_networks(&self) -> &Networks { + &self.networks + } + + fn get_networks_mut(&mut self) -> &mut Networks { + &mut self.networks } fn get_processor_list(&self) -> &[Processor] { diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -102,6 +106,14 @@ impl SystemExt for System { fn get_uptime(&self) -> u64 { 0 } + + fn get_load_average(&self) -> LoadAvg { + LoadAvg { + one: 0., + five: 0., + fifteen: 0., + } + } } impl Default for System { diff --git a/src/windows/ffi.rs b/src/windows/ffi.rs --- a/src/windows/ffi.rs +++ b/src/windows/ffi.rs @@ -1,333 +1,220 @@ -// +// // Sysinfo -// -// Copyright (c) 2015 Guillaume Gomez +// +// Copyright (c) 2020 Guillaume Gomez // -use libc::{c_int, c_char, c_void, c_uchar, c_uint, size_t, uint32_t, uint64_t, c_ushort}; - -extern "C" { - pub static kCFAllocatorDefault: CFAllocatorRef; - - pub fn proc_pidinfo(pid: c_int, flavor: c_int, arg: u64, buffer: *mut c_void, - buffersize: c_int) -> c_int; - pub fn proc_listallpids(buffer: *mut c_void, buffersize: c_int) -> c_int; - //pub fn proc_name(pid: c_int, buffer: *mut c_void, buffersize: u32) -> c_int; - //pub fn proc_regionfilename(pid: c_int, address: u64, buffer: *mut c_void, - // buffersize: u32) -> c_int; - //pub fn proc_pidpath(pid: c_int, buffer: *mut c_void, buffersize: u32) -> c_int; - - pub fn IOMasterPort(a: i32, b: *mut mach_port_t) -> i32; - pub fn IOServiceMatching(a: *const c_char) -> *mut c_void; - pub fn IOServiceGetMatchingServices(a: mach_port_t, b: *mut c_void, c: *mut io_iterator_t) -> i32; - pub fn IOIteratorNext(iterator: io_iterator_t) -> io_object_t; - pub fn IOObjectRelease(obj: io_object_t) -> i32; - pub fn IOServiceOpen(device: io_object_t, a: u32, t: u32, x: *mut io_connect_t) -> i32; - pub fn IOServiceClose(a: io_connect_t) -> i32; - pub fn IOConnectCallStructMethod(connection: mach_port_t, - selector: u32, - inputStruct: *mut KeyData_t, - inputStructCnt: size_t, - outputStruct: *mut KeyData_t, - outputStructCnt: *mut size_t) -> i32; - pub fn IORegistryEntryCreateCFProperties(entry: io_registry_entry_t, - properties: *mut CFMutableDictionaryRef, - allocator: CFAllocatorRef, - options: IOOptionBits) - -> kern_return_t; - pub fn CFDictionaryContainsKey(d: CFDictionaryRef, key: *const c_void) -> Boolean; - pub fn CFDictionaryGetValue(d: CFDictionaryRef, key: *const c_void) -> *const c_void; - pub fn IORegistryEntryGetName(entry: io_registry_entry_t, name: *mut c_char) -> kern_return_t; - pub fn CFRelease(cf: CFTypeRef); - pub fn CFStringCreateWithCStringNoCopy(alloc: *mut c_void, cStr: *const c_char, - encoding: CFStringEncoding, - contentsDeallocator: *mut c_void) -> CFStringRef; - - pub static kCFAllocatorNull: CFAllocatorRef; - - pub fn mach_absolute_time() -> u64; - //pub fn task_for_pid(host: u32, pid: pid_t, task: *mut task_t) -> u32; - pub fn mach_task_self() -> u32; - pub fn mach_host_self() -> u32; - //pub fn task_info(host_info: u32, t: u32, c: *mut c_void, x: *mut u32) -> u32; - pub fn host_statistics64(host_info: u32, x: u32, y: *mut c_void, z: *const u32) -> u32; - pub fn host_processor_info(host_info: u32, t: u32, num_cpu_u: *mut u32, - cpu_info: *mut *mut i32, num_cpu_info: *mut u32) -> u32; - //pub fn host_statistics(host_priv: u32, flavor: u32, host_info: *mut c_void, - // host_count: *const u32) -> u32; - pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> u32; -} - -// TODO: waiting for https://github.com/rust-lang/libc/pull/678 -macro_rules! cfg_if { - ($( - if #[cfg($($meta:meta),*)] { $($it:item)* } - ) else * else { - $($it2:item)* - }) => { - __cfg_if_items! { - () ; - $( ( ($($meta),*) ($($it)*) ), )* - ( () ($($it2)*) ), - } - } -} - -// TODO: waiting for https://github.com/rust-lang/libc/pull/678 -macro_rules! __cfg_if_items { - (($($not:meta,)*) ; ) => {}; - (($($not:meta,)*) ; ( ($($m:meta),*) ($($it:item)*) ), $($rest:tt)*) => { - __cfg_if_apply! { cfg(all(not(any($($not),*)), $($m,)*)), $($it)* } - __cfg_if_items! { ($($not,)* $($m,)*) ; $($rest)* } - } -} - -// TODO: waiting for https://github.com/rust-lang/libc/pull/678 -macro_rules! __cfg_if_apply { - ($m:meta, $($it:item)*) => { - $(#[$m] $it)* - } -} - -// TODO: waiting for https://github.com/rust-lang/libc/pull/678 -cfg_if! { - if #[cfg(any(target_arch = "arm", target_arch = "x86"))] { - pub type timeval32 = ::libc::timeval; - } else { - use libc::timeval32; +// TO BE REMOVED ONCE https://github.com/retep998/winapi-rs/pull/802 IS MERGED!!! + +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(non_upper_case_globals)] +#![allow(dead_code)] + +use winapi::shared::basetsd::ULONG64; +use winapi::shared::guiddef::GUID; +use winapi::shared::ifdef::{NET_IFINDEX, NET_LUID}; +use winapi::shared::minwindef::BYTE; +use winapi::shared::netioapi::NETIOAPI_API; +use winapi::shared::ntdef::{PVOID, UCHAR, ULONG, WCHAR}; +use winapi::{ENUM, STRUCT}; + +const ANY_SIZE: usize = 1; + +pub const IF_MAX_STRING_SIZE: usize = 256; +pub const IF_MAX_PHYS_ADDRESS_LENGTH: usize = 32; + +pub type NET_IF_NETWORK_GUID = GUID; +pub type PMIB_IF_TABLE2 = *mut MIB_IF_TABLE2; +pub type PMIB_IF_ROW2 = *mut MIB_IF_ROW2; + +macro_rules! BITFIELD { + ($base:ident $field:ident: $fieldtype:ty [ + $($thing:ident $set_thing:ident[$r:expr],)+ + ]) => { + impl $base {$( + #[inline] + pub fn $thing(&self) -> $fieldtype { + let size = ::std::mem::size_of::<$fieldtype>() * 8; + self.$field << (size - $r.end) >> (size - $r.end + $r.start) + } + #[inline] + pub fn $set_thing(&mut self, val: $fieldtype) { + let mask = ((1 << ($r.end - $r.start)) - 1) << $r.start; + self.$field &= !mask; + self.$field |= (val << $r.start) & mask; + } + )+} } } -// TODO: waiting for https://github.com/rust-lang/libc/pull/678 -#[repr(C)] -pub struct if_data64 { - pub ifi_type: c_uchar, - pub ifi_typelen: c_uchar, - pub ifi_physical: c_uchar, - pub ifi_addrlen: c_uchar, - pub ifi_hdrlen: c_uchar, - pub ifi_recvquota: c_uchar, - pub ifi_xmitquota: c_uchar, - pub ifi_unused1: c_uchar, - pub ifi_mtu: uint32_t, - pub ifi_metric: uint32_t, - pub ifi_baudrate: uint64_t, - pub ifi_ipackets: uint64_t, - pub ifi_ierrors: uint64_t, - pub ifi_opackets: uint64_t, - pub ifi_oerrors: uint64_t, - pub ifi_collisions: uint64_t, - pub ifi_ibytes: uint64_t, - pub ifi_obytes: uint64_t, - pub ifi_imcasts: uint64_t, - pub ifi_omcasts: uint64_t, - pub ifi_iqdrops: uint64_t, - pub ifi_noproto: uint64_t, - pub ifi_recvtiming: uint32_t, - pub ifi_xmittiming: uint32_t, - pub ifi_lastchange: timeval32, -} - -// TODO: waiting for https://github.com/rust-lang/libc/pull/678 -#[repr(C)] -pub struct if_msghdr2 { - pub ifm_msglen: c_ushort, - pub ifm_version: c_uchar, - pub ifm_type: c_uchar, - pub ifm_addrs: c_int, - pub ifm_flags: c_int, - pub ifm_index: c_ushort, - pub ifm_snd_len: c_int, - pub ifm_snd_maxlen: c_int, - pub ifm_snd_drops: c_int, - pub ifm_timer: c_int, - pub ifm_data: if_data64, -} - -#[repr(C)] -pub struct __CFAllocator { - __private: c_void, +STRUCT! {struct MIB_IF_TABLE2 { + NumEntries: ULONG, + Table: [MIB_IF_ROW2; ANY_SIZE], +}} + +ENUM! {enum NDIS_MEDIUM { + NdisMedium802_3 = 0, + NdisMedium802_5 = 1, + NdisMediumFddi = 2, + NdisMediumWan = 3, + NdisMediumLocalTalk = 4, + NdisMediumDix = 5, // defined for convenience, not a real medium + NdisMediumArcnetRaw = 6, + NdisMediumArcnet878_2 = 7, + NdisMediumAtm = 8, + NdisMediumWirelessWan = 9, + NdisMediumIrda = 10, + NdisMediumBpc = 11, + NdisMediumCoWan = 12, + NdisMedium1394 = 13, + NdisMediumInfiniBand = 14, + NdisMediumTunnel = 15, + NdisMediumNative802_11 = 16, + NdisMediumLoopback = 17, + NdisMediumWiMAX = 18, + NdisMediumIP = 19, + NdisMediumMax = 20, // Not a real medium, defined as an upper-bound +}} + +ENUM! {enum TUNNEL_TYPE { + TUNNEL_TYPE_NONE = 0, + TUNNEL_TYPE_OTHER = 1, + TUNNEL_TYPE_DIRECT = 2, + TUNNEL_TYPE_6TO4 = 11, + TUNNEL_TYPE_ISATAP = 13, + TUNNEL_TYPE_TEREDO = 14, + TUNNEL_TYPE_IPHTTPS = 15, +}} + +ENUM! {enum NDIS_PHYSICAL_MEDIUM { + NdisPhysicalMediumUnspecified = 0, + NdisPhysicalMediumWirelessLan = 1, + NdisPhysicalMediumCableModem = 2, + NdisPhysicalMediumPhoneLine = 3, + NdisPhysicalMediumPowerLine = 4, + NdisPhysicalMediumDSL = 5, // includes ADSL and UADSL (G.Lite) + NdisPhysicalMediumFibreChannel = 6, + NdisPhysicalMedium1394 = 7, + NdisPhysicalMediumWirelessWan = 8, + NdisPhysicalMediumNative802_11 = 9, + NdisPhysicalMediumBluetooth = 10, + NdisPhysicalMediumInfiniband = 11, + NdisPhysicalMediumWiMax = 12, + NdisPhysicalMediumUWB = 13, + NdisPhysicalMedium802_3 = 14, + NdisPhysicalMedium802_5 = 15, + NdisPhysicalMediumIrda = 16, + NdisPhysicalMediumWiredWAN = 17, + NdisPhysicalMediumWiredCoWan = 18, + NdisPhysicalMediumOther = 19, + NdisPhysicalMediumMax = 20, // Not a real physical type, defined as an upper-bound +}} + +ENUM! {enum NET_IF_ACCESS_TYPE { + NET_IF_ACCESS_LOOPBACK = 1, + NET_IF_ACCESS_BROADCAST = 2, + NET_IF_ACCESS_POINT_TO_POINT = 3, + NET_IF_ACCESS_POINT_TO_MULTI_POINT = 4, + NET_IF_ACCESS_MAXIMUM = 5, +}} + +ENUM! {enum NET_IF_DIRECTION_TYPE { + NET_IF_DIRECTION_SENDRECEIVE = 0, + NET_IF_DIRECTION_SENDONLY = 1, + NET_IF_DIRECTION_RECEIVEONLY = 2, + NET_IF_DIRECTION_MAXIMUM = 3, +}} + +ENUM! {enum IF_OPER_STATUS { + IfOperStatusUp = 1, + IfOperStatusDown = 2, + IfOperStatusTesting = 3, + IfOperStatusUnknown = 4, + IfOperStatusDormant = 5, + IfOperStatusNotPresent = 6, + IfOperStatusLowerLayerDown = 7, +}} + +ENUM! {enum NET_IF_ADMIN_STATUS { + NET_IF_ADMIN_STATUS_UP = 1, + NET_IF_ADMIN_STATUS_DOWN = 2, + NET_IF_ADMIN_STATUS_TESTING = 3, +}} + +ENUM! {enum NET_IF_MEDIA_CONNECT_STATE { + MediaConnectStateUnknown = 0, + MediaConnectStateConnected = 1, + MediaConnectStateDisconnected = 2, +}} + +ENUM! {enum NET_IF_CONNECTION_TYPE { + NET_IF_CONNECTION_DEDICATED = 1, + NET_IF_CONNECTION_PASSIVE = 2, + NET_IF_CONNECTION_DEMAND = 3, + NET_IF_CONNECTION_MAXIMUM = 4, +}} + +STRUCT! {struct MIB_IF_ROW2_InterfaceAndOperStatusFlags { + bitfield: BYTE, +}} +BITFIELD! {MIB_IF_ROW2_InterfaceAndOperStatusFlags bitfield: BYTE [ + HardwareInterface set_HardwareInterface[0..1], + FilterInterface set_FilterInterface[1..2], + ConnectorPresent set_ConnectorPresent[2..3], + NotAuthenticated set_NotAuthenticated[3..4], + NotMediaConnected set_NotMediaConnected[4..5], + Paused set_Paused[5..6], + LowPower set_LowPower[6..7], + EndPointInterface set_EndPointInterface[7..8], +]} + +STRUCT! {struct MIB_IF_ROW2 { + InterfaceLuid: NET_LUID, + InterfaceIndex: NET_IFINDEX, + InterfaceGuid: GUID, + Alias: [WCHAR; IF_MAX_STRING_SIZE + 1], + Description: [WCHAR; IF_MAX_STRING_SIZE + 1], + PhysicalAddressLength: ULONG, + PhysicalAddress: [UCHAR; IF_MAX_PHYS_ADDRESS_LENGTH], + PermanentPhysicalAddress: [UCHAR; IF_MAX_PHYS_ADDRESS_LENGTH], + Mtu: ULONG, + Type: ULONG, // Interface Type. + TunnelType: TUNNEL_TYPE, // Tunnel Type, if Type = IF_TUNNEL. + MediaType: NDIS_MEDIUM, + PhysicalMediumType: NDIS_PHYSICAL_MEDIUM, + AccessType: NET_IF_ACCESS_TYPE, + DirectionType: NET_IF_DIRECTION_TYPE, + InterfaceAndOperStatusFlags: MIB_IF_ROW2_InterfaceAndOperStatusFlags, + OperStatus: IF_OPER_STATUS, + AdminStatus: NET_IF_ADMIN_STATUS, + MediaConnectState: NET_IF_MEDIA_CONNECT_STATE, + NetworkGuid: NET_IF_NETWORK_GUID, + ConnectionType: NET_IF_CONNECTION_TYPE, + TransmitLinkSpeed: ULONG64, + ReceiveLinkSpeed: ULONG64, + InOctets: ULONG64, + InUcastPkts: ULONG64, + InNUcastPkts: ULONG64, + InDiscards: ULONG64, + InErrors: ULONG64, + InUnknownProtos: ULONG64, + InUcastOctets: ULONG64, + InMulticastOctets: ULONG64, + InBroadcastOctets: ULONG64, + OutOctets: ULONG64, + OutUcastPkts: ULONG64, + OutNUcastPkts: ULONG64, + OutDiscards: ULONG64, + OutErrors: ULONG64, + OutUcastOctets: ULONG64, + OutMulticastOctets: ULONG64, + OutBroadcastOctets: ULONG64, + OutQLen: ULONG64, +}} + +extern "system" { + pub fn GetIfTable2(Table: *mut PMIB_IF_TABLE2) -> NETIOAPI_API; + pub fn GetIfEntry2(Row: PMIB_IF_ROW2) -> NETIOAPI_API; + pub fn FreeMibTable(Memory: PVOID); } - -#[repr(C)] -pub struct __CFDictionary { - __private: c_void, -} - -#[repr(C)] -pub struct __CFString { - __private: c_void, -} - -pub type CFAllocatorRef = *const __CFAllocator; -pub type CFMutableDictionaryRef = *mut __CFDictionary; -pub type CFDictionaryRef = *const __CFDictionary; -#[allow(non_camel_case_types)] -pub type io_name_t = [u8; 128]; -#[allow(non_camel_case_types)] -pub type io_registry_entry_t = io_object_t; -pub type CFTypeRef = *const c_void; -pub type CFStringRef = *const __CFString; - -//#[allow(non_camel_case_types)] -//pub type policy_t = i32; -#[allow(non_camel_case_types)] -//pub type integer_t = i32; -//#[allow(non_camel_case_types)] -//pub type time_t = i64; -//#[allow(non_camel_case_types)] -//pub type suseconds_t = i32; -//#[allow(non_camel_case_types)] -//pub type mach_vm_size_t = u64; -//#[allow(non_camel_case_types)] -//pub type task_t = u32; -//#[allow(non_camel_case_types)] -//pub type pid_t = i32; -#[allow(non_camel_case_types)] -pub type natural_t = u32; -#[allow(non_camel_case_types)] -pub type mach_port_t = u32; -#[allow(non_camel_case_types)] -pub type io_object_t = mach_port_t; -#[allow(non_camel_case_types)] -pub type io_iterator_t = io_object_t; -#[allow(non_camel_case_types)] -pub type io_connect_t = io_object_t; -#[allow(non_camel_case_types)] -pub type boolean_t = c_uint; -#[allow(non_camel_case_types)] -pub type kern_return_t = c_int; -pub type Boolean = c_uchar; -pub type IOOptionBits = u32; -pub type CFStringEncoding = u32; - -/*#[repr(C)] -pub struct task_thread_times_info { - pub user_time: time_value, - pub system_time: time_value, -}*/ - -/*#[repr(C)] -pub struct task_basic_info_64 { - pub suspend_count: integer_t, - pub virtual_size: mach_vm_size_t, - pub resident_size: mach_vm_size_t, - pub user_time: time_value_t, - pub system_time: time_value_t, - pub policy: policy_t, -}*/ - -#[repr(C)] -pub struct vm_statistics64 { - pub free_count: natural_t, - pub active_count: natural_t, - pub inactive_count: natural_t, - pub wire_count: natural_t, - pub zero_fill_count: u64, - pub reactivations: u64, - pub pageins: u64, - pub pageouts: u64, - pub faults: u64, - pub cow_faults: u64, - pub lookups: u64, - pub hits: u64, - pub purges: u64, - pub purgeable_count: natural_t, - pub speculative_count: natural_t, - pub decompressions: u64, - pub compressions: u64, - pub swapins: u64, - pub swapouts: u64, - pub compressor_page_count: natural_t, - pub throttled_count: natural_t, - pub external_page_count: natural_t, - pub internal_page_count: natural_t, - pub total_uncompressed_pages_in_compressor: u64, -} - -#[repr(C)] -pub struct Val_t { - pub key: [i8; 5], - pub data_size: u32, - pub data_type: [i8; 5], // UInt32Char_t - pub bytes: [i8; 32], // SMCBytes_t -} - -#[repr(C)] -pub struct KeyData_vers_t { - pub major: u8, - pub minor: u8, - pub build: u8, - pub reserved: [u8; 1], - pub release: u16, -} - -#[repr(C)] -pub struct KeyData_pLimitData_t { - pub version: u16, - pub length: u16, - pub cpu_plimit: u32, - pub gpu_plimit: u32, - pub mem_plimit: u32, -} - -#[repr(C)] -pub struct KeyData_keyInfo_t { - pub data_size: u32, - pub data_type: u32, - pub data_attributes: u8, -} - -#[repr(C)] -pub struct KeyData_t { - pub key: u32, - pub vers: KeyData_vers_t, - pub p_limit_data: KeyData_pLimitData_t, - pub key_info: KeyData_keyInfo_t, - pub result: u8, - pub status: u8, - pub data8: u8, - pub data32: u32, - pub bytes: [i8; 32], // SMCBytes_t -} - -#[repr(C)] -pub struct xsw_usage { - pub xsu_total: u64, - pub xsu_avail: u64, - pub xsu_used: u64, - pub xsu_pagesize: u32, - pub xsu_encrypted: boolean_t, -} - -//pub const HOST_CPU_LOAD_INFO_COUNT: usize = 4; -//pub const HOST_CPU_LOAD_INFO: u32 = 3; -pub const KERN_SUCCESS: u32 = 0; - -pub const HW_NCPU: u32 = 3; -pub const CTL_HW: u32 = 6; -pub const CTL_VM: u32 = 2; -pub const VM_SWAPUSAGE: u32 = 5; -pub const PROCESSOR_CPU_LOAD_INFO: u32 = 2; -pub const CPU_STATE_USER: u32 = 0; -pub const CPU_STATE_SYSTEM: u32 = 1; -pub const CPU_STATE_IDLE: u32 = 2; -pub const CPU_STATE_NICE: u32 = 3; -pub const CPU_STATE_MAX: usize = 4; -pub const HW_MEMSIZE: u32 = 24; - -//pub const TASK_THREAD_TIMES_INFO: u32 = 3; -//pub const TASK_THREAD_TIMES_INFO_COUNT: u32 = 4; -//pub const TASK_BASIC_INFO_64: u32 = 5; -//pub const TASK_BASIC_INFO_64_COUNT: u32 = 10; -pub const HOST_VM_INFO64: u32 = 4; -pub const HOST_VM_INFO64_COUNT: u32 = 38; - -pub const MACH_PORT_NULL: i32 = 0; -pub const KERNEL_INDEX_SMC: i32 = 2; -pub const SMC_CMD_READ_KEYINFO: u8 = 9; -pub const SMC_CMD_READ_BYTES: u8 = 5; - -pub const KIO_RETURN_SUCCESS: i32 = 0; -#[allow(non_upper_case_globals)] -pub const kCFStringEncodingMacRoman: CFStringEncoding = 0; diff --git a/src/windows/mod.rs b/src/windows/mod.rs --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -4,24 +4,8 @@ // Copyright (c) 2015 Guillaume Gomez // -/*pub mod component; -pub mod disk; -mod ffi; -pub mod network; -pub mod process; -pub mod processor; -pub mod system; - -pub use self::component::Component; -pub use self::disk::{Disk, DiskType}; -pub use self::network::NetworkData; -pub use self::process::{Process,ProcessStatus}; -pub use self::processor::Processor; -pub use self::system::System;*/ - mod component; mod disk; -//mod ffi; #[macro_use] mod macros; mod network; diff --git a/src/windows/mod.rs b/src/windows/mod.rs --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -30,9 +14,11 @@ mod processor; mod system; mod tools; +mod ffi; + pub use self::component::Component; pub use self::disk::{Disk, DiskType}; -pub use self::network::NetworkData; +pub use self::network::{NetworkData, Networks}; pub use self::process::{Process, ProcessStatus}; pub use self::processor::Processor; pub use self::system::System; diff --git a/src/windows/network.rs b/src/windows/network.rs --- a/src/windows/network.rs +++ b/src/windows/network.rs @@ -4,54 +4,168 @@ // Copyright (c) 2017 Guillaume Gomez // -use windows::processor::Query; -use windows::tools::KeyHandler; +use std::collections::{HashMap, HashSet}; + +use windows::ffi::{self, MIB_IF_ROW2, PMIB_IF_TABLE2}; use NetworkExt; +use NetworksExt; +use NetworksIter; + +use winapi::shared::ifdef::NET_LUID; +use winapi::shared::winerror::NO_ERROR; + +macro_rules! old_and_new { + ($ty_:expr, $name:ident, $old:ident, $new_val:expr) => {{ + $ty_.$old = $ty_.$name; + $ty_.$name = $new_val; + }}; +} + +/// Network interfaces. +/// +/// ```no_run +/// use sysinfo::{NetworksExt, System, SystemExt}; +/// +/// let s = System::new_all(); +/// let networks = s.get_networks(); +/// ``` +pub struct Networks { + interfaces: HashMap<String, NetworkData>, +} + +impl Networks { + pub(crate) fn new() -> Networks { + Networks { + interfaces: HashMap::new(), + } + } +} + +impl NetworksExt for Networks { + fn iter<'a>(&'a self) -> NetworksIter<'a> { + NetworksIter::new(self.interfaces.iter()) + } + + fn refresh_networks_list(&mut self) { + let mut table: PMIB_IF_TABLE2 = ::std::ptr::null_mut(); + if unsafe { ffi::GetIfTable2(&mut table) } != NO_ERROR { + return; + } + let mut to_be_removed = HashSet::with_capacity(self.interfaces.len()); + + for key in self.interfaces.keys() { + to_be_removed.insert(key.clone()); + } + // In here, this is tricky: we have to filter out the software interfaces to only keep + // the hardware ones. To do so, we first check the connection potential speed (if 0, not + // interesting), then we check its state: if not open, not interesting either. And finally, + // we count the members of a same group: if there is more than 1, then it's software level. + let mut groups = HashMap::new(); + let mut indexes = Vec::new(); + let ptr = unsafe { (*table).Table.as_ptr() }; + for i in 0..unsafe { *table }.NumEntries { + let ptr = unsafe { &*ptr.offset(i as _) }; + if ptr.TransmitLinkSpeed == 0 && ptr.ReceiveLinkSpeed == 0 { + continue; + } else if ptr.MediaConnectState == ffi::MediaConnectStateDisconnected + || ptr.PhysicalAddressLength == 0 + { + continue; + } + let id = vec![ + ptr.InterfaceGuid.Data2, + ptr.InterfaceGuid.Data3, + ptr.InterfaceGuid.Data4[0] as _, + ptr.InterfaceGuid.Data4[1] as _, + ptr.InterfaceGuid.Data4[2] as _, + ptr.InterfaceGuid.Data4[3] as _, + ptr.InterfaceGuid.Data4[4] as _, + ptr.InterfaceGuid.Data4[5] as _, + ptr.InterfaceGuid.Data4[6] as _, + ptr.InterfaceGuid.Data4[7] as _, + ]; + let entry = groups.entry(id.clone()).or_insert(0); + *entry += 1; + if *entry > 1 { + continue; + } + indexes.push((i, id)); + } + for (i, id) in indexes { + let ptr = unsafe { &*ptr.offset(i as _) }; + if *groups.get(&id).unwrap_or(&0) > 1 { + continue; + } + let mut pos = 0; + for x in ptr.Alias.iter() { + if *x == 0 { + break; + } + pos += 1; + } + let interface_name = match String::from_utf16(&ptr.Alias[..pos]) { + Ok(s) => s, + _ => continue, + }; + to_be_removed.remove(&interface_name); + let mut interface = + self.interfaces + .entry(interface_name) + .or_insert_with(|| NetworkData { + id: ptr.InterfaceLuid, + current_out: ptr.OutOctets, + old_out: ptr.OutOctets, + current_in: ptr.InOctets, + old_in: ptr.InOctets, + }); + old_and_new!(interface, current_out, old_out, ptr.OutOctets); + old_and_new!(interface, current_in, old_in, ptr.InOctets); + } + unsafe { + ffi::FreeMibTable(table as _); + } + for key in to_be_removed { + self.interfaces.remove(&key); + } + } + + fn refresh(&mut self) { + let mut entry: MIB_IF_ROW2 = unsafe { ::std::mem::MaybeUninit::uninit().assume_init() }; + for (_, interface) in self.interfaces.iter_mut() { + entry.InterfaceLuid = interface.id; + entry.InterfaceIndex = 0; // to prevent the function to pick this one as index + if unsafe { ffi::GetIfEntry2(&mut entry) } != NO_ERROR { + continue; + } + old_and_new!(interface, current_out, old_out, entry.OutOctets); + old_and_new!(interface, current_in, old_in, entry.InOctets); + } + } +} /// Contains network information. pub struct NetworkData { + id: NET_LUID, current_out: u64, + old_out: u64, current_in: u64, - keys_in: Vec<KeyHandler>, - keys_out: Vec<KeyHandler>, + old_in: u64, } impl NetworkExt for NetworkData { fn get_income(&self) -> u64 { - self.current_in + self.current_in - self.old_in } fn get_outcome(&self) -> u64 { - self.current_out + self.current_out - self.old_out } -} -pub fn new() -> NetworkData { - NetworkData { - current_in: 0, - current_out: 0, - keys_in: Vec::new(), - keys_out: Vec::new(), + fn get_total_income(&self) -> u64 { + self.current_in } -} -pub fn refresh(network: &mut NetworkData, query: &Option<Query>) { - if let &Some(ref query) = query { - network.current_in = 0; - for key in &network.keys_in { - network.current_in += query.get_u64(&key.unique_id).expect("key disappeared"); - } - network.current_out = 0; - for key in &network.keys_out { - network.current_out += query.get_u64(&key.unique_id).expect("key disappeared"); - } + fn get_total_outcome(&self) -> u64 { + self.current_out } } - -pub fn get_keys_in(network: &mut NetworkData) -> &mut Vec<KeyHandler> { - &mut network.keys_in -} - -pub fn get_keys_out(network: &mut NetworkData) -> &mut Vec<KeyHandler> { - &mut network.keys_out -} diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -5,24 +5,120 @@ // use std::collections::HashMap; +use std::mem; +use std::ops::DerefMut; +use std::ptr::null_mut; use std::sync::{Arc, Mutex}; -use std::thread::{self /*, sleep*/, JoinHandle}; -//use std::time::Duration; use windows::tools::KeyHandler; +use LoadAvg; use ProcessorExt; -use winapi::shared::minwindef::{FALSE, ULONG}; +use ntapi::ntpoapi::PROCESSOR_POWER_INFORMATION; + +use winapi::shared::minwindef::FALSE; use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::handleapi::CloseHandle; use winapi::um::pdh::{ - PdhAddCounterW, PdhCloseQuery, PdhCollectQueryData, PdhCollectQueryDataEx, + PdhAddCounterW, PdhAddEnglishCounterA, PdhCloseQuery, PdhCollectQueryDataEx, PdhGetFormattedCounterValue, PdhOpenQueryA, PdhRemoveCounter, PDH_FMT_COUNTERVALUE, - PDH_FMT_DOUBLE, PDH_FMT_LARGE, PDH_HCOUNTER, PDH_HQUERY, + PDH_FMT_DOUBLE, PDH_HCOUNTER, PDH_HQUERY, }; -use winapi::um::synchapi::{CreateEventA, WaitForSingleObject}; -use winapi::um::winbase::{INFINITE, WAIT_OBJECT_0}; -use winapi::um::winnt::HANDLE; +use winapi::um::powerbase::CallNtPowerInformation; +use winapi::um::synchapi::CreateEventA; +use winapi::um::sysinfoapi::SYSTEM_INFO; +use winapi::um::winbase::{RegisterWaitForSingleObject, INFINITE}; +use winapi::um::winnt::{ProcessorInformation, BOOLEAN, HANDLE, PVOID, WT_EXECUTEDEFAULT}; + +// This formula comes from linux's include/linux/sched/loadavg.h +// https://github.com/torvalds/linux/blob/345671ea0f9258f410eb057b9ced9cefbbe5dc78/include/linux/sched/loadavg.h#L20-L23 +const LOADAVG_FACTOR_1F: f64 = 0.9200444146293232478931553241; +const LOADAVG_FACTOR_5F: f64 = 0.6592406302004437462547604110; +const LOADAVG_FACTOR_15F: f64 = 0.2865047968601901003248854266; +// The time interval in seconds between taking load counts, same as Linux +const SAMPLING_INTERVAL: usize = 5; + +// maybe use a read/write lock instead? +static LOAD_AVG: once_cell::sync::Lazy<Mutex<Option<LoadAvg>>> = + once_cell::sync::Lazy::new(|| unsafe { init_load_avg() }); + +pub(crate) fn get_load_average() -> LoadAvg { + if let Ok(avg) = LOAD_AVG.lock() { + if let Some(avg) = &*avg { + return avg.clone(); + } + } + return LoadAvg::default(); +} + +unsafe extern "system" fn load_avg_callback(counter: PVOID, _: BOOLEAN) { + let mut display_value: PDH_FMT_COUNTERVALUE = mem::MaybeUninit::uninit().assume_init(); + + if PdhGetFormattedCounterValue(counter as _, PDH_FMT_DOUBLE, null_mut(), &mut display_value) + != ERROR_SUCCESS as _ + { + return; + } + if let Ok(mut avg) = LOAD_AVG.lock() { + if let Some(avg) = avg.deref_mut() { + let current_load = display_value.u.doubleValue(); + + avg.one = avg.one * LOADAVG_FACTOR_1F + current_load * (1.0 - LOADAVG_FACTOR_1F); + avg.five = avg.five * LOADAVG_FACTOR_5F + current_load * (1.0 - LOADAVG_FACTOR_5F); + avg.fifteen = + avg.fifteen * LOADAVG_FACTOR_15F + current_load * (1.0 - LOADAVG_FACTOR_15F); + } + } +} + +unsafe fn init_load_avg() -> Mutex<Option<LoadAvg>> { + // You can see the original implementation here: https://github.com/giampaolo/psutil + let mut query = null_mut(); + + if PdhOpenQueryA(null_mut(), 0, &mut query) != ERROR_SUCCESS as _ { + return Mutex::new(None); + } + + let mut counter: PDH_HCOUNTER = mem::zeroed(); + if PdhAddEnglishCounterA( + query, + b"\\System\\Processor Queue Length\0".as_ptr() as _, + 0, + &mut counter, + ) != ERROR_SUCCESS as _ + { + PdhCloseQuery(query); + return Mutex::new(None); + } + + let event = CreateEventA(null_mut(), FALSE, FALSE, b"LoadUpdateEvent\0".as_ptr() as _); + if event.is_null() { + PdhCloseQuery(query); + return Mutex::new(None); + } + + if PdhCollectQueryDataEx(query, SAMPLING_INTERVAL as _, event) != ERROR_SUCCESS as _ { + PdhCloseQuery(query); + return Mutex::new(None); + } + + let mut wait_handle = null_mut(); + if RegisterWaitForSingleObject( + &mut wait_handle, + event, + Some(load_avg_callback), + counter as _, + INFINITE, + WT_EXECUTEDEFAULT, + ) == 0 + { + PdhRemoveCounter(counter); + PdhCloseQuery(query); + return Mutex::new(None); + } + + return Mutex::new(Some(LoadAvg::default())); +} #[derive(Debug)] pub enum CounterValue { diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -37,13 +133,6 @@ impl CounterValue { _ => panic!("not a float"), } } - - pub fn get_u64(&self) -> u64 { - match *self { - CounterValue::Integer(v) => v, - _ => panic!("not an integer"), - } - } } #[allow(dead_code)] diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -81,56 +170,6 @@ struct InternalQuery { unsafe impl Send for InternalQuery {} unsafe impl Sync for InternalQuery {} -impl InternalQuery { - pub fn record(&self) -> bool { - unsafe { - let status = PdhCollectQueryData(self.query); - if status != ERROR_SUCCESS as i32 { - eprintln!("PdhCollectQueryData error: {:x} {:?}", status, self.query); - return false; - } - if PdhCollectQueryDataEx(self.query, 1, self.event) != ERROR_SUCCESS as i32 { - return false; - } - if WaitForSingleObject(self.event, INFINITE) == WAIT_OBJECT_0 { - if let Ok(ref mut data) = self.data.lock() { - let mut counter_type: ULONG = 0; - let mut display_value: PDH_FMT_COUNTERVALUE = ::std::mem::zeroed(); - for (_, x) in data.iter_mut() { - match x.value { - CounterValue::Float(ref mut value) => { - if PdhGetFormattedCounterValue( - x.counter, - PDH_FMT_DOUBLE, - &mut counter_type, - &mut display_value, - ) == ERROR_SUCCESS as i32 - { - *value = *display_value.u.doubleValue() as f32 / 100f32; - } - } - CounterValue::Integer(ref mut value) => { - if PdhGetFormattedCounterValue( - x.counter, - PDH_FMT_LARGE, - &mut counter_type, - &mut display_value, - ) == ERROR_SUCCESS as i32 - { - *value = *display_value.u.largeValue() as u64; - } - } - } - } - } - true - } else { - false - } - } - } -} - impl Drop for InternalQuery { fn drop(&mut self) { unsafe { diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -153,20 +192,15 @@ impl Drop for InternalQuery { pub struct Query { internal: Arc<InternalQuery>, - thread: Option<JoinHandle<()>>, } impl Query { pub fn new() -> Option<Query> { - let mut query = ::std::ptr::null_mut(); + let mut query = null_mut(); unsafe { - if PdhOpenQueryA(::std::ptr::null_mut(), 0, &mut query) == ERROR_SUCCESS as i32 { - let event = CreateEventA( - ::std::ptr::null_mut(), - FALSE, - FALSE, - b"some_ev\0".as_ptr() as *const i8, - ); + if PdhOpenQueryA(null_mut(), 0, &mut query) == ERROR_SUCCESS as i32 { + let event = + CreateEventA(null_mut(), FALSE, FALSE, b"some_ev\0".as_ptr() as *const i8); if event.is_null() { PdhCloseQuery(query); None diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -176,10 +210,7 @@ impl Query { event: event, data: Mutex::new(HashMap::new()), }); - Some(Query { - internal: q, - thread: None, - }) + Some(Query { internal: q }) } } else { None diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -196,15 +227,6 @@ impl Query { None } - pub fn get_u64(&self, name: &String) -> Option<u64> { - if let Ok(data) = self.internal.data.lock() { - if let Some(ref counter) = data.get(name) { - return Some(counter.value.get_u64()); - } - } - None - } - pub fn add_counter(&mut self, name: &String, getter: Vec<u16>, value: CounterValue) -> bool { if let Ok(data) = self.internal.data.lock() { if data.contains_key(name) { diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -233,13 +255,6 @@ impl Query { } true } - - pub fn start(&mut self) { - let internal = Arc::clone(&self.internal); - self.thread = Some(thread::spawn(move || loop { - internal.record(); - })); - } } /// Struct containing a processor information. diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -248,6 +263,9 @@ pub struct Processor { cpu_usage: f32, key_idle: Option<KeyHandler>, key_used: Option<KeyHandler>, + vendor_id: String, + brand: String, + frequency: u64, } impl ProcessorExt for Processor { diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -258,25 +276,139 @@ impl ProcessorExt for Processor { fn get_name(&self) -> &str { &self.name } + + fn get_frequency(&self) -> u64 { + self.frequency + } + + fn get_vendor_id(&self) -> &str { + &self.vendor_id + } + + fn get_brand(&self) -> &str { + &self.brand + } } impl Processor { - fn new_with_values(name: &str) -> Processor { + pub(crate) fn new_with_values( + name: &str, + vendor_id: String, + brand: String, + frequency: u64, + ) -> Processor { Processor { name: name.to_owned(), cpu_usage: 0f32, key_idle: None, key_used: None, + vendor_id, + brand, + frequency, } } + + pub(crate) fn set_cpu_usage(&mut self, value: f32) { + self.cpu_usage = value; + } } -pub fn create_processor(name: &str) -> Processor { - Processor::new_with_values(name) +fn get_vendor_id_not_great(info: &SYSTEM_INFO) -> String { + use winapi::um::winnt; + // https://docs.microsoft.com/fr-fr/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info + match unsafe { info.u.s() }.wProcessorArchitecture { + winnt::PROCESSOR_ARCHITECTURE_INTEL => "Intel x86", + winnt::PROCESSOR_ARCHITECTURE_MIPS => "MIPS", + winnt::PROCESSOR_ARCHITECTURE_ALPHA => "RISC Alpha", + winnt::PROCESSOR_ARCHITECTURE_PPC => "PPC", + winnt::PROCESSOR_ARCHITECTURE_SHX => "SHX", + winnt::PROCESSOR_ARCHITECTURE_ARM => "ARM", + winnt::PROCESSOR_ARCHITECTURE_IA64 => "Intel Itanium-based x64", + winnt::PROCESSOR_ARCHITECTURE_ALPHA64 => "RISC Alpha x64", + winnt::PROCESSOR_ARCHITECTURE_MSIL => "MSIL", + winnt::PROCESSOR_ARCHITECTURE_AMD64 => "(Intel or AMD) x64", + winnt::PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 => "Intel Itanium-based x86", + winnt::PROCESSOR_ARCHITECTURE_NEUTRAL => "unknown", + winnt::PROCESSOR_ARCHITECTURE_ARM64 => "ARM x64", + winnt::PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 => "ARM", + winnt::PROCESSOR_ARCHITECTURE_IA32_ON_ARM64 => "Intel Itanium-based x86", + _ => "unknown", + } + .to_owned() +} + +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { + #[cfg(target_arch = "x86")] + use std::arch::x86::__cpuid; + #[cfg(target_arch = "x86_64")] + use std::arch::x86_64::__cpuid; + + fn add_u32(v: &mut Vec<u8>, i: u32) { + let i = &i as *const u32 as *const u8; + unsafe { + v.push(*i); + v.push(*i.offset(1)); + v.push(*i.offset(2)); + v.push(*i.offset(3)); + } + } + + // First, we try to get the complete name. + let res = unsafe { __cpuid(0x80000000) }; + let n_ex_ids = res.eax; + let brand = if n_ex_ids >= 0x80000004 { + let mut extdata = Vec::with_capacity(5); + + for i in 0x80000000..=n_ex_ids { + extdata.push(unsafe { __cpuid(i) }); + } + + let mut out = Vec::with_capacity(4 * 4 * 3); // 4 * u32 * nb_entries + for i in 2..5 { + add_u32(&mut out, extdata[i].eax); + add_u32(&mut out, extdata[i].ebx); + add_u32(&mut out, extdata[i].ecx); + add_u32(&mut out, extdata[i].edx); + } + let mut pos = 0; + for e in out.iter() { + if *e == 0 { + break; + } + pos += 1; + } + match ::std::str::from_utf8(&out[..pos]) { + Ok(s) => s.to_owned(), + _ => String::new(), + } + } else { + String::new() + }; + + // Failed to get full name, let's retry for the short version! + let res = unsafe { __cpuid(0) }; + let mut x = Vec::with_capacity(16); // 3 * u32 + add_u32(&mut x, res.ebx); + add_u32(&mut x, res.edx); + add_u32(&mut x, res.ecx); + let mut pos = 0; + for e in x.iter() { + if *e == 0 { + break; + } + pos += 1; + } + let vendor_id = match ::std::str::from_utf8(&x[..pos]) { + Ok(s) => s.to_owned(), + Err(_) => get_vendor_id_not_great(info), + }; + (vendor_id, brand) } -pub fn set_cpu_usage(p: &mut Processor, value: f32) { - p.cpu_usage = value; +#[cfg(all(not(target_arch = "x86_64"), not(target_arch = "x86")))] +pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { + (get_vendor_id_not_great(info), String::new()) } pub fn get_key_idle(p: &mut Processor) -> &mut Option<KeyHandler> { diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -286,3 +418,35 @@ pub fn get_key_idle(p: &mut Processor) -> &mut Option<KeyHandler> { pub fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> { &mut p.key_used } + +// From https://stackoverflow.com/a/43813138: +// +// If your PC has 64 or fewer logical processors installed, the above code will work fine. However, +// if your PC has more than 64 logical processors installed, use GetActiveProcessorCount() or +// GetLogicalProcessorInformation() to determine the total number of logical processors installed. +pub fn get_frequencies(nb_processors: usize) -> Vec<u64> { + let size = nb_processors * mem::size_of::<PROCESSOR_POWER_INFORMATION>(); + let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_processors); + + if unsafe { + CallNtPowerInformation( + ProcessorInformation, + null_mut(), + 0, + infos.as_mut_ptr() as _, + size as _, + ) + } == 0 + { + unsafe { + infos.set_len(nb_processors); + } + // infos.Number + infos + .into_iter() + .map(|i| i.CurrentMhz as u64) + .collect::<Vec<_>>() + } else { + vec![0; nb_processors] + } +} diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -13,12 +13,13 @@ use std::collections::HashMap; use std::mem::{size_of, zeroed}; use DiskExt; +use LoadAvg; +use Networks; use Pid; use ProcessExt; use RefreshKind; use SystemExt; -use windows::network::{self, NetworkData}; use windows::process::{ compute_cpu_usage, get_handle, get_system_computation_time, update_proc_info, Process, }; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -28,12 +29,10 @@ use windows::tools::*; use ntapi::ntexapi::{ NtQuerySystemInformation, SystemProcessInformation, SYSTEM_PROCESS_INFORMATION, }; -use winapi::shared::minwindef::{DWORD, FALSE}; +use winapi::shared::minwindef::FALSE; use winapi::shared::ntdef::{PVOID, ULONG}; use winapi::shared::ntstatus::STATUS_INFO_LENGTH_MISMATCH; -use winapi::shared::winerror::ERROR_SUCCESS; use winapi::um::minwinbase::STILL_ACTIVE; -use winapi::um::pdh::PdhEnumObjectItemsW; use winapi::um::processthreadsapi::GetExitCodeProcess; use winapi::um::sysinfoapi::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; use winapi::um::winnt::HANDLE; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -51,7 +50,7 @@ pub struct System { temperatures: Vec<Component>, disks: Vec<Disk>, query: Option<Query>, - network: NetworkData, + networks: Networks, uptime: u64, } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -74,7 +73,7 @@ impl SystemExt for System { temperatures: component::get_components(), disks: Vec::with_capacity(2), query: Query::new(), - network: network::new(), + networks: Networks::new(), uptime: get_uptime(), }; // TODO: in case a translation fails, it might be nice to log it somewhere... diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -122,101 +121,6 @@ impl SystemExt for System { } } } - - if let Some(network_trans) = get_translation(&"Network Interface".to_owned(), &x) { - let network_in_trans = get_translation(&"Bytes Received/Sec".to_owned(), &x); - let network_out_trans = get_translation(&"Bytes Sent/sec".to_owned(), &x); - - const PERF_DETAIL_WIZARD: DWORD = 400; - const PDH_MORE_DATA: DWORD = 0x800007D2; - - let mut network_trans_utf16: Vec<u16> = network_trans.encode_utf16().collect(); - network_trans_utf16.push(0); - let mut dwCounterListSize: DWORD = 0; - let mut dwInstanceListSize: DWORD = 0; - let status = unsafe { - PdhEnumObjectItemsW( - ::std::ptr::null(), - ::std::ptr::null(), - network_trans_utf16.as_ptr(), - ::std::ptr::null_mut(), - &mut dwCounterListSize, - ::std::ptr::null_mut(), - &mut dwInstanceListSize, - PERF_DETAIL_WIZARD, - 0, - ) - }; - if status != PDH_MORE_DATA as i32 { - eprintln!("PdhEnumObjectItems invalid status: {:x}", status); - } else { - let mut pwsCounterListBuffer: Vec<u16> = - Vec::with_capacity(dwCounterListSize as usize); - let mut pwsInstanceListBuffer: Vec<u16> = - Vec::with_capacity(dwInstanceListSize as usize); - unsafe { - pwsCounterListBuffer.set_len(dwCounterListSize as usize); - pwsInstanceListBuffer.set_len(dwInstanceListSize as usize); - } - let status = unsafe { - PdhEnumObjectItemsW( - ::std::ptr::null(), - ::std::ptr::null(), - network_trans_utf16.as_ptr(), - pwsCounterListBuffer.as_mut_ptr(), - &mut dwCounterListSize, - pwsInstanceListBuffer.as_mut_ptr(), - &mut dwInstanceListSize, - PERF_DETAIL_WIZARD, - 0, - ) - }; - if status != ERROR_SUCCESS as i32 { - eprintln!("PdhEnumObjectItems invalid status: {:x}", status); - } else { - for (pos, x) in pwsInstanceListBuffer - .split(|x| *x == 0) - .filter(|x| x.len() > 0) - .enumerate() - { - let net_interface = String::from_utf16(x).expect("invalid utf16"); - if let Some(ref network_in_trans) = network_in_trans { - let mut key_in = None; - add_counter( - format!( - "\\{}({})\\{}", - network_trans, net_interface, network_in_trans - ), - query, - &mut key_in, - format!("net{}_in", pos), - CounterValue::Integer(0), - ); - if key_in.is_some() { - network::get_keys_in(&mut s.network).push(key_in.unwrap()); - } - } - if let Some(ref network_out_trans) = network_out_trans { - let mut key_out = None; - add_counter( - format!( - "\\{}({})\\{}", - network_trans, net_interface, network_out_trans - ), - query, - &mut key_out, - format!("net{}_out", pos), - CounterValue::Integer(0), - ); - if key_out.is_some() { - network::get_keys_out(&mut s.network).push(key_out.unwrap()); - } - } - } - } - } - } - query.start(); } s.refresh_specifics(refreshes); s diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -231,7 +135,7 @@ impl SystemExt for System { idle_time = Some(query.get(&key_idle.unique_id).expect("key disappeared")); } if let Some(idle_time) = idle_time { - set_cpu_usage(p, 1. - idle_time); + p.set_cpu_usage(1. - idle_time); } } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -250,18 +154,23 @@ impl SystemExt for System { } } + /// Refresh components' temperature. + /// /// Please note that on Windows, you need to have Administrator priviledges to get this /// information. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let mut s = System::new(); + /// s.refresh_temperatures(); + /// ``` fn refresh_temperatures(&mut self) { for component in &mut self.temperatures { component.refresh(); } } - fn refresh_network(&mut self) { - network::refresh(&mut self.network, &self.query); - } - fn refresh_process(&mut self, pid: Pid) -> bool { if refresh_existing_process(self, pid, true) == false { self.process_list.remove(&pid); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -379,7 +288,7 @@ impl SystemExt for System { }); } - fn refresh_disk_list(&mut self) { + fn refresh_disks_list(&mut self) { self.disks = unsafe { get_disks() }; } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -427,13 +336,21 @@ impl SystemExt for System { &self.disks[..] } - fn get_network(&self) -> &NetworkData { - &self.network + fn get_networks(&self) -> &Networks { + &self.networks + } + + fn get_networks_mut(&mut self) -> &mut Networks { + &mut self.networks } fn get_uptime(&self) -> u64 { self.uptime } + + fn get_load_average(&self) -> LoadAvg { + get_load_average() + } } fn is_proc_running(handle: HANDLE) -> bool { diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -4,7 +4,7 @@ // Copyright (c) 2018 Guillaume Gomez // -use windows::processor::{create_processor, CounterValue, Processor, Query}; +use windows::processor::{self, CounterValue, Processor, Query}; use sys::disk::{new_disk, Disk, DiskType}; diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -44,56 +44,25 @@ impl KeyHandler { } } -/*#[allow(non_snake_case)] -#[allow(unused)] -unsafe fn browser() { - use winapi::um::pdh::{PdhBrowseCountersA, PDH_BROWSE_DLG_CONFIG_A}; - use winapi::shared::winerror::ERROR_SUCCESS; - - let mut BrowseDlgData: PDH_BROWSE_DLG_CONFIG_A = ::std::mem::zeroed(); - let mut CounterPathBuffer: [i8; 255] = ::std::mem::zeroed(); - const PERF_DETAIL_WIZARD: u32 = 400; - let text = b"Select a counter to monitor.\0"; - - BrowseDlgData.set_IncludeInstanceIndex(FALSE as u32); - BrowseDlgData.set_SingleCounterPerAdd(TRUE as u32); - BrowseDlgData.set_SingleCounterPerDialog(TRUE as u32); - BrowseDlgData.set_LocalCountersOnly(FALSE as u32); - BrowseDlgData.set_WildCardInstances(TRUE as u32); - BrowseDlgData.set_HideDetailBox(TRUE as u32); - BrowseDlgData.set_InitializePath(FALSE as u32); - BrowseDlgData.set_DisableMachineSelection(FALSE as u32); - BrowseDlgData.set_IncludeCostlyObjects(FALSE as u32); - BrowseDlgData.set_ShowObjectBrowser(FALSE as u32); - BrowseDlgData.hWndOwner = ::std::ptr::null_mut(); - BrowseDlgData.szReturnPathBuffer = CounterPathBuffer.as_mut_ptr(); - BrowseDlgData.cchReturnPathLength = 255; - BrowseDlgData.pCallBack = None; - BrowseDlgData.dwCallBackArg = 0; - BrowseDlgData.CallBackStatus = ERROR_SUCCESS as i32; - BrowseDlgData.dwDefaultDetailLevel = PERF_DETAIL_WIZARD; - BrowseDlgData.szDialogBoxCaption = text as *const _ as usize as *mut i8; - let ret = PdhBrowseCountersA(&mut BrowseDlgData as *mut _); - println!("browser: {:?}", ret); - for x in CounterPathBuffer.iter() { - print!("{:?} ", *x); - } - println!(""); - for x in 0..256 { - print!("{:?} ", *BrowseDlgData.szReturnPathBuffer.offset(x)); - } - println!(""); -}*/ - pub fn init_processors() -> Vec<Processor> { unsafe { let mut sys_info: SYSTEM_INFO = zeroed(); GetSystemInfo(&mut sys_info); + let (vendor_id, brand) = processor::get_vendor_id_and_brand(&sys_info); + let frequencies = processor::get_frequencies(sys_info.dwNumberOfProcessors as usize); let mut ret = Vec::with_capacity(sys_info.dwNumberOfProcessors as usize + 1); for nb in 0..sys_info.dwNumberOfProcessors { - ret.push(create_processor(&format!("CPU {}", nb + 1))); + ret.push(Processor::new_with_values( + &format!("CPU {}", nb + 1), + vendor_id.clone(), + brand.clone(), + frequencies[nb as usize], + )); } - ret.insert(0, create_processor("Total CPU")); + ret.insert( + 0, + Processor::new_with_values("Total CPU", vendor_id, brand, 0), + ); ret } }
4ae1791d21f84f911ca8a77e3ebc19996b7de808
Feature Request: support retrieve CPU number and load info Thanks for providing the awesome library for retrieving system information. But some information cannot be retrieved by this crate, like CPU number and CPU average load. (So I must use another crate like https://docs.rs/sys-info/0.5.8/sys_info/index.html). If this crate can provide a full feature, it's will be great. Thanks to all authors and contributors for this repo.
0.10
245
Ah indeed. I'll check if it's available as well on windows and OSX, otherwise I'll have a bit more work to do for them.
4ae1791d21f84f911ca8a77e3ebc19996b7de808
2019-06-24T15:31:47Z
diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -25,14 +25,15 @@ mod tests { #[test] fn test_refresh_process() { let mut sys = System::new(); - assert!(sys.refresh_process(utils::get_current_pid())); + assert!(sys.refresh_process(utils::get_current_pid().expect("failed to get current pid"))); } #[test] fn test_get_process() { let mut sys = System::new(); sys.refresh_processes(); - let p = sys.get_process(utils::get_current_pid()).expect("didn't find process"); + let p = sys.get_process(utils::get_current_pid().expect("failed to get current pid")) + .expect("didn't find process"); assert!(p.memory() > 0); } diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -51,7 +52,8 @@ mod tests { let mut sys = System::new(); sys.refresh_processes(); - let p = sys.get_process(utils::get_current_pid()).expect("didn't find process"); + let p = sys.get_process(utils::get_current_pid().expect("failed to get current pid")) + .expect("didn't find process"); p.foo(); // If this doesn't compile, it'll simply mean that the Process type // doesn't implement the Send trait. p.bar(); // If this doesn't compile, it'll simply mean that the Process type
[ "182" ]
GuillaumeGomez__sysinfo-183
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sysinfo" -version = "0.8.6" +version = "0.9.0" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] description = "Library to handle processes" diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -58,21 +58,29 @@ pub fn to_cpath(path: &Path) -> Vec<u8> { } /// Returns the pid for the current process. -#[cfg(all(not(target_os = "windows"), not(target_os = "unknown")))] -pub fn get_current_pid() -> Pid { - unsafe { ::libc::getpid() } -} - -/// Returns the pid for the current process. -#[cfg(target_os = "windows")] -pub fn get_current_pid() -> Pid { - use winapi::um::processthreadsapi::GetCurrentProcessId; - - unsafe { GetCurrentProcessId() as Pid } -} +/// +/// `Err` is returned in case the platform isn't supported. +pub fn get_current_pid() -> Result<Pid, &'static str> { + cfg_if! { + if #[cfg(all(not(target_os = "windows"), not(target_os = "unknown")))] { + fn inner() -> Result<Pid, &'static str> { + unsafe { Ok(::libc::getpid()) } + } + } else if #[cfg(target_os = "windows")] { + fn inner() -> Result<Pid, &'static str> { + use winapi::um::processthreadsapi::GetCurrentProcessId; -/// Returns the pid for the current process. -#[cfg(target_os = "unknown")] -pub fn get_current_pid() -> Pid { - panic!("Unavailable on this platform") + unsafe { Ok(GetCurrentProcessId() as Pid) } + } + } else if #[cfg(target_os = "unknown")] { + fn inner() -> Result<Pid, &'static str> { + Err("Unavailable on this platform") + } + } else { + fn inner() -> Result<Pid, &'static str> { + Err("Unknown platform") + } + } + } + inner() }
5744eb9221c99229f38375d776ee681032ca4f86
Make get_current_pid() return Result to prevent panic on unknown platform
0.8
183
5744eb9221c99229f38375d776ee681032ca4f86
2019-06-22T11:19:14Z
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -54,7 +54,6 @@ extern crate cfg_if; extern crate libc; extern crate rayon; -#[cfg(test)] #[macro_use] extern crate doc_comment;
[ "76" ]
GuillaumeGomez__sysinfo-178
GuillaumeGomez/sysinfo
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -55,7 +55,7 @@ script: - rustc --version - sysctl -a | grep mem - if [[ "$TRAVIS_RUST_VERSION" == "nightly" ]]; then - rustup component add clippy-preview && cargo clippy; + (rustup component add clippy-preview && cargo clippy) || touch clippy_install_failed; fi - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then cargo build --features debug; diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -78,8 +78,8 @@ script: - if [[ -z "$EXTRA" ]]; then RUST_BACKTRACE=1 cargo build; fi - - if [[ "$TRAVIS_RUST_VERSION" == "nightly" && -z "$EXTRA" ]]; then - cargo clippy $EXTRA; + - if [[ "$TRAVIS_RUST_VERSION" == "nightly" && -z "$EXTRA" && ! -f clippy_install_failed ]]; then + cargo clippy $EXTRA || echo "clippy failed"; fi - cd .. - if [[ -z "$EXTRA" ]]; then diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -16,8 +16,6 @@ build = "build.rs" cfg-if = "0.1" rayon = "^1.0" libc = "0.2" - -[dev-dependencies] doc-comment = "0.3" [target.'cfg(windows)'.dependencies] diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -33,3 +33,146 @@ cfg_if!{ } } } + +macro_rules! impl_get_set { + ($name:ident, $with:ident, $without:ident) => { + doc_comment! { +concat!("Returns the value of the \"", stringify!($name), "\" refresh kind. + +# Examples + +``` +use sysinfo::RefreshKind; + +let r = RefreshKind::new(); +assert_eq!(r.", stringify!($name), "(), false); + +let r = r.with_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), true); +```"), + pub fn $name(&self) -> bool { + self.$name + } + } + + doc_comment! { +concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `true`. + +# Examples + +``` +use sysinfo::RefreshKind; + +let r = RefreshKind::new(); +assert_eq!(r.", stringify!($name), "(), false); + +let r = r.with_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), true); +```"), + pub fn $with(mut self) -> RefreshKind { + self.$name = true; + self + } + } + + doc_comment! { +concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `false`. + +# Examples + +``` +use sysinfo::RefreshKind; + +let r = RefreshKind::everything(); +assert_eq!(r.", stringify!($name), "(), true); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), false); +```"), + pub fn $without(mut self) -> RefreshKind { + self.$name = false; + self + } + } + } +} + +/// Used to determine what you want to refresh specifically on [`System`] type. +/// +/// # Example +/// +/// ``` +/// use sysinfo::{RefreshKind, System, SystemExt}; +/// +/// // We want everything except disks. +/// let mut system = System::new_with_specifics(RefreshKind::everything().without_disk_list()); +/// +/// assert_eq!(system.get_disks().len(), 0); +/// assert!(system.get_process_list().len() > 0); +/// ``` +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RefreshKind { + system: bool, + network: bool, + processes: bool, + disk_list: bool, + disks: bool, +} + +impl RefreshKind { + /// Creates a new `RefreshKind` with every refresh set to `false`. + /// + /// # Examples + /// + /// ``` + /// use sysinfo::RefreshKind; + /// + /// let r = RefreshKind::new(); + /// + /// assert_eq!(r.system(), false); + /// assert_eq!(r.network(), false); + /// assert_eq!(r.processes(), false); + /// assert_eq!(r.disk_list(), false); + /// assert_eq!(r.disks(), false); + /// ``` + pub fn new() -> RefreshKind { + RefreshKind { + system: false, + network: false, + processes: false, + disks: false, + disk_list: false, + } + } + + /// Creates a new `RefreshKind` with every refresh set to `true`. + /// + /// # Examples + /// + /// ``` + /// use sysinfo::RefreshKind; + /// + /// let r = RefreshKind::everything(); + /// + /// assert_eq!(r.system(), true); + /// assert_eq!(r.network(), true); + /// assert_eq!(r.processes(), true); + /// assert_eq!(r.disk_list(), true); + /// assert_eq!(r.disks(), true); + /// ``` + pub fn everything() -> RefreshKind { + RefreshKind { + system: true, + network: true, + processes: true, + disks: true, + disk_list: true, + } + } + + impl_get_set!(system, with_system, without_system); + impl_get_set!(network, with_network, without_network); + impl_get_set!(processes, with_processes, without_processes); + impl_get_set!(disks, with_disks, without_disks); + impl_get_set!(disk_list, with_disk_list, without_disk_list); +} diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -11,7 +11,7 @@ use sys::Disk; use sys::disk; use sys::network; use sys::NetworkData; -use ::{DiskExt, ProcessExt, SystemExt}; +use ::{DiskExt, ProcessExt, RefreshKind, SystemExt}; use Pid; use std::cell::UnsafeCell; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -124,7 +124,7 @@ impl System { } impl SystemExt for System { - fn new() -> System { + fn new_with_specifics(refreshes: RefreshKind) -> System { let mut s = System { process_list: Process::new(0, None, 0), mem_total: 0, diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -134,11 +134,11 @@ impl SystemExt for System { processors: Vec::new(), page_size_kb: unsafe { sysconf(_SC_PAGESIZE) as u64 / 1024 }, temperatures: component::get_components(), - disks: get_all_disks(), + disks: Vec::new(), network: network::new(), uptime: get_uptime(), }; - s.refresh_all(); + s.refresh_specifics(refreshes); s } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -11,7 +11,7 @@ use sys::processor::*; use sys::process::*; use sys::disk::{self, Disk, DiskType}; -use ::{ComponentExt, DiskExt, ProcessExt, ProcessorExt, SystemExt}; +use ::{ComponentExt, DiskExt, ProcessExt, ProcessorExt, RefreshKind, SystemExt}; use std::borrow::Borrow; use std::cell::UnsafeCell; diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -538,7 +538,7 @@ fn get_arg_max() -> usize { let mut size = ::std::mem::size_of::<c_int>(); unsafe { if libc::sysctl(mib.as_mut_ptr(), 2, (&mut arg_max) as *mut i32 as *mut c_void, - &mut size, ::std::ptr::null_mut(), 0) == -1 { + &mut size, ::std::ptr::null_mut(), 0) == -1 { 4096 // We default to this value } else { arg_max as usize diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -562,7 +562,7 @@ impl System { } impl SystemExt for System { - fn new() -> System { + fn new_with_specifics(refreshes: RefreshKind) -> System { let mut s = System { process_list: HashMap::new(), mem_total: 0, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -573,12 +573,12 @@ impl SystemExt for System { page_size_kb: unsafe { sysconf(_SC_PAGESIZE) as u64 >> 10 }, // divide by 1024 temperatures: Vec::new(), connection: get_io_service_connection(), - disks: get_disks(), + disks: Vec::new(), network: network::new(), uptime: get_uptime(), port: unsafe { ffi::mach_host_self() }, }; - s.refresh_all(); + s.refresh_specifics(refreshes); s } diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -78,6 +77,7 @@ cfg_if! { pub use common::{ AsU32, Pid, + RefreshKind, }; pub use sys::{ Component, diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1,12 +1,13 @@ -// +// // Sysinfo -// +// // Copyright (c) 2017 Guillaume Gomez // use sys::{Component, Disk, DiskType, NetworkData, Process, Processor}; use Pid; use ProcessStatus; +use RefreshKind; use std::collections::HashMap; use std::ffi::OsStr; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -103,13 +104,70 @@ pub trait ProcessorExt { fn get_name(&self) -> &str; } -/// Contains all the methods of the `System` struct. -pub trait SystemExt { - /// Creates a new `System` instance. It only contains the disks' list at this stage. Use the - /// [`refresh_all`] method to update its internal information (or any of the `refresh_` method). +/// Contains all the methods of the [`System`] type. +pub trait SystemExt: Sized { + /// Creates a new [`System`] instance. It only contains the disks' list and the processes list + /// at this stage. Use the [`refresh_all`] method to update its internal information (or any of + /// the `refresh_` method). /// /// [`refresh_all`]: #method.refresh_all - fn new() -> Self; + fn new() -> Self { + let mut s = Self::new_with_specifics(RefreshKind::new()); + s.refresh_all(); + s + } + + /// Creates a new [`System`] instance and refresh the data corresponding to the + /// given [`RefreshKind`]. + /// + /// # Example + /// + /// ``` + /// use sysinfo::{RefreshKind, System, SystemExt}; + /// + /// // We want everything except disks. + /// let mut system = System::new_with_specifics(RefreshKind::everything().without_disk_list()); + /// + /// assert_eq!(system.get_disks().len(), 0); + /// assert!(system.get_process_list().len() > 0); + /// + /// // If you want the disks list afterwards, just call the corresponding + /// // "refresh_disk_list": + /// system.refresh_disk_list(); + /// assert!(system.get_disks().len() > 0); + /// ``` + fn new_with_specifics(refreshes: RefreshKind) -> Self; + + /// Refreshes according to the given [`RefreshKind`]. It calls the corresponding + /// "refresh_" methods. + /// + /// # Examples + /// + /// ``` + /// use sysinfo::{RefreshKind, System, SystemExt}; + /// + /// let mut s = System::new(); + /// + /// // Let's just update network data and processes: + /// s.refresh_specifics(RefreshKind::new().with_network().with_processes()); + /// ``` + fn refresh_specifics(&mut self, refreshes: RefreshKind) { + if refreshes.system() { + self.refresh_system(); + } + if refreshes.network() { + self.refresh_network(); + } + if refreshes.processes() { + self.refresh_processes(); + } + if refreshes.disk_list() { + self.refresh_disk_list(); + } + if refreshes.disks() { + self.refresh_disks(); + } + } /// Refresh system information (such as memory, swap, CPU usage and components' temperature). fn refresh_system(&mut self); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -15,6 +15,7 @@ use std::mem::{size_of, zeroed}; use DiskExt; use Pid; use ProcessExt; +use RefreshKind; use SystemExt; use windows::network::{self, NetworkData}; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -90,7 +91,7 @@ unsafe impl<'a> Sync for WrapSystem<'a> {} impl SystemExt for System { #[allow(non_snake_case)] - fn new() -> System { + fn new_with_specifics(refreshes: RefreshKind) -> System { let mut s = System { process_list: HashMap::new(), mem_total: 0, diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -99,7 +100,7 @@ impl SystemExt for System { swap_free: 0, processors: init_processors(), temperatures: component::get_components(), - disks: unsafe { get_disks() }, + disks: Vec::new(), query: Query::new(), network: network::new(), uptime: get_uptime(), diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -220,7 +221,7 @@ impl SystemExt for System { } query.start(); } - s.refresh_all(); + s.refresh_specifics(refreshes); s }
bf0691f89ac36af1418a522591cc012ce584d0aa
`sysinfo::System::new()` slow? A simple program creating a `sysinfo::System` takes several times longer to run (after `cargo build --release`) than existing unix utilities from the procps suite (~40ms instead of ~14ms): ``` extern crate sysinfo; use sysinfo::SystemExt; fn main() { let mut system = sysinfo::System::new(); } ``` I haven't done experiments (just observations), so the following analysis is expectation, not known truth: I wouldn't expect any significant *computation* to be going on here, and running `strace` shows this simple program making many more system calls than ps or pgrep would under most modes of operation. One optimization that I'd expect to help based on observed syscall behavior is reading from files in /proc with a larger buffer size. The below is what I see for reading from `/proc/some-program-pid/environ`: ``` read(4, "LS_COLORS=rs=0:di=01;34:ln=01;36", 32) = 32 read(4, ":mh=00:pi=40;33:so=01;35:do=01;3"..., 64) = 64 read(4, "31;01:su=37;41:sg=30;43:ca=30;41"..., 128) = 128 read(4, ":*.lzma=01;31:*.tlz=01;31:*.txz="..., 256) = 256 read(4, "1:*.rz=01;31:*.jpg=01;35:*.jpeg="..., 512) = 512 read(4, ".gl=01;35:*.dl=01;35:*.webm=01;3"..., 1024) = 1024 ... ``` This ends up being around eight or nine syscalls where a single one would do if we used a reasonable buffer size like 16384. If we want to avoid oversized Vecs, we can read into a stack buffer and copy into a Vec; this would still be *much* faster than suffering syscall overhead. In addition, it might be possible to refactor the API so that creating a `sysinfo::System` does no system calls (in much the same way `Vec::new() `does no allocation) and add options to `refresh_all` to specify which pieces of data to read. This would decrease the number of entries hit in each /proc entry and should also significantly decrease the number of system calls made. If these ideas sound reasonable I can write a patch.
0.8
178
Even more than reasonable: it sounds great! I'll gladly accept any patch improving the speed of this crate. A first step on improving this issue is done in #88. I'll try to check how to reduce computation times. [Here's the flamegraph of the benchmark.](https://rawgit.com/antoyo/d0169a8bbe8204091f261719b9a93c9d/raw/c0f434a3702757f5fab88f3c9c043d294e8d8f30/sysinfo-rs-crate-flamegraph.svg) I would like to add that the design of the API at the moment means it does a lot of unnecessary work. For example, if I just want to get into about the current process I can't do it without first populating the list with all processes. There ought to be an API which given a PID, constructs a new Process struct and returns it back to the caller. There is a function on unix API which allows to only update one specific process: https://github.com/GuillaumeGomez/sysinfo/blob/master/src/linux/system.rs#L64 I think I'll add it to the mac API as well (and the windows one when it gets finished some day...). But (judging by the doc comment) it won't work unless the full list of processes has already been populated - and it's that which takes the time. I don't care about the other 597 processes. I can rewrite it in order to make it work even if the process list is empty. It's quite easy to do. I'll try to do it this evening. Did the refactor happen, by chance? I'm seeing `sysinfo::System::new()` taking over 1 sec to run on Windows. Would be great if you could instead do as was mentioned, and specify which subsystem to refresh rather than all of them refreshing during construction. I don't remember. I'm currently in a gtk-rs pre-release status so quite busy. I'll try to take a look in the next week. Don't hesitate to ping me if you don't see anything moving after that (very likely that I'll forget, sorry about that...). @GuillaumeGomez - I wonder if it's the process list refresh that is the high cost. It might be possible to split that off from the constructor and then people can run that manually. We have a call to `refresh_all` [here](https://github.com/GuillaumeGomez/sysinfo/blob/master/src/windows/system.rs#L221) and if we look at the benchmarks available [here](https://github.com/GuillaumeGomez/sysinfo/pull/117), the `refresh_all` clearly is very slow. We could remove this call but that'd mean that `System::new` would basically return a type with almost nothing. We can discuss about it if you want? But if we make this change, it'll have to be reflected on all other systems as well. Another solution would be to provide two constructors, like `new` and `new_refreshed` or something among the lines. Well anyway, what do you think of those solutions? @jonathandturner Also I wonder, why is it such an issue that `System::new` is slow? You're supposed to call it once and that's it. You're supposed to call it multiple times... @GuillaumeGomez - would it be possible to have a constructor "refresh all but processes"? Would be worth it to try to see if it's faster. It'll be faster in any case. But then we could provide a type which would tell *what* we want to update. But again, why this need about `System::new` to be faster? It's about the choice you give users. If a user has *no choice* but to wait for the constructor before they can do anything with the type, then they'll be required to pay it at some point. It forces software design decisions up front that don't need to be forced. An alternate design would give more choice to the developers who use your crate. For example, many crates don't do heavy processing during ::new(..), but instead use a different method so that you might have more control. One example about how that might look: ```rust sysinfo::System::with_network().with_cpu(); ``` Now the user can decide when, and how much, they want to pay to get the features they want. If there's an especially expensive operation -- say, maybe the processes piece is that expensive operation -- being able to opt-out and only use it when you need it gives the developer the choice. I'm not a big fan of the interface you suggested but I agree with your point. I'll add it quickly.
5744eb9221c99229f38375d776ee681032ca4f86
2019-02-28T23:34:55Z
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -40,14 +40,22 @@ matrix: script: - rustc --version - sysctl -a | grep mem - - cargo install clippy || touch clippy_failed + - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then + rustup component add clippy-preview && cargo clippy; + fi + - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then + cargo build --features debug; + fi - RUST_BACKTRACE=1 cargo build - - if [ ! -f clippy_failed ]; then cargo clippy; fi - - if [ ! -f clippy_failed ]; then cargo bench; fi + - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then + RUST_BACKTRACE=1 cargo bench; + fi - RUST_BACKTRACE=1 cargo test - cd examples - RUST_BACKTRACE=1 cargo build - - if [ ! -f ../clippy_failed ]; then cargo clippy; fi + - if [ "$TRAVIS_RUST_VERSION" == "nightly" ]; then + cargo clippy; + fi - cd .. - make - LD_LIBRARY_PATH=./target/debug ./simple
[ "160" ]
GuillaumeGomez__sysinfo-161
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -13,9 +13,9 @@ categories = ["filesystem", "os::macos-apis", "os::unix-apis", "os::windows-apis build = "build.rs" [dependencies] -libc = "^0.2" cfg-if = "0.1" rayon = "^1.0" +libc = "0.2" [target.'cfg(windows)'.dependencies] winapi = { version = "0.3", features = ["fileapi", "handleapi", "ioapiset", "minwindef", "pdh", "psapi", "synchapi", "sysinfoapi", "tlhelp32", "winbase", "winerror", "winioctl", "winnt"] } diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ path = "src/sysinfo.rs" [features] c-interface = [] +debug = ["libc/extra_traits"] [badges] travis-ci = { repository = "GuillaumeGomez/sysinfo" } diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -50,12 +50,15 @@ extern "C" { pub fn mach_task_self() -> u32; pub fn mach_host_self() -> u32; //pub fn task_info(host_info: u32, t: u32, c: *mut c_void, x: *mut u32) -> u32; - pub fn host_statistics64(host_info: u32, x: u32, y: *mut c_void, z: *const u32) -> u32; + pub fn host_statistics64(host_info: u32, x: u32, y: *mut c_void, z: *const u32) -> kern_return_t; pub fn host_processor_info(host_info: u32, t: u32, num_cpu_u: *mut u32, - cpu_info: *mut *mut i32, num_cpu_info: *mut u32) -> u32; + cpu_info: *mut *mut i32, num_cpu_info: *mut u32) -> kern_return_t; //pub fn host_statistics(host_priv: u32, flavor: u32, host_info: *mut c_void, // host_count: *const u32) -> u32; - pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> u32; + pub fn vm_deallocate(target_task: u32, address: *mut i32, size: u32) -> kern_return_t; + + // pub fn proc_pidpath(pid: i32, buf: *mut i8, bufsize: u32) -> i32; + // pub fn proc_name(pid: i32, buf: *mut i8, bufsize: u32) -> i32; } // TODO: waiting for https://github.com/rust-lang/libc/pull/678 diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -99,6 +102,7 @@ cfg_if! { } // TODO: waiting for https://github.com/rust-lang/libc/pull/678 +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct if_data64 { pub ifi_type: c_uchar, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -129,6 +133,7 @@ pub struct if_data64 { } // TODO: waiting for https://github.com/rust-lang/libc/pull/678 +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct if_msghdr2 { pub ifm_msglen: c_ushort, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -144,16 +149,19 @@ pub struct if_msghdr2 { pub ifm_data: if_data64, } +#[cfg_attr(feature = "debug", derive(Debug))] #[repr(C)] pub struct __CFAllocator { __private: c_void, } +#[cfg_attr(feature = "debug", derive(Debug))] #[repr(C)] pub struct __CFDictionary { __private: c_void, } +#[cfg_attr(feature = "debug", derive(Debug))] #[repr(C)] pub struct __CFString { __private: c_void, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -217,6 +225,7 @@ pub struct task_basic_info_64 { pub policy: policy_t, }*/ +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct vm_statistics64 { pub free_count: natural_t, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -245,6 +254,7 @@ pub struct vm_statistics64 { pub total_uncompressed_pages_in_compressor: u64, } +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct Val_t { pub key: [i8; 5], diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -253,6 +263,7 @@ pub struct Val_t { pub bytes: [i8; 32], // SMCBytes_t } +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct KeyData_vers_t { pub major: u8, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -262,6 +273,7 @@ pub struct KeyData_vers_t { pub release: u16, } +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct KeyData_pLimitData_t { pub version: u16, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -271,6 +283,7 @@ pub struct KeyData_pLimitData_t { pub mem_plimit: u32, } +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct KeyData_keyInfo_t { pub data_size: u32, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -278,6 +291,7 @@ pub struct KeyData_keyInfo_t { pub data_attributes: u8, } +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct KeyData_t { pub key: u32, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -291,6 +305,7 @@ pub struct KeyData_t { pub bytes: [i8; 32], // SMCBytes_t } +#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))] #[repr(C)] pub struct xsw_usage { pub xsu_total: u64, diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -302,7 +317,7 @@ pub struct xsw_usage { //pub const HOST_CPU_LOAD_INFO_COUNT: usize = 4; //pub const HOST_CPU_LOAD_INFO: u32 = 3; -pub const KERN_SUCCESS: u32 = 0; +pub const KERN_SUCCESS: kern_return_t = 0; pub const HW_NCPU: u32 = 3; pub const CTL_HW: u32 = 6; diff --git a/src/mac/ffi.rs b/src/mac/ffi.rs --- a/src/mac/ffi.rs +++ b/src/mac/ffi.rs @@ -328,6 +343,8 @@ pub const KERNEL_INDEX_SMC: i32 = 2; pub const SMC_CMD_READ_KEYINFO: u8 = 9; pub const SMC_CMD_READ_BYTES: u8 = 5; +// pub const PROC_PIDPATHINFO_MAXSIZE: usize = 4096; + pub const KIO_RETURN_SUCCESS: i32 = 0; #[allow(non_upper_case_globals)] pub const kCFStringEncodingMacRoman: CFStringEncoding = 0; diff --git a/src/mac/process.rs b/src/mac/process.rs --- a/src/mac/process.rs +++ b/src/mac/process.rs @@ -277,3 +277,7 @@ pub fn has_been_updated(p: &mut Process) -> bool { p.updated = false; old } + +pub fn force_update(p: &mut Process) { + p.updated = true; +} diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -1,6 +1,6 @@ -// +// // Sysinfo -// +// // Copyright (c) 2015 Guillaume Gomez // diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -13,12 +13,14 @@ use sys::disk::{self, Disk, DiskType}; use ::{ComponentExt, DiskExt, ProcessExt, ProcessorExt, SystemExt}; +use std::borrow::Borrow; use std::cell::UnsafeCell; use std::collections::HashMap; use std::ffi::{OsStr, OsString}; +use std::ops::Deref; use std::os::unix::ffi::OsStringExt; use std::sync::Arc; -use std::path::Path; +use std::path::{Path, PathBuf}; use sys::processor; use std::{fs, mem, ptr}; diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -27,6 +29,8 @@ use libc::{self, c_void, c_int, size_t, c_char, sysconf, _SC_PAGESIZE}; use utils; use Pid; +use std::process::Command; + use rayon::prelude::*; /// Structs containing system's information. diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -43,6 +47,7 @@ pub struct System { disks: Vec<Disk>, network: NetworkData, uptime: u64, + port: ffi::mach_port_t, } impl Drop for System { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -285,6 +290,30 @@ fn get_uptime() -> u64 { unsafe { libc::difftime(csec, bsec) as u64 } } +fn parse_command_line<T: Deref<Target = str> + Borrow<str>>(cmd: &[T]) -> Vec<String> { + let mut x = 0; + let mut command = Vec::with_capacity(cmd.len()); + while x < cmd.len() { + let mut y = x; + if cmd[y].starts_with('\'') || cmd[y].starts_with('"') { + let c = if cmd[y].starts_with('\'') { + '\'' + } else { + '"' + }; + while y < cmd.len() && !cmd[y].ends_with(c) { + y += 1; + } + command.push(cmd[x..y].join(" ")); + x = y; + } else { + command.push(cmd[x].to_owned()); + } + x += 1; + } + command +} + struct Wrap<'a>(UnsafeCell<&'a mut HashMap<Pid, Process>>); unsafe impl<'a> Send for Wrap<'a> {} diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -308,6 +337,10 @@ fn update_process(wrap: &Wrap, pid: Pid, (0, 0, None) }; if let Some(ref mut p) = (*wrap.0.get()).get_mut(&pid) { + if p.memory == 0 { // We don't have access to this process' information. + force_update(p); + return Ok(None); + } p.status = thread_status; let mut task_info = ::std::mem::zeroed::<libc::proc_taskinfo>(); if ffi::proc_pidinfo(pid, diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -332,7 +365,39 @@ fn update_process(wrap: &Wrap, pid: Pid, 0, &mut task_info as *mut libc::proc_taskallinfo as *mut c_void, taskallinfo_size as i32) != taskallinfo_size as i32 { - return Err(()); + match Command::new("/bin/ps") // not very nice, might be worth running a which first. + .arg("wwwe") + .arg("-o") + .arg("ppid=,command=") + .arg(pid.to_string().as_str()) + .output() { + Ok(o) => { + let o = String::from_utf8(o.stdout).unwrap_or_else(|_| String::new()); + let mut o = o.split(' ').filter(|c| !c.is_empty()).collect::<Vec<_>>(); + if o.len() < 2 { + return Err(()); + } + let mut command = parse_command_line(&o[1..]); + if let Some(ref mut x) = command.last_mut() { + **x = x.replace("\n", ""); + } + let p = match i32::from_str_radix(&o[0].replace("\n", ""), 10) { + Ok(x) => x, + _ => return Err(()), + }; + let mut p = Process::new(pid, if p == 0 { None } else { Some(p) }, 0); + p.exe = PathBuf::from(&command[0]); + p.name = match p.exe.file_name() { + Some(x) => x.to_str().unwrap_or_else(|| "").to_owned(), + None => String::new(), + }; + p.cmd = command; + return Ok(Some(p)); + } + _ => { + return Err(()); + } + } } let parent = match task_info.pbsd.pbi_ppid as Pid { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -421,7 +486,7 @@ fn update_process(wrap: &Wrap, pid: Pid, } cp = cp.offset(1); } - p.cmd = cmd; + p.cmd = parse_command_line(&cmd); start = cp; while cp < ptr.add(size) { if *cp == 0 { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -443,13 +508,44 @@ fn update_process(wrap: &Wrap, pid: Pid, } } } else { - // we don't have enough priviledges to get access to these info - return Err(()); + return Err(()); // not enough rights I assume? } Ok(Some(p)) } } +fn get_proc_list() -> Option<Vec<Pid>> { + let count = unsafe { ffi::proc_listallpids(::std::ptr::null_mut(), 0) }; + if count < 1 { + return None; + } + let mut pids: Vec<Pid> = Vec::with_capacity(count as usize); + unsafe { pids.set_len(count as usize); } + let count = count * ::std::mem::size_of::<Pid>() as i32; + let x = unsafe { ffi::proc_listallpids(pids.as_mut_ptr() as *mut c_void, count) }; + + if x < 1 || x as usize >= pids.len() { + None + } else { + unsafe { pids.set_len(x as usize); } + Some(pids) + } +} + +fn get_arg_max() -> usize { + let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0]; + let mut arg_max = 0i32; + let mut size = ::std::mem::size_of::<c_int>(); + unsafe { + if libc::sysctl(mib.as_mut_ptr(), 2, (&mut arg_max) as *mut i32 as *mut c_void, + &mut size, ::std::ptr::null_mut(), 0) == -1 { + 4096 // We default to this value + } else { + arg_max as usize + } + } +} + impl System { fn clear_procs(&mut self) { let mut to_delete = Vec::new(); diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -480,6 +576,7 @@ impl SystemExt for System { disks: get_disks(), network: network::new(), uptime: get_uptime(), + port: unsafe { ffi::mach_host_self() }, }; s.refresh_all(); s diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -514,11 +611,9 @@ impl SystemExt for System { } let count: u32 = ffi::HOST_VM_INFO64_COUNT; let mut stat = ::std::mem::zeroed::<ffi::vm_statistics64>(); - if ffi::host_statistics64(ffi::mach_host_self(), ffi::HOST_VM_INFO64, + if ffi::host_statistics64(self.port, ffi::HOST_VM_INFO64, &mut stat as *mut ffi::vm_statistics64 as *mut c_void, - &count as *const u32) == ffi::KERN_SUCCESS { - //self.mem_free = u64::from(stat.free_count + stat.inactive_count - // + stat.speculative_count) * self.page_size_kb; + &count) == ffi::KERN_SUCCESS { // From the apple documentation: // // /* diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -527,7 +622,12 @@ impl SystemExt for System { // * used to hold data that was read speculatively from disk but // * haven't actually been used by anyone so far. // */ - self.mem_free = u64::from(stat.free_count) * self.page_size_kb; + // self.mem_free = u64::from(stat.free_count) * self.page_size_kb; + self.mem_free = self.mem_total - (u64::from(stat.active_count) + + u64::from(stat.inactive_count) + u64::from(stat.wire_count) + + u64::from(stat.speculative_count) + - u64::from(stat.purgeable_count)) + * self.page_size_kb; } if let Some(con) = self.connection { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -604,7 +704,7 @@ impl SystemExt for System { self.processors.push( processor::create_proc("0".to_owned(), Arc::new(ProcessorData::new(::std::ptr::null_mut(), 0)))); - if ffi::host_processor_info(ffi::mach_host_self(), ffi::PROCESSOR_CPU_LOAD_INFO, + if ffi::host_processor_info(self.port, ffi::PROCESSOR_CPU_LOAD_INFO, &mut num_cpu_u as *mut u32, &mut cpu_info as *mut *mut i32, &mut num_cpu_info as *mut u32) == ffi::KERN_SUCCESS { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -619,7 +719,7 @@ impl SystemExt for System { self.processors.push(p); } } - } else if ffi::host_processor_info(ffi::mach_host_self(), ffi::PROCESSOR_CPU_LOAD_INFO, + } else if ffi::host_processor_info(self.port, ffi::PROCESSOR_CPU_LOAD_INFO, &mut num_cpu_u as *mut u32, &mut cpu_info as *mut *mut i32, &mut num_cpu_info as *mut u32) == ffi::KERN_SUCCESS { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -665,45 +765,30 @@ impl SystemExt for System { if count < 1 { return } - let mut pids: Vec<Pid> = Vec::with_capacity(count as usize); - unsafe { pids.set_len(count as usize); } - let count = count * ::std::mem::size_of::<Pid>() as i32; - let x = unsafe { ffi::proc_listallpids(pids.as_mut_ptr() as *mut c_void, count) }; - - if x < 1 || x as usize > pids.len() { - return - } else if pids.len() > x as usize { - unsafe { pids.set_len(x as usize); } - } - - let taskallinfo_size = ::std::mem::size_of::<libc::proc_taskallinfo>() as i32; - let taskinfo_size = ::std::mem::size_of::<libc::proc_taskinfo>() as i32; - let threadinfo_size = ::std::mem::size_of::<libc::proc_threadinfo>() as i32; - - let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0]; - let mut arg_max = 0i32; - let mut size = ::std::mem::size_of::<c_int>(); - unsafe { - while libc::sysctl(mib.as_mut_ptr(), 2, (&mut arg_max) as *mut i32 as *mut c_void, - &mut size, ::std::ptr::null_mut(), 0) == -1 {} + if let Some(pids) = get_proc_list() { + let taskallinfo_size = ::std::mem::size_of::<libc::proc_taskallinfo>() as i32; + let taskinfo_size = ::std::mem::size_of::<libc::proc_taskinfo>() as i32; + let threadinfo_size = ::std::mem::size_of::<libc::proc_threadinfo>() as i32; + let arg_max = get_arg_max(); + + let entries: Vec<Process> = { + let wrap = &Wrap(UnsafeCell::new(&mut self.process_list)); + pids.par_iter() + .flat_map(|pid| { + let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0]; + match update_process(wrap, *pid, taskallinfo_size, taskinfo_size, + threadinfo_size, &mut mib, arg_max as size_t) { + Ok(x) => x, + Err(_) => None, + } + }) + .collect() + }; + entries.into_iter().for_each(|entry| { + self.process_list.insert(entry.pid(), entry); + }); + self.clear_procs(); } - let entries: Vec<Process> = { - let wrap = &Wrap(UnsafeCell::new(&mut self.process_list)); - pids.par_iter() - .flat_map(|pid| { - let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0]; - match update_process(wrap, *pid, taskallinfo_size, taskinfo_size, - threadinfo_size, &mut mib, arg_max as size_t) { - Ok(x) => x, - Err(_) => None, - } - }) - .collect() - }; - entries.into_iter().for_each(|entry| { - self.process_list.insert(entry.pid(), entry); - }); - self.clear_procs(); } fn refresh_process(&mut self, pid: Pid) -> bool { diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -712,12 +797,7 @@ impl SystemExt for System { let threadinfo_size = ::std::mem::size_of::<libc::proc_threadinfo>() as i32; let mut mib: [c_int; 3] = [libc::CTL_KERN, libc::KERN_ARGMAX, 0]; - let mut arg_max = 0i32; - let mut size = ::std::mem::size_of::<c_int>(); - unsafe { - while libc::sysctl(mib.as_mut_ptr(), 2, (&mut arg_max) as *mut i32 as *mut c_void, - &mut size, ::std::ptr::null_mut(), 0) == -1 {} - } + let arg_max = get_arg_max(); match { let wrap = Wrap(UnsafeCell::new(&mut self.process_list)); update_process(&wrap, pid, taskallinfo_size, taskinfo_size,
8cff91770cafe71f388cf8a798fc871509520c1e
Memory usage seems inaccurate I'm writing a improved version of top, and when listing the memory usage of individual processes, I noticed that it doesn't line up with with what's reported by top or activity monitor. Is there any reason that this wouldn't be the case? I'm running MacOS Mojave. ![memory usage](https://i.imgur.com/N4lmSRi.jpg) Also, it looks like the `get_process_list()` function only return processes started by me and not any started by other users, such as root. Is there a fix for this?
0.8
161
> I'm writing a improved version of top, and when listing the memory usage of individual processes, I noticed that it doesn't line up with with what's reported by top or activity monitor. Is there any reason that this wouldn't be the case? I'm running MacOS Mojave. The `Activity Monitor` of Mac doesn't get the same values as `htop`. So it's complicated to guess who's right and who's wrong. However, my computation for the total free memory seems a bit off, I'll try to fix it. > Also, it looks like the `get_process_list()` function only return processes started by me and not any started by other users, such as root. Is there a fix for this? We can actually, I just ignored when I didn't get enough information but this is bad. It'll allow me to test some functions. Ok, thanks for the quick reply On Thu, Feb 28, 2019, 1:13 PM Guillaume Gomez <notifications@github.com> wrote: > I'm writing a improved version of top, and when listing the memory usage > of individual processes, I noticed that it doesn't line up with with what's > reported by top or activity monitor. Is there any reason that this wouldn't > be the case? I'm running MacOS Mojave. > > The Activity Monitor of Mac doesn't get the same values as htop. So it's > complicated to guess who's right and who's wrong. However, my computation > for the total free memory seems a bit off, I'll try to fix it. > > Also, it looks like the get_process_list() function only return processes > started by me and not any started by other users, such as root. Is there a > fix for this? > > We can actually, I just ignored when I didn't get enough information but > this is bad. It'll allow me to test some functions. > > — > You are receiving this because you authored the thread. > Reply to this email directly, view it on GitHub > <https://github.com/GuillaumeGomez/sysinfo/issues/160#issuecomment-468378070>, > or mute the thread > <https://github.com/notifications/unsubscribe-auth/AGIt0MGXftglbhJkLXFiRTR5Sv0NgGlJks5vSBw-gaJpZM4bXVdj> > . >
5744eb9221c99229f38375d776ee681032ca4f86
2018-12-12T23:04:24Z
diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -9,7 +9,7 @@ #[cfg(test)] mod tests { - use ::{System, SystemExt}; + use ::{ProcessExt, System, SystemExt}; use ::utils; #[test] diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -27,4 +27,12 @@ mod tests { let mut sys = System::new(); assert!(sys.refresh_process(utils::get_current_pid())); } + + #[test] + fn test_get_process() { + let mut sys = System::new(); + sys.refresh_processes(); + let p = sys.get_process(utils::get_current_pid()).expect("didn't find process"); + assert!(p.memory() > 0); + } }
[ "148" ]
GuillaumeGomez__sysinfo-150
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sysinfo" -version = "0.6.2" +version = "0.7.0" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] description = "Library to handle processes" diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -6,6 +6,7 @@ use std::fmt::{self, Formatter, Debug}; use std::mem::{size_of, zeroed}; +use std::ops::Deref; use std::path::{Path, PathBuf}; use std::str; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -71,6 +72,20 @@ fn get_process_handler(pid: Pid) -> Option<HANDLE> { } } +#[derive(Clone)] +struct HandleWrapper(HANDLE); + +impl Deref for HandleWrapper { + type Target = HANDLE; + + fn deref(&self) -> &HANDLE { + &self.0 + } +} + +unsafe impl Send for HandleWrapper {} +unsafe impl Sync for HandleWrapper {} + /// Struct containing a process' information. #[derive(Clone)] pub struct Process { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -84,7 +99,7 @@ pub struct Process { memory: u64, parent: Option<Pid>, status: ProcessStatus, - handle: HANDLE, + handle: HandleWrapper, old_cpu: u64, old_sys_cpu: u64, old_user_cpu: u64, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -143,7 +158,7 @@ impl ProcessExt for Process { let mut root = exe.clone(); root.pop(); Process { - handle: process_handler, + handle: HandleWrapper(process_handler), name: name, pid: pid, parent: parent, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -163,7 +178,7 @@ impl ProcessExt for Process { } } else { Process { - handle: ::std::ptr::null_mut(), + handle: HandleWrapper(::std::ptr::null_mut()), name: String::new(), pid: pid, parent: parent, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -184,8 +199,11 @@ impl ProcessExt for Process { } fn kill(&self, signal: ::Signal) -> bool { - let x = unsafe { TerminateProcess(self.handle, signal as c_uint) }; - x != 0 + if self.handle.is_null() { + false + } else { + unsafe { TerminateProcess(*self.handle, signal as c_uint) != 0 } + } } fn name(&self) -> &str { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -243,7 +261,7 @@ impl Drop for Process { if self.handle.is_null() { return } - CloseHandle(self.handle); + CloseHandle(*self.handle); } } } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -421,7 +439,7 @@ pub fn compute_cpu_usage(p: &mut Process, nb_processors: u64) { &mut ftime as *mut FILETIME as *mut c_void, size_of::<FILETIME>()); - GetProcessTimes(p.handle, + GetProcessTimes(*p.handle, &mut ftime as *mut FILETIME, &mut ftime as *mut FILETIME, &mut fsys as *mut FILETIME, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -443,7 +461,7 @@ pub fn compute_cpu_usage(p: &mut Process, nb_processors: u64) { } pub fn get_handle(p: &Process) -> HANDLE { - p.handle + *p.handle } pub fn update_proc_info(p: &mut Process) { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -453,7 +471,7 @@ pub fn update_proc_info(p: &mut Process) { pub fn update_memory(p: &mut Process) { unsafe { let mut pmc: PROCESS_MEMORY_COUNTERS_EX = zeroed(); - if GetProcessMemoryInfo(p.handle, + if GetProcessMemoryInfo(*p.handle, &mut pmc as *mut PROCESS_MEMORY_COUNTERS_EX as *mut c_void as *mut PROCESS_MEMORY_COUNTERS, size_of::<PROCESS_MEMORY_COUNTERS_EX>() as DWORD) != 0 { p.memory = (pmc.PrivateUsage as u64) >> 10u64; // / 1024; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -8,6 +8,7 @@ use sys::component::{self, Component}; use sys::disk::Disk; use sys::processor::*; +use std::cell::UnsafeCell; use std::collections::HashMap; use std::mem::{size_of, zeroed}; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -76,6 +77,15 @@ struct Wrap(Process); unsafe impl Send for Wrap {} +struct WrapSystem<'a>(UnsafeCell<&'a mut System>); + impl<'a> WrapSystem<'a> { + fn get(&self) -> &'a mut System { + unsafe { *(self.0.get()) } + } +} + unsafe impl<'a> Send for WrapSystem<'a> {} +unsafe impl<'a> Sync for WrapSystem<'a> {} + impl SystemExt for System { #[allow(non_snake_case)] fn new() -> System { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -254,24 +264,27 @@ impl SystemExt for System { let mut process_ids: Vec<DWORD> = Vec::with_capacity(PROCESS_LEN); let mut cb_needed = 0; + unsafe { process_ids.set_len(PROCESS_LEN); } + let size = ::std::mem::size_of::<DWORD>() * process_ids.len(); unsafe { - process_ids.set_len(PROCESS_LEN); - let size = ::std::mem::size_of::<DWORD>() * process_ids.len(); if K32EnumProcesses(process_ids.as_mut_ptr(), size as DWORD, &mut cb_needed) == 0 { return } - let nb_processes = cb_needed / ::std::mem::size_of::<DWORD>() as DWORD; - process_ids.set_len(nb_processes as usize); - let this = self as *mut System as usize; + } + let nb_processes = cb_needed / ::std::mem::size_of::<DWORD>() as DWORD; + unsafe { process_ids.set_len(nb_processes as usize); } + + { + let this = WrapSystem(UnsafeCell::new(self)); process_ids.par_iter() .filter_map(|pid| { - let this = &mut *(this as *mut System); let pid = *pid as usize; - if !refresh_existing_process(this, pid, false) { - let mut p = Process::new(pid, get_parent_process_id(pid), 0); + if !refresh_existing_process(this.get(), pid, false) { + let ppid = unsafe { get_parent_process_id(pid) }; + let mut p = Process::new(pid, ppid, 0); update_proc_info(&mut p); Some(Wrap(p)) } else { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -279,11 +292,10 @@ impl SystemExt for System { } }) .collect::<Vec<_>>() - .into_iter() - .for_each(|p| { - self.process_list.insert(p.0.pid(), p.0); - }); - } + }.into_iter() + .for_each(|p| { + self.process_list.insert(p.0.pid(), p.0); + }); self.clear_procs(); }
95d0ba8a80c99f2c6ca67dd3801192dd15e4d51d
`Process` is does not implement `Send + Sync` on windows Hey, on Linux the `Process` struct implements `Send + Sync`, but not on Windows. We have the following [bug report](https://github.com/paritytech/substrate/issues/1253). After looking into the `Process` code for Windows, I think that `HANDLE` is the problem. You probably need to create a pointer wrapper that makes `HANDLE` `SEND + SYNC`.
0.6
150
It's part of the problem, yes. However, `Process` cannot be used safely between threads. I'll make another check for linux but I think it shouldn't be `Send+Sync` either. I need it internally so I can perform faster computations but that's it. To fix your issue, you'll have to wrap it inside a `Mutex` I guess. I'll certainly modify the internal code so that `Process` doesn't implement `Send+Sync` anymore. Sorry for the confusion! Ahh okay. Good to know :) Thanks for the fast answer! Yeah, then we will adapt our code accordingly. I opened an issue about it if you want to follow the evolution: #149. @bkchr: I think you were right: implementing `Send` and `Sync` traits seem like a better solution so let's go for it. I'll send the PR in the next hours.
95d0ba8a80c99f2c6ca67dd3801192dd15e4d51d
2017-02-17T10:54:44Z
diff --git a/.travis.yml b/.travis.yml --- a/.travis.yml +++ b/.travis.yml @@ -16,6 +16,7 @@ script: - cargo install clippy || touch clippy_failed - RUST_BACKTRACE=1 cargo build - if [ ! -f clippy_failed ]; then cargo clippy; fi + - RUST_BACKTRACE=1 cargo test - cd examples - RUST_BACKTRACE=1 cargo build - if [ ! -f ../clippy_failed ]; then cargo clippy; fi diff --git /dev/null b/tests/disk_list.rs new file mode 100644 --- /dev/null +++ b/tests/disk_list.rs @@ -0,0 +1,16 @@ +// +// Sysinfo +// +// Copyright (c) 2017 Guillaume Gomez +// + +extern crate sysinfo; + +#[test] +fn test_disks() { + use sysinfo::SystemExt; + + let s = sysinfo::System::new(); + println!("total memory: {}", s.get_total_memory()); + println!("total cpu cores: {}", s.get_processor_list().len()); +}
[ "50" ]
GuillaumeGomez__sysinfo-51
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sysinfo" -version = "0.2.7" +version = "0.2.8" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] description = "Library to handle processes" diff --git a/src/linux/disk.rs b/src/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/linux/disk.rs @@ -34,8 +34,10 @@ impl From<isize> for DiskType { } pub fn new_disk(name: &str, mount_point: &str, file_system: &str) -> Disk { + #[allow(or_fun_call)] let type_ = isize::from_str(get_all_data(&format!("/sys/block/{}/queue/rotational", - name)).lines() + name)).unwrap_or(String::new()) + .lines() .next() .unwrap_or("-1")).unwrap_or(-1); let mut mount_point = mount_point.as_bytes().to_vec(); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -11,7 +11,7 @@ use sys::Disk; use sys::disk; use ::{DiskExt, ProcessExt, SystemExt}; use std::fs::{File, read_link}; -use std::io::Read; +use std::io::{self, Read}; use std::str::FromStr; use std::path::{Path, PathBuf}; use std::collections::HashMap; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -72,7 +72,7 @@ impl SystemExt for System { } fn refresh_system(&mut self) { - let data = get_all_data("/proc/meminfo"); + let data = get_all_data("/proc/meminfo").unwrap(); let lines: Vec<&str> = data.split('\n').collect(); for component in &mut self.temperatures { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -103,7 +103,7 @@ impl SystemExt for System { _ => continue, } } - let data = get_all_data("/proc/stat"); + let data = get_all_data("/proc/stat").unwrap(); let lines: Vec<&str> = data.split('\n').collect(); let mut i = 0; let first = self.processors.is_empty(); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -234,12 +234,12 @@ impl Default for System { } } -pub fn get_all_data(file_path: &str) -> String { - let mut file = File::open(file_path).unwrap(); +pub fn get_all_data(file_path: &str) -> io::Result<String> { + let mut file = File::open(file_path)?; let mut data = String::new(); file.read_to_string(&mut data).unwrap(); - data + Ok(data) } fn update_time_and_memory(entry: &mut Process, parts: &[&str], page_size_kb: u64) { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -263,7 +263,7 @@ fn _get_process_data(path: &Path, proc_list: &mut HashMap<pid_t, Process>, page_ let mut tmp = PathBuf::from(path); tmp.push("stat"); - let data = get_all_data(tmp.to_str().unwrap()); + let data = get_all_data(tmp.to_str().unwrap()).unwrap(); // The stat file is "interesting" to parse, because spaces cannot // be used as delimiters. The second field stores the command name diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -300,7 +300,7 @@ fn _get_process_data(path: &Path, proc_list: &mut HashMap<pid_t, Process>, page_ tmp = PathBuf::from(path); tmp.push("status"); - let status_data = get_all_data(tmp.to_str().unwrap()); + let status_data = get_all_data(tmp.to_str().unwrap()).unwrap(); // We're only interested in the lines starting with Uid: and Gid: // here. From these lines, we're looking at the second entry to get diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -370,7 +370,8 @@ fn copy_from_file(entry: &Path) -> Vec<String> { } fn get_all_disks() -> Vec<Disk> { - let content = get_all_data("/proc/mounts"); + #[allow(or_fun_call)] + let content = get_all_data("/proc/mounts").unwrap_or(String::new()); let disks: Vec<_> = content.lines() .filter(|line| line.trim_left() .starts_with("/dev/sda")) diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -12,7 +12,7 @@ //! # Examples //! //! ``` -//! extern crate sysinfo; +//! use sysinfo::SystemExt; //! //! let mut system = sysinfo::System::new(); //!
37829411d4186264c24dfa96f15522655d5060bb
panic when get linux disk info The test code is very simple: ``` extern crate sysinfo; use sysinfo::{System, SystemExt}; fn main() { let s = System::new(); println!("total memory: {}", s.get_total_memory()); println!("total cpu cores: {}", s.get_processor_list().len()); } ``` the panic backtrace: ``` RUST_BACKTRACE=1 ./target/debug/sysinfo thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Error { repr: Os { code: 2, message: "No such file or directory" } }', /checkout/src/libcore/result.rs:860 stack backtrace: 1: 0x55efabcfdd99 - std::sys::imp::backtrace::tracing::imp::write::hbb14611794d3841b at /checkout/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs:42 2: 0x55efabd0096e - std::panicking::default_hook::{{closure}}::h6ed906c7818ac88c at /checkout/src/libstd/panicking.rs:351 3: 0x55efabd00574 - std::panicking::default_hook::h23eeafbf7c1c05c3 at /checkout/src/libstd/panicking.rs:367 4: 0x55efabd00d0b - std::panicking::rust_panic_with_hook::hd0067971b6d1240e at /checkout/src/libstd/panicking.rs:545 5: 0x55efabd00b94 - std::panicking::begin_panic::h1fd1f10a3de8f902 at /checkout/src/libstd/panicking.rs:507 6: 0x55efabd00b09 - std::panicking::begin_panic_fmt::haa043917b5d6f21b at /checkout/src/libstd/panicking.rs:491 7: 0x55efabd00a97 - rust_begin_unwind at /checkout/src/libstd/panicking.rs:467 8: 0x55efabd283ed - core::panicking::panic_fmt::he9c7f335d160b59d at /checkout/src/libcore/panicking.rs:69 9: 0x55efabcd86a2 - core::result::unwrap_failed::h4d928bd97e49e0a6 at /checkout/src/libcore/macros.rs:29 10: 0x55efabccd608 - <core::result::Result<T, E>>::unwrap::h5d22eb351173816f at /checkout/src/libcore/result.rs:737 11: 0x55efabcf3113 - sysinfo::linux::system::get_all_data::h57c5a3a2a1e56705 at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/system.rs:238 12: 0x55efabcef98b - sysinfo::linux::disk::new_disk::hd348afa584fe4d3b at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/disk.rs:37 13: 0x55efabcf5940 - sysinfo::linux::system::get_all_disks::h57ad867ae2125280 at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/system.rs:392 14: 0x55efabcf16c6 - <sysinfo::linux::system::System as sysinfo::traits::SystemExt>::new::hfa809b791153da6b at /home/pingcap/.cargo/registry/src/github.com-1ecc6299db9ec823/sysinfo-0.2.7/src/linux/system.rs:68 15: 0x55efabcbb67a - sysinfo::main::h4522594c2b4e189e at /data/office-cluster-deploy/sysinfo/src/main.rs:8 16: 0x55efabd09b0a - __rust_maybe_catch_panic at /checkout/src/libpanic_unwind/lib.rs:98 17: 0x55efabd014b6 - std::rt::lang_start::hb7fc7ec87b663023 at /checkout/src/libstd/panicking.rs:429 at /checkout/src/libstd/panic.rs:361 at /checkout/src/libstd/rt.rs:57 18: 0x55efabcbb8a2 - main 19: 0x7f2b96308f44 - __libc_start_main 20: 0x55efabcb9089 - <unknown> 21: 0x0 - <unknown> ```
0.2
51
My os is ubuntu12.04 ``` $ cat /proc/mounts | grep "/dev/sda" /dev/sda6 / ext4 rw,relatime,errors=remount-ro,data=ordered 0 0 /dev/sda1 /boot ext4 rw,relatime,data=ordered 0 0 /dev/sda6 /var/lib/docker/devicemapper ext4 rw,relatime,errors=remount-ro,data=ordered 0 0 ```
37829411d4186264c24dfa96f15522655d5060bb
2022-02-02T20:15:17Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -254,7 +254,7 @@ fn test_process_times() { std::process::Command::new("waitfor") .arg("/t") .arg("3") - .arg("CwdSignal") + .arg("ProcessTimes") .stdout(std::process::Stdio::null()) .spawn() .unwrap() diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -291,3 +291,85 @@ fn test_process_times() { panic!("Process not found!"); } } + +// Checks that `refresh_processes` is removing dead processes. +#[test] +fn test_refresh_processes() { + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + let mut p = if cfg!(target_os = "windows") { + std::process::Command::new("waitfor") + .arg("/t") + .arg("300") + .arg("RefreshProcesses") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + } else { + std::process::Command::new("sleep") + .arg("300") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + }; + + let pid = Pid::from_u32(p.id() as u32); + std::thread::sleep(std::time::Duration::from_secs(1)); + + // Checks that the process is listed as it should. + let mut s = sysinfo::System::new(); + s.refresh_processes(); + assert!(s.process(pid).is_some()); + + p.kill().expect("Unable to kill process."); + // We need this, otherwise the process will still be around as a zombie on linux. + let _ = p.wait(); + // Let's give some time to the system to clean up... + std::thread::sleep(std::time::Duration::from_secs(1)); + + s.refresh_processes(); + // Checks that the process isn't listed anymore. + assert!(s.process(pid).is_none()); +} + +// Checks that `refresh_process` is NOT removing dead processes. +#[test] +fn test_refresh_process() { + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + let mut p = if cfg!(target_os = "windows") { + std::process::Command::new("waitfor") + .arg("/t") + .arg("300") + .arg("RefreshProcess") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + } else { + std::process::Command::new("sleep") + .arg("300") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + }; + + let pid = Pid::from_u32(p.id() as u32); + std::thread::sleep(std::time::Duration::from_secs(1)); + + // Checks that the process is listed as it should. + let mut s = sysinfo::System::new(); + s.refresh_process(pid); + assert!(s.process(pid).is_some()); + + p.kill().expect("Unable to kill process."); + // We need this, otherwise the process will still be around as a zombie on linux. + let _ = p.wait(); + // Let's give some time to the system to clean up... + std::thread::sleep(std::time::Duration::from_secs(1)); + + s.refresh_process(pid); + // Checks that the process is still listed. + assert!(s.process(pid).is_some()); +}
[ "686" ]
GuillaumeGomez__sysinfo-687
GuillaumeGomez/sysinfo
diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -46,6 +46,9 @@ macro_rules! pid_decl { Self(v) } } + #[allow(clippy::from_over_into)] + // This Into implementation is required otherwise it seems you can't do `pid.into()` + // for some reasons... impl Into<$typ> for Pid { fn into(self) -> $typ { self.0 diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -24,6 +24,7 @@ macro_rules! old_and_new { }}; } +#[allow(clippy::ptr_arg)] fn read<P: AsRef<Path>>(parent: P, path: &str, data: &mut Vec<u8>) -> u64 { if let Ok(mut f) = File::open(parent.as_ref().join(path)) { if let Ok(size) = f.read(data) { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -214,8 +214,8 @@ impl System { to_delete.push(*pid); } else if compute_cpu { compute_cpu_usage(proc_, total_time, max_value); + proc_.updated = false; } - proc_.updated = false; } for pid in to_delete { self.process_list.tasks.remove(&pid); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -400,16 +400,15 @@ impl SystemExt for System { fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { let uptime = self.uptime(); - if refresh_procs( + refresh_procs( &mut self.process_list, Path::new("/proc"), Pid(0), uptime, &self.info, refresh_kind, - ) { - self.clear_procs(refresh_kind); - } + ); + self.clear_procs(refresh_kind); self.need_processors_update = true; } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -444,6 +443,7 @@ impl SystemExt for System { let max_cpu_usage = self.get_max_process_cpu_usage(); if let Some(p) = self.process_list.tasks.get_mut(&pid) { compute_cpu_usage(p, total_time / self.processors.len() as f32, max_cpu_usage); + p.updated = false; } } else if let Some(p) = self.process_list.tasks.get_mut(&pid) { p.updated = false; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -633,8 +633,8 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// /// It does the same as `system.refresh_processes_specifics(ProcessRefreshKind::everything())`. /// - /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can this behaviour by - /// using [`set_open_files_limit`][crate::set_open_files_limit]. + /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour + /// by using [`set_open_files_limit`][crate::set_open_files_limit]. /// /// ```no_run /// use sysinfo::{System, SystemExt}; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -648,8 +648,8 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// Gets all processes and updates the specified information. /// - /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can this behaviour by - /// using [`set_open_files_limit`][crate::set_open_files_limit]. + /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour + /// by using [`set_open_files_limit`][crate::set_open_files_limit]. /// /// ```no_run /// use sysinfo::{ProcessRefreshKind, System, SystemExt}; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -660,7 +660,8 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind); /// Refreshes *only* the process corresponding to `pid`. Returns `false` if the process doesn't - /// exist. If it isn't listed yet, it'll be added. + /// exist (it will **NOT** be removed from the processes if it doesn't exist anymore). If it + /// isn't listed yet, it'll be added. /// /// It is the same as calling /// `sys.refresh_process_specifics(pid, ProcessRefreshKind::everything())`. diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -676,7 +677,8 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { } /// Refreshes *only* the process corresponding to `pid`. Returns `false` if the process doesn't - /// exist. If it isn't listed yet, it'll be added. + /// exist (it will **NOT** be removed from the processes if it doesn't exist anymore). If it + /// isn't listed yet, it'll be added. /// /// ```no_run /// use sysinfo::{Pid, ProcessRefreshKind, System, SystemExt}; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -186,15 +186,12 @@ impl SystemExt for System { #[allow(clippy::map_entry)] fn refresh_process_specifics(&mut self, pid: Pid, refresh_kind: ProcessRefreshKind) -> bool { if self.process_list.contains_key(&pid) { - if !refresh_existing_process(self, pid, refresh_kind) { - self.process_list.remove(&pid); - return false; - } - return true; + return refresh_existing_process(self, pid, refresh_kind); } let now = get_now(); if let Some(mut p) = Process::new_from_pid(pid, now) { p.update(refresh_kind, self.processors.len() as u64, now); + p.updated = false; self.process_list.insert(pid, p); true } else { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -289,14 +286,14 @@ impl SystemExt for System { Some(p) }) .collect::<Vec<_>>(); + for p in processes.into_iter() { + self.process_list.insert(p.pid(), p); + } self.process_list.retain(|_, v| { let x = v.updated; v.updated = false; x }); - for p in processes.into_iter() { - self.process_list.insert(p.pid(), p); - } break; } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -473,6 +470,7 @@ fn refresh_existing_process(s: &mut System, pid: Pid, refresh_kind: ProcessRefre } update_memory(entry); entry.update(refresh_kind, s.processors.len() as u64, get_now()); + entry.updated = false; true } else { false
8a13566c75b44d51b7da3fc58901e863e72a9e26
[Linux] Issue with process removal logic after calling `refresh_process()` I'm observing an issue with the following scenario: 1) Call `refresh_processes()` 2) Call `refresh_process()` on a running process P 3) Kill the process P 4) Call `refresh_processes()` 5) Call `processes()` to get the list of running processes The result of step 5 is incorrect because it still contains the killed process P but only if step 2 is executing, otherwise the result is correct. I'm not sure if this intended behavior, but to me this seems like a logic issue in this code : https://github.com/GuillaumeGomez/sysinfo/blob/a0b24672cea1477083835701058f13c1d7730818/src/linux/system.rs#L449 Calling `refresh_process` is equivalent to calling `refresh_processes_specifics(ProcessRefreshKind::everything())`, so it triggers `refresh_kind.cpu()`, and we never set the updated status of the process to false. This in turn, prevents the process from being removed from the list here (only for the next `refresh_processes` call): https://github.com/GuillaumeGomez/sysinfo/blob/a0b24672cea1477083835701058f13c1d7730818/src/linux/system.rs#L213 I currently workaround this by using instead `ProcessRefreshKind::everything().without_cpu()`, but it seems calling `refresh_process` should never alter the result of the following call to `refresh_processes` with any RefreshKind.
0.23
687
This is definitely a bug. I'll add a test with this scenario to ensure the killed process doesn't show up.
6f1c70092ee030535cc2939960baf41ce331a4b2
2022-01-17T17:26:04Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -245,6 +245,8 @@ fn cpu_usage_is_not_nan() { #[test] fn test_process_times() { + use std::time::{SystemTime, UNIX_EPOCH}; + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { return; } diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -275,6 +277,16 @@ fn test_process_times() { assert!(p.run_time() >= 1); assert!(p.run_time() <= 2); assert!(p.start_time() > p.run_time()); + // On linux, for whatever reason, the uptime seems to be older than the boot time, leading + // to this weird `+ 3` to ensure the test is passing as it should... + assert!( + p.start_time() + 3 + > SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(), + ); + assert!(p.start_time() >= s.boot_time()); } else { panic!("Process not found!"); }
[ "680" ]
GuillaumeGomez__sysinfo-681
GuillaumeGomez/sysinfo
diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -10,7 +10,7 @@ use std::str::FromStr; use libc::{gid_t, kill, uid_t}; -use crate::sys::system::REMAINING_FILES; +use crate::sys::system::{SystemInfo, REMAINING_FILES}; use crate::sys::utils::{get_all_data, get_all_data_from_file, realpath}; use crate::utils::into_iter; use crate::{DiskUsage, Pid, ProcessExt, ProcessRefreshKind, ProcessStatus, Signal}; diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -82,6 +82,7 @@ pub struct Process { stime: u64, old_utime: u64, old_stime: u64, + start_time_without_boot_time: u64, start_time: u64, run_time: u64, pub(crate) updated: bool, diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -101,7 +102,12 @@ pub struct Process { } impl Process { - pub(crate) fn new(pid: Pid, parent: Option<Pid>, start_time: u64) -> Process { + pub(crate) fn new( + pid: Pid, + parent: Option<Pid>, + start_time_without_boot_time: u64, + info: &SystemInfo, + ) -> Process { Process { name: String::with_capacity(20), pid, diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -119,7 +125,8 @@ impl Process { old_utime: 0, old_stime: 0, updated: true, - start_time, + start_time_without_boot_time, + start_time: start_time_without_boot_time + info.boot_time, run_time: 0, uid: 0, gid: 0, diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -293,10 +300,9 @@ unsafe impl<'a, T> Sync for Wrap<'a, T> {} pub(crate) fn _get_process_data( path: &Path, proc_list: &mut Process, - page_size_kb: u64, pid: Pid, uptime: u64, - clock_cycle: u64, + info: &SystemInfo, refresh_kind: ProcessRefreshKind, ) -> Result<(Option<Process>, Pid), ()> { let pid = match path.file_name().and_then(|x| x.to_str()).map(Pid::from_str) { diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -330,11 +336,10 @@ pub(crate) fn _get_process_data( path, entry, &parts, - page_size_kb, parent_memory, parent_virtual_memory, uptime, - clock_cycle, + info, refresh_kind, ); if refresh_kind.disk_usage() { diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -361,8 +366,9 @@ pub(crate) fn _get_process_data( } }; - let start_time = u64::from_str(parts[21]).unwrap_or(0) / clock_cycle; - let mut p = Process::new(pid, parent_pid, start_time); + // To be noted that the start time is invalid here, it still needs + let start_time = u64::from_str(parts[21]).unwrap_or(0) / info.clock_cycle; + let mut p = Process::new(pid, parent_pid, start_time, info); p.stat_file = stat_file; get_status(&mut p, parts[2]); diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -419,11 +425,10 @@ pub(crate) fn _get_process_data( path, &mut p, &parts, - page_size_kb, proc_list.memory, proc_list.virtual_memory, uptime, - clock_cycle, + info, refresh_kind, ); if refresh_kind.disk_usage() { diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -437,16 +442,15 @@ fn update_time_and_memory( path: &Path, entry: &mut Process, parts: &[&str], - page_size_kb: u64, parent_memory: u64, parent_virtual_memory: u64, uptime: u64, - clock_cycle: u64, + info: &SystemInfo, refresh_kind: ProcessRefreshKind, ) { { // rss - entry.memory = u64::from_str(parts[23]).unwrap_or(0) * page_size_kb; + entry.memory = u64::from_str(parts[23]).unwrap_or(0) * info.page_size_kb; if entry.memory >= parent_memory { entry.memory -= parent_memory; } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -460,15 +464,14 @@ fn update_time_and_memory( u64::from_str(parts[13]).unwrap_or(0), u64::from_str(parts[14]).unwrap_or(0), ); - entry.run_time = uptime.saturating_sub(entry.start_time); + entry.run_time = uptime.saturating_sub(entry.start_time_without_boot_time); } refresh_procs( entry, &path.join("task"), - page_size_kb, entry.pid, uptime, - clock_cycle, + info, refresh_kind, ); } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -476,10 +479,9 @@ fn update_time_and_memory( pub(crate) fn refresh_procs( proc_list: &mut Process, path: &Path, - page_size_kb: u64, pid: Pid, uptime: u64, - clock_cycle: u64, + info: &SystemInfo, refresh_kind: ProcessRefreshKind, ) -> bool { if let Ok(d) = fs::read_dir(path) { diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -509,10 +511,9 @@ pub(crate) fn refresh_procs( if let Ok((p, _)) = _get_process_data( e.as_path(), proc_list.get(), - page_size_kb, pid, uptime, - clock_cycle, + info, refresh_kind, ) { p diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -526,15 +527,9 @@ pub(crate) fn refresh_procs( let new_tasks = folders .iter() .filter_map(|e| { - if let Ok((p, pid)) = _get_process_data( - e.as_path(), - proc_list, - page_size_kb, - pid, - uptime, - clock_cycle, - refresh_kind, - ) { + if let Ok((p, pid)) = + _get_process_data(e.as_path(), proc_list, pid, uptime, info, refresh_kind) + { updated_pids.push(pid); p } else { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -97,6 +97,22 @@ fn boot_time() -> u64 { } } +pub(crate) struct SystemInfo { + pub(crate) page_size_kb: u64, + pub(crate) clock_cycle: u64, + pub(crate) boot_time: u64, +} + +impl SystemInfo { + fn new() -> Self { + Self { + page_size_kb: unsafe { sysconf(_SC_PAGESIZE) / 1024 } as _, + clock_cycle: unsafe { sysconf(_SC_CLK_TCK) } as _, + boot_time: boot_time(), + } + } +} + declare_signals! { c_int, Signal::Hangup => libc::SIGHUP, diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -146,18 +162,16 @@ pub struct System { swap_free: u64, global_processor: Processor, processors: Vec<Processor>, - page_size_kb: u64, components: Vec<Component>, disks: Vec<Disk>, networks: Networks, users: Vec<User>, - boot_time: u64, /// Field set to `false` in `update_processors` and to `true` in `refresh_processes_specifics`. /// /// The reason behind this is to avoid calling the `update_processors` more than necessary. /// For example when running `refresh_all` or `refresh_specifics`. need_processors_update: bool, - clock_cycle: u64, + info: SystemInfo, } impl System { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -311,8 +325,10 @@ impl SystemExt for System { const SUPPORTED_SIGNALS: &'static [Signal] = supported_signals(); fn new_with_specifics(refreshes: RefreshKind) -> System { + let info = SystemInfo::new(); + let process_list = Process::new(Pid(0), None, 0, &info); let mut s = System { - process_list: Process::new(Pid(0), None, 0), + process_list, mem_total: 0, mem_free: 0, mem_available: 0, diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -338,14 +354,12 @@ impl SystemExt for System { String::new(), ), processors: Vec::with_capacity(4), - page_size_kb: unsafe { sysconf(_SC_PAGESIZE) / 1024 } as _, components: Vec::new(), disks: Vec::with_capacity(2), networks: Networks::new(), users: Vec::new(), - boot_time: boot_time(), need_processors_update: true, - clock_cycle: unsafe { sysconf(_SC_CLK_TCK) } as _, + info, }; s.refresh_specifics(refreshes); s diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -389,10 +403,9 @@ impl SystemExt for System { if refresh_procs( &mut self.process_list, Path::new("/proc"), - self.page_size_kb, Pid(0), uptime, - self.clock_cycle, + &self.info, refresh_kind, ) { self.clear_procs(refresh_kind); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -405,10 +418,9 @@ impl SystemExt for System { let found = match _get_process_data( &Path::new("/proc/").join(pid.to_string()), &mut self.process_list, - self.page_size_kb, Pid(0), uptime, - self.clock_cycle, + &self.info, refresh_kind, ) { Ok((Some(p), pid)) => { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -539,7 +551,7 @@ impl SystemExt for System { } fn boot_time(&self) -> u64 { - self.boot_time + self.info.boot_time } fn load_average(&self) -> LoadAvg { diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -95,7 +95,7 @@ pub unsafe fn get_disks() -> Vec<Disk> { #[cfg(feature = "multithread")] use rayon::iter::ParallelIterator; - crate::utils::into_iter(0..size_of::<DWORD>() * 8) + crate::utils::into_iter(0..DWORD::BITS) .filter_map(|x| { if (drives >> x) & 1 == 0 { return None;
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
On Linux `ProcessExt::start_time()` does not return the time since the epoch as documented It seems to just return `(22) starttime` from `/proc/[pid]/stat`, see `man proc`: "The time the process started after system boot." `info.process(get_current_pid().unwrap()).unwrap().start_time()` is much smaller than the expected 1642369341. Note that just adding `boot_time()` only works half the time and is otherwise off by one second, are fractions lost somewhere along the way? info.process(get_current_pid().unwrap()).unwrap().start_time() + info.boot_time() = 1642369340 SystemTime::now().duration_since(UNIX_EPOCH).unwrap() = 1642369341
0.22
681
It's pretty bad in any case. Interested into sending a PR? Otherwise I'll try to fix it as soon as possible.
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
2022-01-14T22:08:03Z
diff --git /dev/null b/tests/code_checkers/docs.rs new file mode 100644 --- /dev/null +++ b/tests/code_checkers/docs.rs @@ -0,0 +1,135 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use super::utils::{show_error, TestResult}; +use std::ffi::OsStr; +use std::path::Path; + +fn to_correct_name(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + + for c in s.chars() { + if c.is_uppercase() { + if !out.is_empty() { + out.push('_'); + } + out.push_str(c.to_lowercase().to_string().as_str()); + } else { + out.push(c); + } + } + out +} + +fn check_md_doc_path(p: &Path, md_line: &str, ty_line: &str) -> bool { + let parts = md_line.split("/").collect::<Vec<_>>(); + if let Some(md_name) = parts.last().and_then(|n| n.split(".md").next()) { + if let Some(name) = ty_line + .split_whitespace() + .filter(|s| !s.is_empty()) + .skip(2) + .next() + { + if let Some(name) = name + .split('<') + .next() + .and_then(|n| n.split('{').next()) + .and_then(|n| n.split('(').next()) + .and_then(|n| n.split(';').next()) + { + let correct = to_correct_name(name); + if correct.as_str() == md_name { + return true; + } + show_error( + p, + &format!( + "Invalid markdown file name `{}`, should have been `{}`", + md_name, correct + ), + ); + return false; + } + } + show_error(p, &format!("Cannot extract type name from `{}`", ty_line)); + } else { + show_error(p, &format!("Cannot extract md name from `{}`", md_line)); + } + return false; +} + +fn check_doc_comments_before(p: &Path, lines: &[&str], start: usize) -> bool { + let mut found_docs = false; + + for pos in (0..start).rev() { + let trimmed = lines[pos].trim(); + if trimmed.starts_with("///") { + if !lines[start].trim().starts_with("pub enum ThreadStatus {") { + show_error( + p, + &format!( + "Types should use common documentation by using `#[doc = include_str!(` \ + and by putting the markdown file in the `md_doc` folder instead of `{}`", + &lines[pos], + ), + ); + return false; + } + return true; + } else if trimmed.starts_with("#[doc = include_str!(") { + found_docs = true; + if !check_md_doc_path(p, trimmed, lines[start]) { + return false; + } + } else if !trimmed.starts_with("#[") && !trimmed.starts_with("//") { + break; + } + } + if !found_docs { + show_error( + p, + &format!( + "Missing documentation for public item: `{}` (if it's not supposed to be a public \ + item, use `pub(crate)` instead)", + lines[start], + ), + ); + return false; + } + true +} + +pub fn check_docs(content: &str, p: &Path) -> TestResult { + let mut res = TestResult { + nb_tests: 0, + nb_errors: 0, + }; + + // No need to check if we are in the `src` folder or if we are in a `ffi.rs` file. + if p.parent().unwrap().file_name().unwrap() == OsStr::new("src") + || p.file_name().unwrap() == OsStr::new("ffi.rs") + { + return res; + } + let lines = content.lines().collect::<Vec<_>>(); + + for pos in 1..lines.len() { + let line = lines[pos]; + let trimmed = line.trim(); + if trimmed.starts_with("//!") { + show_error(p, "There shouln't be inner doc comments (`//!`)"); + res.nb_tests += 1; + res.nb_errors += 1; + continue; + } else if !line.starts_with("pub fn ") + && !trimmed.starts_with("pub struct ") + && !trimmed.starts_with("pub enum ") + { + continue; + } + res.nb_tests += 1; + if !check_doc_comments_before(p, &lines, pos) { + res.nb_errors += 1; + } + } + res +} diff --git a/tests/code_checkers/mod.rs b/tests/code_checkers/mod.rs --- a/tests/code_checkers/mod.rs +++ b/tests/code_checkers/mod.rs @@ -1,5 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. +mod docs; mod headers; mod signals; mod utils; diff --git a/tests/code_checkers/mod.rs b/tests/code_checkers/mod.rs --- a/tests/code_checkers/mod.rs +++ b/tests/code_checkers/mod.rs @@ -10,6 +11,7 @@ use utils::TestResult; const CHECKS: &[(fn(&str, &Path) -> TestResult, &[&str])] = &[ (headers::check_license_header, &["src", "tests", "examples"]), (signals::check_signals, &["src"]), + (docs::check_docs, &["src"]), ]; fn handle_tests(res: &mut [TestResult]) {
[ "592" ]
GuillaumeGomez__sysinfo-679
GuillaumeGomez/sysinfo
diff --git a/src/apple/macos/component.rs b/src/apple/macos/component.rs --- a/src/apple/macos/component.rs +++ b/src/apple/macos/component.rs @@ -18,7 +18,7 @@ pub(crate) const COMPONENTS_TEMPERATURE_IDS: &[(&str, &[i8])] = &[ ("Battery", &['T' as i8, 'B' as i8, '0' as i8, 'T' as i8]), // Battery "TB0T" ]; -pub struct ComponentFFI { +pub(crate) struct ComponentFFI { input_structure: ffi::KeyData_t, val: ffi::Val_t, } diff --git a/src/apple/macos/system.rs b/src/apple/macos/system.rs --- a/src/apple/macos/system.rs +++ b/src/apple/macos/system.rs @@ -16,7 +16,7 @@ unsafe fn free_cpu_load_info(cpu_load: &mut processor_cpu_load_info_t) { } } -pub struct SystemTimeInfo { +pub(crate) struct SystemTimeInfo { timebase_to_ns: f64, clock_per_sec: f64, old_cpu_load: processor_cpu_load_info_t, diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -9,7 +9,7 @@ use std::mem; use std::ops::Deref; use std::sync::Arc; -pub struct UnsafePtr<T>(*mut T); +pub(crate) struct UnsafePtr<T>(*mut T); unsafe impl<T> Send for UnsafePtr<T> {} unsafe impl<T> Sync for UnsafePtr<T> {} diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -22,7 +22,7 @@ impl<T> Deref for UnsafePtr<T> { } } -pub struct ProcessorData { +pub(crate) struct ProcessorData { pub cpu_info: UnsafePtr<i32>, pub num_cpu_info: u32, } diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -117,7 +117,7 @@ impl ProcessorExt for Processor { } } -pub fn get_cpu_frequency() -> u64 { +pub(crate) fn get_cpu_frequency() -> u64 { let mut speed: u64 = 0; let mut len = std::mem::size_of::<u64>(); unsafe { diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -192,7 +192,7 @@ pub(crate) fn update_processor_usage<F: FnOnce(Arc<ProcessorData>, *mut i32) -> global_processor.set_cpu_usage(total_cpu_usage); } -pub fn init_processors( +pub(crate) fn init_processors( port: libc::mach_port_t, processors: &mut Vec<Processor>, global_processor: &mut Processor, diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -279,7 +279,7 @@ fn get_sysctl_str(s: &[u8]) -> String { } } -pub fn get_vendor_id_and_brand() -> (String, String) { +pub(crate) fn get_vendor_id_and_brand() -> (String, String) { // On apple M1, `sysctl machdep.cpu.vendor` returns "", so fallback to "Apple" if the result // is empty. let mut vendor = get_sysctl_str(b"machdep.cpu.vendor\0"); diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -83,7 +83,7 @@ where users } -pub fn get_users_list() -> Vec<User> { +pub(crate) fn get_users_list() -> Vec<User> { users_list(|shell, uid| { !endswith(shell, b"/false") && !endswith(shell, b"/uucico") && uid < 65536 }) diff --git a/src/apple/utils.rs b/src/apple/utils.rs --- a/src/apple/utils.rs +++ b/src/apple/utils.rs @@ -2,11 +2,11 @@ use libc::c_char; -pub fn cstr_to_rust(c: *const c_char) -> Option<String> { +pub(crate) fn cstr_to_rust(c: *const c_char) -> Option<String> { cstr_to_rust_with_size(c, None) } -pub fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> Option<String> { +pub(crate) fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> Option<String> { if c.is_null() { return None; } diff --git a/src/freebsd/component.rs b/src/freebsd/component.rs --- a/src/freebsd/component.rs +++ b/src/freebsd/component.rs @@ -3,7 +3,7 @@ use super::utils::get_sys_value_by_name; use crate::ComponentExt; -/// Dummy struct representing a component. +#[doc = include_str!("../../md_doc/component.md")] pub struct Component { id: Vec<u8>, label: String, diff --git a/src/freebsd/disk.rs b/src/freebsd/disk.rs --- a/src/freebsd/disk.rs +++ b/src/freebsd/disk.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use super::utils::c_buf_to_str; -/// Struct containing a disk information. +#[doc = include_str!("../../md_doc/disk.md")] pub struct Disk { name: OsString, c_mount_point: Vec<libc::c_char>, diff --git a/src/freebsd/processor.rs b/src/freebsd/processor.rs --- a/src/freebsd/processor.rs +++ b/src/freebsd/processor.rs @@ -2,7 +2,7 @@ use crate::ProcessorExt; -/// Dummy struct that represents a processor. +#[doc = include_str!("../../md_doc/processor.md")] pub struct Processor { pub(crate) cpu_usage: f32, name: String, diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -10,7 +10,7 @@ use std::time::SystemTime; /// This struct is used to switch between the "old" and "new" every time you use "get_mut". #[derive(Debug)] -pub struct VecSwitcher<T> { +pub(crate) struct VecSwitcher<T> { v1: Vec<T>, v2: Vec<T>, first: bool, diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -61,7 +61,7 @@ pub unsafe fn init_mib(name: &[u8], mib: &mut [c_int]) { libc::sysctlnametomib(name.as_ptr() as _, mib.as_mut_ptr(), &mut len); } -pub fn boot_time() -> u64 { +pub(crate) fn boot_time() -> u64 { let mut boot_time = timeval { tv_sec: 0, tv_usec: 0, diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -109,7 +109,7 @@ pub unsafe fn get_sys_value_array<T: Sized>(mib: &[c_int], value: &mut [T]) -> b ) == 0 } -pub fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> { +pub(crate) fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> { unsafe { let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len()); if let Some(pos) = buf.iter().position(|x| *x == 0) { diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -121,7 +121,7 @@ pub fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> { } } -pub fn c_buf_to_string(buf: &[libc::c_char]) -> Option<String> { +pub(crate) fn c_buf_to_string(buf: &[libc::c_char]) -> Option<String> { c_buf_to_str(buf).map(|s| s.to_owned()) } diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -155,7 +155,7 @@ pub unsafe fn get_sys_value_by_name<T: Sized>(name: &[u8], value: &mut T) -> boo && original == len } -pub fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> { +pub(crate) fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> { let mut size = 0; unsafe { diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -191,7 +191,7 @@ pub fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> { } } -pub fn get_system_info(mib: &[c_int], default: Option<&str>) -> Option<String> { +pub(crate) fn get_system_info(mib: &[c_int], default: Option<&str>) -> Option<String> { let mut size = 0; // Call first to get size diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -258,7 +258,7 @@ pub unsafe fn from_cstr_array(ptr: *const *const c_char) -> Vec<String> { ret } -pub fn get_now() -> u64 { +pub(crate) fn get_now() -> u64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .map(|n| n.as_secs()) diff --git a/src/freebsd/utils.rs b/src/freebsd/utils.rs --- a/src/freebsd/utils.rs +++ b/src/freebsd/utils.rs @@ -266,19 +266,19 @@ pub fn get_now() -> u64 { } // All this is needed because `kinfo_proc` doesn't implement `Send` (because it contains pointers). -pub struct WrapMap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>); +pub(crate) struct WrapMap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>); unsafe impl<'a> Send for WrapMap<'a> {} unsafe impl<'a> Sync for WrapMap<'a> {} -pub struct ProcList<'a>(pub &'a [libc::kinfo_proc]); +pub(crate) struct ProcList<'a>(pub &'a [libc::kinfo_proc]); unsafe impl<'a> Send for ProcList<'a> {} -pub struct WrapItem<'a>(pub &'a libc::kinfo_proc); +pub(crate) struct WrapItem<'a>(pub &'a libc::kinfo_proc); unsafe impl<'a> Send for WrapItem<'a> {} unsafe impl<'a> Sync for WrapItem<'a> {} -pub struct IntoIter<'a>(std::slice::Iter<'a, libc::kinfo_proc>); +pub(crate) struct IntoIter<'a>(std::slice::Iter<'a, libc::kinfo_proc>); unsafe impl<'a> Send for IntoIter<'a> {} impl<'a> std::iter::Iterator for IntoIter<'a> { diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -158,7 +158,7 @@ impl ComponentExt for Component { } } -pub fn get_components() -> Vec<Component> { +pub(crate) fn get_components() -> Vec<Component> { let mut components = Vec::with_capacity(10); if let Ok(dir) = read_dir(&Path::new("/sys/class/hwmon/")) { for entry in dir.flatten() { diff --git a/src/linux/disk.rs b/src/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/linux/disk.rs @@ -253,7 +253,7 @@ fn get_all_disks_inner(content: &str) -> Vec<Disk> { .collect() } -pub fn get_all_disks() -> Vec<Disk> { +pub(crate) fn get_all_disks() -> Vec<Disk> { get_all_disks_inner(&get_all_data("/proc/mounts", 16_385).unwrap_or_default()) } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -220,7 +220,7 @@ impl Drop for Process { } } -pub fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) { +pub(crate) fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) { // First time updating the values without reference, wait for a second cycle to update cpu_usage if p.old_utime == 0 && p.old_stime == 0 { return; diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -235,7 +235,7 @@ pub fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) { .min(max_value); } -pub fn set_time(p: &mut Process, utime: u64, stime: u64) { +pub(crate) fn set_time(p: &mut Process, utime: u64, stime: u64) { p.old_utime = p.utime; p.old_stime = p.stime; p.utime = utime; diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -10,7 +10,7 @@ use crate::ProcessorExt; /// Struct containing values to compute a CPU usage. #[derive(Clone, Copy)] -pub struct CpuValues { +pub(crate) struct CpuValues { user: u64, nice: u64, system: u64, diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -217,11 +217,11 @@ impl ProcessorExt for Processor { } } -pub fn get_raw_times(p: &Processor) -> (u64, u64) { +pub(crate) fn get_raw_times(p: &Processor) -> (u64, u64) { (p.total_time, p.old_total_time) } -pub fn get_cpu_frequency(cpu_core_index: usize) -> u64 { +pub(crate) fn get_cpu_frequency(cpu_core_index: usize) -> u64 { let mut s = String::new(); if File::open(format!( "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq", diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -257,7 +257,7 @@ pub fn get_cpu_frequency(cpu_core_index: usize) -> u64 { .unwrap_or_default() } -pub fn get_physical_core_count() -> Option<usize> { +pub(crate) fn get_physical_core_count() -> Option<usize> { let mut s = String::new(); if let Err(_e) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) { sysinfo_debug!("Cannot read `/proc/cpuinfo` file: {:?}", _e); diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -292,7 +292,7 @@ pub fn get_physical_core_count() -> Option<usize> { } /// Returns the brand/vendor string for the first CPU (which should be the same for all CPUs). -pub fn get_vendor_id_and_brand() -> (String, String) { +pub(crate) fn get_vendor_id_and_brand() -> (String, String) { let mut s = String::new(); if File::open("/proc/cpuinfo") .and_then(|mut f| f.read_to_string(&mut s)) diff --git a/src/linux/utils.rs b/src/linux/utils.rs --- a/src/linux/utils.rs +++ b/src/linux/utils.rs @@ -17,7 +17,7 @@ pub(crate) fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Res } #[allow(clippy::useless_conversion)] -pub fn realpath(original: &Path) -> std::path::PathBuf { +pub(crate) fn realpath(original: &Path) -> std::path::PathBuf { use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; use std::fs; use std::mem::MaybeUninit; diff --git a/src/windows/component.rs b/src/windows/component.rs --- a/src/windows/component.rs +++ b/src/windows/component.rs @@ -92,7 +92,7 @@ impl ComponentExt for Component { } } -pub fn get_components() -> Vec<Component> { +pub(crate) fn get_components() -> Vec<Component> { match Component::new() { Some(c) => vec![c], None => Vec::new(), diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -8,7 +8,7 @@ use std::path::Path; use winapi::um::fileapi::GetDiskFreeSpaceExW; use winapi::um::winnt::ULARGE_INTEGER; -pub fn new_disk( +pub(crate) fn new_disk( name: &OsStr, mount_point: &[u16], file_system: &[u8], diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -792,6 +792,7 @@ fn check_sub(a: u64, b: u64) -> u64 { a - b } } + /// Before changing this function, you must consider the following: /// https://github.com/GuillaumeGomez/sysinfo/issues/459 pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64) { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -871,11 +872,11 @@ pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64) { } } -pub fn get_handle(p: &Process) -> HANDLE { +pub(crate) fn get_handle(p: &Process) -> HANDLE { *p.handle } -pub fn update_disk_usage(p: &mut Process) { +pub(crate) fn update_disk_usage(p: &mut Process) { let mut counters = MaybeUninit::<IO_COUNTERS>::uninit(); let ret = unsafe { GetProcessIoCounters(*p.handle, counters.as_mut_ptr()) }; if ret == 0 { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -889,7 +890,7 @@ pub fn update_disk_usage(p: &mut Process) { } } -pub fn update_memory(p: &mut Process) { +pub(crate) fn update_memory(p: &mut Process) { unsafe { let mut pmc: PROCESS_MEMORY_COUNTERS_EX = zeroed(); if GetProcessMemoryInfo( diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -160,7 +160,7 @@ impl Drop for InternalQuery { } } -pub struct Query { +pub(crate) struct Query { internal: InternalQuery, } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -364,7 +364,7 @@ fn get_vendor_id_not_great(info: &SYSTEM_INFO) -> String { } #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { +pub(crate) fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { #[cfg(target_arch = "x86")] use std::arch::x86::__cpuid; #[cfg(target_arch = "x86_64")] diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -433,11 +433,11 @@ pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { } #[cfg(all(not(target_arch = "x86_64"), not(target_arch = "x86")))] -pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { +pub(crate) fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { (get_vendor_id_not_great(info), String::new()) } -pub fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> { +pub(crate) fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> { &mut p.key_used } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -446,7 +446,7 @@ pub fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> { // If your PC has 64 or fewer logical processors installed, the above code will work fine. However, // if your PC has more than 64 logical processors installed, use GetActiveProcessorCount() or // GetLogicalProcessorInformation() to determine the total number of logical processors installed. -pub fn get_frequencies(nb_processors: usize) -> Vec<u64> { +pub(crate) fn get_frequencies(nb_processors: usize) -> Vec<u64> { let size = nb_processors * mem::size_of::<PROCESSOR_POWER_INFORMATION>(); let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_processors); diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -474,7 +474,7 @@ pub fn get_frequencies(nb_processors: usize) -> Vec<u64> { } } -pub fn get_physical_core_count() -> Option<usize> { +pub(crate) fn get_physical_core_count() -> Option<usize> { // we cannot use the number of processors here to pre calculate the buf size // GetLogicalProcessorInformationEx with RelationProcessorCore passed to it not only returns // the logical cores but also numa nodes diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -25,18 +25,17 @@ use winapi::um::winioctl::{ }; use winapi::um::winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, HANDLE}; -pub struct KeyHandler { +pub(crate) struct KeyHandler { pub unique_id: String, - pub win_key: Vec<u16>, } impl KeyHandler { - pub fn new(unique_id: String, win_key: Vec<u16>) -> KeyHandler { - KeyHandler { unique_id, win_key } + pub fn new(unique_id: String) -> KeyHandler { + KeyHandler { unique_id } } } -pub fn init_processors() -> (Vec<Processor>, String, String) { +pub(crate) fn init_processors() -> (Vec<Processor>, String, String) { unsafe { let mut sys_info: SYSTEM_INFO = zeroed(); GetSystemInfo(&mut sys_info); diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -214,7 +213,7 @@ pub unsafe fn get_disks() -> Vec<Disk> { .collect::<Vec<_>>() } -pub fn add_english_counter( +pub(crate) fn add_english_counter( s: String, query: &mut Query, keys: &mut Option<KeyHandler>, diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -222,7 +221,7 @@ pub fn add_english_counter( ) { let mut full = s.encode_utf16().collect::<Vec<_>>(); full.push(0); - if query.add_english_counter(&counter_name, full.clone()) { - *keys = Some(KeyHandler::new(counter_name, full)); + if query.add_english_counter(&counter_name, full) { + *keys = Some(KeyHandler::new(counter_name)); } } diff --git a/src/windows/utils.rs b/src/windows/utils.rs --- a/src/windows/utils.rs +++ b/src/windows/utils.rs @@ -5,12 +5,12 @@ use winapi::shared::minwindef::FILETIME; use std::time::SystemTime; #[inline] -pub fn filetime_to_u64(f: FILETIME) -> u64 { +pub(crate) fn filetime_to_u64(f: FILETIME) -> u64 { (f.dwHighDateTime as u64) << 32 | (f.dwLowDateTime as u64) } #[inline] -pub fn get_now() -> u64 { +pub(crate) fn get_now() -> u64 { SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .map(|n| n.as_secs())
b1d66813b7a5f35832302e5ed3d4d85ab94e9464
Add check to ensure that types are using common md files and not manual doc comments For example `System` or `Process`.
0.22
679
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
2022-01-14T16:21:58Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -128,6 +128,52 @@ pub fn set_open_files_limit(mut _new_limit: isize) -> bool { } } +// FIXME: Can be removed once negative trait bounds are supported. +#[cfg(doctest)] +mod doctest { + /// Check that `Process` doesn't implement `Clone`. + /// + /// First we check that the "basic" code works: + /// + /// ```no_run + /// use sysinfo::{Process, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let p: &Process = s.processes().values().next().unwrap(); + /// ``` + /// + /// And now we check if it fails when we try to clone it: + /// + /// ```compile_fail + /// use sysinfo::{Process, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// let p: &Process = s.processes().values().next().unwrap(); + /// let p = (*p).clone(); + /// ``` + mod process_clone {} + + /// Check that `System` doesn't implement `Clone`. + /// + /// First we check that the "basic" code works: + /// + /// ```no_run + /// use sysinfo::{Process, System, SystemExt}; + /// + /// let s = System::new(); + /// ``` + /// + /// And now we check if it fails when we try to clone it: + /// + /// ```compile_fail + /// use sysinfo::{Process, System, SystemExt}; + /// + /// let s = System::new(); + /// let s = s.clone(); + /// ``` + mod system_clone {} +} + #[cfg(test)] mod test { use crate::*;
[ "609" ]
GuillaumeGomez__sysinfo-678
GuillaumeGomez/sysinfo
diff --git a/src/apple/app_store/process.rs b/src/apple/app_store/process.rs --- a/src/apple/app_store/process.rs +++ b/src/apple/app_store/process.rs @@ -5,7 +5,6 @@ use std::path::Path; use crate::{DiskUsage, Pid, ProcessExt, ProcessStatus, Signal}; #[doc = include_str!("../../../md_doc/process.md")] -#[derive(Clone)] pub struct Process; impl ProcessExt for Process { diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -15,7 +15,6 @@ use crate::sys::process::ThreadStatus; use crate::sys::system::Wrap; #[doc = include_str!("../../../md_doc/process.md")] -#[derive(Clone)] pub struct Process { pub(crate) name: String, pub(crate) cmd: Vec<String>, diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -12,7 +12,6 @@ impl fmt::Display for ProcessStatus { } #[doc = include_str!("../../md_doc/process.md")] -#[derive(Clone)] pub struct Process { pid: Pid, parent: Option<Pid>,
46333182d9a86be3b27adb2e6f34cd75f3620f9c
Ensure that `Clone` isn't implemented on `Process` Can be done by adding a `compile_fail` test in a doc comment.
0.22
678
c1a6c6f2c438d7cf4c947f555df3d6d408ef0fe4
2021-12-08T11:08:48Z
diff --git /dev/null b/.cirrus.yml new file mode 100644 --- /dev/null +++ b/.cirrus.yml @@ -0,0 +1,35 @@ +task: + name: rust 1.54 on freebsd 11 + freebsd_instance: + image: freebsd-11-4-release-amd64 + setup_script: + - pkg install -y curl + - curl https://sh.rustup.rs -sSf --output rustup.sh + - sh rustup.sh -y --profile=minimal --default-toolchain=1.54 + - . $HOME/.cargo/env + - rustup --version + - rustup component add clippy + test_script: + - . $HOME/.cargo/env + - cargo check + - cargo check --example simple + - cargo test + - cargo clippy -- -D warnings + +task: + name: rust nightly on freebsd 11 + freebsd_instance: + image: freebsd-11-4-release-amd64 + setup_script: + - pkg install -y curl + - curl https://sh.rustup.rs -sSf --output rustup.sh + - sh rustup.sh -y --profile=minimal --default-toolchain=nightly + - . $HOME/.cargo/env + - rustup --version + - rustup component add clippy + test_script: + - . $HOME/.cargo/env + - cargo check + - cargo check --example simple + - cargo test + - cargo clippy -- -D warnings diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -99,7 +99,6 @@ jobs: args: --features apple-sandbox --target=${{ matrix.triple.target }} --manifest-path=Cargo.toml use-cross: ${{ matrix.triple.cross }} - tests: needs: [check] name: Test ${{ matrix.os }} (rust ${{matrix.toolchain}}) diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -160,19 +159,22 @@ jobs: override: true - run: cargo build --features=c-interface - test_freebsd: - runs-on: macos-latest - name: Check stable / FreeBSD host + unknown-targets: + runs-on: ubuntu-latest + strategy: + matrix: + toolchain: + - "1.54.0" # minimum supported rust version + - stable + - nightly steps: - uses: actions/checkout@v2 - - uses: vmactions/freebsd-vm@v0.1.5 - id: test + - uses: actions-rs/toolchain@v1 with: - usesh: true - prepare: pkg install -y curl - run: | - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | RUSTUP_IO_THREADS=1 sh -s -- --profile minimal --default-toolchain stable -y - $HOME/.cargo/bin/cargo check - $HOME/.cargo/bin/cargo test - cd examples - $HOME/.cargo/bin/cargo check + profile: minimal + toolchain: ${{ matrix.toolchain }} + override: true + components: clippy + - run: cargo clippy --features unknown-ci -- -D warnings + - run: cargo check --features unknown-ci + - run: cargo test --features unknown-ci diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -562,6 +562,52 @@ pub enum ProcessStatus { Unknown(u32), } +/// Returns the pid for the current process. +/// +/// `Err` is returned in case the platform isn't supported. +/// +/// ```no_run +/// use sysinfo::get_current_pid; +/// +/// match get_current_pid() { +/// Ok(pid) => { +/// println!("current pid: {}", pid); +/// } +/// Err(e) => { +/// eprintln!("failed to get current pid: {}", e); +/// } +/// } +/// ``` +#[allow(clippy::unnecessary_wraps)] +pub fn get_current_pid() -> Result<Pid, &'static str> { + cfg_if::cfg_if! { + if #[cfg(target = "unknown-ci")] { + fn inner() -> Result<Pid, &'static str> { + Err("Unknown platform (CI)") + } + } else if #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] { + fn inner() -> Result<Pid, &'static str> { + unsafe { Ok(::libc::getpid()) } + } + } else if #[cfg(target_os = "windows")] { + fn inner() -> Result<Pid, &'static str> { + use winapi::um::processthreadsapi::GetCurrentProcessId; + + unsafe { Ok(GetCurrentProcessId() as Pid) } + } + } else if #[cfg(target_os = "unknown")] { + fn inner() -> Result<Pid, &'static str> { + Err("Unavailable on this platform") + } + } else { + fn inner() -> Result<Pid, &'static str> { + Err("Unknown platform") + } + } + } + inner() +} + #[cfg(test)] mod tests { use super::ProcessStatus; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -29,7 +29,14 @@ macro_rules! sysinfo_debug { } cfg_if::cfg_if! { - if #[cfg(any(target_os = "macos", target_os = "ios"))] { + if #[cfg(feature = "unknown-ci")] { + // This is used in CI to check that the build for unknown targets is compiling fine. + mod unknown; + use unknown as sys; + + #[cfg(test)] + pub(crate) const MIN_USERS: usize = 0; + } else if #[cfg(any(target_os = "macos", target_os = "ios"))] { mod apple; use apple as sys; extern crate core_foundation_sys; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -104,35 +110,42 @@ mod utils; /// let s = System::new_all(); /// ``` pub fn set_open_files_limit(mut _new_limit: isize) -> bool { - #[cfg(any(target_os = "linux", target_os = "android"))] - { - if _new_limit < 0 { - _new_limit = 0; - } - let max = sys::system::get_max_nb_fds(); - if _new_limit > max { - _new_limit = max; - } - if let Ok(ref mut x) = unsafe { sys::system::REMAINING_FILES.lock() } { - // If files are already open, to be sure that the number won't be bigger when those - // files are closed, we subtract the current number of opened files to the new limit. - let diff = max - **x; - **x = _new_limit - diff; - true + cfg_if::cfg_if! { + if #[cfg(all(not(feature = "unknown-ci"), any(target_os = "linux", target_os = "android")))] + { + if _new_limit < 0 { + _new_limit = 0; + } + let max = sys::system::get_max_nb_fds(); + if _new_limit > max { + _new_limit = max; + } + if let Ok(ref mut x) = unsafe { sys::system::REMAINING_FILES.lock() } { + // If files are already open, to be sure that the number won't be bigger when those + // files are closed, we subtract the current number of opened files to the new + // limit. + let diff = max - **x; + **x = _new_limit - diff; + true + } else { + false + } } else { false } } - #[cfg(all(not(target_os = "linux"), not(target_os = "android")))] - { - false - } } #[cfg(test)] mod test { use crate::*; + #[cfg(feature = "unknown-ci")] + #[test] + fn check_unknown_ci_feature() { + assert!(!System::IS_SUPPORTED); + } + #[test] fn check_process_memory_usage() { let mut s = System::new(); diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -179,6 +192,9 @@ mod test { #[cfg(target_os = "linux")] #[test] fn check_processes_cpu_usage() { + if !System::IS_SUPPORTED { + return; + } let mut s = System::new(); s.refresh_processes(); diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -9,7 +9,7 @@ #[cfg(test)] mod tests { - use crate::{utils, ProcessExt, System, SystemExt}; + use crate::{ProcessExt, System, SystemExt}; #[test] fn test_refresh_system() { diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -34,9 +34,13 @@ mod tests { #[cfg(not(feature = "apple-sandbox"))] if System::IS_SUPPORTED { assert!( - sys.refresh_process(utils::get_current_pid().expect("failed to get current pid")), + sys.refresh_process(crate::get_current_pid().expect("failed to get current pid")), "process not listed", ); + // Ensure that the process was really added to the list! + assert!(sys + .process(crate::get_current_pid().expect("failed to get current pid")) + .is_some()); } } diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -44,7 +48,7 @@ mod tests { fn test_get_process() { let mut sys = System::new(); sys.refresh_processes(); - if let Some(p) = sys.process(utils::get_current_pid().expect("failed to get current pid")) { + if let Some(p) = sys.process(crate::get_current_pid().expect("failed to get current pid")) { assert!(p.memory() > 0); } else { #[cfg(not(feature = "apple-sandbox"))] diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -67,7 +71,7 @@ mod tests { let mut sys = System::new(); sys.refresh_processes(); - if let Some(p) = sys.process(utils::get_current_pid().expect("failed to get current pid")) { + if let Some(p) = sys.process(crate::get_current_pid().expect("failed to get current pid")) { p.foo(); // If this doesn't compile, it'll simply mean that the Process type // doesn't implement the Send trait. p.bar(); // If this doesn't compile, it'll simply mean that the Process type diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -89,7 +89,10 @@ fn test_cmd() { assert!(!s.processes().is_empty()); if let Some(process) = s.process(p.id() as sysinfo::Pid) { if cfg!(target_os = "windows") { - assert_eq!(process.cmd(), &["waitfor", "/t", "3", "CmdSignal"]); + // Sometimes, we get the full path instead for some reasons... So just in case, + // we check for the command independently that from the arguments. + assert!(process.cmd()[0].contains("waitfor")); + assert_eq!(&process.cmd()[1..], &["/t", "3", "CmdSignal"]); } else { assert_eq!(process.cmd(), &["sleep", "3"]); }
[ "622" ]
GuillaumeGomez__sysinfo-627
GuillaumeGomez/sysinfo
diff --git a/CHANGELOG.md b/CHANGELOG.md --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 0.21.2 + + * Unsupported targets: fix build. + # 0.21.1 * Linux: Process CPU usage cannot go above maximum value (number of CPUs * 100) anymore. diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sysinfo" -version = "0.21.1" +version = "0.21.2" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] description = "Library to get system information such as processes, processors, disks, components and networks" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -43,3 +43,5 @@ apple-app-store = ["apple-sandbox"] c-interface = [] multithread = ["rayon"] debug = ["libc/extra_traits"] +# This feature is used on CI to emulate unknown/unsupported target. +unknown-ci = [] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -60,8 +67,8 @@ cfg_if::cfg_if! { } pub use common::{ - AsU32, DiskType, DiskUsage, Gid, LoadAvg, NetworksIter, Pid, ProcessStatus, RefreshKind, - Signal, Uid, User, + get_current_pid, AsU32, DiskType, DiskUsage, Gid, LoadAvg, NetworksIter, Pid, ProcessStatus, + RefreshKind, Signal, Uid, User, }; pub use sys::{Component, Disk, NetworkData, Networks, Process, Processor, System}; pub use traits::{ diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -70,7 +77,6 @@ pub use traits::{ #[cfg(feature = "c-interface")] pub use c_interface::*; -pub use utils::get_current_pid; #[cfg(feature = "c-interface")] mod c_interface; diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -97,12 +97,12 @@ fn append_files(components: &mut Vec<Component>, folder: &Path) { if is_file(&p_input) { let label = get_file_line(p_label.as_path(), 10) .unwrap_or_else(|| format!("Component {}", key)) // needed for raspberry pi - .replace("\n", ""); + .replace('\n', ""); let max = get_file_line(p_max.as_path(), 10).map(|max| { - max.replace("\n", "").parse::<f32>().unwrap_or(100_000f32) / 1000f32 + max.replace('\n', "").parse::<f32>().unwrap_or(100_000f32) / 1000f32 }); let crit = get_file_line(p_crit.as_path(), 10).map(|crit| { - crit.replace("\n", "").parse::<f32>().unwrap_or(100_000f32) / 1000f32 + crit.replace('\n', "").parse::<f32>().unwrap_or(100_000f32) / 1000f32 }); components.push(Component::new(label, p_input.as_path(), max, crit)); } diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -151,7 +151,7 @@ impl ComponentExt for Component { fn refresh(&mut self) { if let Some(content) = get_file_line(self.input_file.as_path(), 10) { self.temperature = content - .replace("\n", "") + .replace('\n', "") .parse::<f32>() .unwrap_or(100_000f32) / 1000f32; diff --git a/src/linux/disk.rs b/src/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/linux/disk.rs @@ -227,6 +227,7 @@ fn get_all_disks_inner(content: &str) -> Vec<Disk> { // Check if fs_vfstype is one of our 'ignored' file systems. let filtered = matches!( *fs_vfstype, + "rootfs" | // https://www.kernel.org/doc/Documentation/filesystems/ramfs-rootfs-initramfs.txt "sysfs" | // pseudo file system for kernel objects "proc" | // another pseudo file system "tmpfs" | diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -15,8 +15,8 @@ use std::str::FromStr; use libc::{gid_t, kill, sysconf, uid_t, _SC_CLK_TCK}; use crate::sys::system::REMAINING_FILES; -use crate::sys::utils::{get_all_data, get_all_data_from_file}; -use crate::utils::{into_iter, realpath}; +use crate::sys::utils::{get_all_data, get_all_data_from_file, realpath}; +use crate::utils::into_iter; use crate::{DiskUsage, Pid, ProcessExt, ProcessStatus, Signal}; #[doc(hidden)] diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -628,7 +628,7 @@ fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> O for line in reader.lines().flatten() { if let Some(stripped) = line.strip_prefix(info_str) { - return Some(stripped.replace("\"", "")); + return Some(stripped.replace('"', "")); } } } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -645,7 +645,7 @@ fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> O }; for line in reader.lines().flatten() { if let Some(stripped) = line.strip_prefix(info_str) { - return Some(stripped.replace("\"", "")); + return Some(stripped.replace('"', "")); } } None diff --git a/src/linux/utils.rs b/src/linux/utils.rs --- a/src/linux/utils.rs +++ b/src/linux/utils.rs @@ -19,3 +19,35 @@ pub(crate) fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Res let mut file = File::open(file_path.as_ref())?; get_all_data_from_file(&mut file, size) } + +#[allow(clippy::useless_conversion)] +pub fn realpath(original: &Path) -> std::path::PathBuf { + use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; + use std::fs; + use std::mem::MaybeUninit; + use std::path::PathBuf; + + fn and(x: u32, y: u32) -> u32 { + x & y + } + + // let ori = Path::new(original.to_str().unwrap()); + // Right now lstat on windows doesn't work quite well + // if cfg!(windows) { + // return PathBuf::from(ori); + // } + let result = PathBuf::from(original); + let mut result_s = result.to_str().unwrap_or("").as_bytes().to_vec(); + result_s.push(0); + let mut buf = MaybeUninit::<stat>::uninit(); + let res = unsafe { lstat(result_s.as_ptr() as *const c_char, buf.as_mut_ptr()) }; + let buf = unsafe { buf.assume_init() }; + if res < 0 || and(buf.st_mode.into(), S_IFMT.into()) != S_IFLNK.into() { + PathBuf::new() + } else { + match fs::read_link(&result) { + Ok(f) => f, + Err(_) => PathBuf::new(), + } + } +} diff --git a/src/unknown/network.rs b/src/unknown/network.rs --- a/src/unknown/network.rs +++ b/src/unknown/network.rs @@ -22,7 +22,7 @@ impl Networks { } impl NetworksExt for Networks { - fn iter<'a>(&'a self) -> NetworksIter<'a> { + fn iter(&self) -> NetworksIter { NetworksIter::new(self.interfaces.iter()) } diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -4,8 +4,9 @@ // Copyright (c) 2015 Guillaume Gomez // -use crate::{DiskUsage, Pid, ProcessExt, Signal}; +use crate::{DiskUsage, Pid, ProcessExt, ProcessStatus, Signal}; +use std::fmt; use std::path::Path; impl fmt::Display for ProcessStatus { diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -39,7 +40,7 @@ impl ProcessExt for Process { } fn exe(&self) -> &Path { - &Path::new("") + Path::new("") } fn pid(&self) -> Pid { diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -51,11 +52,11 @@ impl ProcessExt for Process { } fn cwd(&self) -> &Path { - &Path::new("") + Path::new("") } fn root(&self) -> &Path { - &Path::new("") + Path::new("") } fn memory(&self) -> u64 { diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -4,95 +4,20 @@ // Copyright (c) 2017 Guillaume Gomez // -#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] -use std::{ffi::OsStr, os::unix::ffi::OsStrExt, path::Path}; - -use crate::Pid; - -#[allow(clippy::useless_conversion)] -#[cfg(any(target_os = "linux", target_os = "android"))] -pub fn realpath(original: &Path) -> std::path::PathBuf { - use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; - use std::fs; - use std::mem::MaybeUninit; - use std::path::PathBuf; - - fn and(x: u32, y: u32) -> u32 { - x & y - } - - // let ori = Path::new(original.to_str().unwrap()); - // Right now lstat on windows doesn't work quite well - // if cfg!(windows) { - // return PathBuf::from(ori); - // } - let result = PathBuf::from(original); - let mut result_s = result.to_str().unwrap_or("").as_bytes().to_vec(); - result_s.push(0); - let mut buf = MaybeUninit::<stat>::uninit(); - let res = unsafe { lstat(result_s.as_ptr() as *const c_char, buf.as_mut_ptr()) }; - let buf = unsafe { buf.assume_init() }; - if res < 0 || and(buf.st_mode.into(), S_IFMT.into()) != S_IFLNK.into() { - PathBuf::new() - } else { - match fs::read_link(&result) { - Ok(f) => f, - Err(_) => PathBuf::new(), - } - } -} - /* convert a path to a NUL-terminated Vec<u8> suitable for use with C functions */ -#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))] -pub fn to_cpath(path: &Path) -> Vec<u8> { +#[cfg(all( + not(feature = "unknown-ci"), + any(target_os = "linux", target_os = "android", target_vendor = "apple") +))] +pub(crate) fn to_cpath(path: &std::path::Path) -> Vec<u8> { + use std::{ffi::OsStr, os::unix::ffi::OsStrExt}; + let path_os: &OsStr = path.as_ref(); let mut cpath = path_os.as_bytes().to_vec(); cpath.push(0); cpath } -/// Returns the pid for the current process. -/// -/// `Err` is returned in case the platform isn't supported. -/// -/// ```no_run -/// use sysinfo::get_current_pid; -/// -/// match get_current_pid() { -/// Ok(pid) => { -/// println!("current pid: {}", pid); -/// } -/// Err(e) => { -/// eprintln!("failed to get current pid: {}", e); -/// } -/// } -/// ``` -#[allow(clippy::unnecessary_wraps)] -pub fn get_current_pid() -> Result<Pid, &'static str> { - cfg_if::cfg_if! { - if #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] { - fn inner() -> Result<Pid, &'static str> { - unsafe { Ok(::libc::getpid()) } - } - } else if #[cfg(target_os = "windows")] { - fn inner() -> Result<Pid, &'static str> { - use winapi::um::processthreadsapi::GetCurrentProcessId; - - unsafe { Ok(GetCurrentProcessId() as Pid) } - } - } else if #[cfg(target_os = "unknown")] { - fn inner() -> Result<Pid, &'static str> { - Err("Unavailable on this platform") - } - } else { - fn inner() -> Result<Pid, &'static str> { - Err("Unknown platform") - } - } - } - inner() -} - /// Converts the value into a parallel iterator (if the multithread feature is enabled) /// Uses the rayon::iter::IntoParallelIterator trait #[cfg(all( diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -105,9 +30,10 @@ pub fn get_current_pid() -> Result<Pid, &'static str> { ), feature = "multithread" ), - not(feature = "apple-sandbox") + not(feature = "apple-sandbox"), + not(feature = "unknown-ci") ))] -pub fn into_iter<T>(val: T) -> T::Iter +pub(crate) fn into_iter<T>(val: T) -> T::Iter where T: rayon::iter::IntoParallelIterator, { diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -126,6 +52,7 @@ where ), not(feature = "multithread") ), + not(feature = "unknown-ci"), not(feature = "apple-sandbox") ))] pub fn into_iter<T>(val: T) -> T::IntoIter diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -88,6 +88,7 @@ unsafe fn init_load_avg() -> Mutex<Option<LoadAvg>> { let mut query = null_mut(); if PdhOpenQueryA(null_mut(), 0, &mut query) != ERROR_SUCCESS as _ { + sysinfo_debug!("init_load_avg: PdhOpenQueryA failed"); return Mutex::new(None); } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -100,17 +101,20 @@ unsafe fn init_load_avg() -> Mutex<Option<LoadAvg>> { ) != ERROR_SUCCESS as _ { PdhCloseQuery(query); + sysinfo_debug!("init_load_avg: failed to get processor queue length"); return Mutex::new(None); } let event = CreateEventA(null_mut(), FALSE, FALSE, b"LoadUpdateEvent\0".as_ptr() as _); if event.is_null() { PdhCloseQuery(query); + sysinfo_debug!("init_load_avg: failed to create event `LoadUpdateEvent`"); return Mutex::new(None); } if PdhCollectQueryDataEx(query, SAMPLING_INTERVAL as _, event) != ERROR_SUCCESS as _ { PdhCloseQuery(query); + sysinfo_debug!("init_load_avg: PdhCollectQueryDataEx failed"); return Mutex::new(None); } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -126,6 +130,7 @@ unsafe fn init_load_avg() -> Mutex<Option<LoadAvg>> { { PdhRemoveCounter(counter); PdhCloseQuery(query); + sysinfo_debug!("init_load_avg: RegisterWaitForSingleObject failed"); Mutex::new(None) } else { Mutex::new(Some(LoadAvg::default())) diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -175,6 +180,7 @@ impl Query { }; Some(Query { internal: q }) } else { + sysinfo_debug!("Query::new: PdhOpenQueryA failed"); None } } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -198,6 +204,7 @@ impl Query { let data = *display_value.u.doubleValue(); Some(data as f32) } else { + sysinfo_debug!("Query::get: PdhGetFormattedCounterValue failed"); Some(0.) }; } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -208,6 +215,7 @@ impl Query { #[allow(clippy::ptr_arg)] pub fn add_counter(&mut self, name: &String, getter: Vec<u16>) -> bool { if self.internal.data.contains_key(name) { + sysinfo_debug!("Query::add_english_counter: doesn't have key `{:?}`", name); return false; } unsafe { diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -216,7 +224,11 @@ impl Query { if ret == ERROR_SUCCESS as _ { self.internal.data.insert(name.clone(), counter); } else { - sysinfo_debug!("failed to add counter '{}': {:x}...", name, ret); + sysinfo_debug!( + "Query::add_english_counter: failed to add counter '{}': {:x}...", + name, + ret, + ); return false; } } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -416,6 +428,7 @@ pub fn get_frequencies(nb_processors: usize) -> Vec<u64> { .map(|i| i.CurrentMhz as u64) .collect::<Vec<_>>() } else { + sysinfo_debug!("get_frequencies: CallNtPowerInformation failed"); vec![0; nb_processors] } } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -445,7 +458,12 @@ pub fn get_physical_core_count() -> Option<usize> { // For some reasons, the function might return a size not big enough... match e.raw_os_error() { Some(value) if value == ERROR_INSUFFICIENT_BUFFER as _ => {} - _ => return None, + _ => { + sysinfo_debug!( + "get_physical_core_count: GetLogicalProcessorInformationEx failed" + ); + return None; + } } } else { break;
3e6d919394fd281ffd0e8484cd9020fa0462dc9d
Taking rootfs as a disk by mistake In some kinds of Linux systems, there is a virtual type of filesystem named `rootfs`. However, sysinfo cannot recognize it correctly and takes it as the real disk. This is the version of centos: ``` [VM-9-75-centos ~]$ cat /proc/version Linux version 3.10.0-1062.18.1.el7.x86_64 (mockbuild@kbuilder.bsys.centos.org) (gcc version 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) ) #1 SMP Tue Mar 17 23:49:17 UTC 2020 ``` Disk info: ``` [VM-9-75-centos ~]$ lsblk -d NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sr0 11:0 1 16.5M 0 rom vda 253:0 0 50G 0 disk vdb 253:16 0 3.5T 0 disk /data vdc 253:32 0 3.5T 0 disk /data1 ``` Mount info(part): ``` [VM-9-75-centos ~]$ cat /proc/mounts rootfs / rootfs rw 0 0 sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0 proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0 devtmpfs /dev devtmpfs rw,nosuid,size=65919208k,nr_inodes=16479802,mode=755 0 0 ... ... ```
0.21
627
3e6d919394fd281ffd0e8484cd9020fa0462dc9d
2021-11-23T19:49:11Z
diff --git a/.cirrus.yml b/.cirrus.yml --- a/.cirrus.yml +++ b/.cirrus.yml @@ -12,14 +12,14 @@ task: test_script: - . $HOME/.cargo/env - cargo check - - cargo check --example simple - - cargo test - cargo clippy -- -D warnings + - cargo check --example simple + - FREEBSD_CI=1 cargo test -j1 task: - name: rust nightly on freebsd 11 + name: rust nightly on freebsd 13 freebsd_instance: - image: freebsd-11-4-release-amd64 + image: freebsd-13-0-release-amd64 setup_script: - pkg install -y curl - curl https://sh.rustup.rs -sSf --output rustup.sh diff --git a/.cirrus.yml b/.cirrus.yml --- a/.cirrus.yml +++ b/.cirrus.yml @@ -30,6 +30,6 @@ task: test_script: - . $HOME/.cargo/env - cargo check - - cargo check --example simple - - cargo test - cargo clippy -- -D warnings + - cargo check --example simple + - FREEBSD_CI=1 cargo test -j1 diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +51,14 @@ cfg_if::cfg_if! { } else if #[cfg(any(target_os = "linux", target_os = "android"))] { mod linux; use linux as sys; + pub(crate) mod users; + + #[cfg(test)] + pub(crate) const MIN_USERS: usize = 1; + } else if #[cfg(target_os = "freebsd")] { + mod freebsd; + use freebsd as sys; + pub(crate) mod users; #[cfg(test)] pub(crate) const MIN_USERS: usize = 1; diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -285,7 +294,7 @@ mod test { // We don't want to test on unsupported systems. if System::IS_SUPPORTED { let s = System::new(); - assert!(!s.host_name().expect("Failed to get host name").is_empty()); + assert!(s.host_name().is_some()); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -345,16 +354,3 @@ mod test { assert!(s.physical_core_count().unwrap_or(0) <= s.processors().len()); } } - -// Used to check that System is Send and Sync. -#[cfg(doctest)] -/// ``` -/// fn is_send<T: Send>() {} -/// is_send::<sysinfo::System>(); -/// ``` -/// -/// ``` -/// fn is_sync<T: Sync>() {} -/// is_sync::<sysinfo::System>(); -/// ``` -pub mod check_if_system_is_send_and_sync {} diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -41,7 +41,7 @@ fn test_cwd() { }; let pid = p.id() as sysinfo::Pid; - std::thread::sleep(std::time::Duration::from_millis(250)); + std::thread::sleep(std::time::Duration::from_secs(1)); let mut s = sysinfo::System::new(); s.refresh_processes(); p.kill().expect("Unable to kill process."); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -77,7 +77,7 @@ fn test_cmd() { .spawn() .unwrap() }; - std::thread::sleep(std::time::Duration::from_millis(250)); + std::thread::sleep(std::time::Duration::from_millis(500)); let mut s = sysinfo::System::new(); assert!(s.processes().is_empty()); s.refresh_processes(); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -123,7 +123,7 @@ fn test_environ() { }; let pid = p.id() as sysinfo::Pid; - std::thread::sleep(std::time::Duration::from_millis(250)); + std::thread::sleep(std::time::Duration::from_secs(1)); let mut s = sysinfo::System::new(); s.refresh_processes(); p.kill().expect("Unable to kill process."); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -167,6 +167,11 @@ fn test_process_disk_usage() { if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { return; } + if std::env::var("FREEBSD_CI").is_ok() { + // For an unknown reason, when running this test on Cirrus CI, it fails. It works perfectly + // locally though... Dark magic... + return; + } fn inner() -> sysinfo::System { { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -175,6 +180,8 @@ fn test_process_disk_usage() { .expect("failed to write to file"); } fs::remove_file("test.txt").expect("failed to remove file"); + // Waiting a bit just in case... + std::thread::sleep(std::time::Duration::from_millis(250)); let mut system = sysinfo::System::new(); assert!(system.processes().is_empty()); system.refresh_processes(); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -264,11 +271,9 @@ fn test_process_times() { s.refresh_processes(); p.kill().expect("Unable to kill process."); - let processes = s.processes(); - let p = processes.get(&pid); - - if let Some(p) = p { + if let Some(p) = s.process(pid) { assert_eq!(p.pid(), pid); + assert!(p.run_time() >= 1); assert!(p.run_time() <= 2); assert!(p.start_time() > p.run_time()); } else {
[ "433" ]
GuillaumeGomez__sysinfo-620
GuillaumeGomez/sysinfo
diff --git a/.cirrus.yml b/.cirrus.yml --- a/.cirrus.yml +++ b/.cirrus.yml @@ -1,7 +1,7 @@ task: - name: rust 1.54 on freebsd 11 + name: rust 1.54 on freebsd 13 freebsd_instance: - image: freebsd-11-4-release-amd64 + image: freebsd-13-0-release-amd64 setup_script: - pkg install -y curl - curl https://sh.rustup.rs -sSf --output rustup.sh diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -25,7 +25,7 @@ winapi = { version = "0.3.9", features = ["fileapi", "handleapi", "ifdef", "ioap ntapi = "0.3" [target.'cfg(not(any(target_os = "unknown", target_arch = "wasm32")))'.dependencies] -libc = "^0.2.103" +libc = "^0.2.112" [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] core-foundation-sys = "0.8" diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -379,14 +379,17 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { "system" => { writeln!( &mut io::stdout(), - "System name: {}\n\ - System kernel version: {}\n\ - System OS version: {}\n\ - System host name: {}", + "System name: {}\n\ + System kernel version: {}\n\ + System OS version: {}\n\ + System OS (long) version: {}\n\ + System host name: {}", sys.name().unwrap_or_else(|| "<unknown>".to_owned()), sys.kernel_version() .unwrap_or_else(|| "<unknown>".to_owned()), sys.os_version().unwrap_or_else(|| "<unknown>".to_owned()), + sys.long_os_version() + .unwrap_or_else(|| "<unknown>".to_owned()), sys.host_name().unwrap_or_else(|| "<unknown>".to_owned()), ); } diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -420,7 +420,7 @@ impl SystemExt for System { self.swap_free } - // need to be checked + // TODO: need to be checked fn used_swap(&self) -> u64 { self.swap_total - self.swap_free } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -583,7 +583,7 @@ pub struct DiskUsage { /// Enum describing the different status of a process. #[derive(Clone, Copy, Debug, PartialEq)] pub enum ProcessStatus { - /// ## Linux + /// ## Linux/FreeBSD /// /// Waiting in uninterruptible disk sleep. /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -597,7 +597,7 @@ pub enum ProcessStatus { Idle, /// Running. Run, - /// ## Linux + /// ## Linux/FreeBSD /// /// Sleeping in an interruptible waiting. /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -609,7 +609,7 @@ pub enum ProcessStatus { /// /// Not available. Sleep, - /// ## Linux + /// ## Linux/FreeBSD /// /// Stopped (on a signal) or (before Linux 2.6.33) trace stopped. /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -621,14 +621,10 @@ pub enum ProcessStatus { /// /// Not available. Stop, - /// ## Linux + /// ## Linux/FreeBSD/macOS /// /// Zombie process. Terminated but not reaped by its parent. /// - /// ## macOS - /// - /// Awaiting collection by parent. - /// /// ## Other OS /// /// Not available. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -641,7 +637,7 @@ pub enum ProcessStatus { /// /// Not available. Tracing, - /// ## Linux + /// ## Linux/FreeBSD /// /// Dead/uninterruptible sleep (usually IO). /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -673,6 +669,14 @@ pub enum ProcessStatus { /// /// Not available. Parked, + /// ## FreeBSD + /// + /// Blocked on a lock. + /// + /// ## Other OS + /// + /// Not available. + LockBlocked, /// Unknown. Unknown(u32), } diff --git /dev/null b/src/freebsd/component.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/component.rs @@ -0,0 +1,69 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use super::utils::get_sys_value_by_name; +use crate::ComponentExt; + +/// Dummy struct representing a component. +pub struct Component { + id: Vec<u8>, + label: String, + temperature: f32, + max: f32, +} + +impl ComponentExt for Component { + fn temperature(&self) -> f32 { + self.temperature + } + + fn max(&self) -> f32 { + self.max + } + + fn critical(&self) -> Option<f32> { + None + } + + fn label(&self) -> &str { + &self.label + } + + fn refresh(&mut self) { + if let Some(temperature) = unsafe { refresh_component(&self.id) } { + self.temperature = temperature; + if self.temperature > self.max { + self.max = self.temperature; + } + } + } +} + +unsafe fn refresh_component(id: &[u8]) -> Option<f32> { + let mut temperature: libc::c_int = 0; + if !get_sys_value_by_name(id, &mut temperature) { + None + } else { + // convert from Kelvin (x 10 -> 273.2 x 10) to Celsius + Some((temperature - 2732) as f32 / 10.) + } +} + +pub unsafe fn get_components(nb_cpus: usize) -> Vec<Component> { + // For now, we only have temperature for CPUs... + let mut components = Vec::with_capacity(nb_cpus); + + for core in 0..nb_cpus { + let id = format!("dev.cpu.{}.temperature\0", core) + .as_bytes() + .to_vec(); + if let Some(temperature) = refresh_component(&id) { + components.push(Component { + id, + label: format!("CPU {}", core + 1), + temperature, + max: temperature, + }); + } + } + components +} diff --git /dev/null b/src/freebsd/disk.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/disk.rs @@ -0,0 +1,139 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::{DiskExt, DiskType}; + +use std::ffi::{OsStr, OsString}; +use std::path::{Path, PathBuf}; + +use super::utils::c_buf_to_str; + +/// Struct containing a disk information. +pub struct Disk { + name: OsString, + c_mount_point: Vec<libc::c_char>, + mount_point: PathBuf, + total_space: u64, + available_space: u64, + file_system: Vec<u8>, + is_removable: bool, +} + +impl DiskExt for Disk { + fn type_(&self) -> DiskType { + DiskType::Unknown(-1) + } + + fn name(&self) -> &OsStr { + &self.name + } + + fn file_system(&self) -> &[u8] { + &self.file_system + } + + fn mount_point(&self) -> &Path { + &self.mount_point + } + + fn total_space(&self) -> u64 { + self.total_space + } + + fn available_space(&self) -> u64 { + self.available_space + } + + fn is_removable(&self) -> bool { + self.is_removable + } + + fn refresh(&mut self) -> bool { + unsafe { + let mut vfs: libc::statvfs = std::mem::zeroed(); + refresh_disk(self, &mut vfs) + } + } +} + +// FIXME: if you want to get disk I/O usage: +// statfs.[f_syncwrites, f_asyncwrites, f_syncreads, f_asyncreads] + +unsafe fn refresh_disk(disk: &mut Disk, vfs: &mut libc::statvfs) -> bool { + if libc::statvfs(disk.c_mount_point.as_ptr() as *const _, vfs) < 0 { + return false; + } + disk.total_space = vfs.f_blocks * vfs.f_frsize; + disk.available_space = vfs.f_favail * vfs.f_frsize; + true +} + +pub unsafe fn get_all_disks() -> Vec<Disk> { + let mut fs_infos: *mut libc::statfs = std::ptr::null_mut(); + + let count = libc::getmntinfo(&mut fs_infos, libc::MNT_WAIT); + + if count < 1 { + return Vec::new(); + } + let mut vfs: libc::statvfs = std::mem::zeroed(); + let fs_infos: &[libc::statfs] = std::slice::from_raw_parts(fs_infos as _, count as _); + let mut disks = Vec::new(); + + for fs_info in fs_infos { + if fs_info.f_mntfromname[0] == 0 || fs_info.f_mntonname[0] == 0 { + // If we have missing information, no need to look any further... + continue; + } + let fs_type: &[libc::c_char] = + if let Some(pos) = fs_info.f_fstypename.iter().position(|x| *x == 0) { + &fs_info.f_fstypename[..pos] + } else { + &fs_info.f_fstypename + }; + let fs_type: &[u8] = std::slice::from_raw_parts(fs_type.as_ptr() as _, fs_type.len()); + match fs_type { + b"autofs" | b"devfs" | b"linprocfs" | b"procfs" | b"fdesckfs" | b"tmpfs" + | b"linsysfs" => { + sysinfo_debug!( + "Memory filesystem `{:?}`, ignoring it.", + c_buf_to_str(&fs_info.f_fstypename).unwrap(), + ); + continue; + } + _ => {} + } + + if libc::statvfs(fs_info.f_mntonname.as_ptr(), &mut vfs) != 0 { + continue; + } + + let mount_point = match c_buf_to_str(&fs_info.f_mntonname) { + Some(m) => m, + None => { + sysinfo_debug!("Cannot get disk mount point, ignoring it."); + continue; + } + }; + + let name = if mount_point == "/" { + OsString::from("root") + } else { + OsString::from(mount_point) + }; + + // 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"); + + disks.push(Disk { + name, + c_mount_point: fs_info.f_mntonname.to_vec(), + mount_point: PathBuf::from(mount_point), + total_space: vfs.f_blocks * vfs.f_frsize, + available_space: vfs.f_favail * vfs.f_frsize, + file_system: fs_type.to_vec(), + is_removable, + }); + } + disks +} diff --git /dev/null b/src/freebsd/mod.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/mod.rs @@ -0,0 +1,16 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +pub mod component; +pub mod disk; +pub mod network; +pub mod process; +pub mod processor; +pub mod system; +mod utils; + +pub use self::component::Component; +pub use self::disk::Disk; +pub use self::network::{NetworkData, Networks}; +pub use self::process::Process; +pub use self::processor::Processor; +pub use self::system::System; diff --git /dev/null b/src/freebsd/network.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/network.rs @@ -0,0 +1,199 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use std::collections::{hash_map, HashMap}; +use std::mem::MaybeUninit; + +use super::utils; +use crate::{NetworkExt, NetworksExt, NetworksIter}; + +macro_rules! old_and_new { + ($ty_:expr, $name:ident, $old:ident, $data:expr) => {{ + $ty_.$old = $ty_.$name; + $ty_.$name = $data.$name; + }}; +} + +#[doc = include_str!("../../md_doc/networks.md")] +pub struct Networks { + interfaces: HashMap<String, NetworkData>, +} + +impl Networks { + pub(crate) fn new() -> Networks { + Networks { + interfaces: HashMap::new(), + } + } +} + +impl NetworksExt for Networks { + fn iter(&self) -> NetworksIter { + NetworksIter::new(self.interfaces.iter()) + } + + fn refresh_networks_list(&mut self) { + unsafe { + self.refresh_interfaces(true); + } + // Remove interfaces which are gone. + self.interfaces.retain(|_, n| n.updated); + } + + fn refresh(&mut self) { + unsafe { + self.refresh_interfaces(false); + } + } +} + +impl Networks { + unsafe fn refresh_interfaces(&mut self, refresh_all: bool) { + let mut nb_interfaces: libc::c_int = 0; + if !utils::get_sys_value( + &[ + libc::CTL_NET, + libc::PF_LINK, + libc::NETLINK_GENERIC, + libc::IFMIB_SYSTEM, + libc::IFMIB_IFCOUNT, + ], + &mut nb_interfaces, + ) { + return; + } + if refresh_all { + // We don't need to update this value if we're not updating all interfaces. + for interface in self.interfaces.values_mut() { + interface.updated = false; + } + } + let mut data: libc::ifmibdata = MaybeUninit::zeroed().assume_init(); + for row in 1..nb_interfaces { + let mib = [ + libc::CTL_NET, + libc::PF_LINK, + libc::NETLINK_GENERIC, + libc::IFMIB_IFDATA, + row, + libc::IFDATA_GENERAL, + ]; + + if !utils::get_sys_value(&mib, &mut data) { + continue; + } + if let Some(name) = utils::c_buf_to_string(&data.ifmd_name) { + let data = &data.ifmd_data; + match self.interfaces.entry(name) { + hash_map::Entry::Occupied(mut e) => { + let mut interface = e.get_mut(); + + old_and_new!(interface, ifi_ibytes, old_ifi_ibytes, data); + old_and_new!(interface, ifi_obytes, old_ifi_obytes, data); + old_and_new!(interface, ifi_ipackets, old_ifi_ipackets, data); + 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); + interface.updated = true; + } + hash_map::Entry::Vacant(e) => { + if !refresh_all { + // This is simply a refresh, we don't want to add new interfaces! + continue; + } + e.insert(NetworkData { + ifi_ibytes: data.ifi_ibytes, + old_ifi_ibytes: 0, + ifi_obytes: data.ifi_obytes, + old_ifi_obytes: 0, + ifi_ipackets: data.ifi_ipackets, + old_ifi_ipackets: 0, + ifi_opackets: data.ifi_opackets, + old_ifi_opackets: 0, + ifi_ierrors: data.ifi_ierrors, + old_ifi_ierrors: 0, + ifi_oerrors: data.ifi_oerrors, + old_ifi_oerrors: 0, + updated: true, + }); + } + } + } + } + } +} + +#[doc = include_str!("../../md_doc/network_data.md")] +pub struct NetworkData { + /// Total number of bytes received over interface. + ifi_ibytes: u64, + old_ifi_ibytes: u64, + /// Total number of bytes transmitted over interface. + ifi_obytes: u64, + old_ifi_obytes: u64, + /// Total number of packets received. + ifi_ipackets: u64, + old_ifi_ipackets: u64, + /// Total number of packets transmitted. + ifi_opackets: u64, + old_ifi_opackets: u64, + /// Shows the total number of packets received with error. This includes + /// too-long-frames errors, ring-buffer overflow errors, CRC errors, + /// frame alignment errors, fifo overruns, and missed packets. + ifi_ierrors: u64, + old_ifi_ierrors: u64, + /// similar to `ifi_ierrors` + ifi_oerrors: u64, + old_ifi_oerrors: u64, + /// Whether or not the above data has been updated during refresh + updated: bool, +} + +impl NetworkExt for NetworkData { + fn received(&self) -> u64 { + self.ifi_ibytes.saturating_sub(self.old_ifi_ibytes) + } + + fn total_received(&self) -> u64 { + self.ifi_ibytes + } + + fn transmitted(&self) -> u64 { + self.ifi_obytes.saturating_sub(self.old_ifi_obytes) + } + + fn total_transmitted(&self) -> u64 { + self.ifi_obytes + } + + fn packets_received(&self) -> u64 { + self.ifi_ipackets.saturating_sub(self.old_ifi_ipackets) + } + + fn total_packets_received(&self) -> u64 { + self.ifi_ipackets + } + + fn packets_transmitted(&self) -> u64 { + self.ifi_opackets.saturating_sub(self.old_ifi_opackets) + } + + fn total_packets_transmitted(&self) -> u64 { + self.ifi_opackets + } + + fn errors_on_received(&self) -> u64 { + self.ifi_ierrors.saturating_sub(self.old_ifi_ierrors) + } + + fn total_errors_on_received(&self) -> u64 { + self.ifi_ierrors + } + + fn errors_on_transmitted(&self) -> u64 { + self.ifi_oerrors.saturating_sub(self.old_ifi_oerrors) + } + + fn total_errors_on_transmitted(&self) -> u64 { + self.ifi_oerrors + } +} diff --git /dev/null b/src/freebsd/process.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/process.rs @@ -0,0 +1,284 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::{DiskUsage, Pid, ProcessExt, ProcessRefreshKind, ProcessStatus, Signal}; + +use std::fmt; +use std::path::{Path, PathBuf}; + +use super::utils::{get_sys_value_str, WrapMap}; + +#[doc(hidden)] +impl From<libc::c_char> for ProcessStatus { + fn from(status: libc::c_char) -> ProcessStatus { + match status { + libc::SIDL => ProcessStatus::Idle, + libc::SRUN => ProcessStatus::Run, + libc::SSLEEP => ProcessStatus::Sleep, + libc::SSTOP => ProcessStatus::Stop, + libc::SZOMB => ProcessStatus::Zombie, + libc::SWAIT => ProcessStatus::Dead, + libc::SLOCK => ProcessStatus::LockBlocked, + x => ProcessStatus::Unknown(x as _), + } + } +} + +impl fmt::Display for ProcessStatus { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(match *self { + ProcessStatus::Idle => "Idle", + ProcessStatus::Run => "Runnable", + ProcessStatus::Sleep => "Sleeping", + ProcessStatus::Stop => "Stopped", + ProcessStatus::Zombie => "Zombie", + ProcessStatus::Dead => "Dead", + ProcessStatus::LockBlocked => "LockBlocked", + _ => "Unknown", + }) + } +} + +#[doc = include_str!("../../md_doc/process.md")] +pub struct Process { + pub(crate) name: String, + pub(crate) cmd: Vec<String>, + pub(crate) exe: PathBuf, + pub(crate) pid: Pid, + parent: Option<Pid>, + pub(crate) environ: Vec<String>, + pub(crate) cwd: PathBuf, + pub(crate) root: PathBuf, + pub(crate) memory: u64, + pub(crate) virtual_memory: u64, + pub(crate) updated: bool, + cpu_usage: f32, + start_time: u64, + run_time: u64, + pub(crate) status: ProcessStatus, + /// User id of the process owner. + pub uid: libc::uid_t, + /// Group id of the process owner. + pub gid: libc::gid_t, + read_bytes: u64, + old_read_bytes: u64, + written_bytes: u64, + old_written_bytes: u64, +} + +impl ProcessExt for Process { + fn kill(&self) -> bool { + self.kill_with(Signal::Kill).unwrap() + } + + fn kill_with(&self, signal: Signal) -> Option<bool> { + let c_signal = match signal { + Signal::Hangup => libc::SIGHUP, + Signal::Interrupt => libc::SIGINT, + Signal::Quit => libc::SIGQUIT, + Signal::Illegal => libc::SIGILL, + Signal::Trap => libc::SIGTRAP, + Signal::Abort => libc::SIGABRT, + Signal::IOT => libc::SIGIOT, + Signal::Bus => libc::SIGBUS, + Signal::FloatingPointException => libc::SIGFPE, + Signal::Kill => libc::SIGKILL, + Signal::User1 => libc::SIGUSR1, + Signal::Segv => libc::SIGSEGV, + Signal::User2 => libc::SIGUSR2, + Signal::Pipe => libc::SIGPIPE, + Signal::Alarm => libc::SIGALRM, + Signal::Term => libc::SIGTERM, + Signal::Child => libc::SIGCHLD, + Signal::Continue => libc::SIGCONT, + Signal::Stop => libc::SIGSTOP, + Signal::TSTP => libc::SIGTSTP, + Signal::TTIN => libc::SIGTTIN, + Signal::TTOU => libc::SIGTTOU, + Signal::Urgent => libc::SIGURG, + Signal::XCPU => libc::SIGXCPU, + Signal::XFSZ => libc::SIGXFSZ, + Signal::VirtualAlarm => libc::SIGVTALRM, + Signal::Profiling => libc::SIGPROF, + Signal::Winch => libc::SIGWINCH, + Signal::IO => libc::SIGIO, + Signal::Sys => libc::SIGSYS, + Signal::Poll | Signal::Power => return None, + }; + unsafe { Some(libc::kill(self.pid, c_signal) == 0) } + } + + fn name(&self) -> &str { + &self.name + } + + fn cmd(&self) -> &[String] { + &self.cmd + } + + fn exe(&self) -> &Path { + self.exe.as_path() + } + + fn pid(&self) -> Pid { + self.pid + } + + fn environ(&self) -> &[String] { + &self.environ + } + + fn cwd(&self) -> &Path { + self.cwd.as_path() + } + + fn root(&self) -> &Path { + self.root.as_path() + } + + fn memory(&self) -> u64 { + self.memory + } + + fn virtual_memory(&self) -> u64 { + self.virtual_memory + } + + fn parent(&self) -> Option<Pid> { + self.parent + } + + fn status(&self) -> ProcessStatus { + self.status + } + + fn start_time(&self) -> u64 { + self.start_time + } + + fn run_time(&self) -> u64 { + self.run_time + } + + fn cpu_usage(&self) -> f32 { + self.cpu_usage + } + + fn disk_usage(&self) -> DiskUsage { + DiskUsage { + written_bytes: self.written_bytes.saturating_sub(self.old_written_bytes), + total_written_bytes: self.written_bytes, + read_bytes: self.read_bytes.saturating_sub(self.old_read_bytes), + total_read_bytes: self.read_bytes, + } + } +} + +pub(crate) unsafe fn get_process_data( + kproc: &libc::kinfo_proc, + wrap: &WrapMap, + page_size: isize, + fscale: f32, + now: u64, + refresh_kind: ProcessRefreshKind, +) -> Option<Process> { + if kproc.ki_pid != 1 && (kproc.ki_flag as libc::c_int & libc::P_SYSTEM) != 0 { + // We filter out the kernel threads. + return None; + } + + // We now get the values needed for both new and existing process. + let cpu_usage = if refresh_kind.cpu() { + (100 * kproc.ki_pctcpu) as f32 / fscale + } else { + 0. + }; + // Processes can be reparented apparently? + let parent = if kproc.ki_ppid != 0 { + Some(kproc.ki_ppid) + } else { + None + }; + let status = ProcessStatus::from(kproc.ki_stat); + + // from FreeBSD source /src/usr.bin/top/machine.c + let virtual_memory = (kproc.ki_size / 1_000) as u64; + let memory = (kproc.ki_rssize * page_size) as u64; + // FIXME: This is to get the "real" run time (in micro-seconds). + // let run_time = (kproc.ki_runtime + 5_000) / 10_000; + + if let Some(proc_) = (*wrap.0.get()).get_mut(&kproc.ki_pid) { + proc_.cpu_usage = cpu_usage; + proc_.parent = parent; + proc_.status = status; + proc_.virtual_memory = virtual_memory; + proc_.memory = memory; + proc_.run_time = now.saturating_sub(proc_.start_time); + proc_.updated = true; + + if refresh_kind.disk_usage() { + proc_.old_read_bytes = proc_.read_bytes; + proc_.read_bytes = kproc.ki_rusage.ru_inblock as _; + proc_.old_written_bytes = proc_.written_bytes; + proc_.written_bytes = kproc.ki_rusage.ru_oublock as _; + } + + return None; + } + + // This is a new process, we need to get more information! + let mut buffer = [0; libc::PATH_MAX as usize + 1]; + + let exe = get_sys_value_str( + &[ + libc::CTL_KERN, + libc::KERN_PROC, + libc::KERN_PROC_PATHNAME, + kproc.ki_pid, + ], + &mut buffer, + ) + .unwrap_or_else(String::new); + // For some reason, it can return completely invalid path like `p\u{5}`. So we need to use + // procstat to get around this problem. + // let cwd = get_sys_value_str( + // &[ + // libc::CTL_KERN, + // libc::KERN_PROC, + // libc::KERN_PROC_CWD, + // kproc.ki_pid, + // ], + // &mut buffer, + // ) + // .map(|s| s.into()) + // .unwrap_or_else(PathBuf::new); + + let start_time = kproc.ki_start.tv_sec as u64; + Some(Process { + pid: kproc.ki_pid, + parent, + uid: kproc.ki_ruid, + gid: kproc.ki_rgid, + start_time, + run_time: now.saturating_sub(start_time), + cpu_usage, + virtual_memory, + memory, + // procstat_getfiles + cwd: PathBuf::new(), + exe: exe.into(), + // kvm_getargv isn't thread-safe so we get it in the main thread. + name: String::new(), + // kvm_getargv isn't thread-safe so we get it in the main thread. + cmd: Vec::new(), + // kvm_getargv isn't thread-safe so we get it in the main thread. + root: PathBuf::new(), + // kvm_getenvv isn't thread-safe so we get it in the main thread. + environ: Vec::new(), + status, + read_bytes: kproc.ki_rusage.ru_inblock as _, + old_read_bytes: 0, + written_bytes: kproc.ki_rusage.ru_oublock as _, + old_written_bytes: 0, + updated: true, + }) +} diff --git /dev/null b/src/freebsd/processor.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/processor.rs @@ -0,0 +1,44 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::ProcessorExt; + +/// Dummy struct that represents a processor. +pub struct Processor { + pub(crate) cpu_usage: f32, + name: String, + pub(crate) vendor_id: String, + frequency: u64, +} + +impl Processor { + pub(crate) fn new(name: String, vendor_id: String, frequency: u64) -> Processor { + Processor { + cpu_usage: 0., + name, + vendor_id, + frequency, + } + } +} + +impl ProcessorExt for Processor { + fn cpu_usage(&self) -> f32 { + self.cpu_usage + } + + fn name(&self) -> &str { + &self.name + } + + fn frequency(&self) -> u64 { + self.frequency + } + + fn vendor_id(&self) -> &str { + &self.vendor_id + } + + fn brand(&self) -> &str { + "" + } +} diff --git /dev/null b/src/freebsd/system.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/system.rs @@ -0,0 +1,702 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::{ + sys::{component::Component, Disk, Networks, Process, Processor}, + LoadAvg, Pid, ProcessRefreshKind, RefreshKind, SystemExt, User, +}; + +use std::cell::UnsafeCell; +use std::collections::HashMap; +use std::ffi::CStr; +use std::mem::MaybeUninit; +use std::path::{Path, PathBuf}; +use std::ptr::NonNull; + +use super::utils::{ + self, boot_time, c_buf_to_string, from_cstr_array, get_sys_value, get_sys_value_array, + get_sys_value_by_name, get_sys_value_str_by_name, get_system_info, init_mib, +}; + +use libc::c_int; + +#[doc = include_str!("../../md_doc/system.md")] +pub struct System { + process_list: HashMap<Pid, Process>, + mem_total: u64, + mem_free: u64, + mem_used: u64, + mem_available: u64, + swap_total: u64, + swap_used: u64, + global_processor: Processor, + processors: Vec<Processor>, + components: Vec<Component>, + disks: Vec<Disk>, + networks: Networks, + users: Vec<User>, + boot_time: u64, + system_info: SystemInfo, +} + +impl SystemExt for System { + const IS_SUPPORTED: bool = true; + + fn new_with_specifics(refreshes: RefreshKind) -> System { + let system_info = SystemInfo::new(); + + let mut s = System { + process_list: HashMap::with_capacity(200), + mem_total: 0, + mem_free: 0, + mem_available: 0, + mem_used: 0, + swap_total: 0, + swap_used: 0, + global_processor: Processor::new(String::new(), String::new(), 0), + processors: Vec::with_capacity(system_info.nb_cpus as _), + components: Vec::with_capacity(2), + disks: Vec::with_capacity(1), + networks: Networks::new(), + users: Vec::new(), + boot_time: boot_time(), + system_info, + }; + s.refresh_specifics(refreshes); + s + } + + fn refresh_memory(&mut self) { + if self.mem_total == 0 { + self.mem_total = self.system_info.get_total_memory(); + } + self.mem_used = self.system_info.get_used_memory(); + self.mem_free = self.system_info.get_free_memory(); + let (swap_used, swap_total) = self.system_info.get_swap_info(); + self.swap_total = swap_total; + self.swap_used = swap_used; + } + + fn refresh_cpu(&mut self) { + if self.processors.is_empty() { + let mut frequency: libc::size_t = 0; + + // We get the processor vendor ID in here. + let vendor_id = + get_sys_value_str_by_name(b"hw.model\0").unwrap_or_else(|| "<unknown>".to_owned()); + for pos in 0..self.system_info.nb_cpus { + unsafe { + // The information can be missing if it's running inside a VM. + if !get_sys_value_by_name( + format!("dev.cpu.{}.freq\0", pos).as_bytes(), + &mut frequency, + ) { + frequency = 0; + } + } + self.processors.push(Processor::new( + format!("cpu {}", pos), + vendor_id.clone(), + frequency as _, + )); + } + self.global_processor.vendor_id = vendor_id; + } + self.system_info + .get_cpu_usage(&mut self.global_processor, &mut self.processors); + } + + fn refresh_components_list(&mut self) { + if self.processors.is_empty() { + self.refresh_cpu(); + } + self.components = unsafe { super::component::get_components(self.processors.len()) }; + } + + fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { + unsafe { self.refresh_procs(refresh_kind) } + } + + fn refresh_process_specifics(&mut self, pid: Pid, refresh_kind: ProcessRefreshKind) -> bool { + let res = unsafe { + let kd = self.system_info.kd.as_ptr(); + let mut count = 0; + let procs = libc::kvm_getprocs(kd, libc::KERN_PROC_PROC, 0, &mut count); + if count < 1 { + sysinfo_debug!("kvm_getprocs returned nothing..."); + return false; + } + let now = super::utils::get_now(); + + let fscale = self.system_info.fscale; + let page_size_k = self.system_info.page_size_k as isize; + let proc_list = utils::WrapMap(UnsafeCell::new(&mut self.process_list)); + let procs = utils::ProcList(std::slice::from_raw_parts_mut(procs, count as _)); + + #[cfg(feature = "multithread")] + use rayon::iter::ParallelIterator; + + let iter = crate::utils::into_iter(procs); + #[cfg(not(feature = "multithread"))] + { + iter.find(|kproc| kproc.ki_pid == pid) + } + #[cfg(feature = "multithread")] + { iter.find_any(|kproc| kproc.0.ki_pid == pid) } + // Yep, this `and_then is called on what's returned by the `find` from above... + // (I mostly added this comment because rustfmt is acting weird in here.) + .and_then(|kproc| { + super::process::get_process_data( + kproc.0, + &proc_list, + page_size_k, + fscale, + now, + refresh_kind, + ) + .map(|p| (kproc, p)) + }) + }; + if let Some((kproc, proc_)) = res { + unsafe { + self.add_missing_proc_info(self.system_info.kd.as_ptr(), kproc.0, proc_); + } + true + } else { + self.process_list + .get(&pid) + .map(|p| p.updated) + .unwrap_or(false) + } + } + + fn refresh_disks_list(&mut self) { + self.disks = unsafe { super::disk::get_all_disks() }; + } + + fn refresh_users_list(&mut self) { + self.users = crate::users::get_users_list(); + } + + // COMMON PART + // + // Need to be moved into a "common" file to avoid duplication. + + fn processes(&self) -> &HashMap<Pid, Process> { + &self.process_list + } + + fn process(&self, pid: Pid) -> Option<&Process> { + self.process_list.get(&pid) + } + + fn networks(&self) -> &Networks { + &self.networks + } + + fn networks_mut(&mut self) -> &mut Networks { + &mut self.networks + } + + fn global_processor_info(&self) -> &Processor { + &self.global_processor + } + + fn processors(&self) -> &[Processor] { + &self.processors + } + + fn physical_core_count(&self) -> Option<usize> { + let mut physical_core_count: u32 = 0; + + if unsafe { get_sys_value_by_name(b"hw.ncpu\0", &mut physical_core_count) } { + Some(physical_core_count as _) + } else { + None + } + } + + fn total_memory(&self) -> u64 { + self.mem_total + } + + fn free_memory(&self) -> u64 { + self.mem_free + } + + fn available_memory(&self) -> u64 { + self.mem_available + } + + fn used_memory(&self) -> u64 { + self.mem_used + } + + fn total_swap(&self) -> u64 { + self.swap_total + } + + fn free_swap(&self) -> u64 { + self.swap_total - self.swap_used + } + + // TODO: need to be checked + fn used_swap(&self) -> u64 { + self.swap_used + } + + fn components(&self) -> &[Component] { + &self.components + } + + fn components_mut(&mut self) -> &mut [Component] { + &mut self.components + } + + fn disks(&self) -> &[Disk] { + &self.disks + } + + fn disks_mut(&mut self) -> &mut [Disk] { + &mut self.disks + } + + fn uptime(&self) -> u64 { + let csec = unsafe { libc::time(::std::ptr::null_mut()) }; + + unsafe { libc::difftime(csec, self.boot_time as _) as u64 } + } + + fn boot_time(&self) -> u64 { + self.boot_time + } + + fn load_average(&self) -> LoadAvg { + let mut loads = vec![0f64; 3]; + unsafe { + libc::getloadavg(loads.as_mut_ptr(), 3); + } + LoadAvg { + one: loads[0], + five: loads[1], + fifteen: loads[2], + } + } + + fn users(&self) -> &[User] { + &self.users + } + + fn name(&self) -> Option<String> { + self.system_info.get_os_name() + } + + fn long_os_version(&self) -> Option<String> { + self.system_info.get_os_release_long() + } + + fn host_name(&self) -> Option<String> { + self.system_info.get_hostname() + } + + fn kernel_version(&self) -> Option<String> { + self.system_info.get_kernel_version() + } + + fn os_version(&self) -> Option<String> { + self.system_info.get_os_release() + } +} + +impl Default for System { + fn default() -> Self { + Self::new() + } +} + +impl System { + unsafe fn refresh_procs(&mut self, refresh_kind: ProcessRefreshKind) { + let kd = self.system_info.kd.as_ptr(); + let procs = { + let mut count = 0; + let procs = libc::kvm_getprocs(kd, libc::KERN_PROC_PROC, 0, &mut count); + if count < 1 { + sysinfo_debug!("kvm_getprocs returned nothing..."); + return; + } + #[cfg(feature = "multithread")] + use rayon::iter::{ParallelIterator, ParallelIterator as IterTrait}; + #[cfg(not(feature = "multithread"))] + use std::iter::Iterator as IterTrait; + + crate::utils::into_iter(&mut self.process_list).for_each(|(_, proc_)| { + proc_.updated = false; + }); + + let fscale = self.system_info.fscale; + let page_size_k = self.system_info.page_size_k as isize; + let now = super::utils::get_now(); + let proc_list = utils::WrapMap(UnsafeCell::new(&mut self.process_list)); + let procs = utils::ProcList(std::slice::from_raw_parts_mut(procs, count as _)); + + IterTrait::filter_map(crate::utils::into_iter(procs), |kproc| { + super::process::get_process_data( + kproc.0, + &proc_list, + page_size_k, + fscale, + now, + refresh_kind, + ) + .map(|p| (kproc, p)) + }) + .collect::<Vec<_>>() + }; + + // We remove all processes that don't exist anymore. + self.process_list.retain(|_, v| v.updated); + + for (kproc, proc_) in procs { + let kproc = kproc.0; + self.add_missing_proc_info(kd, kproc, proc_); + } + } + + unsafe fn add_missing_proc_info( + &mut self, + kd: *mut libc::kvm_t, + kproc: &libc::kinfo_proc, + mut proc_: Process, + ) { + proc_.cmd = from_cstr_array(libc::kvm_getargv(kd, kproc, 0) as _); + self.system_info.get_proc_missing_info(kproc, &mut proc_); + if !proc_.cmd.is_empty() { + // First, we try to retrieve the name from the command line. + let p = Path::new(&proc_.cmd[0]); + if let Some(name) = p.file_name().and_then(|s| s.to_str()) { + proc_.name = name.to_owned(); + } + if proc_.root.as_os_str().is_empty() { + if let Some(parent) = p.parent() { + proc_.root = parent.to_path_buf(); + } + } + } + if proc_.name.is_empty() { + // The name can be cut short because the `ki_comm` field size is limited, + // which is why we prefer to get the name from the command line as much as + // possible. + proc_.name = c_buf_to_string(&kproc.ki_comm).unwrap_or_else(String::new); + } + proc_.environ = from_cstr_array(libc::kvm_getenvv(kd, kproc, 0) as _); + self.process_list.insert(proc_.pid, proc_); + } +} + +// FIXME: to be removed once 0.2.108 libc has been published! +const CPUSTATES: usize = 5; + +/// This struct is used to get system information more easily. +#[derive(Debug)] +struct SystemInfo { + hw_physical_memory: [c_int; 2], + page_size_k: c_int, + virtual_page_count: [c_int; 4], + virtual_wire_count: [c_int; 4], + virtual_active_count: [c_int; 4], + virtual_cache_count: [c_int; 4], + virtual_inactive_count: [c_int; 4], + virtual_free_count: [c_int; 4], + os_type: [c_int; 2], + os_release: [c_int; 2], + kern_version: [c_int; 2], + hostname: [c_int; 2], + buf_space: [c_int; 2], + nb_cpus: c_int, + kd: NonNull<libc::kvm_t>, + // For these two fields, we could use `kvm_getcptime` but the function isn't very efficient... + mib_cp_time: [c_int; 2], + mib_cp_times: [c_int; 2], + // For the global CPU usage. + cp_time: utils::VecSwitcher<libc::c_ulong>, + // For each processor CPU usage. + cp_times: utils::VecSwitcher<libc::c_ulong>, + /// From FreeBSD manual: "The kernel fixed-point scale factor". It's used when computing + /// processes' CPU usage. + fscale: f32, + procstat: *mut libc::procstat, +} + +// This is needed because `kd: *mut libc::kvm_t` isn't thread-safe. +unsafe impl Send for SystemInfo {} +unsafe impl Sync for SystemInfo {} + +impl SystemInfo { + fn new() -> Self { + let kd = unsafe { + let mut errbuf = + MaybeUninit::<[libc::c_char; libc::_POSIX2_LINE_MAX as usize]>::uninit(); + NonNull::new(libc::kvm_openfiles( + std::ptr::null(), + b"/dev/null\0".as_ptr() as *const _, + std::ptr::null(), + 0, + errbuf.as_mut_ptr() as *mut _, + )) + .expect("kvm_openfiles failed") + }; + + let mut smp: c_int = 0; + let mut nb_cpus: c_int = 1; + unsafe { + if !get_sys_value_by_name(b"kern.smp.active\0", &mut smp) { + smp = 0; + } + #[allow(clippy::collapsible_if)] // I keep as is for readability reasons. + if smp != 0 { + if !get_sys_value_by_name(b"kern.smp.cpus\0", &mut nb_cpus) || nb_cpus < 1 { + nb_cpus = 1; + } + } + } + + let mut si = SystemInfo { + hw_physical_memory: Default::default(), + page_size_k: 0, + virtual_page_count: Default::default(), + virtual_wire_count: Default::default(), + virtual_active_count: Default::default(), + virtual_cache_count: Default::default(), + virtual_inactive_count: Default::default(), + virtual_free_count: Default::default(), + buf_space: Default::default(), + os_type: Default::default(), + os_release: Default::default(), + kern_version: Default::default(), + hostname: Default::default(), + nb_cpus, + kd, + mib_cp_time: Default::default(), + mib_cp_times: Default::default(), + cp_time: utils::VecSwitcher::new(vec![0; CPUSTATES]), + cp_times: utils::VecSwitcher::new(vec![0; nb_cpus as usize * CPUSTATES]), + fscale: 0., + procstat: std::ptr::null_mut(), + }; + unsafe { + let mut fscale: c_int = 0; + if !get_sys_value_by_name(b"kern.fscale\0", &mut fscale) { + // Default value used in htop. + fscale = 2048; + } + si.fscale = fscale as f32; + + if !get_sys_value_by_name(b"vm.stats.vm.v_page_size\0", &mut si.page_size_k) { + panic!("cannot get page size..."); + } + si.page_size_k /= 1_000; + + init_mib(b"hw.physmem\0", &mut si.hw_physical_memory); + init_mib(b"vm.stats.vm.v_page_count\0", &mut si.virtual_page_count); + init_mib(b"vm.stats.vm.v_wire_count\0", &mut si.virtual_wire_count); + init_mib( + b"vm.stats.vm.v_active_count\0", + &mut si.virtual_active_count, + ); + init_mib(b"vm.stats.vm.v_cache_count\0", &mut si.virtual_cache_count); + init_mib( + b"vm.stats.vm.v_inactive_count\0", + &mut si.virtual_inactive_count, + ); + init_mib(b"vm.stats.vm.v_free_count\0", &mut si.virtual_free_count); + init_mib(b"vfs.bufspace\0", &mut si.buf_space); + + init_mib(b"kern.ostype\0", &mut si.os_type); + init_mib(b"kern.osrelease\0", &mut si.os_release); + init_mib(b"kern.version\0", &mut si.kern_version); + init_mib(b"kern.hostname\0", &mut si.hostname); + + init_mib(b"kern.cp_time\0", &mut si.mib_cp_time); + init_mib(b"kern.cp_times\0", &mut si.mib_cp_times); + } + + si + } + + fn get_os_name(&self) -> Option<String> { + get_system_info(&[self.os_type[0], self.os_type[1]], Some("FreeBSD")) + } + + fn get_kernel_version(&self) -> Option<String> { + get_system_info(&[self.kern_version[0], self.kern_version[1]], None) + } + + fn get_os_release_long(&self) -> Option<String> { + get_system_info(&[self.os_release[0], self.os_release[1]], None) + } + + fn get_os_release(&self) -> Option<String> { + // It returns something like "13.0-RELEASE". We want to keep everything until the "-". + get_system_info(&[self.os_release[0], self.os_release[1]], None) + .and_then(|s| s.split('-').next().map(|s| s.to_owned())) + } + + fn get_hostname(&self) -> Option<String> { + get_system_info(&[self.hostname[0], self.hostname[1]], Some("")) + } + + /// Returns (used, total). + fn get_swap_info(&self) -> (u64, u64) { + // Magic number used in htop. Cannot find how they got when reading `kvm_getswapinfo` source + // code so here we go... + const LEN: usize = 16; + let mut swap = MaybeUninit::<[libc::kvm_swap; LEN]>::uninit(); + unsafe { + let nswap = + libc::kvm_getswapinfo(self.kd.as_ptr(), swap.as_mut_ptr() as *mut _, LEN as _, 0) + as usize; + if nswap < 1 { + return (0, 0); + } + let swap = + std::slice::from_raw_parts(swap.as_ptr() as *mut libc::kvm_swap, nswap.min(LEN)); + let (used, total) = swap.iter().fold((0, 0), |(used, total), swap| { + (used + swap.ksw_used as u64, total + swap.ksw_total as u64) + }); + ( + used * self.page_size_k as u64, + total * self.page_size_k as u64, + ) + } + } + + fn get_total_memory(&self) -> u64 { + let mut total_memory: u64 = 0; + unsafe { + get_sys_value(&self.hw_physical_memory, &mut total_memory); + } + total_memory / 1_000 + } + + fn get_used_memory(&self) -> u64 { + let mut mem_active: u64 = 0; + let mut mem_wire: u64 = 0; + + unsafe { + get_sys_value(&self.virtual_active_count, &mut mem_active); + get_sys_value(&self.virtual_wire_count, &mut mem_wire); + } + + (mem_active * self.page_size_k as u64) + (mem_wire * self.page_size_k as u64) + } + + fn get_free_memory(&self) -> u64 { + let mut buffers_mem: u64 = 0; + let mut inactive_mem: u64 = 0; + let mut cached_mem: u64 = 0; + let mut free_mem: u64 = 0; + + unsafe { + get_sys_value(&self.buf_space, &mut buffers_mem); + get_sys_value(&self.virtual_inactive_count, &mut inactive_mem); + get_sys_value(&self.virtual_cache_count, &mut cached_mem); + get_sys_value(&self.virtual_free_count, &mut free_mem); + } + // For whatever reason, buffers_mem is already the right value... + buffers_mem / 1_024 + + (inactive_mem * self.page_size_k as u64) + + (cached_mem * self.page_size_k as u64) + + (free_mem * self.page_size_k as u64) + } + + fn get_cpu_usage(&mut self, global: &mut Processor, processors: &mut [Processor]) { + unsafe { + get_sys_value_array(&self.mib_cp_time, self.cp_time.get_mut()); + get_sys_value_array(&self.mib_cp_times, self.cp_times.get_mut()); + } + + fn fill_processor( + proc_: &mut Processor, + new_cp_time: &[libc::c_ulong], + old_cp_time: &[libc::c_ulong], + ) { + let mut total_new: u64 = 0; + let mut total_old: u64 = 0; + let mut cp_diff: libc::c_ulong = 0; + + for i in 0..(CPUSTATES as usize) { + // We obviously don't want to get the idle part of the processor usage, otherwise + // we would always be at 100%... + if i != libc::CP_IDLE as usize { + cp_diff += new_cp_time[i] - old_cp_time[i]; + } + total_new += new_cp_time[i] as u64; + total_old += old_cp_time[i] as u64; + } + + let total_diff = total_new - total_old; + if total_diff < 1 { + proc_.cpu_usage = 0.; + } else { + proc_.cpu_usage = cp_diff as f32 / total_diff as f32 * 100.; + } + } + + fill_processor(global, self.cp_time.get_new(), self.cp_time.get_old()); + let old_cp_times = self.cp_times.get_old(); + let new_cp_times = self.cp_times.get_new(); + for (pos, proc_) in processors.iter_mut().enumerate() { + let index = pos * CPUSTATES as usize; + + fill_processor(proc_, &new_cp_times[index..], &old_cp_times[index..]); + } + } + + #[allow(clippy::collapsible_if)] // I keep as is for readability reasons. + unsafe fn get_proc_missing_info(&mut self, kproc: &libc::kinfo_proc, proc_: &mut Process) { + if self.procstat.is_null() { + self.procstat = libc::procstat_open_sysctl(); + } + if self.procstat.is_null() { + return; + } + let head = libc::procstat_getfiles(self.procstat, kproc as *const _ as usize as *mut _, 0); + if head.is_null() { + return; + } + let mut entry = (*head).stqh_first; + let mut done = 0; + while !entry.is_null() && done < 2 { + { + let tmp = &*entry; + if tmp.fs_uflags & libc::PS_FST_UFLAG_CDIR != 0 { + if !tmp.fs_path.is_null() { + if let Ok(p) = CStr::from_ptr(tmp.fs_path).to_str() { + proc_.cwd = PathBuf::from(p); + done += 1; + } + } + } else if tmp.fs_uflags & libc::PS_FST_UFLAG_RDIR != 0 { + if !tmp.fs_path.is_null() { + if let Ok(p) = CStr::from_ptr(tmp.fs_path).to_str() { + proc_.root = PathBuf::from(p); + done += 1; + } + } + } + } + entry = (*entry).next.stqe_next; + } + libc::procstat_freefiles(self.procstat, head); + } +} + +impl Drop for SystemInfo { + fn drop(&mut self) { + unsafe { + libc::kvm_close(self.kd.as_ptr()); + if !self.procstat.is_null() { + libc::procstat_close(self.procstat); + } + } + } +} diff --git /dev/null b/src/freebsd/utils.rs new file mode 100644 --- /dev/null +++ b/src/freebsd/utils.rs @@ -0,0 +1,380 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +use crate::{Pid, Process}; +use libc::{c_char, c_int, timeval}; +use std::cell::UnsafeCell; +use std::collections::HashMap; +use std::ffi::CStr; +use std::mem; +use std::time::SystemTime; + +/// This struct is used to switch between the "old" and "new" every time you use "get_mut". +#[derive(Debug)] +pub struct VecSwitcher<T> { + v1: Vec<T>, + v2: Vec<T>, + first: bool, +} + +impl<T: Clone> VecSwitcher<T> { + pub fn new(v1: Vec<T>) -> Self { + let v2 = v1.clone(); + + Self { + v1, + v2, + first: true, + } + } + + pub fn get_mut(&mut self) -> &mut [T] { + self.first = !self.first; + if self.first { + // It means that `v2` will be the "new". + &mut self.v2 + } else { + // It means that `v1` will be the "new". + &mut self.v1 + } + } + + pub fn get_old(&self) -> &[T] { + if self.first { + &self.v1 + } else { + &self.v2 + } + } + + pub fn get_new(&self) -> &[T] { + if self.first { + &self.v2 + } else { + &self.v1 + } + } +} + +#[inline] +pub unsafe fn init_mib(name: &[u8], mib: &mut [c_int]) { + let mut len = mib.len(); + libc::sysctlnametomib(name.as_ptr() as _, mib.as_mut_ptr(), &mut len); +} + +pub fn boot_time() -> u64 { + let mut boot_time = timeval { + tv_sec: 0, + tv_usec: 0, + }; + let mut len = std::mem::size_of::<timeval>(); + let mut mib: [c_int; 2] = [libc::CTL_KERN, libc::KERN_BOOTTIME]; + if unsafe { + libc::sysctl( + mib.as_mut_ptr(), + mib.len() as _, + &mut boot_time as *mut timeval as *mut _, + &mut len, + std::ptr::null_mut(), + 0, + ) + } < 0 + { + 0 + } else { + boot_time.tv_sec as _ + } +} + +pub unsafe fn get_sys_value<T: Sized>(mib: &[c_int], value: &mut T) -> bool { + let mut len = mem::size_of::<T>() as libc::size_t; + libc::sysctl( + mib.as_ptr(), + mib.len() as _, + value as *mut _ as *mut _, + &mut len, + std::ptr::null_mut(), + 0, + ) == 0 +} + +pub unsafe fn get_sys_value_array<T: Sized>(mib: &[c_int], value: &mut [T]) -> bool { + let mut len = (mem::size_of::<T>() * value.len()) as libc::size_t; + libc::sysctl( + mib.as_ptr(), + mib.len() as _, + value.as_mut_ptr() as *mut _, + &mut len as *mut _, + std::ptr::null_mut(), + 0, + ) == 0 +} + +pub fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> { + unsafe { + let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len()); + if let Some(pos) = buf.iter().position(|x| *x == 0) { + // Shrink buffer to terminate the null bytes + std::str::from_utf8(&buf[..pos]).ok() + } else { + std::str::from_utf8(buf).ok() + } + } +} + +pub fn c_buf_to_string(buf: &[libc::c_char]) -> Option<String> { + c_buf_to_str(buf).map(|s| s.to_owned()) +} + +pub unsafe fn get_sys_value_str(mib: &[c_int], buf: &mut [libc::c_char]) -> Option<String> { + let mut len = (mem::size_of::<libc::c_char>() * buf.len()) as libc::size_t; + if libc::sysctl( + mib.as_ptr(), + mib.len() as _, + buf.as_mut_ptr() as *mut _, + &mut len, + std::ptr::null_mut(), + 0, + ) != 0 + { + return None; + } + c_buf_to_string(&buf[..len / mem::size_of::<libc::c_char>()]) +} + +pub unsafe fn get_sys_value_by_name<T: Sized>(name: &[u8], value: &mut T) -> bool { + let mut len = mem::size_of::<T>() as libc::size_t; + let original = len; + + libc::sysctlbyname( + name.as_ptr() as *const c_char, + value as *mut _ as *mut _, + &mut len, + std::ptr::null_mut(), + 0, + ) == 0 + && original == len +} + +pub fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> { + let mut size = 0; + + unsafe { + if libc::sysctlbyname( + name.as_ptr() as *const c_char, + std::ptr::null_mut(), + &mut size, + std::ptr::null_mut(), + 0, + ) == 0 + && size > 0 + { + // now create a buffer with the size and get the real value + let mut buf: Vec<libc::c_char> = vec![0; size as usize]; + + if libc::sysctlbyname( + name.as_ptr() as *const c_char, + buf.as_mut_ptr() as *mut _, + &mut size, + std::ptr::null_mut(), + 0, + ) == 0 + && size > 0 + { + c_buf_to_string(&buf) + } else { + // getting the system value failed + None + } + } else { + None + } + } +} + +pub fn get_system_info(mib: &[c_int], default: Option<&str>) -> Option<String> { + let mut size = 0; + + // Call first to get size + unsafe { + libc::sysctl( + mib.as_ptr(), + mib.len() as _, + std::ptr::null_mut(), + &mut size, + std::ptr::null_mut(), + 0, + ) + }; + + // exit early if we did not update the size + if size == 0 { + default.map(|s| s.to_owned()) + } else { + // set the buffer to the correct size + let mut buf: Vec<libc::c_char> = vec![0; size as usize]; + + if unsafe { + libc::sysctl( + mib.as_ptr(), + mib.len() as _, + buf.as_mut_ptr() as _, + &mut size, + std::ptr::null_mut(), + 0, + ) + } == -1 + { + // If command fails return default + default.map(|s| s.to_owned()) + } else { + c_buf_to_string(&buf) + } + } +} + +pub unsafe fn from_cstr_array(ptr: *const *const c_char) -> Vec<String> { + if ptr.is_null() { + return Vec::new(); + } + let mut max = 0; + loop { + let ptr = ptr.add(max); + if (*ptr).is_null() { + break; + } + max += 1; + } + if max == 0 { + return Vec::new(); + } + let mut ret = Vec::with_capacity(max); + + for pos in 0..max { + let p = ptr.add(pos); + if let Ok(s) = CStr::from_ptr(*p).to_str() { + ret.push(s.to_owned()); + } + } + ret +} + +pub fn get_now() -> u64 { + SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map(|n| n.as_secs()) + .unwrap_or(0) +} + +// All this is needed because `kinfo_proc` doesn't implement `Send` (because it contains pointers). +pub struct WrapMap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>); + +unsafe impl<'a> Send for WrapMap<'a> {} +unsafe impl<'a> Sync for WrapMap<'a> {} + +pub struct ProcList<'a>(pub &'a [libc::kinfo_proc]); +unsafe impl<'a> Send for ProcList<'a> {} + +pub struct WrapItem<'a>(pub &'a libc::kinfo_proc); +unsafe impl<'a> Send for WrapItem<'a> {} +unsafe impl<'a> Sync for WrapItem<'a> {} + +pub struct IntoIter<'a>(std::slice::Iter<'a, libc::kinfo_proc>); +unsafe impl<'a> Send for IntoIter<'a> {} + +impl<'a> std::iter::Iterator for IntoIter<'a> { + type Item = WrapItem<'a>; + + fn next(&mut self) -> Option<Self::Item> { + self.0.next().map(WrapItem) + } +} + +impl<'a> std::iter::ExactSizeIterator for IntoIter<'a> { + fn len(&self) -> usize { + self.0.len() + } +} + +impl<'a> std::iter::IntoIterator for ProcList<'a> { + type Item = WrapItem<'a>; + type IntoIter = IntoIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + IntoIter(self.0.iter()) + } +} + +#[cfg(feature = "multithread")] +mod multithread { + use super::{IntoIter, ProcList, WrapItem}; + use rayon::iter::plumbing::{bridge, Consumer, Producer, ProducerCallback, UnindexedConsumer}; + use rayon::prelude::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator}; + + struct IterProducer<'a>(std::slice::Iter<'a, libc::kinfo_proc>); + unsafe impl<'a> Send for IterProducer<'a> {} + unsafe impl<'a> Sync for IterProducer<'a> {} + + impl<'a> Producer for IterProducer<'a> { + type Item = WrapItem<'a>; + type IntoIter = IntoIter<'a>; + + fn into_iter(self) -> Self::IntoIter { + IntoIter(self.0) + } + + fn split_at(self, index: usize) -> (Self, Self) { + let (left, right) = self.0.as_slice().split_at(index); + (IterProducer(left.iter()), IterProducer(right.iter())) + } + } + + impl<'a> IntoParallelIterator for ProcList<'a> { + type Item = WrapItem<'a>; + type Iter = IntoIter<'a>; + + fn into_par_iter(self) -> Self::Iter { + IntoIter(self.0.iter()) + } + } + + impl<'a> std::iter::DoubleEndedIterator for IntoIter<'a> { + fn next_back(&mut self) -> Option<Self::Item> { + self.0.next_back().map(WrapItem) + } + } + + impl<'a> ParallelIterator for IntoIter<'a> { + type Item = WrapItem<'a>; + + fn drive_unindexed<C>(self, consumer: C) -> C::Result + where + C: UnindexedConsumer<Self::Item>, + { + bridge(self, consumer) + } + + fn opt_len(&self) -> Option<usize> { + Some(self.0.len()) + } + } + + impl<'a> IndexedParallelIterator for IntoIter<'a> { + fn drive<C>(self, consumer: C) -> C::Result + where + C: Consumer<Self::Item>, + { + bridge(self, consumer) + } + + fn len(&self) -> usize { + self.0.len() + } + + fn with_producer<CB>(self, callback: CB) -> CB::Output + where + CB: ProducerCallback<Self::Item>, + { + callback.callback(IterProducer(self.0)) + } + } +} diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ #![deny(missing_docs)] #![deny(rustdoc::broken_intra_doc_links)] #![allow(clippy::upper_case_acronyms)] +#![allow(clippy::non_send_fields_in_send_ty)] #![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] diff --git a/src/linux/mod.rs b/src/linux/mod.rs --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -6,7 +6,6 @@ pub mod network; pub mod process; pub mod processor; pub mod system; -pub mod users; pub(crate) mod utils; pub use self::component::Component; diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -61,7 +61,7 @@ impl fmt::Display for ProcessStatus { ProcessStatus::Wakekill => "Wakekill", ProcessStatus::Waking => "Waking", ProcessStatus::Parked => "Parked", - ProcessStatus::Unknown(_) => "Unknown", + _ => "Unknown", }) } } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -239,9 +239,9 @@ impl ProcessExt for Process { fn disk_usage(&self) -> DiskUsage { DiskUsage { - written_bytes: self.written_bytes - self.old_written_bytes, + written_bytes: self.written_bytes.saturating_sub(self.old_written_bytes), total_written_bytes: self.written_bytes, - read_bytes: self.read_bytes - self.old_read_bytes, + read_bytes: self.read_bytes.saturating_sub(self.old_read_bytes), total_read_bytes: self.read_bytes, } } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -408,7 +408,7 @@ impl SystemExt for System { } fn refresh_users_list(&mut self) { - self.users = crate::linux::users::get_users_list(); + self.users = crate::users::get_users_list(); } // COMMON PART diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -343,7 +343,7 @@ pub trait ProcessExt: Debug { /// Returns number of bytes read and written to disk. /// - /// /!\\ On Windows, this method actually returns **ALL** I/O read and written bytes. + /// ⚠️ On Windows and FreeBSD, this method actually returns **ALL** I/O read and written bytes. /// /// ```no_run /// use sysinfo::{ProcessExt, System, SystemExt}; diff --git a/src/linux/users.rs b/src/users.rs --- a/src/linux/users.rs +++ b/src/users.rs @@ -90,6 +90,7 @@ pub fn get_users_list() -> Vec<User> { .collect() } +#[inline] fn parse_id(id: &str) -> Option<u32> { id.parse::<u32>().ok() } diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -22,7 +22,8 @@ pub(crate) fn to_cpath(path: &std::path::Path) -> Vec<u8> { target_os = "linux", target_os = "android", target_vendor = "apple", - target_os = "windows" + target_os = "windows", + target_os = "freebsd", ), feature = "multithread" ), diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -44,7 +45,8 @@ where target_os = "linux", target_os = "android", target_vendor = "apple", - target_os = "windows" + target_os = "windows", + target_os = "freebsd", ), not(feature = "multithread") ),
a2c2a7779336384b726a73567002de19574ec843
Add FreeBSD support? As FreeBSD is still used on lots of places it might be nice to support it. I don't think you want to add this but are you open to PRs to support FreeBSD?
0.21
620
I gave it a try a long time ago but had issues finding some information. If you feel like giving it a try, you're very welcome to do so! Ah that's a bummer, i've always been interested in freebsd but never found any reason to use it so this might be a nice way to learn some new things. Good luck then. :wink: A general hint to anybody who would like to give it a try: In contrast to e.g. Linux, there's no /proc directory on modern FreeBSD (at least not by default). Most of the information you'd usually get from procfs is set or retrieved using sysctl(8). This allows access to a hierarchical MIB with just about any information you'll need. Some examples: ``` hw.physmem: 8413745152 kern.maxfiles: 256767 kern.boottime: { sec = 1613061579, usec = 955761 } Thu Feb 11 17:39:39 2021 kern.geom.label.gptid.enable: 0 vm.loadavg: { 0.56 0.42 0.34 } vm.stats.vm.v_kthreads: 37 vm.swap_total: 8589934592 vfs.zfs.min_auto_ashift: 12 net.inet.ip.forwarding: 0 debug.kdb.break_to_debugger: 0 ``` All that kind of stuff (over 5,000 sysctls on FreeBSD 12.x). Often it's obvious what a sysctl represents, but sometimes a little research is necessary... @GuillaumeGomez Do you still remember what information you had trouble finding? I had actually mostly issues with the different types needed. The fields seem to depend from one BSD to another, making it really difficult to figure out how to generalize it. However, it's been 4 years now or even more that I gave it a try, so I don't remember anything more specific. But I remember for sure encountering multiples issues (mostly around documentation, had to spend a lot of time reading source codes). Ah, I see. Well, this is true: As the BSDs are whole operating systems (unlike Linux), so there's no "add support for one, get the others for free". While they share common ancestry, they have diverged much over the years. 20 years ago a popular book about FreeBSD was published and rightfully claimed that much of what was covered would be useful for readers who wanted to get into OpenBSD or NetBSD instead. This clearly is no longer the case. FreeBSD for example uses the GEOM storage framework which is unique even among the BSD family of operating systems. So even for things like detecting disks, there is no way to generalize it (not even the device names are the same across all BSDs!). The documentation is usually pretty good, though. Sure, there are dark and dusty corners, but in general it's very useful. @mjarkk: Did you start some work on this? If you ran into problems and have questions about FreeBSD, I'd be happy to help (however I'm just an admin and not a developer who knows Rust). I kinda got stuk on getting a nice development environment running in freebsd and meanwhile kinda forgot this issue. But now that you've brought this up again and i have more free time to spend soon i can give it a second try. Maybe i should not go for the remote vscode code editor and just take the time to setup a desktop and run a editor just inside the vm :). Well, maybe I just can build it somehow enabling linux procfs? It needs to work out of the box on all freebsd installations. So no, you have to deal with the "default" environment. Have fun! :D I do understand your point; but right now I need to run a program using a package using a package using sysinfo, so any workaround will go. Actualy, I do need to use sysinfo::{get_current_pid, set_open_files_limit, Pid, ProcessExt, System, SystemExt} - but run it already yesterday... No I meant in case you add support for freebsd. Why? `This OpenJDK implementation requires fdescfs(5) mounted on /dev/fd and procfs(5) mounted on /proc. If you have not done it yet, please do the following: mount -t fdescfs fdesc /dev/fd mount -t procfs proc /proc To make it permanent, you need the following lines in /etc/fstab: fdesc /dev/fd fdescfs rw 0 0 proc /proc procfs rw 0 0 ` You can't ask `sysinfo` users on freebsd to install stuff in order to make `sysinfo` work. I refuse. Not install, but enable. procfs and linux-compatible procfs exists in base FreeBSD, and only has to be mounted. Same, it should work without requiring any change from the user. Enabling procfs is actually a fairly common thing on FreeBSD. Even packages like Bash ask you to do it. But some people prefer to not use procfs and they also have valid reasons for this. Well, it's your software; but I'd prefer soft running with some extra setup to soft not running at all. You can simply have a fallback like we have on windows or mac. Getting system information is really random. So if there is procfs available, just use it, otherwise, try your best? XD But I need to BUILD sysinfo! @tarkhil welp there is one solution.. get your code editor up and start writing support for FreeBSD :) I'm going to look into this upcoming weekend unless @tarkhil wants to write some code hehe I've been looking into this, and I think @kraileth is correct about sysctl. It should provide everything you'd be able to get from /proc. Here are some findings: - `hw.realmem` returns what we refer to as "total" memory (in bytes) - `hw.usermem` returns what we refer to as "free" or "available" memory (in bytes -- from what I can tell, FreeBSD does not distinguish between free and available?) - `kern.boottime` returns the boot time - `vm.swap_total` returns the total available swap (in bytes) - `kern.version` returns the kernel version - `kern.hostname` returns the hostname - `vm.loadavg` returns the load average - `kern.smp.cores` returns the number of physical cores Thanks for the information! Do you also know how to get information for processes, network and disk info too by any chance? For disk info you can have a look at `sysctl kern.geom.confxml`. It will output some XML that contains about all the info that you probably want about drives, partitions, etc. What info about network and processes are you looking for? * For processes: https://docs.rs/sysinfo/0.18.1/sysinfo/trait.ProcessExt.html * For network: https://docs.rs/sysinfo/0.18.1/sysinfo/trait.NetworkExt.html Also, please note that even with all this information, it'll require me a lot of time before implementing anything. I'm quite short in time and setting up a freebsd VM and develop anything inside it doesn't like something that will be done easily. I'm a little new to FreeBSD, so not entirely sure on networks and processes. I'm learning as I go. If I have free time next week, I can see how far I'm able to get to a usable PR. It may be possible to leverage the existing Apple code, but we'd need to trim out things that are Mach-specific. Same with Linux and the non-POSIX-y parts. @GuillaumeGomez I can offer to set up a FreeBSD VM for you if that helps. You'd just have to tell me exactly what you need and to mail me a public SSH key. @ryanavella Have a look at `netstat(1)`, it should be able to provide the required info. I'd also recommend to take a look at `libxo(3)`, a formating library that is supported by netstat (that way you can have it output e.g. XML or JSON which is of course better to parse than standard command output). For processes you should get relevant info with `procstat(1)` (which also supports libxo). @kraileth I intend to build one myself with virtualbox so then I can make my stuff work somehow, but thanks for the suggestion! @ryanavella I'm not sure much of mac can be reused. Maybe the users and disk but the rest seems very apple specific. But thanks in advance in any case! Wow, this was a lot more involved than I expected. A lot of the code I was able to leverage from Apple, but some required researching libprocstat and various system calls. Unfortunately the libc crate is lacking for FreeBSD, so I had to handcode some of the FFI. Users are finished. System/process stuff is halfway done. I haven't even looked at networks, disks, or components yet. I still have a few outstanding questions which are halting progress, and which I couldn't find documented anywhere: - Does FreeBSD distinguish between free and available memory? - Does the `vm.swap_total` sysctl return total swap, or total *available* swap? (docs are ambiguous here) - Is there a way to calculate all desired swap values on FreeBSD? > Unfortunately the libc crate is lacking for FreeBSD, so I had to handcode some of the FFI. It's fine, don't worry. It happened a lot of times in `sysinfo` already. Generally I add FFI in sysinfo, make a release and then send a PR to libc. > Users are finished. System/process stuff is halfway done. I haven't even looked at networks, disks, or components yet. Nice, you're moving forward quite fast. :) > Does FreeBSD distinguish between free and available memory? No idea. > Does the `vm.swap_total` sysctl return total swap, or total available swap? (docs are ambiguous here) For reference, here is what freebsd docs say: > Corresponding values are available through sysctl vm.swap_total, that gives the total bytes available for swapping So super confusing... Only one solution: check the values with swap being used... > Is there a way to calculate all desired swap values on FreeBSD? No idea. For all my "no idea" answers, I recommend to check how htop does it: <https://github.com/htop-dev/htop/>. For example they get swap info [here](https://github.com/htop-dev/htop/blob/master/freebsd/FreeBSDProcessList.c#L369).
3e6d919394fd281ffd0e8484cd9020fa0462dc9d
2021-06-28T13:42:01Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -341,10 +341,11 @@ mod test { if System::IS_SUPPORTED { assert!(!s.processors().is_empty()); + // In case we are running inside a VM, it's possible to not have a physical core, only + // logical ones, which is why we don't test `physical_cores_count > 0`. let physical_cores_count = s .physical_core_count() .expect("failed to get number of physical cores"); - assert!(physical_cores_count > 0); assert!(physical_cores_count <= s.processors().len()); } else { assert!(s.processors().is_empty());
[ "519" ]
GuillaumeGomez__sysinfo-529
GuillaumeGomez/sysinfo
diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -263,10 +263,8 @@ pub fn get_cpu_frequency(cpu_core_index: usize) -> u64 { pub fn get_physical_core_count() -> Option<usize> { let mut s = String::new(); - if File::open("/proc/cpuinfo") - .and_then(|mut f| f.read_to_string(&mut s)) - .is_err() - { + if let Err(_e) = File::open("/proc/cpuinfo").and_then(|mut f| f.read_to_string(&mut s)) { + sysinfo_debug!("Cannot read `/proc/cpuinfo` file: {:?}", _e); return None; }
3aa83dc410ebe2f6d5063a095104ea6c6394507f
test_physical_core_numbers fails on armv7hl aarch64 and ppc64le ``` ---- test_physical_core_numbers stdout ---- thread 'test_physical_core_numbers' panicked at 'assertion failed: count.unwrap() > 0', tests/processor.rs:36:9 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace failures: test_physical_core_numbers ``` You can find the full logs in https://koji.fedoraproject.org/koji/taskinfo?taskID=70748857 (click on the buildArch jobs for the arch you want, then on build.log).
0.18
529
For this one, please show me the content of `/proc/cpuinfo`. Also, why are you running the tests to build a package? Fedora policy is to always run the tests at the end of the build to validate that the package will actually work. This isn't specific to rust, it's done for all packages that have tests available. armv7hl: ``` processor : 0 model name : ARMv7 Processor rev 2 (v7l) BogoMIPS : 80.00 Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 CPU implementer : 0x50 CPU architecture: 7 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 1 model name : ARMv7 Processor rev 2 (v7l) BogoMIPS : 80.00 Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 CPU implementer : 0x50 CPU architecture: 7 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 2 model name : ARMv7 Processor rev 2 (v7l) BogoMIPS : 80.00 Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 CPU implementer : 0x50 CPU architecture: 7 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 3 model name : ARMv7 Processor rev 2 (v7l) BogoMIPS : 80.00 Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 CPU implementer : 0x50 CPU architecture: 7 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 4 model name : ARMv7 Processor rev 2 (v7l) BogoMIPS : 80.00 Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm aes pmull sha1 sha2 crc32 CPU implementer : 0x50 CPU architecture: 7 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 Hardware : Generic DT based system Revision : 0000 Serial : 0000000000000000 ``` aarch64: ``` processor : 0 BogoMIPS : 80.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid CPU implementer : 0x50 CPU architecture: 8 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 1 BogoMIPS : 80.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid CPU implementer : 0x50 CPU architecture: 8 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 2 BogoMIPS : 80.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid CPU implementer : 0x50 CPU architecture: 8 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 3 BogoMIPS : 80.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid CPU implementer : 0x50 CPU architecture: 8 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 processor : 4 BogoMIPS : 80.00 Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid CPU implementer : 0x50 CPU architecture: 8 CPU variant : 0x3 CPU part : 0x000 CPU revision : 2 ``` ppc64le: ``` processor : 0 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 1 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 2 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 3 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 4 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 5 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 6 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) processor : 7 cpu : POWER9 (architected), altivec supported clock : 2250.000000MHz revision : 2.2 (pvr 004e 1202) timebase : 512000000 platform : pSeries model : IBM pSeries (emulated by qemu) machine : CHRP IBM pSeries (emulated by qemu) MMU : Radix ``` > Fedora policy is to always run the tests at the end of the build to validate that the package will actually work. This isn't specific to rust, it's done for all packages that have tests available. Interesting. Well thanks to that, we were able to catch a few issues. It's a perfect timing because I made a few fixes recently so I was about to release a new version. :) Thanks for providing me the information!
3aa83dc410ebe2f6d5063a095104ea6c6394507f
2021-06-11T08:30:22Z
diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -89,4 +89,15 @@ mod tests { assert!(!hostname.contains('\u{0}')) } } + + #[test] + fn check_uptime() { + let sys = System::new(); + let uptime = sys.get_uptime(); + if System::IS_SUPPORTED { + std::thread::sleep(std::time::Duration::from_millis(1000)); + let new_uptime = sys.get_uptime(); + assert!(uptime < new_uptime); + } + } }
[ "508" ]
GuillaumeGomez__sysinfo-509
GuillaumeGomez/sysinfo
diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -121,7 +121,6 @@ pub struct System { components: Vec<Component>, disks: Vec<Disk>, networks: Networks, - uptime: u64, users: Vec<User>, boot_time: u64, } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -278,7 +277,6 @@ impl SystemExt for System { components: Vec::new(), disks: Vec::with_capacity(2), networks: Networks::new(), - uptime: get_uptime(), users: Vec::new(), boot_time: boot_time(), }; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -294,7 +292,6 @@ impl SystemExt for System { } fn refresh_memory(&mut self) { - self.uptime = get_uptime(); if let Ok(data) = get_all_data("/proc/meminfo", 16_385) { for line in data.split('\n') { let field = match line.split(':').next() { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -319,18 +316,17 @@ impl SystemExt for System { } fn refresh_cpu(&mut self) { - self.uptime = get_uptime(); self.refresh_processors(None); } fn refresh_processes(&mut self) { - self.uptime = get_uptime(); + let uptime = self.get_uptime(); if refresh_procs( &mut self.process_list, Path::new("/proc"), self.page_size_kb, 0, - self.uptime, + uptime, get_secs_since_epoch(), ) { self.clear_procs(); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -338,13 +334,13 @@ impl SystemExt for System { } fn refresh_process(&mut self, pid: Pid) -> bool { - self.uptime = get_uptime(); + let uptime = self.get_uptime(); let found = match _get_process_data( &Path::new("/proc/").join(pid.to_string()), &mut self.process_list, self.page_size_kb, 0, - self.uptime, + uptime, get_secs_since_epoch(), ) { Ok((Some(p), pid)) => { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -456,7 +452,12 @@ impl SystemExt for System { } fn get_uptime(&self) -> u64 { - self.uptime + let content = get_all_data("/proc/uptime", 50).unwrap_or_default(); + content + .split('.') + .next() + .and_then(|t| t.parse().ok()) + .unwrap_or_default() } fn get_boot_time(&self) -> u64 { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -1037,15 +1038,6 @@ pub fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<Str get_all_data_from_file(&mut file, size) } -fn get_uptime() -> u64 { - let content = get_all_data("/proc/uptime", 50).unwrap_or_default(); - content - .split('.') - .next() - .and_then(|t| t.parse().ok()) - .unwrap_or_default() -} - fn get_secs_since_epoch() -> u64 { match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { Ok(n) => n.as_secs(),
5c69175f028a5608093d31597b93031d165774c5
Uptime: To cache, or not to cache? I've been looking into FreeBSD support this week (#433), and while trying to implement `SystemExt::get_uptime`, I found an inconsistency. Linux uses whatever value was cached during the most recent refresh. https://github.com/GuillaumeGomez/sysinfo/blob/f8574e459d0b1d65ed649cd0897b36422d449217/src/linux/system.rs#L458-L460 Apple and Windows re-compute the uptime each time it is called. https://github.com/GuillaumeGomez/sysinfo/blob/f8574e459d0b1d65ed649cd0897b36422d449217/src/apple/system.rs#L451-L455 https://github.com/GuillaumeGomez/sysinfo/blob/f8574e459d0b1d65ed649cd0897b36422d449217/src/windows/system.rs#L391-L393 Which of these should be the intended behavior?
0.18
509
Linux should be updated to look like the others. Gonna send a PR which will also enforce this behaviour with a test (and thanks for working on freebsd!).
3aa83dc410ebe2f6d5063a095104ea6c6394507f
2021-06-06T19:49:13Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -343,8 +343,14 @@ mod test { if System::IS_SUPPORTED { assert!(!s.get_processors().is_empty()); + assert!( + s.get_physical_core_count() + .expect("failed to get number of physical cores") + <= s.get_processors().len() + ); } else { assert!(s.get_processors().is_empty()); + assert_eq!(s.get_physical_core_count(), None); } } }
[ "502" ]
GuillaumeGomez__sysinfo-503
GuillaumeGomez/sysinfo
diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -166,6 +166,13 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { "processors" => { // Note: you should refresh a few times before using this, so that usage statistics // can be ascertained + writeln!( + &mut io::stdout(), + "number of physical cores: {}", + sys.get_physical_core_count() + .map(|c| c.to_string()) + .unwrap_or_else(|| "Unknown".to_owned()), + ); writeln!( &mut io::stdout(), "total process usage: {}%", diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -8,6 +8,7 @@ use crate::sys::tools::KeyHandler; use crate::{LoadAvg, ProcessorExt}; use std::collections::HashMap; +use std::io::Error; use std::mem; use std::ops::DerefMut; use std::ptr::null_mut; diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -16,7 +17,7 @@ use std::sync::Mutex; use ntapi::ntpoapi::PROCESSOR_POWER_INFORMATION; use winapi::shared::minwindef::FALSE; -use winapi::shared::winerror::ERROR_SUCCESS; +use winapi::shared::winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS}; use winapi::um::handleapi::CloseHandle; use winapi::um::pdh::{ PdhAddCounterW, PdhAddEnglishCounterA, PdhCloseQuery, PdhCollectQueryData, diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -29,8 +30,8 @@ use winapi::um::sysinfoapi::GetLogicalProcessorInformationEx; use winapi::um::sysinfoapi::SYSTEM_INFO; use winapi::um::winbase::{RegisterWaitForSingleObject, INFINITE}; use winapi::um::winnt::{ - ProcessorInformation, BOOLEAN, HANDLE, PVOID, SYSTEM_LOGICAL_PROCESSOR_INFORMATION, - WT_EXECUTEDEFAULT, + ProcessorInformation, RelationAll, RelationProcessorCore, BOOLEAN, HANDLE, + PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PVOID, WT_EXECUTEDEFAULT, }; // This formula comes from linux's include/linux/sched/loadavg.h diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -421,30 +422,51 @@ pub fn get_frequencies(nb_processors: usize) -> Vec<u64> { pub fn get_physical_core_count() -> Option<usize> { // we cannot use the number of processors here to pre calculate the buf size - // GetLogicalProcessorInformationEx with RelationProcessorCore passed to it not only returns the logical cores but also numa nodes + // GetLogicalProcessorInformationEx with RelationProcessorCore passed to it not only returns + // the logical cores but also numa nodes // // GetLogicalProcessorInformationEx: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformationex let mut needed_size = 0; - unsafe { GetLogicalProcessorInformationEx(0, null_mut(), &mut needed_size) }; - let size = mem::size_of::<SYSTEM_LOGICAL_PROCESSOR_INFORMATION>() as u32; - if needed_size == 0 || needed_size < size || needed_size % size != 0 { - return None; + unsafe { GetLogicalProcessorInformationEx(RelationAll, null_mut(), &mut needed_size) }; + + let mut buf: Vec<u8> = Vec::with_capacity(needed_size as _); + + loop { + if unsafe { + GetLogicalProcessorInformationEx( + RelationAll, + buf.as_mut_ptr() as *mut _, + &mut needed_size, + ) + } == FALSE + { + let e = Error::last_os_error(); + // For some reasons, the function might return a size not big enough... + match e.raw_os_error() { + Some(value) if value == ERROR_INSUFFICIENT_BUFFER as _ => {} + _ => return None, + } + } else { + break; + } + buf.reserve(needed_size as usize - buf.capacity()); } - let count = needed_size / size; - let mut buf = Vec::with_capacity(count as _); - - if unsafe { GetLogicalProcessorInformationEx(0, buf.as_mut_ptr(), &mut needed_size) } == 0 { - return None; + unsafe { + buf.set_len(needed_size as _); } - unsafe { - buf.set_len(count as _); + let mut i = 0; + let raw_buf = buf.as_ptr(); + let mut count = 0; + while i < buf.len() { + let p = unsafe { &*(raw_buf.add(i) as PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) }; + i += p.Size as usize; + if p.Relationship == RelationProcessorCore { + // Only count the physical cores. + count += 1; + } } - Some( - buf.iter() - .filter(|proc_info| proc_info.Relationship == 0) // Only get the physical cores - .count(), - ) + Some(count) }
05427d4e26b83be87f64865b3c15c9663e5d2e62
Issue getting processor counts on Windows I was wondering why the physical number of CPUs would show up greater than the number of CPU cores on Windows 10? https://github.com/mikemadden42/inv/blob/master/src/main.rs#L33 ``` # Window 10 21H1 Number of cores: 2 Number of physical processors: 3 ``` ``` Get-WmiObject Win32_Processor | Select-Object Name,NumberOfLogicalProcessors,MaxClockSpeed,L3CacheSize Name NumberOfLogicalProcessors MaxClockSpeed L3CacheSize ---- ------------------------- ------------- ----------- Intel(R) Core(TM) i7-5600U CPU @ 2.60GHz 1 2594 0 Intel(R) Core(TM) i7-5600U CPU @ 2.60GHz 1 2594 0 ```
0.18
503
I get that information there: https://github.com/GuillaumeGomez/sysinfo/blob/master/src/windows/tools.rs#L44-L61. Surprisingly, I initiate the vec with "nb processors + 1" but I don't put an extra one into it. This is weird... My bad, the physical core count is actually there: https://github.com/GuillaumeGomez/sysinfo/blob/master/src/windows/processor.rs#L422-L450 So my guess is that the filter is failing somehow...
3aa83dc410ebe2f6d5063a095104ea6c6394507f
2021-05-12T19:50:07Z
diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -248,3 +274,51 @@ impl NetworkExt for NetworkData { self.tx_errors } } + +#[cfg(test)] +mod test { + use super::refresh_networks_list_from_sysfs; + use std::collections::HashMap; + use std::fs; + + #[test] + fn refresh_networks_list_add_interface() { + let sys_net_dir = tempfile::tempdir().expect("failed to create temporary directory"); + + fs::create_dir(sys_net_dir.path().join("itf1")).expect("failed to create subdirectory"); + + let mut interfaces = HashMap::new(); + + refresh_networks_list_from_sysfs(&mut interfaces, sys_net_dir.path()); + assert_eq!(interfaces.keys().collect::<Vec<_>>(), ["itf1"]); + + fs::create_dir(sys_net_dir.path().join("itf2")).expect("failed to create subdirectory"); + + refresh_networks_list_from_sysfs(&mut interfaces, sys_net_dir.path()); + let mut itf_names: Vec<String> = interfaces.keys().map(|n| n.to_owned()).collect(); + itf_names.sort(); + assert_eq!(itf_names, ["itf1", "itf2"]); + } + + #[test] + fn refresh_networks_list_remove_interface() { + let sys_net_dir = tempfile::tempdir().expect("failed to create temporary directory"); + + let itf1_dir = sys_net_dir.path().join("itf1"); + let itf2_dir = sys_net_dir.path().join("itf2"); + fs::create_dir(&itf1_dir).expect("failed to create subdirectory"); + fs::create_dir(&itf2_dir).expect("failed to create subdirectory"); + + let mut interfaces = HashMap::new(); + + refresh_networks_list_from_sysfs(&mut interfaces, sys_net_dir.path()); + let mut itf_names: Vec<String> = interfaces.keys().map(|n| n.to_owned()).collect(); + itf_names.sort(); + assert_eq!(itf_names, ["itf1", "itf2"]); + + fs::remove_dir(&itf1_dir).expect("failed to remove subdirectory"); + + refresh_networks_list_from_sysfs(&mut interfaces, sys_net_dir.path()); + assert_eq!(interfaces.keys().collect::<Vec<_>>(), ["itf2"]); + } +}
[ "479" ]
GuillaumeGomez__sysinfo-481
GuillaumeGomez/sysinfo
diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -9,7 +9,7 @@ use std::io::Read; use std::path::Path; use crate::{NetworkExt, NetworksExt, NetworksIter}; -use std::collections::HashMap; +use std::collections::{hash_map, HashMap}; /// Network interfaces. /// diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -60,6 +60,73 @@ impl Networks { } } +fn refresh_networks_list_from_sysfs( + interfaces: &mut HashMap<String, NetworkData>, + sysfs_net: &Path, +) { + if let Ok(dir) = std::fs::read_dir(sysfs_net) { + let mut data = vec![0; 30]; + + for stats in interfaces.values_mut() { + stats.updated = false; + } + + for entry in dir.flatten() { + let parent = &entry.path().join("statistics"); + let entry = match entry.file_name().into_string() { + Ok(entry) => entry, + Err(_) => continue, + }; + let rx_bytes = read(parent, "rx_bytes", &mut data); + let tx_bytes = read(parent, "tx_bytes", &mut data); + let rx_packets = read(parent, "rx_packets", &mut data); + let tx_packets = read(parent, "tx_packets", &mut data); + let rx_errors = read(parent, "rx_errors", &mut data); + let tx_errors = read(parent, "tx_errors", &mut data); + // let rx_compressed = read(parent, "rx_compressed", &mut data); + // let tx_compressed = read(parent, "tx_compressed", &mut data); + match interfaces.entry(entry) { + hash_map::Entry::Occupied(mut e) => { + let mut interface = e.get_mut(); + old_and_new!(interface, rx_bytes, old_rx_bytes); + old_and_new!(interface, tx_bytes, old_tx_bytes); + old_and_new!(interface, rx_packets, old_rx_packets); + old_and_new!(interface, tx_packets, old_tx_packets); + old_and_new!(interface, rx_errors, old_rx_errors); + 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); + interface.updated = true; + } + hash_map::Entry::Vacant(e) => { + e.insert(NetworkData { + rx_bytes, + old_rx_bytes: rx_bytes, + tx_bytes, + old_tx_bytes: tx_bytes, + rx_packets, + old_rx_packets: rx_packets, + tx_packets, + old_tx_packets: tx_packets, + rx_errors, + old_rx_errors: rx_errors, + tx_errors, + old_tx_errors: tx_errors, + // rx_compressed, + // old_rx_compressed: rx_compressed, + // tx_compressed, + // old_tx_compressed: tx_compressed, + updated: true, + }); + } + }; + } + + // Remove interfaces that are gone + interfaces.retain(|_n, d| d.updated); + } +} + impl NetworksExt for Networks { fn iter(&self) -> NetworksIter { NetworksIter::new(self.interfaces.iter()) diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -74,50 +141,7 @@ impl NetworksExt for Networks { } fn refresh_networks_list(&mut self) { - if let Ok(dir) = std::fs::read_dir("/sys/class/net/") { - let mut data = vec![0; 30]; - for entry in dir.flatten() { - let parent = &entry.path().join("statistics"); - let entry = match entry.file_name().into_string() { - Ok(entry) => entry, - Err(_) => continue, - }; - let rx_bytes = read(parent, "rx_bytes", &mut data); - let tx_bytes = read(parent, "tx_bytes", &mut data); - let rx_packets = read(parent, "rx_packets", &mut data); - let tx_packets = read(parent, "tx_packets", &mut data); - let rx_errors = read(parent, "rx_errors", &mut data); - let tx_errors = read(parent, "tx_errors", &mut data); - // let rx_compressed = read(parent, "rx_compressed", &mut data); - // let tx_compressed = read(parent, "tx_compressed", &mut data); - let interface = self.interfaces.entry(entry).or_insert_with(|| NetworkData { - rx_bytes, - old_rx_bytes: rx_bytes, - tx_bytes, - old_tx_bytes: tx_bytes, - rx_packets, - old_rx_packets: rx_packets, - tx_packets, - old_tx_packets: tx_packets, - rx_errors, - old_rx_errors: rx_errors, - tx_errors, - old_tx_errors: tx_errors, - // rx_compressed, - // old_rx_compressed: rx_compressed, - // tx_compressed, - // old_tx_compressed: tx_compressed, - }); - old_and_new!(interface, rx_bytes, old_rx_bytes); - old_and_new!(interface, tx_bytes, old_tx_bytes); - old_and_new!(interface, rx_packets, old_rx_packets); - old_and_new!(interface, tx_packets, old_tx_packets); - old_and_new!(interface, rx_errors, old_rx_errors); - old_and_new!(interface, tx_errors, old_tx_errors); - // old_and_new!(interface, rx_compressed, old_rx_compressed); - // old_and_new!(interface, tx_compressed, old_tx_compressed); - } - } + refresh_networks_list_from_sysfs(&mut self.interfaces, Path::new("/sys/class/net/")); } } diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -153,6 +177,8 @@ pub struct NetworkData { // /// compression (e.g: PPP). // tx_compressed: usize, // old_tx_compressed: usize, + /// Whether or not the above data has been updated during refresh + updated: bool, } impl NetworkData {
190926a97e50c2abf1b155ea59abba1c23f4ebf0
[Linux] get_networks keeps returning removed interfaces Using `get_networks` with calls to `refresh_networks_list`, new network interfaces are picked up, however they are still returned when they are removed from the system. Small program to reproduce: ``` use std::thread::sleep; use std::time::Duration; use sysinfo::{NetworksExt, RefreshKind, System, SystemExt}; fn main() { let mut system: System = SystemExt::new_with_specifics(RefreshKind::new().with_networks_list()); loop { let interface_names: Vec<String> = system .get_networks() .iter() .map(|i| i.0.to_owned()) .collect(); println!("{:?}", interface_names); system.refresh_networks_list(); sleep(Duration::from_secs(1)); } } ``` Then run the program, and create a dummy interface, ie with: ``` sudo modprobe dummy sudo ip link add dummy1 type dummy ``` The new interface is picked up by the program, however when you remove it with `ip link del dummy1`, the removal is not.
0.17
481
I only gave a quick look, but I think the `self.interface` HashMap needs to be cleared in the beginning of `refresh_networks_list` https://github.com/GuillaumeGomez/sysinfo/blob/master/src/linux/network.rs#L76 Thanks for the issue! The simpler fix here would be to do it in two passes: we first we check if all our network interfaces still exist, then we add the new ones. The idea is to not clear the associated data we have. Also, do you want to send a fix with a test maybe? :)
190926a97e50c2abf1b155ea59abba1c23f4ebf0
2021-03-17T13:54:47Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -208,6 +208,29 @@ mod test { assert!(s.get_users().len() >= MIN_USERS); } + #[test] + fn check_uid_gid() { + let mut s = System::new(); + assert!(s.get_users().is_empty()); + s.refresh_users_list(); + let users = s.get_users(); + assert!(users.len() >= MIN_USERS); + + for user in users { + match user.get_name() { + "root" => { + assert_eq!(*user.get_uid(), 0); + assert_eq!(*user.get_gid(), 0); + } + _ => { + assert!(*user.get_uid() > 0); + #[cfg(not(target_os = "windows"))] + assert!(*user.get_gid() > 0); + } + } + } + } + #[test] fn check_system_info() { // We don't want to test on unknown systems.
[ "167" ]
GuillaumeGomez__sysinfo-449
GuillaumeGomez/sysinfo
diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -4,7 +4,10 @@ // Copyright (c) 2020 Guillaume Gomez // -use crate::User; +use crate::{ + common::{Gid, Uid}, + User, +}; use crate::sys::utils; use libc::{c_char, endpwent, getgrgid, getgrouplist, getpwent, gid_t, setpwent, strlen}; diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -65,8 +68,15 @@ where continue; } let groups = get_user_groups(unsafe { (*pw).pw_name }, unsafe { (*pw).pw_gid }); + let uid = unsafe { (*pw).pw_uid }; + let gid = unsafe { (*pw).pw_gid }; if let Some(name) = utils::cstr_to_rust(unsafe { (*pw).pw_name }) { - users.push(User { name, groups }); + users.push(User { + uid: Uid(uid), + gid: Gid(gid), + name, + groups, + }); } } unsafe { endpwent() }; diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -355,6 +355,50 @@ pub struct LoadAvg { pub fifteen: f64, } +macro_rules! xid { + ($(#[$outer:meta])+ $name:ident, $type:ty) => { + $(#[$outer])+ + #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] + pub struct $name(pub(crate) $type); + + impl std::ops::Deref for $name { + type Target = $type; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + }; +} + +#[cfg(not(target_os = "windows"))] +xid!( + /// A user id wrapping a platform specific type + Uid, + libc::uid_t +); + +#[cfg(target_os = "windows")] +xid!( + /// A user id wrapping a platform specific type + Uid, + u32 +); + +#[cfg(not(target_os = "windows"))] +xid!( + /// A group id wrapping a platform specific type + Gid, + libc::gid_t +); + +#[cfg(target_os = "windows")] +xid!( + /// A group id wrapping a platform specific type + Gid, + u32 +); + /// Type containing user information. /// /// It is returned by [`SystemExt::get_users`][crate::SystemExt::get_users]. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -367,11 +411,21 @@ pub struct LoadAvg { /// ``` #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct User { + pub(crate) uid: Uid, + pub(crate) gid: Gid, pub(crate) name: String, pub(crate) groups: Vec<String>, } impl UserExt for User { + fn get_uid(&self) -> Uid { + self.uid + } + + fn get_gid(&self) -> Gid { + self.gid + } + fn get_name(&self) -> &str { &self.name } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -107,7 +107,7 @@ cfg_if::cfg_if! { } pub use common::{ - AsU32, DiskType, DiskUsage, LoadAvg, NetworksIter, Pid, RefreshKind, Signal, User, + AsU32, DiskType, DiskUsage, Gid, LoadAvg, NetworksIter, Pid, RefreshKind, Signal, Uid, User, }; pub use sys::{Component, Disk, NetworkData, Networks, Process, ProcessStatus, Processor, System}; pub use traits::{ diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -787,7 +787,7 @@ enum InfoType { #[cfg(not(target_os = "android"))] fn get_system_info(info: InfoType) -> Option<String> { - let info = match info { + let info_str = match info { InfoType::Name => "NAME=", InfoType::OsVersion => "VERSION_ID=", }; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -795,7 +795,7 @@ fn get_system_info(info: InfoType) -> Option<String> { let buf = BufReader::new(File::open("/etc/os-release").ok()?); for line in buf.lines().flatten() { - if let Some(stripped) = line.strip_prefix(info) { + if let Some(stripped) = line.strip_prefix(info_str) { return Some(stripped.replace("\"", "")); } } diff --git a/src/linux/users.rs b/src/linux/users.rs --- a/src/linux/users.rs +++ b/src/linux/users.rs @@ -4,7 +4,10 @@ // Copyright (c) 2020 Guillaume Gomez // -use crate::User; +use crate::{ + common::{Gid, Uid}, + User, +}; use libc::{getgrgid, getgrouplist}; use std::fs::File; diff --git a/src/linux/users.rs b/src/linux/users.rs --- a/src/linux/users.rs +++ b/src/linux/users.rs @@ -20,63 +23,68 @@ pub fn get_users_list() -> Vec<User> { .filter_map(|line| { let mut parts = line.split(':'); if let Some(username) = parts.next() { - let mut parts = parts.skip(2); - if let Some(group_id) = parts.next().and_then(|x| x.parse::<u32>().ok()) { - if let Some(command) = parts.last() { - if command.is_empty() - || command.ends_with("/false") - || command.ends_with("/nologin") - { - // We don't want "fake" users so in case the user command is "bad", we - // ignore this user. - return None; - } - let mut c_user = username.as_bytes().to_vec(); - c_user.push(0); - loop { - let mut current = ngroups; - if unsafe { - getgrouplist( - c_user.as_ptr() as *const _, - group_id, - groups.as_mut_ptr(), - &mut current, - ) - } == -1 + let mut parts = parts.skip(1); + // Skip the user if the uid cannot be parsed correctly + if let Some(uid) = parts.next().and_then(parse_id) { + if let Some(group_id) = parts.next().and_then(parse_id) { + if let Some(command) = parts.last() { + if command.is_empty() + || command.ends_with("/false") + || command.ends_with("/nologin") { - if current > ngroups { - groups.resize(current as _, 0); - ngroups = current; - continue; - } - // It really failed, let's move on... + // We don't want "fake" users so in case the user command is "bad", we + // ignore this user. return None; } - // Let's get all the group names! - return Some(User { - name: username.to_owned(), - groups: groups[..current as usize] - .iter() - .filter_map(|id| { - let g = unsafe { getgrgid(*id as _) }; - if g.is_null() { - return None; - } - let mut group_name = Vec::new(); - let c_group_name = unsafe { (*g).gr_name }; - let mut x = 0; - loop { - let c = unsafe { *c_group_name.offset(x) }; - if c == 0 { - break; + let mut c_user = username.as_bytes().to_vec(); + c_user.push(0); + loop { + let mut current = ngroups; + if unsafe { + getgrouplist( + c_user.as_ptr() as *const _, + group_id, + groups.as_mut_ptr(), + &mut current, + ) + } == -1 + { + if current > ngroups { + groups.resize(current as _, 0); + ngroups = current; + continue; + } + // It really failed, let's move on... + return None; + } + // Let's get all the group names! + return Some(User { + uid: Uid(uid), + gid: Gid(group_id), + name: username.to_owned(), + groups: groups[..current as usize] + .iter() + .filter_map(|id| { + let g = unsafe { getgrgid(*id as _) }; + if g.is_null() { + return None; + } + let mut group_name = Vec::new(); + let c_group_name = unsafe { (*g).gr_name }; + let mut x = 0; + loop { + let c = unsafe { *c_group_name.offset(x) }; + if c == 0 { + break; + } + group_name.push(c as u8); + x += 1; } - group_name.push(c as u8); - x += 1; - } - String::from_utf8(group_name).ok() - }) - .collect(), - }); + String::from_utf8(group_name).ok() + }) + .collect(), + }); + } } } } diff --git a/src/linux/users.rs b/src/linux/users.rs --- a/src/linux/users.rs +++ b/src/linux/users.rs @@ -85,3 +93,7 @@ pub fn get_users_list() -> Vec<User> { }) .collect() } + +fn parse_id(id: &str) -> Option<u32> { + id.parse::<u32>().ok() +} diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -4,7 +4,10 @@ // Copyright (c) 2017 Guillaume Gomez // -use crate::sys::{Component, Disk, Networks, Process, Processor}; +use crate::{ + common::{Gid, Uid}, + sys::{Component, Disk, Networks, Process, Processor}, +}; use crate::{ DiskType, DiskUsage, LoadAvg, NetworksIter, Pid, ProcessStatus, RefreshKind, Signal, User, }; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1283,6 +1286,35 @@ pub trait ComponentExt: Debug { /// } /// ``` pub trait UserExt: Debug { + /// Return the user id of the user. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt, UserExt}; + /// + /// let mut s = System::new_all(); + /// for user in s.get_users() { + /// println!("{}", *user.get_uid()); + /// } + /// ``` + fn get_uid(&self) -> Uid; + + /// Return the group id of the user. + /// + /// *NOTE* - On Windows, this value defaults to 0. Windows doesn't have a `username` specific group assigned to the user. + /// They do however have unique [Security Identifiers](https://docs.microsoft.com/en-us/windows/win32/secauthz/security-identifiers) + /// made up of various [Components](https://docs.microsoft.com/en-us/windows/win32/secauthz/sid-components). + /// Pieces of the SID may be a candidate for this field, but it doesn't map well to a single group id. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt, UserExt}; + /// + /// let mut s = System::new_all(); + /// for user in s.get_users() { + /// println!("{}", *user.get_gid()); + /// } + /// ``` + fn get_gid(&self) -> Gid; + /// Returns the name of the user. /// /// ```no_run diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -5,7 +5,10 @@ // use crate::sys::ffi::NetUserGetLocalGroups; -use crate::User; +use crate::{ + common::{Gid, Uid}, + User, +}; use winapi::shared::lmcons::MAX_PREFERRED_LENGTH; use winapi::shared::winerror::{ERROR_MORE_DATA, ERROR_SUCCESS}; diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -99,6 +102,8 @@ pub unsafe fn get_users() -> Vec<User> { if (*buf).usri1_flags & UF_NORMAL_ACCOUNT != 0 { let groups = get_groups_for_user((*buf).usri1_name); users.push(User { + uid: Uid((*buf).usri1_user_id), + gid: Gid(0), name: to_str((*buf).usri1_name), groups, });
58b31e3a5d2821fb0483125220331b3afab5cd11
Add user id and group id
0.16
449
58b31e3a5d2821fb0483125220331b3afab5cd11
2021-01-26T15:07:08Z
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -185,11 +185,11 @@ pub fn set_open_files_limit(mut _new_limit: isize) -> bool { #[cfg(test)] mod test { - use super::*; + use crate::*; #[test] fn check_memory_usage() { - let mut s = ::System::new(); + let mut s = System::new(); s.refresh_all(); assert_eq!( diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -202,17 +202,17 @@ mod test { #[test] fn check_users() { - let mut s = ::System::new(); + let mut s = System::new(); assert!(s.get_users().is_empty()); s.refresh_users_list(); assert!(s.get_users().len() >= MIN_USERS); - let mut s = ::System::new(); + let mut s = System::new(); assert!(s.get_users().is_empty()); s.refresh_all(); assert!(s.get_users().is_empty()); - let s = ::System::new_all(); + let s = System::new_all(); assert!(s.get_users().len() >= MIN_USERS); } diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -220,7 +220,7 @@ mod test { fn check_system_info() { // We don't want to test on unknown systems. if MIN_USERS > 0 { - let s = ::System::new(); + let s = System::new(); assert!(!s.get_name().expect("Failed to get system name").is_empty()); assert!(!s .get_version() diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -233,7 +233,7 @@ mod test { fn check_host_name() { // We don't want to test on unknown systems. if MIN_USERS > 0 { - let s = ::System::new(); + let s = System::new(); assert!(!s .get_host_name() .expect("Failed to get host name") diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -9,8 +9,7 @@ #[cfg(test)] mod tests { - use utils; - use {ProcessExt, System, SystemExt}; + use crate::{utils, ProcessExt, System, SystemExt}; #[test] fn test_refresh_system() {
[ "403" ]
GuillaumeGomez__sysinfo-417
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ readme = "README.md" categories = ["filesystem", "os", "api-bindings"] build = "build.rs" +edition = "2018" [dependencies] cfg-if = "1.0" diff --git a/src/apple/component.rs b/src/apple/component.rs --- a/src/apple/component.rs +++ b/src/apple/component.rs @@ -4,4 +4,4 @@ // Copyright (c) 2021 Guillaume Gomez // -pub use sys::inner::component::*; +pub use crate::sys::inner::component::*; diff --git a/src/apple/disk.rs b/src/apple/disk.rs --- a/src/apple/disk.rs +++ b/src/apple/disk.rs @@ -4,17 +4,16 @@ // Copyright (c) 2017 Guillaume Gomez // -use DiskExt; -use DiskType; +use crate::utils::to_cpath; +use crate::{DiskExt, DiskType}; + +#[cfg(target_os = "macos")] +pub(crate) use crate::sys::inner::disk::*; use libc::statfs; use std::ffi::{OsStr, OsString}; use std::mem; use std::path::{Path, PathBuf}; -use utils::to_cpath; - -#[cfg(target_os = "macos")] -pub(crate) use sys::inner::disk::*; /// Struct containing a disk information. pub struct Disk { diff --git a/src/apple/ffi.rs b/src/apple/ffi.rs --- a/src/apple/ffi.rs +++ b/src/apple/ffi.rs @@ -7,7 +7,7 @@ use libc::{c_int, c_uchar, c_uint, c_ushort, c_void}; // Reexport items defined in either macos or ios ffi module. -pub use sys::inner::ffi::*; +pub use crate::sys::inner::ffi::*; extern "C" { pub fn proc_pidinfo( diff --git a/src/apple/ffi.rs b/src/apple/ffi.rs --- a/src/apple/ffi.rs +++ b/src/apple/ffi.rs @@ -84,7 +84,7 @@ macro_rules! __cfg_if_apply { // TODO: waiting for https://github.com/rust-lang/libc/pull/678 cfg_if! { if #[cfg(any(target_arch = "arm", target_arch = "x86"))] { - pub type timeval32 = ::libc::timeval; + pub type timeval32 = libc::timeval; } else { use libc::timeval32; } diff --git a/src/apple/ios/component.rs b/src/apple/ios/component.rs --- a/src/apple/ios/component.rs +++ b/src/apple/ios/component.rs @@ -4,7 +4,7 @@ // Copyright (c) 2018 Guillaume Gomez // -use ComponentExt; +use crate::ComponentExt; /// Dummy struct representing a component since iOS doesn't support /// obtaining CPU information. diff --git a/src/apple/macos/component.rs b/src/apple/macos/component.rs --- a/src/apple/macos/component.rs +++ b/src/apple/macos/component.rs @@ -4,10 +4,12 @@ // Copyright (c) 2018 Guillaume Gomez // +use crate::sys::ffi; +use crate::ComponentExt; + use libc::{c_char, c_int, c_void}; + use std::mem; -use sys::ffi; -use ComponentExt; pub(crate) const COMPONENTS_TEMPERATURE_IDS: &[(&str, &[i8])] = &[ ("PECI CPU", &['T' as i8, 'C' as i8, 'X' as i8, 'C' as i8]), // PECI CPU "TCXC" diff --git a/src/apple/macos/disk.rs b/src/apple/macos/disk.rs --- a/src/apple/macos/disk.rs +++ b/src/apple/macos/disk.rs @@ -4,10 +4,9 @@ // Copyright (c) 2017 Guillaume Gomez // -use sys::utils; -use utils::to_cpath; -use Disk; -use DiskType; +use crate::sys::{ffi, utils}; +use crate::utils::to_cpath; +use crate::{Disk, DiskType}; use core_foundation_sys::array::{CFArrayGetCount, CFArrayGetValueAtIndex}; use core_foundation_sys::base::{kCFAllocatorDefault, kCFAllocatorNull, CFRelease}; diff --git a/src/apple/macos/disk.rs b/src/apple/macos/disk.rs --- a/src/apple/macos/disk.rs +++ b/src/apple/macos/disk.rs @@ -15,13 +14,14 @@ use core_foundation_sys::dictionary::{CFDictionaryGetValueIfPresent, CFDictionar use core_foundation_sys::number::{kCFBooleanTrue, CFBooleanRef}; use core_foundation_sys::string as cfs; use core_foundation_sys::url::{CFURLGetFileSystemRepresentation, CFURLRef}; + use libc::{c_char, c_void, statfs, strlen, PATH_MAX}; + use std::ffi::{OsStr, OsString}; use std::mem; use std::os::unix::ffi::OsStrExt; use std::path::PathBuf; use std::ptr; -use sys::ffi; unsafe fn to_path(url: CFURLRef) -> Option<PathBuf> { let mut buf = [0u8; PATH_MAX as usize]; diff --git a/src/apple/macos/disk.rs b/src/apple/macos/disk.rs --- a/src/apple/macos/disk.rs +++ b/src/apple/macos/disk.rs @@ -56,7 +56,7 @@ pub(crate) fn get_disks(session: ffi::DASessionRef) -> Vec<Disk> { if !dict.is_null() { // Keeping this around in case one might want the list of the available // keys in "dict". - // ::core_foundation::base::CFShow(dict as _); + // core_foundation::base::CFShow(dict as _); let name = match get_str_value(dict, b"DAMediaName\0").map(OsString::from) { Some(n) => n, None => continue, diff --git a/src/apple/macos/disk.rs b/src/apple/macos/disk.rs --- a/src/apple/macos/disk.rs +++ b/src/apple/macos/disk.rs @@ -104,7 +104,7 @@ unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( cfs::kCFStringEncodingUTF8, kCFAllocatorNull as _, ); - let mut value = ::std::ptr::null(); + let mut value = std::ptr::null(); let ret = if CFDictionaryGetValueIfPresent(dict, key as _, &mut value) != 0 { callback(value) } else { diff --git a/src/apple/macos/ffi.rs b/src/apple/macos/ffi.rs --- a/src/apple/macos/ffi.rs +++ b/src/apple/macos/ffi.rs @@ -9,6 +9,7 @@ use core_foundation_sys::base::CFAllocatorRef; use core_foundation_sys::dictionary::CFMutableDictionaryRef; use core_foundation_sys::string::{CFStringEncoding, CFStringRef}; use core_foundation_sys::url::CFURLRef; + use libc::{c_char, c_void, size_t}; pub(crate) use crate::sys::ffi::*; diff --git a/src/apple/network.rs b/src/apple/network.rs --- a/src/apple/network.rs +++ b/src/apple/network.rs @@ -4,15 +4,14 @@ // Copyright (c) 2017 Guillaume Gomez // +use crate::sys::ffi; + use libc::{self, c_char, CTL_NET, NET_RT_IFLIST2, PF_ROUTE, RTM_IFINFO2}; use std::collections::HashMap; use std::ptr::null_mut; -use sys::ffi; -use NetworkExt; -use NetworksExt; -use NetworksIter; +use crate::{NetworkExt, NetworksExt, NetworksIter}; macro_rules! old_and_new { ($ty_:expr, $name:ident, $old:ident, $new_val:expr) => {{ diff --git a/src/apple/process.rs b/src/apple/process.rs --- a/src/apple/process.rs +++ b/src/apple/process.rs @@ -12,12 +12,10 @@ use std::path::{Path, PathBuf}; use libc::{c_int, c_void, gid_t, kill, size_t, uid_t}; -use DiskUsage; -use Pid; -use ProcessExt; +use crate::{DiskUsage, Pid, ProcessExt, Signal}; -use sys::ffi; -use sys::system::Wrap; +use crate::sys::ffi; +use crate::sys::system::Wrap; /// Enum describing the different status of a process. #[derive(Clone, Copy, Debug)] diff --git a/src/apple/process.rs b/src/apple/process.rs --- a/src/apple/process.rs +++ b/src/apple/process.rs @@ -258,7 +256,7 @@ impl ProcessExt for Process { } } - fn kill(&self, signal: ::Signal) -> bool { + fn kill(&self, signal: Signal) -> bool { unsafe { kill(self.pid, signal as c_int) == 0 } } diff --git a/src/apple/process.rs b/src/apple/process.rs --- a/src/apple/process.rs +++ b/src/apple/process.rs @@ -496,7 +494,7 @@ pub(crate) fn update_process( 3, ptr as *mut c_void, &mut size, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, ) == -1 { diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -4,14 +4,15 @@ // Copyright (c) 2015 Guillaume Gomez // +use crate::sys::ffi; +use crate::sys::system::get_sys_value; + +use crate::ProcessorExt; + use libc::{c_char, c_void}; use std::mem; use std::ops::Deref; use std::sync::Arc; -use sys::ffi; -use sys::system::get_sys_value; - -use ProcessorExt; pub struct UnsafePtr<T>(*mut T); diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -43,11 +44,11 @@ impl ProcessorData { impl Drop for ProcessorData { fn drop(&mut self) { if !self.cpu_info.0.is_null() { - let prev_cpu_info_size = ::std::mem::size_of::<i32>() as u32 * self.num_cpu_info; + let prev_cpu_info_size = std::mem::size_of::<i32>() as u32 * self.num_cpu_info; unsafe { ffi::vm_deallocate(ffi::mach_task_self(), self.cpu_info.0, prev_cpu_info_size); } - self.cpu_info.0 = ::std::ptr::null_mut(); + self.cpu_info.0 = std::ptr::null_mut(); } } } diff --git a/src/apple/processor.rs b/src/apple/processor.rs --- a/src/apple/processor.rs +++ b/src/apple/processor.rs @@ -153,7 +154,7 @@ pub fn init_processors(port: ffi::mach_port_t) -> (Processor, Vec<Processor>) { } let mut num_cpu_u = 0u32; - let mut cpu_info: *mut i32 = ::std::ptr::null_mut(); + let mut cpu_info: *mut i32 = std::ptr::null_mut(); let mut num_cpu_info = 0u32; if ffi::host_processor_info( diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -4,26 +4,25 @@ // Copyright (c) 2015 Guillaume Gomez // +use crate::sys::component::Component; +use crate::sys::disk::*; +use crate::sys::ffi; +use crate::sys::network::Networks; +use crate::sys::process::*; +use crate::sys::processor::*; #[cfg(target_os = "macos")] use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease}; -use libc::c_char; -use sys::component::Component; -use sys::disk::*; -use sys::ffi; -use sys::network::Networks; -use sys::process::*; -use sys::processor::*; -use {LoadAvg, Pid, ProcessExt, ProcessorExt, RefreshKind, SystemExt, User}; +use crate::utils::into_iter; + +use crate::{LoadAvg, Pid, ProcessExt, ProcessorExt, RefreshKind, SystemExt, User}; use std::cell::UnsafeCell; use std::collections::HashMap; use std::mem; use std::sync::Arc; -use libc::{self, c_int, c_void, size_t, sysconf, _SC_PAGESIZE}; - -use utils::into_iter; +use libc::{self, c_char, c_int, c_void, size_t, sysconf, _SC_PAGESIZE}; /// Structs containing system's information. pub struct System { diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -94,7 +93,7 @@ fn boot_time() -> u64 { tv_sec: 0, tv_usec: 0, }; - let mut len = ::std::mem::size_of::<libc::timeval>(); + let mut len = std::mem::size_of::<libc::timeval>(); let mut mib: [libc::c_int; 2] = [libc::CTL_KERN, libc::KERN_BOOTTIME]; if unsafe { libc::sysctl( diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -102,7 +101,7 @@ fn boot_time() -> u64 { 2, &mut boot_time as *mut libc::timeval as *mut _, &mut len, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, ) } < 0 diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -224,7 +223,7 @@ impl SystemExt for System { fn refresh_cpu(&mut self) { // get processor values let mut num_cpu_u = 0u32; - let mut cpu_info: *mut i32 = ::std::ptr::null_mut(); + let mut cpu_info: *mut i32 = std::ptr::null_mut(); let mut num_cpu_info = 0u32; let mut pourcent = 0f32; diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -508,7 +507,7 @@ fn get_arg_max() -> usize { 2, (&mut arg_max) as *mut i32 as *mut c_void, &mut size, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, ) == -1 { diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -533,7 +532,7 @@ pub(crate) unsafe fn get_sys_value( 2, value, &mut len as *mut usize, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, ) == 0 } diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -543,7 +542,7 @@ unsafe fn get_sys_value_by_name(name: &[u8], mut len: usize, value: *mut libc::c name.as_ptr() as *const c_char, value, &mut len, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, ) == 0 } diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -559,7 +558,7 @@ fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> { 2, buf.as_mut_ptr() as _, &mut size, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, ) } == -1 diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -6,8 +6,8 @@ use crate::User; +use crate::sys::utils; use libc::{c_char, endpwent, getgrgid, getgrouplist, getpwent, gid_t, setpwent, strlen}; -use sys::utils; fn get_user_groups(name: *const c_char, group_id: gid_t) -> Vec<String> { let mut add = 0; diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -86,7 +86,7 @@ pub fn get_users_list() -> Vec<User> { // unsafe { // let node_name = ffi::CFStringCreateWithCStringNoCopy( -// ::std::ptr::null_mut(), +// std::ptr::null_mut(), // node_name.as_ptr() as *const c_char, // ffi::kCFStringEncodingMacRoman, // ffi::kCFAllocatorNull as *mut c_void, diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -95,18 +95,18 @@ pub fn get_users_list() -> Vec<User> { // ffi::kCFAllocatorDefault, // ffi::kODSessionDefault, // node_name, -// ::std::ptr::null_mut(), +// std::ptr::null_mut(), // ); // let query = ffi::ODQueryCreateWithNode( // ffi::kCFAllocatorDefault, // node_ref, // ffi::kODRecordTypeUsers as _, // kODRecordTypeGroups -// ::std::ptr::null(), +// std::ptr::null(), // 0, -// ::std::ptr::null(), -// ::std::ptr::null(), +// std::ptr::null(), +// std::ptr::null(), // 0, -// ::std::ptr::null_mut(), +// std::ptr::null_mut(), // ); // if query.is_null() { // return users; diff --git a/src/apple/users.rs b/src/apple/users.rs --- a/src/apple/users.rs +++ b/src/apple/users.rs @@ -114,7 +114,7 @@ pub fn get_users_list() -> Vec<User> { // let results = ffi::ODQueryCopyResults( // query, // false as _, -// ::std::ptr::null_mut(), +// std::ptr::null_mut(), // ); // let len = ffi::CFArrayGetCount(results); // for i in 0..len { diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -306,7 +306,7 @@ pub extern "C" fn sysinfo_get_process_by_pid(system: CSystem, pid: pid_t) -> CPr let ret = if let Some(process) = system.get_process(pid) { process as *const Process as CProcess } else { - ::std::ptr::null() + std::ptr::null() }; Box::into_raw(system); ret diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -391,7 +391,7 @@ pub extern "C" fn sysinfo_process_get_executable_path(process: CProcess) -> RStr return c.into_raw() as _; } } - ::std::ptr::null() + std::ptr::null() } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -406,7 +406,7 @@ pub extern "C" fn sysinfo_process_get_root_directory(process: CProcess) -> RStri return c.into_raw() as _; } } - ::std::ptr::null() + std::ptr::null() } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -421,7 +421,7 @@ pub extern "C" fn sysinfo_process_get_current_directory(process: CProcess) -> RS return c.into_raw() as _; } } - ::std::ptr::null() + std::ptr::null() } } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -4,10 +4,7 @@ // Copyright (c) 2015 Guillaume Gomez // -use NetworkData; -use Networks; -use NetworksExt; -use UserExt; +use crate::{NetworkData, Networks, NetworksExt, UserExt}; /// Trait to have a common fallback for the [`Pid`][crate::Pid] type. pub trait AsU32 { diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -4,20 +4,10 @@ // Copyright (c) 2020 Guillaume Gomez // -use Component; -use ComponentExt; -use Disk; -use DiskExt; -use NetworkData; -use NetworkExt; -use Networks; -use NetworksExt; -use Process; -use ProcessExt; -use Processor; -use ProcessorExt; -use System; -use SystemExt; +use crate::{ + Component, ComponentExt, Disk, DiskExt, NetworkData, NetworkExt, Networks, NetworksExt, + Process, ProcessExt, Processor, ProcessorExt, System, SystemExt, +}; use std::fmt; diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -4,7 +4,7 @@ // Copyright (c) 2018 Guillaume Gomez // -use ComponentExt; +use crate::ComponentExt; use std::collections::HashMap; use std::fs::{metadata, read_dir, File}; diff --git a/src/linux/disk.rs b/src/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/linux/disk.rs @@ -4,10 +4,8 @@ // Copyright (c) 2017 Guillaume Gomez // -use super::system::get_all_data; -use utils; -use DiskExt; -use DiskType; +use crate::sys::system::get_all_data; +use crate::{utils, DiskExt, DiskType}; use libc::statvfs; use std::ffi::{OsStr, OsString}; diff --git a/src/linux/network.rs b/src/linux/network.rs --- a/src/linux/network.rs +++ b/src/linux/network.rs @@ -8,10 +8,8 @@ use std::fs::File; use std::io::Read; use std::path::Path; +use crate::{NetworkExt, NetworksExt, NetworksIter}; use std::collections::HashMap; -use NetworkExt; -use NetworksExt; -use NetworksIter; /// Network interfaces. /// diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -11,9 +11,7 @@ use std::path::{Path, PathBuf}; use libc::{c_int, gid_t, kill, uid_t}; -use DiskUsage; -use Pid; -use ProcessExt; +use crate::{DiskUsage, Pid, ProcessExt, Signal}; /// Enum describing the different status of a process. #[derive(Clone, Copy, Debug)] diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -167,7 +165,7 @@ impl ProcessExt for Process { } } - fn kill(&self, signal: ::Signal) -> bool { + fn kill(&self, signal: Signal) -> bool { unsafe { kill(self.pid, signal as c_int) == 0 } } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -238,7 +236,7 @@ impl ProcessExt for Process { impl Drop for Process { fn drop(&mut self) { if self.stat_file.is_some() { - if let Ok(ref mut x) = unsafe { ::linux::system::REMAINING_FILES.lock() } { + if let Ok(ref mut x) = unsafe { crate::sys::system::REMAINING_FILES.lock() } { **x += 1; } } diff --git a/src/linux/processor.rs b/src/linux/processor.rs --- a/src/linux/processor.rs +++ b/src/linux/processor.rs @@ -10,7 +10,7 @@ use std::collections::HashSet; use std::fs::File; use std::io::Read; -use ProcessorExt; +use crate::ProcessorExt; /// Struct containing values to compute a CPU usage. #[derive(Clone, Copy)] diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -4,17 +4,11 @@ // Copyright (c) 2015 Guillaume Gomez // -use sys::component::{self, Component}; -use sys::disk; -use sys::process::*; -use sys::processor::*; - -use Disk; -use LoadAvg; -use Networks; -use Pid; -use User; -use {ProcessExt, RefreshKind, SystemExt}; +use crate::sys::component::{self, Component}; +use crate::sys::disk; +use crate::sys::process::*; +use crate::sys::processor::*; +use crate::{Disk, LoadAvg, Networks, Pid, ProcessExt, RefreshKind, SystemExt, User}; use libc::{self, c_char, gid_t, sysconf, uid_t, _SC_CLK_TCK, _SC_HOST_NAME_MAX, _SC_PAGESIZE}; use std::cell::UnsafeCell; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -26,8 +20,7 @@ use std::str::FromStr; use std::sync::{Arc, Mutex}; use std::time::SystemTime; -use utils::into_iter; -use utils::realpath; +use crate::utils::{into_iter, realpath}; // This whole thing is to prevent having too many files open at once. It could be problematic // for processes using a lot of files and using sysinfo at the same time. diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -91,7 +84,7 @@ pub(crate) fn get_max_nb_fds() -> isize { macro_rules! to_str { ($e:expr) => { - unsafe { ::std::str::from_utf8_unchecked($e) } + unsafe { std::str::from_utf8_unchecked($e) } }; } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -829,7 +822,7 @@ fn _get_process_data( let mut tmp = PathBuf::from(path); tmp.push("stat"); - let mut file = ::std::fs::File::open(&tmp).map_err(|_| ())?; + let mut file = std::fs::File::open(&tmp).map_err(|_| ())?; let data = get_all_data_from_file(&mut file, 1024).map_err(|_| ())?; let stat_file = check_nb_open_files(file); let parts = parse_stat_file(&data)?; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -929,8 +922,8 @@ fn copy_from_file(entry: &Path) -> Vec<String> { for (pos, x) in data.iter().enumerate() { if *x == 0 { if pos - start >= 1 { - if let Ok(s) = ::std::str::from_utf8(&data[start..pos]) - .map(|x| x.trim().to_owned()) + if let Ok(s) = + std::str::from_utf8(&data[start..pos]).map(|x| x.trim().to_owned()) { out.push(s); } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -4,15 +4,10 @@ // Copyright (c) 2017 Guillaume Gomez // -use sys::{Component, Disk, Networks, Process, Processor}; -use DiskType; -use DiskUsage; -use LoadAvg; -use NetworksIter; -use Pid; -use ProcessStatus; -use RefreshKind; -use User; +use crate::sys::{Component, Disk, Networks, Process, Processor}; +use crate::{ + DiskType, DiskUsage, LoadAvg, NetworksIter, Pid, ProcessStatus, RefreshKind, Signal, User, +}; use std::collections::HashMap; use std::ffi::OsStr; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -133,7 +128,7 @@ pub trait ProcessExt: Debug { /// process.kill(Signal::Kill); /// } /// ``` - fn kill(&self, signal: ::Signal) -> bool; + fn kill(&self, signal: Signal) -> bool; /// Returns the name of the process. /// diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -4,10 +4,9 @@ // Copyright (c) 2015 Guillaume Gomez // +use crate::{DiskUsage, Pid, ProcessExt, Signal}; + use std::path::Path; -use DiskUsage; -use Pid; -use ProcessExt; /// Enum describing the different status of a process. #[derive(Clone, Copy, Debug)] diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -25,7 +24,7 @@ impl ProcessExt for Process { Process { pid, parent } } - fn kill(&self, _signal: ::Signal) -> bool { + fn kill(&self, _signal: Signal) -> bool { false } diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -4,13 +4,13 @@ // Copyright (c) 2017 Guillaume Gomez // +use crate::Pid; #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] use std::ffi::OsStr; #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] use std::os::unix::ffi::OsStrExt; #[cfg(not(any(target_os = "windows", target_os = "unknown", target_arch = "wasm32")))] use std::path::Path; -use Pid; #[allow(clippy::useless_conversion)] #[cfg(not(any( diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -20,7 +20,7 @@ use Pid; target_os = "macos", target_os = "ios" )))] -pub fn realpath(original: &Path) -> ::std::path::PathBuf { +pub fn realpath(original: &Path) -> std::path::PathBuf { use libc::{c_char, lstat, stat, S_IFLNK, S_IFMT}; use std::fs; use std::mem::MaybeUninit; diff --git a/src/windows/component.rs b/src/windows/component.rs --- a/src/windows/component.rs +++ b/src/windows/component.rs @@ -4,6 +4,8 @@ // Copyright (c) 2018 Guillaume Gomez // +use crate::ComponentExt; + use std::ptr::null_mut; use winapi::shared::rpcdce::{ diff --git a/src/windows/component.rs b/src/windows/component.rs --- a/src/windows/component.rs +++ b/src/windows/component.rs @@ -23,8 +25,6 @@ use winapi::um::wbemcli::{ IWbemServices, WBEM_FLAG_FORWARD_ONLY, WBEM_FLAG_NONSYSTEM_ONLY, WBEM_FLAG_RETURN_IMMEDIATELY, }; -use ComponentExt; - /// Struct containing a component information (temperature and name for the moment). /// /// Please note that on Windows, you need to have Administrator priviledges to get this diff --git a/src/windows/component.rs b/src/windows/component.rs --- a/src/windows/component.rs +++ b/src/windows/component.rs @@ -325,7 +325,7 @@ impl Connection { unsafe { (*p_obj).BeginEnumeration(WBEM_FLAG_NONSYSTEM_ONLY as _); - let mut p_val: VARIANT = ::std::mem::MaybeUninit::uninit().assume_init(); + let mut p_val: VARIANT = std::mem::MaybeUninit::uninit().assume_init(); // "CurrentTemperature" let temp = bstr!( 'C', 'u', 'r', 'r', 'e', 'n', 't', 'T', 'e', 'm', 'p', 'e', 'r', 'a', 't', 'u', diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -4,12 +4,11 @@ // Copyright (c) 2018 Guillaume Gomez // +use crate::{DiskExt, DiskType}; + use std::ffi::{OsStr, OsString}; use std::path::Path; -use DiskExt; -use DiskType; - use winapi::um::fileapi::GetDiskFreeSpaceExW; use winapi::um::winnt::ULARGE_INTEGER; diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -75,11 +74,11 @@ impl DiskExt for Disk { fn refresh(&mut self) -> bool { if self.total_space != 0 { unsafe { - let mut tmp: ULARGE_INTEGER = ::std::mem::zeroed(); + let mut tmp: ULARGE_INTEGER = std::mem::zeroed(); if GetDiskFreeSpaceExW( self.mount_point.as_ptr(), - ::std::ptr::null_mut(), - ::std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), &mut tmp, ) != 0 { diff --git a/src/windows/ffi.rs b/src/windows/ffi.rs --- a/src/windows/ffi.rs +++ b/src/windows/ffi.rs @@ -35,7 +35,7 @@ macro_rules! BITFIELD { impl $base {$( #[inline] pub fn $thing(&self) -> $fieldtype { - let size = ::std::mem::size_of::<$fieldtype>() * 8; + let size = std::mem::size_of::<$fieldtype>() * 8; self.$field << (size - $r.end) >> (size - $r.end + $r.start) } #[inline] diff --git a/src/windows/network.rs b/src/windows/network.rs --- a/src/windows/network.rs +++ b/src/windows/network.rs @@ -4,12 +4,10 @@ // Copyright (c) 2017 Guillaume Gomez // -use std::collections::{HashMap, HashSet}; +use crate::sys::ffi::{self, MIB_IF_ROW2, PMIB_IF_TABLE2}; +use crate::{NetworkExt, NetworksExt, NetworksIter}; -use windows::ffi::{self, MIB_IF_ROW2, PMIB_IF_TABLE2}; -use NetworkExt; -use NetworksExt; -use NetworksIter; +use std::collections::{HashMap, HashSet}; use winapi::shared::ifdef::NET_LUID; use winapi::shared::winerror::NO_ERROR; diff --git a/src/windows/network.rs b/src/windows/network.rs --- a/src/windows/network.rs +++ b/src/windows/network.rs @@ -48,7 +46,7 @@ impl NetworksExt for Networks { } fn refresh_networks_list(&mut self) { - let mut table: PMIB_IF_TABLE2 = ::std::ptr::null_mut(); + let mut table: PMIB_IF_TABLE2 = std::ptr::null_mut(); if unsafe { ffi::GetIfTable2(&mut table) } != NO_ERROR { return; } diff --git a/src/windows/network.rs b/src/windows/network.rs --- a/src/windows/network.rs +++ b/src/windows/network.rs @@ -152,7 +150,7 @@ impl NetworksExt for Networks { } fn refresh(&mut self) { - let mut entry: MIB_IF_ROW2 = unsafe { ::std::mem::MaybeUninit::uninit().assume_init() }; + let mut entry: MIB_IF_ROW2 = unsafe { std::mem::MaybeUninit::uninit().assume_init() }; for (_, interface) in self.interfaces.iter_mut() { entry.InterfaceLuid = interface.id; entry.InterfaceIndex = 0; // to prevent the function to pick this one as index diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -4,6 +4,8 @@ // Copyright (c) 2018 Guillaume Gomez // +use crate::{DiskUsage, Pid, ProcessExt, Signal}; + use std::fmt::{self, Debug}; use std::mem::{size_of, zeroed, MaybeUninit}; use std::ops::Deref; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -16,10 +18,6 @@ use libc::{c_void, memcpy}; use once_cell::sync::Lazy; -use DiskUsage; -use Pid; -use ProcessExt; - use ntapi::ntpsapi::{ NtQueryInformationProcess, ProcessBasicInformation, ProcessCommandLineInformation, PROCESSINFOCLASS, PROCESS_BASIC_INFORMATION, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -361,7 +359,7 @@ impl ProcessExt for Process { } } - fn kill(&self, _signal: ::Signal) -> bool { + fn kill(&self, _signal: Signal) -> bool { let mut kill = process::Command::new("taskkill.exe"); kill.arg("/PID").arg(self.pid().to_string()).arg("/F"); match kill.output() { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -547,7 +545,7 @@ fn get_cmd_line_old(handle: HANDLE) -> Vec<String> { ppeb as *mut _, peb_copy.as_mut_ptr() as *mut _, size_of::<PEB>() as SIZE_T, - ::std::ptr::null_mut(), + std::ptr::null_mut(), ) != TRUE { return Vec::new(); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -561,7 +559,7 @@ fn get_cmd_line_old(handle: HANDLE) -> Vec<String> { proc_param as *mut PRTL_USER_PROCESS_PARAMETERS as *mut _, rtl_proc_param_copy.as_mut_ptr() as *mut _, size_of::<RTL_USER_PROCESS_PARAMETERS>() as SIZE_T, - ::std::ptr::null_mut(), + std::ptr::null_mut(), ) != TRUE { return Vec::new(); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -579,7 +577,7 @@ fn get_cmd_line_old(handle: HANDLE) -> Vec<String> { rtl_proc_param_copy.CommandLine.Buffer as *mut _, buffer_copy.as_mut_ptr() as *mut _, len * 2, - ::std::ptr::null_mut(), + std::ptr::null_mut(), ) != TRUE { return Vec::new(); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -693,7 +691,7 @@ pub(crate) fn get_executable_path(_pid: Pid) -> PathBuf { pub(crate) fn get_system_computation_time() -> ULARGE_INTEGER { unsafe { - let mut now: ULARGE_INTEGER = ::std::mem::zeroed(); + let mut now: ULARGE_INTEGER = std::mem::zeroed(); let mut ftime: FILETIME = zeroed(); GetSystemTimeAsFileTime(&mut ftime); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -717,8 +715,8 @@ fn check_sub(a: u64, b: u64) -> u64 { pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64, now: ULARGE_INTEGER) { unsafe { - let mut sys: ULARGE_INTEGER = ::std::mem::zeroed(); - let mut user: ULARGE_INTEGER = ::std::mem::zeroed(); + let mut sys: ULARGE_INTEGER = std::mem::zeroed(); + let mut user: ULARGE_INTEGER = std::mem::zeroed(); let mut ftime: FILETIME = zeroed(); let mut fsys: FILETIME = zeroed(); let mut fuser: FILETIME = zeroed(); diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -4,16 +4,15 @@ // Copyright (c) 2017 Guillaume Gomez // +use crate::sys::tools::KeyHandler; +use crate::{LoadAvg, ProcessorExt}; + use std::collections::HashMap; use std::mem; use std::ops::DerefMut; use std::ptr::null_mut; use std::sync::Mutex; -use windows::tools::KeyHandler; -use LoadAvg; -use ProcessorExt; - use ntapi::ntpoapi::PROCESSOR_POWER_INFORMATION; use winapi::shared::minwindef::FALSE; diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -206,7 +205,7 @@ impl Query { return false; } unsafe { - let mut counter: PDH_HCOUNTER = ::std::mem::zeroed(); + let mut counter: PDH_HCOUNTER = std::mem::zeroed(); let ret = PdhAddCounterW(self.internal.query, getter.as_ptr(), 0, &mut counter); if ret == ERROR_SUCCESS as _ { self.internal.data.insert(name.clone(), counter); diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -346,7 +345,7 @@ pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { } pos += 1; } - match ::std::str::from_utf8(&out[..pos]) { + match std::str::from_utf8(&out[..pos]) { Ok(s) => s.to_owned(), _ => String::new(), } diff --git a/src/windows/processor.rs b/src/windows/processor.rs --- a/src/windows/processor.rs +++ b/src/windows/processor.rs @@ -367,7 +366,7 @@ pub fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { } pos += 1; } - let vendor_id = match ::std::str::from_utf8(&x[..pos]) { + let vendor_id = match std::str::from_utf8(&x[..pos]) { Ok(s) => s.to_owned(), Err(_) => get_vendor_id_not_great(info), }; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -4,30 +4,25 @@ // Copyright (c) 2018 Guillaume Gomez // -use sys::component::{self, Component}; -use sys::disk::Disk; -use sys::processor::*; -use sys::users::get_users; +use crate::{LoadAvg, Networks, Pid, ProcessExt, RefreshKind, SystemExt, User}; + +use crate::sys::component::{self, Component}; +use crate::sys::disk::Disk; +use crate::sys::process::{ + compute_cpu_usage, get_handle, get_system_computation_time, update_disk_usage, update_memory, + Process, +}; +use crate::sys::processor::*; +use crate::sys::tools::*; +use crate::sys::users::get_users; + +use crate::utils::into_iter; use std::cell::UnsafeCell; use std::collections::HashMap; use std::mem::{size_of, zeroed, MaybeUninit}; use std::time::SystemTime; -use LoadAvg; -use Networks; -use Pid; -use ProcessExt; -use RefreshKind; -use SystemExt; -use User; - -use windows::process::{ - compute_cpu_usage, get_handle, get_system_computation_time, update_disk_usage, update_memory, - Process, -}; -use windows::tools::*; - use ntapi::ntexapi::{ NtQuerySystemInformation, SystemProcessInformation, SYSTEM_PROCESS_INFORMATION, }; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -43,8 +38,6 @@ use winapi::um::sysinfoapi::{ }; use winapi::um::winnt::{HANDLE, OSVERSIONINFOW}; -use utils::into_iter; - /// Struct containing the system's information. pub struct System { process_list: HashMap<usize, Process>, diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -4,10 +4,10 @@ // Copyright (c) 2018 Guillaume Gomez // -use windows::processor::{self, Processor, Query}; +use crate::DiskType; -use sys::disk::{new_disk, Disk}; -use DiskType; +use crate::sys::disk::{new_disk, Disk}; +use crate::sys::processor::{self, Processor, Query}; use std::collections::HashMap; use std::ffi::OsStr; diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -64,25 +64,25 @@ pub unsafe fn open_drive(drive_name: &[u16], open_rights: DWORD) -> HANDLE { drive_name.as_ptr(), open_rights, FILE_SHARE_READ | FILE_SHARE_WRITE, - ::std::ptr::null_mut(), + std::ptr::null_mut(), OPEN_EXISTING, 0, - ::std::ptr::null_mut(), + std::ptr::null_mut(), ) } pub unsafe fn get_drive_size(handle: HANDLE) -> u64 { - let mut pdg: DISK_GEOMETRY = ::std::mem::zeroed(); + let mut pdg: DISK_GEOMETRY = std::mem::zeroed(); let mut junk = 0; let result = DeviceIoControl( handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, - ::std::ptr::null_mut(), + std::ptr::null_mut(), 0, &mut pdg as *mut DISK_GEOMETRY as *mut c_void, size_of::<DISK_GEOMETRY>() as DWORD, &mut junk, - ::std::ptr::null_mut(), + std::ptr::null_mut(), ); if result == TRUE { *pdg.Cylinders.QuadPart() as u64 diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -118,9 +118,9 @@ pub unsafe fn get_disks() -> Vec<Disk> { mount_point.as_ptr(), name.as_mut_ptr(), name.len() as DWORD, - ::std::ptr::null_mut(), - ::std::ptr::null_mut(), - ::std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), file_system.as_mut_ptr(), file_system.len() as DWORD, ) == 0 diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -161,10 +161,10 @@ pub unsafe fn get_disks() -> Vec<Disk> { return new_disk(name, &mount_point, &file_system, DiskType::Unknown(-1), 0); } let disk_size = get_drive_size(handle); - /*let mut spq_trim: ffi::STORAGE_PROPERTY_QUERY = ::std::mem::zeroed(); + /*let mut spq_trim: ffi::STORAGE_PROPERTY_QUERY = std::mem::zeroed(); spq_trim.PropertyId = ffi::StorageDeviceTrimProperty; spq_trim.QueryType = ffi::PropertyStandardQuery; - let mut dtd: ffi::DEVICE_TRIM_DESCRIPTOR = ::std::mem::zeroed();*/ + let mut dtd: ffi::DEVICE_TRIM_DESCRIPTOR = std::mem::zeroed();*/ #[allow(non_snake_case)] #[repr(C)] struct STORAGE_PROPERTY_QUERY { diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -184,7 +184,7 @@ pub unsafe fn get_disks() -> Vec<Disk> { QueryType: 0i32, AdditionalParameters: [0], }; - let mut dtd: DEVICE_TRIM_DESCRIPTOR = ::std::mem::zeroed(); + let mut dtd: DEVICE_TRIM_DESCRIPTOR = std::mem::zeroed(); let mut dw_size = 0; if DeviceIoControl( diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -195,7 +195,7 @@ pub unsafe fn get_disks() -> Vec<Disk> { &mut dtd as *mut DEVICE_TRIM_DESCRIPTOR as *mut c_void, size_of::<DEVICE_TRIM_DESCRIPTOR>() as DWORD, &mut dw_size, - ::std::ptr::null_mut(), + std::ptr::null_mut(), ) == 0 || dw_size != size_of::<DEVICE_TRIM_DESCRIPTOR>() as DWORD { diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -232,9 +232,9 @@ pub unsafe fn load_symbols() -> HashMap<String, u32> { let _dwStatus = RegQueryValueExA( HKEY_PERFORMANCE_DATA, b"Counter 009\0".as_ptr() as *const _, - ::std::ptr::null_mut(), + std::ptr::null_mut(), &mut dwType as *mut i32 as *mut _, - ::std::ptr::null_mut(), + std::ptr::null_mut(), &mut cbCounters as *mut i32 as *mut _, ); diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -243,7 +243,7 @@ pub unsafe fn load_symbols() -> HashMap<String, u32> { let _dwStatus = RegQueryValueExA( HKEY_PERFORMANCE_DATA, b"Counter 009\0".as_ptr() as *const _, - ::std::ptr::null_mut(), + std::ptr::null_mut(), &mut dwType as *mut i32 as *mut _, lpmszCounters.as_mut_ptr(), &mut cbCounters as *mut i32 as *mut _, diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -280,9 +280,9 @@ pub fn get_translation(s: &String, map: &HashMap<String, u32>) -> Option<String> let mut size: usize = 0; unsafe { let _res = PdhLookupPerfNameByIndexW( - ::std::ptr::null(), + std::ptr::null(), *index, - ::std::ptr::null_mut(), + std::ptr::null_mut(), &mut size as *mut usize as *mut _, ); if size == 0 { diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -291,7 +291,7 @@ pub fn get_translation(s: &String, map: &HashMap<String, u32>) -> Option<String> let mut v = Vec::with_capacity(size); v.set_len(size); let _res = PdhLookupPerfNameByIndexW( - ::std::ptr::null(), + std::ptr::null(), *index, v.as_mut_ptr() as *mut _, &mut size as *mut usize as *mut _, diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -4,7 +4,8 @@ // Copyright (c) 2020 Guillaume Gomez // -use User; +use crate::sys::ffi::NetUserGetLocalGroups; +use crate::User; use winapi::shared::lmcons::MAX_PREFERRED_LENGTH; use winapi::shared::winerror::{ERROR_MORE_DATA, ERROR_SUCCESS}; diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -15,8 +16,6 @@ use winapi::um::lmaccess::{ use winapi::um::lmapibuf::NetApiBufferFree; use winapi::um::winnt::LPWSTR; -use sys::ffi::NetUserGetLocalGroups; - unsafe fn to_str(p: LPWSTR) -> String { let mut i = 0; let mut s = Vec::new(); diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -36,7 +35,7 @@ unsafe fn to_str(p: LPWSTR) -> String { } unsafe fn get_groups_for_user(username: LPWSTR) -> Vec<String> { - let mut buf: LPLOCALGROUP_USERS_INFO_0 = ::std::ptr::null_mut(); + let mut buf: LPLOCALGROUP_USERS_INFO_0 = std::ptr::null_mut(); let mut nb_entries = 0; let mut total_entries = 0; let mut groups; diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -79,7 +78,7 @@ unsafe fn get_groups_for_user(username: LPWSTR) -> Vec<String> { pub unsafe fn get_users() -> Vec<User> { let mut users = Vec::new(); let mut i = 0; - let mut buf: PNET_DISPLAY_USER = ::std::ptr::null_mut(); + let mut buf: PNET_DISPLAY_USER = std::ptr::null_mut(); let mut nb_entries = 0; let mut res = ERROR_MORE_DATA;
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
Switch to 2018 edition
0.15
417
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
2021-01-25T20:57:53Z
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -222,8 +223,18 @@ mod test { if MIN_USERS > 0 { let s = System::new(); assert!(!s.get_name().expect("Failed to get system name").is_empty()); + + cfg_if! { + if #[cfg(not(target_os = "windows"))] { + assert!(!s + .get_kernel_version() + .expect("Failed to get system version") + .is_empty()); + } + } + assert!(!s - .get_version() + .get_os_version() .expect("Failed to get system version") .is_empty()); }
[ "413" ]
GuillaumeGomez__sysinfo-414
GuillaumeGomez/sysinfo
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -91,9 +91,10 @@ for (pid, process) in sys.get_processes() { } // Display system information: -println!("System name: {:?}", sys.get_name()); -println!("System version: {:?}", sys.get_version()); -println!("System host name: {:?}", sys.get_host_name()); +println!("System name: {:?}", sys.get_name()); +println!("System kernel version: {:?}", sys.get_kernel_version()); +println!("System OS version: {:?}", sys.get_os_version()); +println!("System host name: {:?}", sys.get_host_name()); ``` By default, `sysinfo` uses multiple threads. However, this can increase the memory usage on some platforms (macOS for example). The behavior can be disabled by setting `default-features = false` in `Cargo.toml` (which disables the `multithread` cargo feature). diff --git a/examples/src/simple.rs b/examples/src/simple.rs --- a/examples/src/simple.rs +++ b/examples/src/simple.rs @@ -381,19 +381,15 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { "system" => { writeln!( &mut io::stdout(), - "System name: {}", - sys.get_name().unwrap_or_else(|| "<unknown>".to_owned()) - ); - writeln!( - &mut io::stdout(), - "System version: {}", - sys.get_version().unwrap_or_else(|| "<unknown>".to_owned()) - ); - writeln!( - &mut io::stdout(), - "System host name: {}", + "System name: {}\n\ + System kernel version: {}\n\ + System OS version: {}\n\ + System host name: {}", + sys.get_name().unwrap_or_else(|| "<unknown>".to_owned()), + sys.get_kernel_version().unwrap_or_else(|| "<unknown>".to_owned()), + sys.get_os_version().unwrap_or_else(|| "<unknown>".to_owned()), sys.get_host_name() - .unwrap_or_else(|| "<unknown>".to_owned()) + .unwrap_or_else(|| "<unknown>".to_owned()), ); } e => { diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -352,7 +352,7 @@ impl SystemExt for System { if unsafe { get_sys_value_by_name( b"hw.physicalcpu\0", - mem::size_of::<u32>(), + &mut mem::size_of::<u32>(), &mut physical_core_count as *mut usize as *mut c_void, ) } { diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -449,9 +449,36 @@ impl SystemExt for System { get_system_info(libc::KERN_HOSTNAME, None) } - fn get_version(&self) -> Option<String> { + fn get_kernel_version(&self) -> Option<String> { get_system_info(libc::KERN_OSRELEASE, None) } + + fn get_os_version(&self) -> Option<String> { + unsafe { + // get the size for the buffer first + let mut size = 0; + if get_sys_value_by_name(b"kern.osproductversion\0", &mut size, std::ptr::null_mut()) + && size > 0 + { + // now create a buffer with the size and get the real value + let mut buf = vec![0_u8; size as usize]; + + if get_sys_value_by_name( + b"kern.osproductversion\0", + &mut size, + buf.as_mut_ptr() as *mut c_void, + ) { + String::from_utf8(buf).ok() + } else { + // getting the system value failed + None + } + } else { + // getting the system value failed, or did not return a buffer size + None + } + } + } } impl Default for System { diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -537,11 +564,11 @@ pub(crate) unsafe fn get_sys_value( ) == 0 } -unsafe fn get_sys_value_by_name(name: &[u8], mut len: usize, value: *mut libc::c_void) -> bool { +unsafe fn get_sys_value_by_name(name: &[u8], len: &mut usize, value: *mut libc::c_void) -> bool { libc::sysctlbyname( name.as_ptr() as *const c_char, value, - &mut len, + len, std::ptr::null_mut(), 0, ) == 0 diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -13,7 +13,7 @@ use crate::{Disk, LoadAvg, Networks, Pid, ProcessExt, RefreshKind, SystemExt, Us use libc::{self, c_char, gid_t, sysconf, uid_t, _SC_CLK_TCK, _SC_HOST_NAME_MAX, _SC_PAGESIZE}; use std::cell::UnsafeCell; use std::collections::HashMap; -use std::fs::{self, File}; +use std::fs::{self, read_to_string, File}; use std::io::{self, BufRead, BufReader, Read}; use std::path::{Path, PathBuf}; use std::str::FromStr; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -519,7 +519,14 @@ impl SystemExt for System { } } - fn get_version(&self) -> Option<String> { + fn get_kernel_version(&self) -> Option<String> { + match read_to_string("/proc/version") { + Ok(s) => s.trim().split(' ').nth(2).map(String::from), + Err(_) => None, + } + } + + fn get_os_version(&self) -> Option<String> { get_system_info("VERSION_ID=") } } diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -41,9 +41,10 @@ //! println!("used swap : {} KB", system.get_used_swap()); //! //! // Display system information: -//! println!("System name: {:?}", system.get_name()); -//! println!("System version: {:?}", system.get_version()); -//! println!("System host name: {:?}", system.get_host_name()); +//! println!("System name: {:?}", system.get_name()); +//! println!("System kernel version: {:?}", system.get_kernel_version()); +//! println!("System OS version: {:?}", system.get_os_version()); +//! println!("System host name: {:?}", system.get_host_name()); //! ``` #![crate_name = "sysinfo"] diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -956,7 +956,7 @@ pub trait SystemExt: Sized + Debug + Default { /// ``` fn get_name(&self) -> Option<String>; - /// Returns the system version. + /// Returns the system's kernel version. /// /// **Important**: this information is computed every time this function is called. /// diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -964,9 +964,21 @@ pub trait SystemExt: Sized + Debug + Default { /// use sysinfo::{System, SystemExt}; /// /// let s = System::new(); - /// println!("OS version: {:?}", s.get_version()); + /// println!("kernel version: {:?}", s.get_kernel_version()); /// ``` - fn get_version(&self) -> Option<String>; + fn get_kernel_version(&self) -> Option<String>; + + /// Returns the system version (e.g. for MacOS this will return 11.1 rather than the kernel version). + /// + /// **Important**: this information is computed every time this function is called. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new(); + /// println!("OS version: {:?}", s.get_os_version()); + /// ``` + fn get_os_version(&self) -> Option<String>; /// Returns the system hostname based off DNS /// diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -148,11 +148,15 @@ impl SystemExt for System { None } - fn get_host_name(&self) -> Option<String> { + fn get_kernel_version(&self) -> Option<String> { None } - fn get_version(&self) -> Option<String> { + fn get_os_version(&self) -> Option<String> { + None + } + + fn get_host_name(&self) -> Option<String> { None } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -400,7 +400,18 @@ impl SystemExt for System { get_dns_hostname() } - fn get_version(&self) -> Option<String> { + // FIXME currently we are figuring out the best way to return kernel version for Windows + // see https://github.com/GuillaumeGomez/sysinfo/issues/415 + // and https://github.com/GuillaumeGomez/sysinfo/issues/410 + // this function currently returns None + fn get_kernel_version(&self) -> Option<String> { + None + } + + // FIXME currently we are figuring out the best way to return OS version for Windows + // see https://github.com/GuillaumeGomez/sysinfo/issues/415 + // and https://github.com/GuillaumeGomez/sysinfo/issues/410 + fn get_os_version(&self) -> Option<String> { get_system_version() } }
639f6afc6dc8808572853b721fa634eefd06b489
`get_version()` returns kernel version on MacOS and iOS `get_verison()` will return the compiled kernel version of MacOS and not the "product" version of MacOS/iOS. This is a problem because while the kernel version is still needed we currently have no way to get the more recognizable system version for system information. example: ``` ❯ sysctl kern.osrelease kern.osrelease: 20.2.0 ``` Instead we should be using `kern.osproductversion` which gives the product MacOS version: ``` ❯ sysctl kern.osproductversion kern.osproductversion: 11.1 ``` related: #410 ?
0.15
414
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
2021-01-09T18:09:21Z
diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -97,6 +97,9 @@ cfg_if! { } else if #[cfg(any(target_os = "linux", target_os = "android"))] { mod linux; use linux as sys; + // Can remove once `slice_internals` is stabilized + // https://doc.rust-lang.org/core/slice/memchr/fn.memchr.html + extern crate memchr; #[cfg(test)] const MIN_USERS: usize = 1; diff --git a/src/sysinfo.rs b/src/sysinfo.rs --- a/src/sysinfo.rs +++ b/src/sysinfo.rs @@ -223,6 +226,18 @@ mod test { .is_empty()); } } + + #[test] + fn check_host_name() { + // We don't want to test on unknown systems. + if MIN_USERS > 0 { + let s = ::System::new(); + assert!(!s + .get_host_name() + .expect("Failed to get host name") + .is_empty()); + } + } } // Used to check that System is Send and Sync.
[ "390" ]
GuillaumeGomez__sysinfo-393
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,9 @@ core-foundation-sys = "0.8" [target.'cfg(any(target_os = "macos", target_os = "ios"))'.build-dependencies] cc = "1.0" +[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] +memchr = "2.3" + [lib] name = "sysinfo" crate_type = ["rlib", "cdylib"] diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -16,7 +16,7 @@ use Pid; use User; use {ProcessExt, RefreshKind, SystemExt}; -use libc::{self, gid_t, sysconf, uid_t, _SC_CLK_TCK, _SC_PAGESIZE}; +use libc::{self, c_char, gid_t, sysconf, uid_t, _SC_CLK_TCK, _SC_HOST_NAME_MAX, _SC_PAGESIZE}; use std::cell::UnsafeCell; use std::collections::HashMap; use std::fs::{self, File}; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -507,6 +507,21 @@ impl SystemExt for System { get_system_info("NAME=") } + fn get_host_name(&self) -> Option<String> { + let hostname_max = unsafe { sysconf(_SC_HOST_NAME_MAX) }; + let mut buffer = vec![0_u8; hostname_max as usize]; + if unsafe { libc::gethostname(buffer.as_mut_ptr() as *mut c_char, buffer.len()) } == 0 { + //shrink buffer to terminate the null bytes + let null_position = memchr::memchr(0, &buffer)?; + buffer.resize(null_position, 0); + + String::from_utf8(buffer).ok() + } else { + sysinfo_debug!("gethostname failed: hostname cannot be retrieved..."); + None + } + } + fn get_version(&self) -> Option<String> { get_system_info("VERSION_ID=") } diff --git a/src/mac/system.rs b/src/mac/system.rs --- a/src/mac/system.rs +++ b/src/mac/system.rs @@ -419,6 +419,10 @@ impl SystemExt for System { get_system_info(libc::KERN_OSTYPE, Some("Darwin")) } + fn get_host_name(&self) -> Option<String> { + get_system_info(libc::KERN_HOSTNAME, None) + } + fn get_version(&self) -> Option<String> { get_system_info(libc::KERN_OSRELEASE, None) } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -958,6 +958,18 @@ pub trait SystemExt: Sized + Debug + Default { /// println!("OS version: {:?}", s.get_version()); /// ``` fn get_version(&self) -> Option<String>; + + /// Returns the system hostname based off DNS + /// + /// **Important**: this information is computed every time this function is called. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new(); + /// println!("Hostname: {:?}", s.get_host_name()); + /// ``` + fn get_host_name(&self) -> Option<String>; } /// Getting volume of received and transmitted data. diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -144,6 +144,10 @@ impl SystemExt for System { None } + fn get_host_name(&self) -> Option<String> { + None + } + fn get_version(&self) -> Option<String> { None } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -31,12 +31,16 @@ use windows::tools::*; use ntapi::ntexapi::{ NtQuerySystemInformation, SystemProcessInformation, SYSTEM_PROCESS_INFORMATION, }; +use winapi::ctypes::wchar_t; use winapi::shared::minwindef::{FALSE, TRUE}; use winapi::shared::ntdef::{PVOID, ULONG}; use winapi::shared::ntstatus::STATUS_INFO_LENGTH_MISMATCH; use winapi::um::minwinbase::STILL_ACTIVE; use winapi::um::processthreadsapi::GetExitCodeProcess; -use winapi::um::sysinfoapi::{GetTickCount64, GetVersionExW, GlobalMemoryStatusEx, MEMORYSTATUSEX}; +use winapi::um::sysinfoapi::{ + ComputerNamePhysicalDnsHostname, GetComputerNameExW, GetTickCount64, GetVersionExW, + GlobalMemoryStatusEx, MEMORYSTATUSEX, +}; use winapi::um::winnt::{HANDLE, OSVERSIONINFOW}; use utils::into_iter; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -395,6 +399,10 @@ impl SystemExt for System { Some("Windows".to_owned()) } + fn get_host_name(&self) -> Option<String> { + get_dns_hostname() + } + fn get_version(&self) -> Option<String> { get_system_version() } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -465,3 +473,35 @@ fn get_system_version() -> Option<String> { None } } + +fn get_dns_hostname() -> Option<String> { + let mut buffer_size = 0; + // Running this first to get the buffer size since the DNS name can be longer than MAX_COMPUTERNAME_LENGTH + // setting the `lpBuffer` to null will return the buffer size + // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getcomputernameexw + unsafe { + GetComputerNameExW( + ComputerNamePhysicalDnsHostname, + std::ptr::null_mut(), + &mut buffer_size, + ) + }; + + // Setting the buffer with the new length + let mut buffer = vec![0_u16; buffer_size as usize]; + + // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ne-sysinfoapi-computer_name_format + if unsafe { + GetComputerNameExW( + ComputerNamePhysicalDnsHostname, + buffer.as_mut_ptr() as *mut wchar_t, + &mut buffer_size, + ) + } == TRUE + { + String::from_utf16(&buffer).ok() + } else { + sysinfo_debug!("Failed to get computer hostname"); + None + } +}
d162ddd4e2f5ebf1139779b3c57304b3542bbc7f
Add `hostname` support It would be *really* nice for this crate to support getting a system's hostname to get the network name of the host. e.g. equivalent to `/bin/hostname`'s output. Sorry if I missed this somewhere in the docs!
0.15
393
`sysinfo` doesn't provide this information yet. From what I can see, on unix-like systems, it just needs to call the `gethostname` function. On windows it's [getcomputernamea](https://docs.microsoft.com/fr-fr/windows/win32/api/winbase/nf-winbase-getcomputernamea). Interested into sending a PR maybe?
8c2b5a0583404120f1a910d9af32f40fd1dd9d08
2024-12-04T00:06:06Z
diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -127,6 +127,6 @@ fn bench_refresh_users_list(b: &mut test::Bencher) { let mut users = sysinfo::Users::new_with_refreshed_list(); b.iter(move || { - users.refresh_list(); + users.refresh(); }); } diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -499,7 +497,7 @@ mod tests { fn check_list() { let mut users = Users::new(); assert!(users.list().is_empty()); - users.refresh_list(); + users.refresh(); assert!(users.list().len() >= MIN_USERS); } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -282,7 +282,7 @@ mod test { fn check_uid_gid() { let mut users = Users::new(); assert!(users.list().is_empty()); - users.refresh_list(); + users.refresh(); let user_list = users.list(); assert!(user_list.len() >= MIN_USERS); diff --git a/tests/users.rs b/tests/users.rs --- a/tests/users.rs +++ b/tests/users.rs @@ -17,7 +17,7 @@ fn test_users() { if sysinfo::IS_SUPPORTED_SYSTEM { let mut users = Users::new(); assert_eq!(users.iter().count(), 0); - users.refresh_list(); + users.refresh(); assert!(users.iter().count() > 0); let count = users.first().unwrap().groups().iter().len(); for _ in 1..10 {
[ "1405" ]
GuillaumeGomez__sysinfo-1411
GuillaumeGomez/sysinfo
diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -163,7 +163,7 @@ fn interpret_input( } "refresh_users" => { writeln!(&mut io::stdout(), "Refreshing user list..."); - users.refresh_list(); + users.refresh(); writeln!(&mut io::stdout(), "Done."); } "refresh_networks" => { diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -252,7 +252,7 @@ impl Users { /// use sysinfo::Users; /// /// let mut users = Users::new(); - /// users.refresh_list(); + /// users.refresh(); /// for user in users.list() { /// println!("{user:?}"); /// } diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -262,7 +262,6 @@ impl Users { } /// Creates a new [`Users`][crate::Users] type with the user list loaded. - /// It is a combination of [`Users::new`] and [`Users::refresh_list`]. /// /// ```no_run /// use sysinfo::Users; diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -274,7 +273,7 @@ impl Users { /// ``` pub fn new_with_refreshed_list() -> Self { let mut users = Self::new(); - users.refresh_list(); + users.refresh(); users } diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -312,9 +311,9 @@ impl Users { /// use sysinfo::Users; /// /// let mut users = Users::new(); - /// users.refresh_list(); + /// users.refresh(); /// ``` - pub fn refresh_list(&mut self) { + pub fn refresh(&mut self) { crate::sys::get_users(&mut self.users); } diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -424,7 +423,7 @@ impl Groups { /// use sysinfo::Groups; /// /// let mut groups = Groups::new(); - /// groups.refresh_list(); + /// groups.refresh(); /// for group in groups.list() { /// println!("{group:?}"); /// } diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -434,7 +433,6 @@ impl Groups { } /// Creates a new [`Groups`][crate::Groups] type with the user list loaded. - /// It is a combination of [`Groups::new`] and [`Groups::refresh_list`]. /// /// ```no_run /// use sysinfo::Groups; diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -446,7 +444,7 @@ impl Groups { /// ``` pub fn new_with_refreshed_list() -> Self { let mut groups = Self::new(); - groups.refresh_list(); + groups.refresh(); groups } diff --git a/src/common/user.rs b/src/common/user.rs --- a/src/common/user.rs +++ b/src/common/user.rs @@ -481,12 +479,12 @@ impl Groups { /// The group list will be emptied then completely recomputed. /// /// ```no_run - /// use sysinfo::Users; + /// use sysinfo::Groups; /// - /// let mut users = Users::new(); - /// users.refresh_list(); + /// let mut groups = Groups::new(); + /// groups.refresh(); /// ``` - pub fn refresh_list(&mut self) { + pub fn refresh(&mut self) { crate::sys::get_groups(&mut self.groups); } }
ee9d6da5bb7794be56acd100406fd1b0200bced5
Remove `refresh_list` methods It's not very coherent with how processes are refreshed. And now with https://github.com/GuillaumeGomez/sysinfo/pull/1404, it makes even less sense to have that. Better just refresh everything and keep the current items.
0.32
1,411
ee9d6da5bb7794be56acd100406fd1b0200bced5
2024-11-22T21:12:44Z
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -115,6 +115,7 @@ tempfile = "3.9" serde_json = "1.0" # Used in documentation tests. bstr = "1.9.0" tempfile = "3.9" +itertools = "0.13.0" [[example]] name = "simple" diff --git a/tests/disk.rs b/tests/disk.rs --- a/tests/disk.rs +++ b/tests/disk.rs @@ -1,34 +1,158 @@ // Take a look at the license at the top of the repository in the LICENSE file. +#[cfg(all(feature = "system", feature = "disk"))] +fn should_skip() -> bool { + if !sysinfo::IS_SUPPORTED_SYSTEM { + return true; + } + + let s = sysinfo::System::new_all(); + + // If we don't have any physical core present, it's very likely that we're inside a VM... + s.physical_core_count().unwrap_or_default() == 0 +} + #[test] #[cfg(all(feature = "system", feature = "disk"))] fn test_disks() { - if sysinfo::IS_SUPPORTED_SYSTEM { - let s = sysinfo::System::new_all(); - // If we don't have any physical core present, it's very likely that we're inside a VM... - if s.physical_core_count().unwrap_or_default() > 0 { - let mut disks = sysinfo::Disks::new(); - assert!(disks.list().is_empty()); - disks.refresh_list(); - assert!(!disks.list().is_empty()); + if should_skip() { + return; + } + + let mut disks = sysinfo::Disks::new(); + assert!(disks.list().is_empty()); + disks.refresh_list(); + assert!(!disks.list().is_empty()); +} + +#[test] +#[cfg(all(feature = "system", feature = "disk"))] +fn test_disk_refresh_kind() { + use itertools::Itertools; + + use sysinfo::{DiskKind, DiskRefreshKind, Disks}; + + if should_skip() { + return; + } + + for fs in [ + DiskRefreshKind::with_kind, + DiskRefreshKind::without_kind, + DiskRefreshKind::with_details, + DiskRefreshKind::without_details, + DiskRefreshKind::with_io_usage, + DiskRefreshKind::without_io_usage, + ] + .iter() + .powerset() + { + let mut refreshes = DiskRefreshKind::new(); + for f in fs { + refreshes = f(refreshes); } + + let assertions = |name: &'static str, disks: &Disks| { + if refreshes.kind() { + // This would ideally assert that *all* are refreshed, but we settle for a weaker + // assertion because failures can't be distinguished from "not refreshed" values. + #[cfg(not(any(target_os = "freebsd", target_os = "windows")))] + assert!( + disks + .iter() + .any(|disk| disk.kind() != DiskKind::Unknown(-1)), + "{name}: disk.kind should be refreshed" + ); + } else { + assert!( + disks + .iter() + .all(|disk| disk.kind() == DiskKind::Unknown(-1)), + "{name}: disk.kind should not be refreshed" + ); + } + + if refreshes.details() { + // These would ideally assert that *all* are refreshed, but we settle for a weaker + // assertion because failures can't be distinguished from "not refreshed" values. + assert!( + disks + .iter() + .any(|disk| disk.available_space() != Default::default()), + "{name}: disk.available_space should be refreshed" + ); + assert!( + disks + .iter() + .any(|disk| disk.total_space() != Default::default()), + "{name}: disk.total_space should be refreshed" + ); + // We can't assert anything about booleans, since false is indistinguishable from + // not-refreshed + } else { + assert!( + disks + .iter() + .all(|disk| disk.available_space() == Default::default()), + "{name}: disk.available_space should not be refreshed" + ); + assert!( + disks + .iter() + .all(|disk| disk.total_space() == Default::default()), + "{name}: disk.total_space should not be refreshed" + ); + assert!( + disks + .iter() + .all(|disk| disk.is_read_only() == <bool as Default>::default()), + "{name}: disk.is_read_only should not be refreshed" + ); + assert!( + disks + .iter() + .all(|disk| disk.is_removable() == <bool as Default>::default()), + "{name}: disk.is_removable should not be refreshed" + ); + } + + if refreshes.io_usage() { + // This would ideally assert that *all* are refreshed, but we settle for a weaker + // assertion because failures can't be distinguished from "not refreshed" values. + assert!( + disks.iter().any(|disk| disk.usage() != Default::default()), + "{name}: disk.usage should be refreshed" + ); + } else { + assert!( + disks.iter().all(|disk| disk.usage() == Default::default()), + "{name}: disk.usage should not be refreshed" + ); + } + }; + + // load and refresh with the desired details should work + let disks = Disks::new_with_refreshed_list_specifics(refreshes); + assertions("full", &disks); + + // load with minimal `DiskRefreshKind`, then refresh for added detail should also work! + let mut disks = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::new()); + disks.refresh_specifics(refreshes); + assertions("incremental", &disks); } } #[test] -#[cfg(feature = "disk")] +#[cfg(all(feature = "system", feature = "disk"))] fn test_disks_usage() { use std::fs::{remove_file, File}; use std::io::Write; use std::path::{Path, PathBuf}; use std::thread::sleep; - use sysinfo::{CpuRefreshKind, Disks, RefreshKind, System}; - - let s = System::new_with_specifics(RefreshKind::new().with_cpu(CpuRefreshKind::new())); + use sysinfo::Disks; - // Skip the tests on unsupported platforms and on systems with no physical cores (likely a VM) - if !sysinfo::IS_SUPPORTED_SYSTEM || s.physical_core_count().unwrap_or_default() == 0 { + if should_skip() { return; }
[ "1375" ]
GuillaumeGomez__sysinfo-1387
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -103,7 +103,7 @@ ntapi = { version = "0.4", optional = true } windows = { version = ">=0.54, <=0.57", optional = true } [target.'cfg(not(any(target_os = "unknown", target_arch = "wasm32")))'.dependencies] -libc = "^0.2.165" +libc = "^0.2.164" [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] core-foundation-sys = "0.8.7" diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -4,6 +4,7 @@ use std::ffi::OsStr; use std::fmt; use std::path::Path; +use crate::common::impl_get_set::impl_get_set; use crate::DiskUsage; /// Struct containing a disk information. diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -133,7 +134,9 @@ impl Disk { self.inner.is_read_only() } - /// Updates the disk' information. + /// Updates the disk' information with everything loaded. + /// + /// Equivalent to <code>[Disk::refresh_specifics]\([DiskRefreshKind::everything]\())</code>. /// /// ```no_run /// use sysinfo::Disks; diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -144,7 +147,21 @@ impl Disk { /// } /// ``` pub fn refresh(&mut self) -> bool { - self.inner.refresh() + self.refresh_specifics(DiskRefreshKind::everything()) + } + + /// Updates the disk's information corresponding to the given [`DiskRefreshKind`]. + /// + /// ```no_run + /// use sysinfo::{Disks, DiskRefreshKind}; + /// + /// let mut disks = Disks::new_with_refreshed_list(); + /// for disk in disks.list_mut() { + /// disk.refresh_specifics(DiskRefreshKind::new()); + /// } + /// ``` + pub fn refresh_specifics(&mut self, refreshes: DiskRefreshKind) -> bool { + self.inner.refresh_specifics(refreshes) } /// Returns number of bytes read and written by the disk diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -244,7 +261,8 @@ impl Disks { } /// Creates a new [`Disks`][crate::Disks] type with the disk list loaded. - /// It is a combination of [`Disks::new`] and [`Disks::refresh_list`]. + /// + /// Equivalent to <code>[Disks::new_with_refreshed_list_specifics]\([DiskRefreshKind::everything]\())</code>. /// /// ```no_run /// use sysinfo::Disks; diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -255,8 +273,24 @@ impl Disks { /// } /// ``` pub fn new_with_refreshed_list() -> Self { + Self::new_with_refreshed_list_specifics(DiskRefreshKind::everything()) + } + + /// Creates a new [`Disks`][crate::Disks] type with the disk list loaded + /// and refreshed according to the given [`DiskRefreshKind`]. It is a combination of + /// [`Disks::new`] and [`Disks::refresh_list_specifics`]. + /// + /// ```no_run + /// use sysinfo::{Disks, DiskRefreshKind}; + /// + /// let mut disks = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::new()); + /// for disk in disks.list() { + /// println!("{disk:?}"); + /// } + /// ``` + pub fn new_with_refreshed_list_specifics(refreshes: DiskRefreshKind) -> Self { let mut disks = Self::new(); - disks.refresh_list(); + disks.refresh_list_specifics(refreshes); disks } diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -291,6 +325,13 @@ impl Disks { /// Refreshes the listed disks' information. /// + /// Equivalent to <code>[Disks::refresh_specifics]\([DiskRefreshKind::everything]\())</code>. + pub fn refresh(&mut self) { + self.refresh_specifics(DiskRefreshKind::everything()); + } + + /// Refreshes the listed disks' information according to the given [`DiskRefreshKind`]. + /// /// ⚠️ If a disk is added or removed, this method won't take it into account. Use /// [`Disks::refresh_list`] instead. /// diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -304,30 +345,45 @@ impl Disks { /// // We wait some time...? /// disks.refresh(); /// ``` - pub fn refresh(&mut self) { - self.inner.refresh(); + pub fn refresh_specifics(&mut self, refreshes: DiskRefreshKind) { + self.inner.refresh_specifics(refreshes); } /// The disk list will be emptied then completely recomputed. /// + /// Equivalent to <code>[Disks::refresh_list_specifics]\([DiskRefreshKind::everything]\())</code>. + /// + /// ```no_run + /// use sysinfo::Disks; + /// + /// let mut disks = Disks::new(); + /// disks.refresh_list(); + /// ``` + pub fn refresh_list(&mut self) { + self.refresh_list_specifics(DiskRefreshKind::everything()); + } + + /// The disk list will be emptied then completely recomputed according to the given + /// [`DiskRefreshKind`]. + /// /// ## Linux /// /// ⚠️ On Linux, the [NFS](https://en.wikipedia.org/wiki/Network_File_System) file /// systems are ignored and the information of a mounted NFS **cannot** be obtained - /// via [`Disks::refresh_list`]. This is due to the fact that I/O function - /// `statvfs` used by [`Disks::refresh_list`] is blocking and + /// via [`Disks::refresh_list_specifics`]. This is due to the fact that I/O function + /// `statvfs` used by [`Disks::refresh_list_specifics`] is blocking and /// [may hang](https://github.com/GuillaumeGomez/sysinfo/pull/876) in some cases, /// requiring to call `systemctl stop` to terminate the NFS service from the remote /// server in some cases. /// /// ```no_run - /// use sysinfo::Disks; + /// use sysinfo::{Disks, DiskRefreshKind}; /// /// let mut disks = Disks::new(); - /// disks.refresh_list(); + /// disks.refresh_list_specifics(DiskRefreshKind::new()); /// ``` - pub fn refresh_list(&mut self) { - self.inner.refresh_list(); + pub fn refresh_list_specifics(&mut self, refreshes: DiskRefreshKind) { + self.inner.refresh_list_specifics(refreshes); } } diff --git a/src/common/disk.rs b/src/common/disk.rs --- a/src/common/disk.rs +++ b/src/common/disk.rs @@ -376,3 +432,61 @@ impl fmt::Display for DiskKind { }) } } + +/// Used to determine what you want to refresh specifically on the [`Disk`] type. +/// +/// ```no_run +/// use sysinfo::{Disks, DiskRefreshKind}; +/// +/// let mut disks = Disks::new_with_refreshed_list_specifics(DiskRefreshKind::everything()); +/// +/// for disk in disks.list() { +/// assert_eq!(disk.total_space(), 0); +/// } +/// ``` +#[derive(Clone, Copy, Debug, Default)] +pub struct DiskRefreshKind { + kind: bool, + details: bool, + io_usage: bool, +} + +impl DiskRefreshKind { + /// Creates a new `DiskRefreshKind` with every refresh set to false. + /// + /// ``` + /// use sysinfo::DiskRefreshKind; + /// + /// let r = DiskRefreshKind::new(); + /// + /// assert_eq!(r.kind(), false); + /// assert_eq!(r.details(), false); + /// assert_eq!(r.io_usage(), false); + /// ``` + pub fn new() -> Self { + Self::default() + } + + /// Creates a new `DiskRefreshKind` with every refresh set to true. + /// + /// ``` + /// use sysinfo::DiskRefreshKind; + /// + /// let r = DiskRefreshKind::everything(); + /// + /// assert_eq!(r.kind(), true); + /// assert_eq!(r.details(), true); + /// assert_eq!(r.io_usage(), true); + /// ``` + pub fn everything() -> Self { + Self { + kind: true, + details: true, + io_usage: true, + } + } + + impl_get_set!(DiskRefreshKind, kind, with_kind, without_kind); + impl_get_set!(DiskRefreshKind, details, with_details, without_details,); + impl_get_set!(DiskRefreshKind, io_usage, with_io_usage, without_io_usage); +} diff --git /dev/null b/src/common/impl_get_set.rs new file mode 100644 --- /dev/null +++ b/src/common/impl_get_set.rs @@ -0,0 +1,173 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +macro_rules! impl_get_set { + ($ty_name:ident, $name:ident, $with:ident, $without:ident $(, $extra_doc:literal)? $(,)?) => { + #[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.")] + $(#[doc = concat!(" +", $extra_doc, " +")])? + #[doc = concat!(" +``` +use sysinfo::", stringify!($ty_name), "; + +let r = ", stringify!($ty_name), "::new(); + +let r = r.with_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), true); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), false); +```")] + pub fn $name(&self) -> bool { + self.$name + } + + #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `true`. + +``` +use sysinfo::", stringify!($ty_name), "; + +let r = ", stringify!($ty_name), "::new(); + +let r = r.with_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), true); +```")] + #[must_use] + pub fn $with(mut self) -> Self { + self.$name = true; + self + } + + #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `false`. + +``` +use sysinfo::", stringify!($ty_name), "; + +let r = ", stringify!($ty_name), "::everything(); +assert_eq!(r.", stringify!($name), "(), true); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), false); +```")] + #[must_use] + pub fn $without(mut self) -> Self { + self.$name = false; + self + } + }; + + // To handle `UpdateKind`. + ($ty_name:ident, $name:ident, $with:ident, $without:ident, UpdateKind $(, $extra_doc:literal)? $(,)?) => { + #[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.")] + $(#[doc = concat!(" +", $extra_doc, " +")])? + #[doc = concat!(" +``` +use sysinfo::{", stringify!($ty_name), ", UpdateKind}; + +let r = ", stringify!($ty_name), "::new(); +assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); + +let r = r.with_", stringify!($name), "(UpdateKind::OnlyIfNotSet); +assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); +```")] + pub fn $name(&self) -> UpdateKind { + self.$name + } + + #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind. + +``` +use sysinfo::{", stringify!($ty_name), ", UpdateKind}; + +let r = ", stringify!($ty_name), "::new(); +assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); + +let r = r.with_", stringify!($name), "(UpdateKind::OnlyIfNotSet); +assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet); +```")] + #[must_use] + pub fn $with(mut self, kind: UpdateKind) -> Self { + self.$name = kind; + self + } + + #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `UpdateKind::Never`. + +``` +use sysinfo::{", stringify!($ty_name), ", UpdateKind}; + +let r = ", stringify!($ty_name), "::everything(); +assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); +```")] + #[must_use] + pub fn $without(mut self) -> Self { + self.$name = UpdateKind::Never; + self + } + }; + + // To handle `*RefreshKind`. + ($ty_name:ident, $name:ident, $with:ident, $without:ident, $typ:ty $(,)?) => { + #[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind. + +``` +use sysinfo::{", stringify!($ty_name), ", ", stringify!($typ), "}; + +let r = ", stringify!($ty_name), "::new(); +assert_eq!(r.", stringify!($name), "().is_some(), false); + +let r = r.with_", stringify!($name), "(", stringify!($typ), "::everything()); +assert_eq!(r.", stringify!($name), "().is_some(), true); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "().is_some(), false); +```")] + pub fn $name(&self) -> Option<$typ> { + self.$name + } + + #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `Some(...)`. + +``` +use sysinfo::{", stringify!($ty_name), ", ", stringify!($typ), "}; + +let r = ", stringify!($ty_name), "::new(); +assert_eq!(r.", stringify!($name), "().is_some(), false); + +let r = r.with_", stringify!($name), "(", stringify!($typ), "::everything()); +assert_eq!(r.", stringify!($name), "().is_some(), true); +```")] + #[must_use] + pub fn $with(mut self, kind: $typ) -> Self { + self.$name = Some(kind); + self + } + + #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `None`. + +``` +use sysinfo::", stringify!($ty_name), "; + +let r = ", stringify!($ty_name), "::everything(); +assert_eq!(r.", stringify!($name), "().is_some(), true); + +let r = r.without_", stringify!($name), "(); +assert_eq!(r.", stringify!($name), "().is_some(), false); +```")] + #[must_use] + pub fn $without(mut self) -> Self { + self.$name = None; + self + } + }; +} + +pub(crate) use impl_get_set; diff --git a/src/common/mod.rs b/src/common/mod.rs --- a/src/common/mod.rs +++ b/src/common/mod.rs @@ -4,6 +4,8 @@ pub(crate) mod component; #[cfg(feature = "disk")] pub(crate) mod disk; +#[cfg(any(feature = "system", feature = "disk"))] +pub(crate) mod impl_get_set; #[cfg(feature = "network")] pub(crate) mod network; #[cfg(feature = "system")] diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -6,6 +6,7 @@ use std::fmt; use std::path::Path; use std::str::FromStr; +use crate::common::impl_get_set::impl_get_set; use crate::common::DiskUsage; use crate::{CpuInner, Gid, ProcessInner, SystemInner, Uid}; diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -1686,178 +1687,6 @@ cfg_if! { } } -macro_rules! impl_get_set { - ($ty_name:ident, $name:ident, $with:ident, $without:ident $(, $extra_doc:literal)? $(,)?) => { - #[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.")] - $(#[doc = concat!(" -", $extra_doc, " -")])? - #[doc = concat!(" -``` -use sysinfo::", stringify!($ty_name), "; - -let r = ", stringify!($ty_name), "::new(); -assert_eq!(r.", stringify!($name), "(), false); - -let r = r.with_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "(), true); - -let r = r.without_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "(), false); -```")] - pub fn $name(&self) -> bool { - self.$name - } - - #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `true`. - -``` -use sysinfo::", stringify!($ty_name), "; - -let r = ", stringify!($ty_name), "::new(); -assert_eq!(r.", stringify!($name), "(), false); - -let r = r.with_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "(), true); -```")] - #[must_use] - pub fn $with(mut self) -> Self { - self.$name = true; - self - } - - #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `false`. - -``` -use sysinfo::", stringify!($ty_name), "; - -let r = ", stringify!($ty_name), "::everything(); -assert_eq!(r.", stringify!($name), "(), true); - -let r = r.without_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "(), false); -```")] - #[must_use] - pub fn $without(mut self) -> Self { - self.$name = false; - self - } - }; - - // To handle `UpdateKind`. - ($ty_name:ident, $name:ident, $with:ident, $without:ident, UpdateKind $(, $extra_doc:literal)? $(,)?) => { - #[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind.")] - $(#[doc = concat!(" -", $extra_doc, " -")])? - #[doc = concat!(" -``` -use sysinfo::{", stringify!($ty_name), ", UpdateKind}; - -let r = ", stringify!($ty_name), "::new(); -assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); - -let r = r.with_", stringify!($name), "(UpdateKind::OnlyIfNotSet); -assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet); - -let r = r.without_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); -```")] - pub fn $name(&self) -> UpdateKind { - self.$name - } - - #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind. - -``` -use sysinfo::{", stringify!($ty_name), ", UpdateKind}; - -let r = ", stringify!($ty_name), "::new(); -assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); - -let r = r.with_", stringify!($name), "(UpdateKind::OnlyIfNotSet); -assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet); -```")] - #[must_use] - pub fn $with(mut self, kind: UpdateKind) -> Self { - self.$name = kind; - self - } - - #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `UpdateKind::Never`. - -``` -use sysinfo::{", stringify!($ty_name), ", UpdateKind}; - -let r = ", stringify!($ty_name), "::everything(); -assert_eq!(r.", stringify!($name), "(), UpdateKind::OnlyIfNotSet); - -let r = r.without_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "(), UpdateKind::Never); -```")] - #[must_use] - pub fn $without(mut self) -> Self { - self.$name = UpdateKind::Never; - self - } - }; - - // To handle `*RefreshKind`. - ($ty_name:ident, $name:ident, $with:ident, $without:ident, $typ:ty $(,)?) => { - #[doc = concat!("Returns the value of the \"", stringify!($name), "\" refresh kind. - -``` -use sysinfo::{", stringify!($ty_name), ", ", stringify!($typ), "}; - -let r = ", stringify!($ty_name), "::new(); -assert_eq!(r.", stringify!($name), "().is_some(), false); - -let r = r.with_", stringify!($name), "(", stringify!($typ), "::everything()); -assert_eq!(r.", stringify!($name), "().is_some(), true); - -let r = r.without_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "().is_some(), false); -```")] - pub fn $name(&self) -> Option<$typ> { - self.$name - } - - #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `Some(...)`. - -``` -use sysinfo::{", stringify!($ty_name), ", ", stringify!($typ), "}; - -let r = ", stringify!($ty_name), "::new(); -assert_eq!(r.", stringify!($name), "().is_some(), false); - -let r = r.with_", stringify!($name), "(", stringify!($typ), "::everything()); -assert_eq!(r.", stringify!($name), "().is_some(), true); -```")] - #[must_use] - pub fn $with(mut self, kind: $typ) -> Self { - self.$name = Some(kind); - self - } - - #[doc = concat!("Sets the value of the \"", stringify!($name), "\" refresh kind to `None`. - -``` -use sysinfo::", stringify!($ty_name), "; - -let r = ", stringify!($ty_name), "::everything(); -assert_eq!(r.", stringify!($name), "().is_some(), true); - -let r = r.without_", stringify!($name), "(); -assert_eq!(r.", stringify!($name), "().is_some(), false); -```")] - #[must_use] - pub fn $without(mut self) -> Self { - self.$name = None; - self - } - }; -} - /// This enum allows you to specify when you want the related information to be updated. /// /// For example if you only want the [`Process::exe()`] information to be refreshed only if it's not diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -71,7 +71,7 @@ cfg_if! { #[cfg(feature = "component")] pub use crate::common::component::{Component, Components}; #[cfg(feature = "disk")] -pub use crate::common::disk::{Disk, DiskKind, Disks}; +pub use crate::common::disk::{Disk, DiskKind, DiskRefreshKind, Disks}; #[cfg(feature = "network")] pub use crate::common::network::{IpNetwork, MacAddr, NetworkData, Networks}; #[cfg(feature = "system")] diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -7,7 +7,7 @@ use crate::{ }, DiskUsage, }; -use crate::{Disk, DiskKind}; +use crate::{Disk, DiskKind, DiskRefreshKind}; use core_foundation_sys::array::CFArrayCreate; use core_foundation_sys::base::kCFAllocatorDefault; diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -72,44 +72,70 @@ impl DiskInner { self.is_read_only } - pub(crate) fn refresh(&mut self) -> bool { - #[cfg(target_os = "macos")] - let Some((read_bytes, written_bytes)) = self - .bsd_name - .as_ref() - .and_then(|name| crate::sys::inner::disk::get_disk_io(name)) - else { - sysinfo_debug!("Failed to update disk i/o stats"); - return false; - }; - #[cfg(not(target_os = "macos"))] - let (read_bytes, written_bytes) = (0, 0); + pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) -> bool { + if refresh_kind.kind() && self.type_ == DiskKind::Unknown(-1) { + let type_ = { + #[cfg(target_os = "macos")] + { + self.bsd_name + .as_ref() + .and_then(|name| crate::sys::inner::disk::get_disk_type(name)) + .unwrap_or(DiskKind::Unknown(-1)) + } + #[cfg(not(target_os = "macos"))] + DiskKind::SSD + }; - self.old_read_bytes = self.read_bytes; - self.old_written_bytes = self.written_bytes; - self.read_bytes = read_bytes; - self.written_bytes = written_bytes; + self.type_ = type_; + } - unsafe { - if let Some(requested_properties) = build_requested_properties(&[ - ffi::kCFURLVolumeAvailableCapacityKey, - ffi::kCFURLVolumeAvailableCapacityForImportantUsageKey, - ]) { - match get_disk_properties(&self.volume_url, &requested_properties) { - Some(disk_props) => { - self.available_space = get_available_volume_space(&disk_props); - true - } - None => { - sysinfo_debug!("Failed to get disk properties"); - false + if refresh_kind.io_usage() { + #[cfg(target_os = "macos")] + match self + .bsd_name + .as_ref() + .and_then(|name| crate::sys::inner::disk::get_disk_io(name)) + { + Some((read_bytes, written_bytes)) => { + self.old_read_bytes = self.read_bytes; + self.old_written_bytes = self.written_bytes; + self.read_bytes = read_bytes; + self.written_bytes = written_bytes; + } + None => { + sysinfo_debug!("Failed to update disk i/o stats"); + } + } + } + + if refresh_kind.details() { + unsafe { + if let Some(requested_properties) = build_requested_properties(&[ + ffi::kCFURLVolumeTotalCapacityKey, + ffi::kCFURLVolumeAvailableCapacityKey, + ffi::kCFURLVolumeAvailableCapacityForImportantUsageKey, + ]) { + match get_disk_properties(&self.volume_url, &requested_properties) { + Some(disk_props) => { + self.total_space = get_int_value( + disk_props.inner(), + DictKey::Extern(ffi::kCFURLVolumeTotalCapacityKey), + ) + .unwrap_or_default() + as u64; + self.available_space = get_available_volume_space(&disk_props); + } + None => { + sysinfo_debug!("Failed to get disk properties"); + } } + } else { + sysinfo_debug!("failed to create volume key list, skipping refresh"); } - } else { - sysinfo_debug!("failed to create volume key list, skipping refresh"); - false } } + + true } pub(crate) fn usage(&self) -> DiskUsage { diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -129,19 +155,19 @@ impl crate::DisksInner { } } - pub(crate) fn refresh_list(&mut self) { + pub(crate) fn refresh_list_specifics(&mut self, refresh_kind: DiskRefreshKind) { unsafe { // SAFETY: We don't keep any Objective-C objects around because we // don't make any direct Objective-C calls in this code. with_autorelease(|| { - get_list(&mut self.disks); + get_list(&mut self.disks, refresh_kind); }) } } - pub(crate) fn refresh(&mut self) { + pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) { for disk in self.list_mut() { - disk.refresh(); + disk.refresh_specifics(refresh_kind); } } diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -154,7 +180,7 @@ impl crate::DisksInner { } } -unsafe fn get_list(container: &mut Vec<Disk>) { +unsafe fn get_list(container: &mut Vec<Disk>, refresh_kind: DiskRefreshKind) { container.clear(); let raw_disks = { diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -252,7 +278,7 @@ unsafe fn get_list(container: &mut Vec<Disk>) { CStr::from_ptr(c_disk.f_mntonname.as_ptr()).to_bytes(), )); - if let Some(disk) = new_disk(mount_point, volume_url, c_disk, &prop_dict) { + if let Some(disk) = new_disk(mount_point, volume_url, c_disk, &prop_dict, refresh_kind) { container.push(disk); } } diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -398,6 +424,7 @@ unsafe fn new_disk( volume_url: RetainedCFURL, c_disk: libc::statfs, disk_props: &RetainedCFDictionary, + refresh_kind: DiskRefreshKind, ) -> Option<Disk> { let bsd_name = get_bsd_name(&c_disk); diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -406,21 +433,33 @@ unsafe fn new_disk( // so we just assume the disk type is an SSD and set disk i/o stats to 0 until Rust has a way to conditionally link to // IOKit in more recent deployment versions. - #[cfg(target_os = "macos")] - let type_ = bsd_name - .as_ref() - .and_then(|name| crate::sys::inner::disk::get_disk_type(name)) - .unwrap_or(DiskKind::Unknown(-1)); - #[cfg(not(target_os = "macos"))] - let type_ = DiskKind::SSD; + let type_ = if refresh_kind.kind() { + #[cfg(target_os = "macos")] + { + bsd_name + .as_ref() + .and_then(|name| crate::sys::inner::disk::get_disk_type(name)) + .unwrap_or(DiskKind::Unknown(-1)) + } + #[cfg(not(target_os = "macos"))] + DiskKind::SSD + } else { + DiskKind::Unknown(-1) + }; - #[cfg(target_os = "macos")] - let (read_bytes, written_bytes) = bsd_name - .as_ref() - .and_then(|name| crate::sys::inner::disk::get_disk_io(name)) - .unwrap_or_default(); - #[cfg(not(target_os = "macos"))] - let (read_bytes, written_bytes) = (0, 0); + let (read_bytes, written_bytes) = if refresh_kind.io_usage() { + #[cfg(target_os = "macos")] + { + bsd_name + .as_ref() + .and_then(|name| crate::sys::inner::disk::get_disk_io(name)) + .unwrap_or_default() + } + #[cfg(not(target_os = "macos"))] + (0, 0) + } else { + (0, 0) + }; // Note: Since we requested these properties from the system, we don't expect // these property retrievals to fail. diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -431,7 +470,7 @@ unsafe fn new_disk( ) .map(OsString::from)?; - let is_removable = { + let is_removable = if refresh_kind.details() { let ejectable = get_bool_value( disk_props.inner(), DictKey::Extern(ffi::kCFURLVolumeIsEjectableKey), diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -459,14 +498,25 @@ unsafe fn new_disk( !internal } + } else { + false }; - let total_space = get_int_value( - disk_props.inner(), - DictKey::Extern(ffi::kCFURLVolumeTotalCapacityKey), - )? as u64; + let total_space = if refresh_kind.details() { + get_int_value( + disk_props.inner(), + DictKey::Extern(ffi::kCFURLVolumeTotalCapacityKey), + ) + .unwrap_or_default() as u64 + } else { + 0 + }; - let available_space = get_available_volume_space(disk_props); + let available_space = if refresh_kind.details() { + get_available_volume_space(disk_props) + } else { + 0 + }; let file_system = { let len = c_disk diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -482,7 +532,7 @@ unsafe fn new_disk( ) }; - let is_read_only = (c_disk.f_flags & libc::MNT_RDONLY as u32) != 0; + let is_read_only = refresh_kind.details() && (c_disk.f_flags & libc::MNT_RDONLY as u32) != 0; Some(Disk { inner: DiskInner { diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -16,7 +16,7 @@ use super::ffi::{ DEVSTAT_WRITE, }; use super::utils::{c_buf_to_utf8_str, get_sys_value_str_by_name}; -use crate::{Disk, DiskKind, DiskUsage}; +use crate::{Disk, DiskKind, DiskRefreshKind, DiskUsage}; #[derive(Debug)] pub(crate) struct DiskInner { diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -69,8 +69,8 @@ impl DiskInner { self.is_read_only } - pub(crate) fn refresh(&mut self) -> bool { - refresh_disk(self) + pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) -> bool { + refresh_disk(self, refresh_kind) } pub(crate) fn usage(&self) -> DiskUsage { diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -90,10 +90,8 @@ impl crate::DisksInner { } } - pub(crate) fn refresh_list(&mut self) { - unsafe { - get_all_list(&mut self.disks, true); - } + pub(crate) fn refresh_list_specifics(&mut self, refresh_kind: DiskRefreshKind) { + unsafe { get_all_list(&mut self.disks, true, refresh_kind) } } pub(crate) fn list(&self) -> &[Disk] { diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -104,9 +102,9 @@ impl crate::DisksInner { &mut self.disks } - pub(crate) fn refresh(&mut self) { + pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) { unsafe { - get_all_list(&mut self.disks, false); + get_all_list(&mut self.disks, false, refresh_kind); } } } diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -164,19 +162,27 @@ impl GetValues for DiskInner { } } -fn refresh_disk(disk: &mut DiskInner) -> bool { - unsafe { - let mut vfs: libc::statvfs = std::mem::zeroed(); - if libc::statvfs(disk.c_mount_point.as_ptr() as *const _, &mut vfs as *mut _) < 0 { - return false; +fn refresh_disk(disk: &mut DiskInner, refresh_kind: DiskRefreshKind) -> bool { + if refresh_kind.details() { + unsafe { + let mut vfs: libc::statvfs = std::mem::zeroed(); + if libc::statvfs(disk.c_mount_point.as_ptr() as *const _, &mut vfs as *mut _) < 0 { + sysinfo_debug!("statvfs failed"); + } else { + let block_size: u64 = vfs.f_frsize as _; + disk.total_space = vfs.f_blocks.saturating_mul(block_size); + disk.available_space = vfs.f_favail.saturating_mul(block_size); + } } - let block_size: u64 = vfs.f_frsize as _; + } - disk.total_space = vfs.f_blocks.saturating_mul(block_size); - disk.available_space = vfs.f_favail.saturating_mul(block_size); - refresh_disk_io(&mut [disk]); - true + if refresh_kind.io_usage() { + unsafe { + refresh_disk_io(&mut [disk]); + } } + + true } unsafe fn initialize_geom() -> Result<(), ()> { diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -291,7 +297,11 @@ fn get_disks_mapping() -> HashMap<String, String> { disk_mapping } -pub unsafe fn get_all_list(container: &mut Vec<Disk>, add_new_disks: bool) { +pub unsafe fn get_all_list( + container: &mut Vec<Disk>, + add_new_disks: bool, + refresh_kind: DiskRefreshKind, +) { let mut fs_infos: *mut libc::statfs = null_mut(); let count = libc::getmntinfo(&mut fs_infos, libc::MNT_WAIT); diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -349,15 +359,21 @@ pub unsafe fn get_all_list(container: &mut Vec<Disk>, add_new_disks: bool) { OsString::from(mount_point) }; - if libc::statvfs(fs_info.f_mntonname.as_ptr(), &mut vfs) != 0 { - continue; - } - - let f_frsize: u64 = vfs.f_frsize as _; - - let is_read_only = (vfs.f_flag & libc::ST_RDONLY) != 0; - let total_space = vfs.f_blocks.saturating_mul(f_frsize); - let available_space = vfs.f_favail.saturating_mul(f_frsize); + let (is_read_only, total_space, available_space) = if refresh_kind.details() { + if libc::statvfs(fs_info.f_mntonname.as_ptr(), &mut vfs) != 0 { + (false, 0, 0) + } else { + let f_frsize: u64 = vfs.f_frsize as _; + + ( + ((vfs.f_flag & libc::ST_RDONLY) != 0), + vfs.f_blocks.saturating_mul(f_frsize), + vfs.f_favail.saturating_mul(f_frsize), + ) + } + } else { + (false, 0, 0) + }; if let Some(disk) = container.iter_mut().find(|d| d.inner.name == name) { disk.inner.updated = true; diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -367,8 +383,12 @@ pub unsafe fn get_all_list(container: &mut Vec<Disk>, 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 = if refresh_kind.details() { + [b"USB", b"usb"].iter().any(|b| *b == &fs_type[..]) + || fs_type.starts_with(b"/dev/cd") + } else { + false + }; container.push(Disk { inner: DiskInner { diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -376,8 +396,8 @@ pub unsafe fn get_all_list(container: &mut Vec<Disk>, add_new_disks: bool) { c_mount_point: fs_info.f_mntonname.to_vec(), mount_point: PathBuf::from(mount_point), dev_id: disk_mapping.get(dev_mount_point).map(ToString::to_string), - total_space: vfs.f_blocks.saturating_mul(f_frsize), - available_space: vfs.f_favail.saturating_mul(f_frsize), + total_space, + available_space, file_system: OsString::from_vec(fs_type), is_removable, is_read_only, diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -404,7 +424,9 @@ pub unsafe fn get_all_list(container: &mut Vec<Disk>, add_new_disks: bool) { c.inner.updated = false; } } - refresh_disk_io(container.as_mut_slice()); + if refresh_kind.io_usage() { + refresh_disk_io(container.as_mut_slice()); + } } // struct DevInfoWrapper { diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::utils::{get_all_utf8_data, to_cpath}; -use crate::{Disk, DiskKind, DiskUsage}; +use crate::{Disk, DiskKind, DiskRefreshKind, DiskUsage}; use libc::statvfs; use std::collections::HashMap; diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -37,7 +37,7 @@ macro_rules! cast { pub(crate) struct DiskInner { type_: DiskKind, device_name: OsString, - actual_device_name: String, + actual_device_name: Option<String>, file_system: OsString, mount_point: PathBuf, total_space: u64, diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -83,39 +83,52 @@ impl DiskInner { self.is_read_only } - pub(crate) fn refresh(&mut self) -> bool { - self.efficient_refresh(&disk_stats()) + pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) -> bool { + self.efficient_refresh(refresh_kind, &disk_stats(&refresh_kind)) } - fn efficient_refresh(&mut self, procfs_disk_stats: &HashMap<String, DiskStat>) -> 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, - ) - }) - else { - sysinfo_debug!("Failed to update disk i/o stats"); - return false; - }; + fn efficient_refresh( + &mut self, + refresh_kind: DiskRefreshKind, + procfs_disk_stats: &HashMap<String, DiskStat>, + ) -> bool { + if refresh_kind.kind() && self.type_ == DiskKind::Unknown(-1) { + self.type_ = find_type_for_device_name(&self.device_name); + } - self.old_read_bytes = self.read_bytes; - self.old_written_bytes = self.written_bytes; - self.read_bytes = read_bytes; - self.written_bytes = written_bytes; - - unsafe { - let mut stat: statvfs = mem::zeroed(); - let mount_point_cpath = to_cpath(&self.mount_point); - if retry_eintr!(statvfs(mount_point_cpath.as_ptr() as *const _, &mut stat)) == 0 { - let tmp = cast!(stat.f_bsize).saturating_mul(cast!(stat.f_bavail)); - self.available_space = cast!(tmp); - true + if refresh_kind.io_usage() { + if self.actual_device_name.is_none() { + self.actual_device_name = Some(get_actual_device_name(&self.device_name)); + } + if let Some((read_bytes, written_bytes)) = procfs_disk_stats + .get(self.actual_device_name.as_ref().unwrap()) + .map(|stat| { + ( + stat.sectors_read * SECTOR_SIZE, + stat.sectors_written * SECTOR_SIZE, + ) + }) + { + self.old_read_bytes = self.read_bytes; + self.old_written_bytes = self.written_bytes; + self.read_bytes = read_bytes; + self.written_bytes = written_bytes; } else { - false + sysinfo_debug!("Failed to update disk i/o stats"); + } + } + + if refresh_kind.details() { + if let Some((total_space, available_space, is_read_only)) = + unsafe { load_statvfs_values(&self.mount_point) } + { + self.total_space = total_space; + self.available_space = available_space; + self.is_read_only = is_read_only; } } + + true } pub(crate) fn usage(&self) -> DiskUsage { diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -135,17 +148,19 @@ impl crate::DisksInner { } } - pub(crate) fn refresh_list(&mut self) { + pub(crate) fn refresh_list_specifics(&mut self, refresh_kind: DiskRefreshKind) { get_all_list( &mut self.disks, &get_all_utf8_data("/proc/mounts", 16_385).unwrap_or_default(), + refresh_kind, ) } - pub(crate) fn refresh(&mut self) { - let procfs_disk_stats = disk_stats(); + pub(crate) fn refresh_specifics(&mut self, refresh_kind: DiskRefreshKind) { + let procfs_disk_stats = disk_stats(&refresh_kind); for disk in self.list_mut() { - disk.inner.efficient_refresh(&procfs_disk_stats); + disk.inner + .efficient_refresh(refresh_kind, &procfs_disk_stats); } } diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -177,38 +192,53 @@ fn get_actual_device_name(device: &OsStr) -> String { .unwrap_or_default() } +unsafe fn load_statvfs_values(mount_point: &Path) -> Option<(u64, u64, bool)> { + let mount_point_cpath = to_cpath(mount_point); + let mut stat: statvfs = mem::zeroed(); + if retry_eintr!(statvfs(mount_point_cpath.as_ptr() as *const _, &mut stat)) == 0 { + let bsize = cast!(stat.f_bsize); + let blocks = cast!(stat.f_blocks); + let bavail = cast!(stat.f_bavail); + let total = bsize.saturating_mul(blocks); + if total == 0 { + return None; + } + let available = bsize.saturating_mul(bavail); + let is_read_only = (stat.f_flag & libc::ST_RDONLY) != 0; + + Some((total, available, is_read_only)) + } else { + None + } +} + fn new_disk( device_name: &OsStr, mount_point: &Path, file_system: &OsStr, removable_entries: &[PathBuf], procfs_disk_stats: &HashMap<String, DiskStat>, -) -> Option<Disk> { - let mount_point_cpath = to_cpath(mount_point); - let type_ = find_type_for_device_name(device_name); - let mut total = 0; - let mut available = 0; - let mut is_read_only = false; - unsafe { - let mut stat: statvfs = mem::zeroed(); - if retry_eintr!(statvfs(mount_point_cpath.as_ptr() as *const _, &mut stat)) == 0 { - let bsize = cast!(stat.f_bsize); - let blocks = cast!(stat.f_blocks); - let bavail = cast!(stat.f_bavail); - total = bsize.saturating_mul(blocks); - available = bsize.saturating_mul(bavail); - is_read_only = (stat.f_flag & libc::ST_RDONLY) != 0; - } - if total == 0 { - return None; - } - let mount_point = mount_point.to_owned(); - let is_removable = removable_entries + refresh_kind: DiskRefreshKind, +) -> Disk { + let type_ = if refresh_kind.kind() { + find_type_for_device_name(device_name) + } else { + DiskKind::Unknown(-1) + }; + + let (total_space, available_space, is_read_only) = if refresh_kind.details() { + unsafe { load_statvfs_values(mount_point).unwrap_or((0, 0, false)) } + } else { + (0, 0, false) + }; + + let is_removable = refresh_kind.details() + && removable_entries .iter() .any(|e| e.as_os_str() == device_name); + let (actual_device_name, read_bytes, written_bytes) = if refresh_kind.io_usage() { let actual_device_name = get_actual_device_name(device_name); - let (read_bytes, written_bytes) = procfs_disk_stats .get(&actual_device_name) .map(|stat| { diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -218,24 +248,27 @@ fn new_disk( ) }) .unwrap_or_default(); + (Some(actual_device_name), read_bytes, written_bytes) + } else { + (None, 0, 0) + }; - Some(Disk { - inner: DiskInner { - type_, - device_name: device_name.to_owned(), - actual_device_name, - file_system: file_system.to_owned(), - mount_point, - total_space: cast!(total), - available_space: cast!(available), - is_removable, - is_read_only, - old_read_bytes: 0, - old_written_bytes: 0, - read_bytes, - written_bytes, - }, - }) + Disk { + inner: DiskInner { + type_, + device_name: device_name.to_owned(), + actual_device_name, + file_system: file_system.to_owned(), + mount_point: mount_point.to_owned(), + total_space, + available_space, + is_removable, + is_read_only, + old_read_bytes: 0, + old_written_bytes: 0, + read_bytes, + written_bytes, + }, } } diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -310,7 +343,7 @@ fn find_type_for_device_name(device_name: &OsStr) -> DiskKind { } } -fn get_all_list(container: &mut Vec<Disk>, content: &str) { +fn get_all_list(container: &mut Vec<Disk>, content: &str, refresh_kind: DiskRefreshKind) { container.clear(); // The goal of this array is to list all removable devices (the ones whose name starts with // "usb-"). diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -331,7 +364,7 @@ fn get_all_list(container: &mut Vec<Disk>, content: &str) { _ => Vec::new(), }; - let procfs_disk_stats = disk_stats(); + let procfs_disk_stats = disk_stats(&refresh_kind); for disk in content .lines() diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -378,13 +411,14 @@ fn get_all_list(container: &mut Vec<Disk>, content: &str) { (fs_file.starts_with("/run") && !fs_file.starts_with("/run/media")) || fs_spec.starts_with("sunrpc")) }) - .filter_map(|(fs_spec, fs_file, fs_vfstype)| { + .map(|(fs_spec, fs_file, fs_vfstype)| { new_disk( fs_spec.as_ref(), Path::new(&fs_file), fs_vfstype.as_ref(), &removable_entries, &procfs_disk_stats, + refresh_kind, ) }) { diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -444,14 +478,18 @@ impl DiskStat { } } -fn disk_stats() -> HashMap<String, DiskStat> { - let path = "/proc/diskstats"; - match fs::read_to_string(path) { - Ok(content) => disk_stats_inner(&content), - Err(_error) => { - sysinfo_debug!("failed to read {path:?}: {_error:?}"); - HashMap::new() +fn disk_stats(refresh_kind: &DiskRefreshKind) -> HashMap<String, DiskStat> { + if refresh_kind.io_usage() { + let path = "/proc/diskstats"; + match fs::read_to_string(path) { + Ok(content) => disk_stats_inner(&content), + Err(_error) => { + sysinfo_debug!("failed to read {path:?}: {_error:?}"); + HashMap::new() + } } + } else { + Default::default() } } diff --git a/src/unknown/disk.rs b/src/unknown/disk.rs --- a/src/unknown/disk.rs +++ b/src/unknown/disk.rs @@ -1,6 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::{Disk, DiskKind, DiskUsage}; +use crate::{Disk, DiskKind, DiskRefreshKind, DiskUsage}; use std::{ffi::OsStr, path::Path}; diff --git a/src/unknown/disk.rs b/src/unknown/disk.rs --- a/src/unknown/disk.rs +++ b/src/unknown/disk.rs @@ -39,7 +39,7 @@ impl DiskInner { false } - pub(crate) fn refresh(&mut self) -> bool { + pub(crate) fn refresh_specifics(&mut self, _refreshes: DiskRefreshKind) -> bool { true } diff --git a/src/unknown/disk.rs b/src/unknown/disk.rs --- a/src/unknown/disk.rs +++ b/src/unknown/disk.rs @@ -65,11 +65,11 @@ impl DisksInner { self.disks } - pub(crate) fn refresh_list(&mut self) { + pub(crate) fn refresh_list_specifics(&mut self, _refreshes: DiskRefreshKind) { // Does nothing. } - pub(crate) fn refresh(&mut self) { + pub(crate) fn refresh_specifics(&mut self, _refreshes: DiskRefreshKind) { // Does nothing. } diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::utils::HandleWrapper; -use crate::{Disk, DiskKind, DiskUsage}; +use crate::{Disk, DiskKind, DiskRefreshKind, DiskUsage}; use std::ffi::{c_void, OsStr, OsString}; use std::mem::size_of; diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -167,25 +167,28 @@ impl DiskInner { self.is_read_only } - pub(crate) fn refresh(&mut self) -> bool { - let Some((read_bytes, written_bytes)) = get_disk_io(&self.device_path, None) else { - sysinfo_debug!("Failed to update disk i/o stats"); - return false; - }; + pub(crate) fn refresh_specifics(&mut self, refreshes: DiskRefreshKind) -> bool { + if refreshes.kind() && self.type_ == DiskKind::Unknown(-1) { + self.type_ = get_disk_kind(&self.device_path, None); + } - self.old_read_bytes = self.read_bytes; - self.old_written_bytes = self.written_bytes; - self.read_bytes = read_bytes; - self.written_bytes = written_bytes; - - if self.total_space != 0 { - unsafe { - let mut tmp = 0; - let lpdirectoryname = PCWSTR::from_raw(self.mount_point.as_ptr()); - if GetDiskFreeSpaceExW(lpdirectoryname, None, None, Some(&mut tmp)).is_ok() { - self.available_space = tmp; - return true; - } + if refreshes.io_usage() { + if let Some((read_bytes, written_bytes)) = get_disk_io(&self.device_path, None) { + self.old_read_bytes = self.read_bytes; + self.old_written_bytes = self.written_bytes; + self.read_bytes = read_bytes; + self.written_bytes = written_bytes; + } else { + sysinfo_debug!("Failed to update disk i/o stats"); + } + } + + if refreshes.details() { + if let Some((total_space, available_space)) = + unsafe { get_drive_size(&self.mount_point) } + { + self.total_space = total_space; + self.available_space = available_space; } } false diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -220,15 +223,15 @@ impl DisksInner { self.disks } - pub(crate) fn refresh_list(&mut self) { + pub(crate) fn refresh_list_specifics(&mut self, refreshes: DiskRefreshKind) { unsafe { - self.disks = get_list(); + self.disks = get_list(refreshes); } } - pub(crate) fn refresh(&mut self) { + pub(crate) fn refresh_specifics(&mut self, refreshes: DiskRefreshKind) { for disk in self.list_mut() { - disk.refresh(); + disk.refresh_specifics(refreshes); } } diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -259,7 +262,7 @@ unsafe fn get_drive_size(mount_point: &[u16]) -> Option<(u64, u64)> { } } -pub(crate) unsafe fn get_list() -> Vec<Disk> { +pub(crate) unsafe fn get_list(refreshes: DiskRefreshKind) -> Vec<Disk> { #[cfg(feature = "multithread")] use rayon::iter::ParallelIterator; diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -268,7 +271,7 @@ pub(crate) unsafe fn get_list() -> Vec<Disk> { let raw_volume_name = PCWSTR::from_raw(volume_name.as_ptr()); let drive_type = GetDriveTypeW(raw_volume_name); - let is_removable = drive_type == DRIVE_REMOVABLE; + let is_removable = refreshes.details() && drive_type == DRIVE_REMOVABLE; if drive_type != DRIVE_FIXED && drive_type != DRIVE_REMOVABLE { return Vec::new(); diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -292,7 +295,7 @@ pub(crate) unsafe fn get_list() -> Vec<Disk> { ); return Vec::new(); } - let is_read_only = (flags & FILE_READ_ONLY_VOLUME) != 0; + let is_read_only = refreshes.details() && (flags & FILE_READ_ONLY_VOLUME) != 0; let mount_paths = get_volume_path_names_for_volume_name(&volume_name[..]); if mount_paths.is_empty() { diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -305,51 +308,25 @@ pub(crate) unsafe fn get_list() -> Vec<Disk> { .copied() .chain([0]) .collect::<Vec<_>>(); - let Some(handle) = HandleWrapper::new_from_file(&device_path[..], Default::default()) - else { - return Vec::new(); - }; - let Some((total_space, available_space)) = get_drive_size(&mount_paths[0][..]) else { - return Vec::new(); - }; - if total_space == 0 { - sysinfo_debug!("total_space == 0"); - return Vec::new(); - } - let spq_trim = STORAGE_PROPERTY_QUERY { - PropertyId: StorageDeviceSeekPenaltyProperty, - QueryType: PropertyStandardQuery, - AdditionalParameters: [0], + let handle = HandleWrapper::new_from_file(&device_path[..], Default::default()); + + let (total_space, available_space) = if refreshes.details() { + get_drive_size(&mount_paths[0][..]).unwrap_or_default() + } else { + (0, 0) }; - let mut result: DEVICE_SEEK_PENALTY_DESCRIPTOR = std::mem::zeroed(); - - let mut dw_size = 0; - let device_io_control = DeviceIoControl( - handle.0, - IOCTL_STORAGE_QUERY_PROPERTY, - Some(&spq_trim as *const STORAGE_PROPERTY_QUERY as *const c_void), - size_of::<STORAGE_PROPERTY_QUERY>() as u32, - Some(&mut result as *mut DEVICE_SEEK_PENALTY_DESCRIPTOR as *mut c_void), - size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32, - Some(&mut dw_size), - None, - ) - .is_ok(); - let type_ = if !device_io_control - || dw_size != size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32 - { - DiskKind::Unknown(-1) + + let type_ = if refreshes.kind() { + get_disk_kind(&device_path, handle.as_ref()) } else { - let is_hdd = result.IncursSeekPenalty.as_bool(); - if is_hdd { - DiskKind::HDD - } else { - DiskKind::SSD - } + DiskKind::Unknown(-1) }; - let (read_bytes, written_bytes) = - get_disk_io(&device_path, Some(handle)).unwrap_or_default(); + let (read_bytes, written_bytes) = if refreshes.io_usage() { + get_disk_io(&device_path, handle).unwrap_or_default() + } else { + (0, 0) + }; let name = os_string_from_zero_terminated(&name); let file_system = os_string_from_zero_terminated(&file_system); diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -383,6 +360,63 @@ fn os_string_from_zero_terminated(name: &[u16]) -> OsString { OsString::from_wide(&name[..len]) } +fn get_disk_kind(device_path: &[u16], borrowed_handle: Option<&HandleWrapper>) -> DiskKind { + let binding = ( + borrowed_handle, + if borrowed_handle.is_none() { + unsafe { HandleWrapper::new_from_file(device_path, Default::default()) } + } else { + None + }, + ); + let handle = match binding { + (Some(handle), _) => handle, + (_, Some(ref handle)) => handle, + (None, None) => return DiskKind::Unknown(-1), + }; + + if handle.is_invalid() { + sysinfo_debug!( + "Expected handle to {:?} to be valid", + String::from_utf16_lossy(device_path) + ); + return DiskKind::Unknown(-1); + } + + let spq_trim = STORAGE_PROPERTY_QUERY { + PropertyId: StorageDeviceSeekPenaltyProperty, + QueryType: PropertyStandardQuery, + AdditionalParameters: [0], + }; + let mut result: DEVICE_SEEK_PENALTY_DESCRIPTOR = unsafe { std::mem::zeroed() }; + + let mut dw_size = 0; + let device_io_control = unsafe { + DeviceIoControl( + handle.0, + IOCTL_STORAGE_QUERY_PROPERTY, + Some(&spq_trim as *const STORAGE_PROPERTY_QUERY as *const c_void), + size_of::<STORAGE_PROPERTY_QUERY>() as u32, + Some(&mut result as *mut DEVICE_SEEK_PENALTY_DESCRIPTOR as *mut c_void), + size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32, + Some(&mut dw_size), + None, + ) + .is_ok() + }; + + if !device_io_control || dw_size != size_of::<DEVICE_SEEK_PENALTY_DESCRIPTOR>() as u32 { + DiskKind::Unknown(-1) + } else { + let is_hdd = result.IncursSeekPenalty.as_bool(); + if is_hdd { + DiskKind::HDD + } else { + DiskKind::SSD + } + } +} + /// Returns a tuple consisting of the total number of bytes read and written by the volume with the specified device path fn get_disk_io(device_path: &[u16], handle: Option<HandleWrapper>) -> Option<(u64, u64)> { let handle = diff --git a/src/windows/disk.rs b/src/windows/disk.rs --- a/src/windows/disk.rs +++ b/src/windows/disk.rs @@ -390,7 +424,7 @@ fn get_disk_io(device_path: &[u16], handle: Option<HandleWrapper>) -> Option<(u6 if handle.is_invalid() { sysinfo_debug!( - "Expected handle to '{:?}' to be valid", + "Expected handle to {:?} to be valid", String::from_utf16_lossy(device_path) ); return None;
5721f848f7e9b5d883e4ff7f88bd0b297d4ee05c
Selectively refreshing disks When running `Disks::new_with_refreshed_list()` on android devices, I often see warnings (from SELinux?) along the lines of: ``` type=1400 audit(0.0:339351): avc: denied { search } for name="block" dev="tmpfs" ino=12 ``` I've done some spelunking, and it appears they are a side-effect of [this `canonicalize` call](https://github.com/GuillaumeGomez/sysinfo/blob/master/src/unix/linux/disk.rs#L157), on certain disks' mount points. (N.b. the dev="tmpfs" in the warning doesn't refer to the type of the filesystem being refreshed. I'm not using `linux-tmpfs`, so they're filtered out. In debugging, I've seen the warning for "ext4" and "fuse" filesystems.) I know these warnings are harmless! ...but I've had customers who were alarmed about them, so I'd prefer to avoid generating them. Given my use-case (I'm only reporting disk usage over time for *one* disk), I'd love some sort of mechanism for *selectively* refreshing `Disks`. There are lots of options. My first suggestion would be a separate `Disks` constructor (`new_with_list()` or `new_with_unrefreshed_list()`?) that loads the *list* of disks from /proc/mounts, but defers the *stat collection* until a later `refresh`. On linux, at least, I think the separation makes sense, and it gives complete control over *what is refreshed* to the library user, without adding much complexity to the interface. On other platforms, I haven't looked, but it seems like the worst-case would simply be that `new_with_list()` calls `new_with_refreshed_list()` on platforms where there's no distinction between listing and refreshing. I'd be happy to do the work. If my proposal sounds reasonable, I'll submit a PR next week and we can hash out the specifics. If not, I'd be open to other ways of solving this... just let me know :)
0.32
1,387
Seems a bit weird to want to have disks but not their path or even their kind. I think the best course would be to instead detect when the `canonicalize` call is actually needed and only call it if so. > Seems a bit weird to want to have disks but not their path or even their kind. I was thinking those *would* be present in the `new_with_list` return. Only the information obtained from `statvfs` would be deferred. > I think the best course would be to instead detect when the canonicalize call is actually needed and only call it if so. Hummm. Canonicalize (on linux) IIUC is just `realpath`. How would one decide if it were necessary? (I think you'd end up reimplementing almost all of `realpath`, right?) The kind is retrieved from the function using `canonicalize`, so both functions would get a call to it. > Hummm. Canonicalize (on linux) IIUC is just `realpath`. How would one decide if it were necessary? (I think you'd end up reimplementing almost all of `realpath`, right?) Mostly checking if it's a link, if not, checking if it doesn't start with `/` or contains `..` (still not great to check that ourselves). Any clue why `statvfs` is emitting this warning? > The kind is retrieved from the function using canonicalize, so both functions would get a call to it. Ah, I see. I was thinking about `vfstype`, not `DiskKind`. You're right that `DiskKind` requires the `canonicalize`. So in my suggestion, I guess the populated fields would be `device_name`, `file_system` and `mount_point`; the other fields would require a `refresh`. > Any clue why statvfs is emitting this warning? I believe it happens during the `canonicalize`, not the `statvfs`. And it's coming from SELinux or apparmor or some similar system for permissions above and beyond POSIX. The fact that it emits these audit warnings *in addition to failing the syscall* is super annoying, at least in this instance :/ I think `DiskKind` is part of the fundamental information for a `Disk`, so I'm not super open to the idea of not having it by default. However the `RefreshKind` approach for `Disks` sounds pretty good, just not sure there are enough different fields to make it relevant currently. I'm not sure what you mean about `RefreshKind`, can you elaborate? Sure. Like for [`refresh_processes_specifics`](https://docs.rs/sysinfo/latest/sysinfo/struct.System.html#method.refresh_processes_specifics): you can pick what you want to refresh with `ProcessRefreshKind`. Ahh, I see. That's perfect! I'd be happy to extend that pattern over `Disks`. So I think I would: * add a `DiskRefreshKind` * add a `Disks::new_with_specifics()` constructor * add a `Disks::refresh_specifics()` refresher * add a `Disk::refresh_specifics()` refresher * make (at least) the linux impl respect the specific refresh kind(s) ... sound about right? That would work for me :) Yes but that wouldn't solve your problem since I still want `DiskKind` to be retrieved for all `Disk` unconditionally. ^^' What if you always get `DiskKind` unless you specifically ask *not* to get it? That could work. Only question, what value do you put into `DiskKind::Unknown`? It's supposed to mean something to the OS. I'm not sure. I don't use the `DiskKind`, personally. The idiomatic Rust thing would be to make it `Option<DiskKind>`, but I'm guessing that's exactly what you want to avoid. Could we add another enum variant (`DiskKind::NeedsReload`)? Indeed, I don't want an `Option`. I'm still wondering if we're not trying to go around a technical issue that could be fixed instead... FWIW: even if it weren't for the annoying warnings, I would still use this functionality, since I'm currently loading way more information than I actually need :) We can do it in two passes then: a PR to implement the selective refresh and another where we can debate what's best for `DiskKind`. Look for a PR early next week! Thanks in advance!
ee9d6da5bb7794be56acd100406fd1b0200bced5
2024-10-07T21:44:33Z
diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -2462,7 +2462,7 @@ mod test { #[test] fn check_cpu_arch() { - assert_eq!(System::cpu_arch().is_some(), IS_SUPPORTED_SYSTEM); + assert!(!System::cpu_arch().is_empty()); } // Ensure that the CPUs frequency isn't retrieved until we ask for it.
[ "1356" ]
GuillaumeGomez__sysinfo-1358
GuillaumeGomez/sysinfo
diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -777,8 +777,8 @@ impl System { /// /// println!("CPU Architecture: {:?}", System::cpu_arch()); /// ``` - pub fn cpu_arch() -> Option<String> { - SystemInner::cpu_arch() + pub fn cpu_arch() -> String { + SystemInner::cpu_arch().unwrap_or_else(|| std::env::consts::ARCH.to_owned()) } }
e022ae4fd1d27c2d7159cad3e7018fc08e5b822d
Use std::env::consts::ARCH for System::cpu_arch The `std::env::consts::ARCH` constant can be used instead of computing the value for every call to the function.
0.32
1,358
Interested into sending a PR? > Interested into sending a PR? Should the function fallback to `std::env::consts::ARCH` if `SystemInner::cpu_arch` returns `None`? Sounds good to me!
ee9d6da5bb7794be56acd100406fd1b0200bced5
2024-10-03T21:06:38Z
diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -33,9 +33,9 @@ fn bench_refresh_all(b: &mut test::Bencher) { fn bench_refresh_processes(b: &mut test::Bencher) { let mut s = sysinfo::System::new(); - s.refresh_processes(sysinfo::ProcessesToUpdate::All); // to load the whole processes list a first time. + s.refresh_processes(sysinfo::ProcessesToUpdate::All, true); // to load the whole processes list a first time. b.iter(move || { - s.refresh_processes(sysinfo::ProcessesToUpdate::All); + s.refresh_processes(sysinfo::ProcessesToUpdate::All, true); }); } diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -44,7 +44,7 @@ fn bench_refresh_processes(b: &mut test::Bencher) { fn bench_first_refresh_processes(b: &mut test::Bencher) { b.iter(move || { let mut s = sysinfo::System::new(); - s.refresh_processes(sysinfo::ProcessesToUpdate::All); + s.refresh_processes(sysinfo::ProcessesToUpdate::All, true); }); } diff --git a/benches/basic.rs b/benches/basic.rs --- a/benches/basic.rs +++ b/benches/basic.rs @@ -57,7 +57,7 @@ fn bench_refresh_process(b: &mut test::Bencher) { // to be sure it'll exist for at least as long as we run let pid = sysinfo::get_current_pid().expect("failed to get current pid"); b.iter(move || { - s.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid])); + s.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true); }); } diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -2393,7 +2450,7 @@ mod test { } let mut s = System::new_all(); let total = s.processes().len() as isize; - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); let new_total = s.processes().len() as isize; // There should be almost no difference in the processes count. assert!( diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -2415,7 +2472,7 @@ mod test { return; } let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); for proc_ in s.cpus() { assert_eq!(proc_.frequency(), 0); } diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -2490,7 +2547,7 @@ mod test { } let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); // All CPU usage will start at zero until the second refresh assert!(s .processes() diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -2499,7 +2556,7 @@ mod test { // Wait a bit to update CPU usage values std::thread::sleep(MINIMUM_CPU_UPDATE_INTERVAL); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, true); assert!(s .processes() .iter() diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -2571,9 +2628,15 @@ mod test { { let mut s = System::new(); // First check what happens in case the process isn't already in our process list. - assert_eq!(s.refresh_processes(ProcessesToUpdate::Some(&[_pid])), 1); + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true), + 1 + ); // Then check that it still returns 1 if the process is already in our process list. - assert_eq!(s.refresh_processes(ProcessesToUpdate::Some(&[_pid])), 1); + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[_pid]), true), + 1 + ); } } } diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -37,6 +37,7 @@ fn test_cwd() { let mut s = System::new(); s.refresh_processes_specifics( ProcessesToUpdate::All, + false, ProcessRefreshKind::new().with_cwd(UpdateKind::Always), ); p.kill().expect("Unable to kill process."); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -63,6 +64,7 @@ fn test_cmd() { assert!(s.processes().is_empty()); s.refresh_processes_specifics( ProcessesToUpdate::All, + false, ProcessRefreshKind::new().with_cmd(UpdateKind::Always), ); p.kill().expect("Unable to kill process"); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -94,6 +96,7 @@ fn build_test_binary(file_name: &str) { } #[test] +#[allow(clippy::zombie_processes)] fn test_environ() { if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") { return; diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -112,6 +115,7 @@ fn test_environ() { s.refresh_processes_specifics( ProcessesToUpdate::Some(&[pid]), + false, sysinfo::ProcessRefreshKind::everything(), ); p.kill().expect("Unable to kill process."); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -145,6 +149,7 @@ fn test_environ() { s.refresh_processes_specifics( ProcessesToUpdate::All, + false, ProcessRefreshKind::new().with_environ(UpdateKind::Always), ); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -169,9 +174,10 @@ fn test_process_refresh() { if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") { return; } - s.refresh_processes(ProcessesToUpdate::Some(&[ - sysinfo::get_current_pid().expect("failed to get current pid") - ])); + s.refresh_processes( + ProcessesToUpdate::Some(&[sysinfo::get_current_pid().expect("failed to get current pid")]), + false, + ); assert!(s .process(sysinfo::get_current_pid().expect("failed to get current pid")) .is_some()); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -213,7 +219,7 @@ fn test_process_disk_usage() { std::thread::sleep(std::time::Duration::from_millis(250)); let mut system = System::new(); assert!(system.processes().is_empty()); - system.refresh_processes(ProcessesToUpdate::All); + system.refresh_processes(ProcessesToUpdate::All, false); assert!(!system.processes().is_empty()); system } diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -249,7 +255,7 @@ fn test_process_disk_usage() { #[test] fn cpu_usage_is_not_nan() { let mut system = System::new(); - system.refresh_processes(ProcessesToUpdate::All); + system.refresh_processes(ProcessesToUpdate::All, false); if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") { return; diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -266,7 +272,7 @@ fn cpu_usage_is_not_nan() { let mut checked = 0; first_pids.into_iter().for_each(|pid| { - system.refresh_processes(ProcessesToUpdate::Some(&[pid])); + system.refresh_processes(ProcessesToUpdate::Some(&[pid]), true); if let Some(p) = system.process(pid) { assert!(!p.cpu_usage().is_nan()); checked += 1; diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -289,7 +295,7 @@ fn test_process_times() { let pid = Pid::from_u32(p.id() as _); std::thread::sleep(std::time::Duration::from_secs(1)); let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); p.kill().expect("Unable to kill process."); if let Some(p) = s.process(pid) { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -319,7 +325,7 @@ fn test_process_session_id() { return; } let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); assert!(s.processes().values().any(|p| p.session_id().is_some())); } diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -336,7 +342,7 @@ fn test_refresh_processes() { // Checks that the process is listed as it should. let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); assert!(s.process(pid).is_some()); // Check that the process name is not empty. diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -348,12 +354,12 @@ fn test_refresh_processes() { // Let's give some time to the system to clean up... std::thread::sleep(std::time::Duration::from_secs(1)); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, true); // Checks that the process isn't listed anymore. assert!(s.process(pid).is_none()); } -// This test ensures that if we refresh only one process, then no process is removed. +// This test ensures that if we refresh only one process, then only this process is removed. #[test] fn test_refresh_process_doesnt_remove() { if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -370,7 +376,7 @@ fn test_refresh_process_doesnt_remove() { let mut s = System::new_with_specifics( RefreshKind::new().with_processes(sysinfo::ProcessRefreshKind::new()), ); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); assert!(s.process(pid1).is_some()); assert!(s.process(pid2).is_some()); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -384,11 +390,23 @@ fn test_refresh_process_doesnt_remove() { // Let's give some time to the system to clean up... std::thread::sleep(std::time::Duration::from_secs(1)); - assert_eq!(s.refresh_processes(ProcessesToUpdate::Some(&[pid1])), 0); + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[pid1]), false), + 0 + ); // We check that none of the two processes were removed. assert!(s.process(pid1).is_some()); assert!(s.process(pid2).is_some()); + + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[pid1]), true), + 0 + ); + + // We check that only `pid1` was removed. + assert!(s.process(pid1).is_none()); + assert!(s.process(pid2).is_some()); } // Checks that `refresh_processes` is adding and removing task. diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -413,7 +431,7 @@ fn test_refresh_tasks() { // Checks that the task is listed as it should. let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); assert!(s .process(pid) diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -432,7 +450,7 @@ fn test_refresh_tasks() { // Let's give some time to the system to clean up... std::thread::sleep(std::time::Duration::from_secs(2)); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, true); assert!(!s .process(pid) diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -449,7 +467,7 @@ fn test_refresh_tasks() { .is_none()); } -// Checks that `refresh_process` is NOT removing dead processes. +// Checks that `refresh_process` is removing dead processes when asked. #[test] fn test_refresh_process() { if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -462,7 +480,7 @@ fn test_refresh_process() { // Checks that the process is listed as it should. let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::Some(&[pid])); + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false); assert!(s.process(pid).is_some()); // Check that the process name is not empty. diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -474,9 +492,19 @@ fn test_refresh_process() { // Let's give some time to the system to clean up... std::thread::sleep(std::time::Duration::from_secs(1)); - assert_eq!(s.refresh_processes(ProcessesToUpdate::Some(&[pid])), 0); + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false), + 0 + ); // Checks that the process is still listed. assert!(s.process(pid).is_some()); + + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), true), + 0 + ); + // Checks that the process is not listed anymore. + assert!(s.process(pid).is_none()); } #[test] diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -490,7 +518,7 @@ fn test_wait_child() { let pid = Pid::from_u32(p.id() as _); let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::Some(&[pid])); + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false); let process = s.process(pid).unwrap(); // Kill the child process. diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -499,7 +527,10 @@ fn test_wait_child() { process.wait(); // Child process should not be present. - assert_eq!(s.refresh_processes(ProcessesToUpdate::Some(&[pid])), 0); + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), true), + 0 + ); assert!(before.elapsed() < std::time::Duration::from_millis(1000)); } diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -526,14 +557,17 @@ fn test_wait_non_child() { let pid = Pid::from_u32(p.id()); let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::Some(&[pid])); + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false); let process = s.process(pid).expect("Process not found!"); // Wait for a non child process. process.wait(); // Child process should not be present. - assert_eq!(s.refresh_processes(ProcessesToUpdate::Some(&[pid])), 0); + assert_eq!( + s.refresh_processes(ProcessesToUpdate::Some(&[pid]), true), + 0 + ); // should wait for 2s. assert!( diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -668,13 +702,13 @@ fn test_process_specific_refresh() { macro_rules! update_specific_and_check { (memory) => { - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::new()); { let p = s.process(pid).unwrap(); assert_eq!(p.memory(), 0, "failed 0 check for memory"); assert_eq!(p.virtual_memory(), 0, "failed 0 check for virtual memory"); } - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new().with_memory()); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::new().with_memory()); { let p = s.process(pid).unwrap(); assert_ne!(p.memory(), 0, "failed non-0 check for memory"); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -682,7 +716,7 @@ fn test_process_specific_refresh() { } // And now we check that re-refreshing nothing won't remove the // information. - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::new()); { let p = s.process(pid).unwrap(); assert_ne!(p.memory(), 0, "failed non-0 check (number 2) for memory"); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -690,7 +724,7 @@ fn test_process_specific_refresh() { } }; ($name:ident, $method:ident, $($extra:tt)+) => { - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::new()); { let p = s.process(pid).unwrap(); assert_eq!( diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -698,7 +732,7 @@ fn test_process_specific_refresh() { concat!("failed 0 check check for ", stringify!($name)), ); } - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new().$method(UpdateKind::Always)); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::new().$method(UpdateKind::Always)); { let p = s.process(pid).unwrap(); assert_ne!( diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -707,7 +741,7 @@ fn test_process_specific_refresh() { } // And now we check that re-refreshing nothing won't remove the // information. - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()); + s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), false, ProcessRefreshKind::new()); { let p = s.process(pid).unwrap(); assert_ne!( diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -717,10 +751,18 @@ fn test_process_specific_refresh() { } } - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()); + s.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid]), + false, + ProcessRefreshKind::new(), + ); check_empty(&s, pid); - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()); + s.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid]), + false, + ProcessRefreshKind::new(), + ); check_empty(&s, pid); update_specific_and_check!(memory); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -750,7 +792,7 @@ fn test_refresh_pids() { let child_pid = Pid::from_u32(p.id() as _); let pids = &[child_pid, self_pid]; std::thread::sleep(std::time::Duration::from_millis(500)); - s.refresh_processes(ProcessesToUpdate::Some(pids)); + s.refresh_processes(ProcessesToUpdate::Some(pids), false); p.kill().expect("Unable to kill process."); assert_eq!(s.processes().len(), 2); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -766,10 +808,10 @@ fn test_process_run_time() { } let mut s = System::new(); let current_pid = sysinfo::get_current_pid().expect("failed to get current pid"); - s.refresh_processes(ProcessesToUpdate::Some(&[current_pid])); + s.refresh_processes(ProcessesToUpdate::Some(&[current_pid]), false); let run_time = s.process(current_pid).expect("no process found").run_time(); std::thread::sleep(std::time::Duration::from_secs(2)); - s.refresh_processes(ProcessesToUpdate::Some(&[current_pid])); + s.refresh_processes(ProcessesToUpdate::Some(&[current_pid]), true); let new_run_time = s.process(current_pid).expect("no process found").run_time(); assert!( new_run_time > run_time, diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -799,7 +841,7 @@ fn test_parent_change() { let pid = Pid::from_u32(p.id() as _); let mut s = System::new(); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, false); assert_eq!( s.process(pid).expect("process was not created").parent(), diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -816,7 +858,7 @@ fn test_parent_change() { // Waiting for the parent process to stop. p.wait().expect("wait failed"); - s.refresh_processes(ProcessesToUpdate::All); + s.refresh_processes(ProcessesToUpdate::All, true); // Parent should not be around anymore. assert!(s.process(pid).is_none()); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -829,7 +871,7 @@ fn test_parent_change() { } // We want to ensure that if `System::refresh_process*` methods are called -// one after the other, it won't impact the CPU usage computation badly. +// one after the other, it won't badly impact the CPU usage computation. #[test] fn test_multiple_single_process_refresh() { if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") || cfg!(windows) { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -853,12 +895,28 @@ fn test_multiple_single_process_refresh() { let mut s = System::new(); let process_refresh_kind = ProcessRefreshKind::new().with_cpu(); - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid_a]), process_refresh_kind); - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid_b]), process_refresh_kind); + s.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid_a]), + false, + process_refresh_kind, + ); + s.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid_b]), + false, + process_refresh_kind, + ); std::thread::sleep(std::time::Duration::from_secs(1)); - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid_a]), process_refresh_kind); - s.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid_b]), process_refresh_kind); + s.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid_a]), + true, + process_refresh_kind, + ); + s.refresh_processes_specifics( + ProcessesToUpdate::Some(&[pid_b]), + true, + process_refresh_kind, + ); let cpu_a = s.process(pid_a).unwrap().cpu_usage(); let cpu_b = s.process(pid_b).unwrap().cpu_usage(); diff --git a/tests/system.rs b/tests/system.rs --- a/tests/system.rs +++ b/tests/system.rs @@ -28,9 +28,12 @@ fn test_refresh_process() { #[cfg(not(feature = "apple-sandbox"))] if sysinfo::IS_SUPPORTED_SYSTEM { assert_eq!( - sys.refresh_processes(ProcessesToUpdate::Some(&[ - sysinfo::get_current_pid().expect("failed to get current pid") - ])), + sys.refresh_processes( + ProcessesToUpdate::Some(&[ + sysinfo::get_current_pid().expect("failed to get current pid") + ]), + false + ), 1, "process not listed", ); diff --git a/tests/system.rs b/tests/system.rs --- a/tests/system.rs +++ b/tests/system.rs @@ -44,7 +47,7 @@ fn test_refresh_process() { #[test] fn test_get_process() { let mut sys = System::new(); - sys.refresh_processes(ProcessesToUpdate::All); + sys.refresh_processes(ProcessesToUpdate::All, false); let current_pid = match sysinfo::get_current_pid() { Ok(pid) => pid, _ => { diff --git a/tests/system.rs b/tests/system.rs --- a/tests/system.rs +++ b/tests/system.rs @@ -76,7 +79,7 @@ fn check_if_send_and_sync() { impl<T> Bar for T where T: Sync {} let mut sys = System::new(); - sys.refresh_processes(ProcessesToUpdate::All); + sys.refresh_processes(ProcessesToUpdate::All, false); let current_pid = match sysinfo::get_current_pid() { Ok(pid) => pid, _ => { diff --git a/tests/system.rs b/tests/system.rs --- a/tests/system.rs +++ b/tests/system.rs @@ -137,7 +140,11 @@ fn test_consecutive_cpu_usage_update() { let mut sys = System::new_all(); assert!(!sys.cpus().is_empty()); - sys.refresh_processes_specifics(ProcessesToUpdate::All, ProcessRefreshKind::new().with_cpu()); + sys.refresh_processes_specifics( + ProcessesToUpdate::All, + true, + ProcessRefreshKind::new().with_cpu(), + ); let stop = Arc::new(AtomicBool::new(false)); // Spawning a few threads to ensure that it will actually have an impact on the CPU usage. diff --git a/tests/system.rs b/tests/system.rs --- a/tests/system.rs +++ b/tests/system.rs @@ -168,6 +175,7 @@ fn test_consecutive_cpu_usage_update() { for pid in &pids { sys.refresh_processes_specifics( ProcessesToUpdate::Some(&[*pid]), + true, ProcessRefreshKind::new().with_cpu(), ); }
[ "1340" ]
GuillaumeGomez__sysinfo-1353
GuillaumeGomez/sysinfo
diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -408,7 +408,7 @@ fn interpret_input( .take(1) .next() { - if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid])) != 0 { + if sys.refresh_processes(sysinfo::ProcessesToUpdate::Some(&[pid]), true) != 0 { writeln!(&mut io::stdout(), "Process `{pid}` updated successfully"); } else { writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated..."); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -54,7 +54,7 @@ pub extern "C" fn sysinfo_refresh_memory(system: CSystem) { let system: &mut System = system.borrow_mut(); system.refresh_memory(); } - Box::into_raw(system); + let _ = Box::into_raw(system); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -68,7 +68,7 @@ pub extern "C" fn sysinfo_refresh_cpu(system: CSystem) { let system: &mut System = system.borrow_mut(); system.refresh_cpu_usage(); } - Box::into_raw(system); + let _ = Box::into_raw(system); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -82,7 +82,7 @@ pub extern "C" fn sysinfo_refresh_all(system: CSystem) { let system: &mut System = system.borrow_mut(); system.refresh_all(); } - Box::into_raw(system); + let _ = Box::into_raw(system); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -96,9 +96,9 @@ pub extern "C" fn sysinfo_refresh_processes(system: CSystem) { let mut system: Box<System> = Box::from_raw(system as *mut System); { let system: &mut System = system.borrow_mut(); - system.refresh_processes(ProcessesToUpdate::All); + system.refresh_processes(ProcessesToUpdate::All, true); } - Box::into_raw(system); + let _ = Box::into_raw(system); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -112,9 +112,9 @@ pub extern "C" fn sysinfo_refresh_process(system: CSystem, pid: PID) { let mut system: Box<System> = Box::from_raw(system as *mut System); { let system: &mut System = system.borrow_mut(); - system.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(pid as _)])); + system.refresh_processes(ProcessesToUpdate::Some(&[Pid::from_u32(pid as _)]), true); } - Box::into_raw(system); + let _ = Box::into_raw(system); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -144,7 +144,7 @@ pub extern "C" fn sysinfo_disks_refresh(disks: CDisks) { let disks: &mut Disks = disks.borrow_mut(); disks.refresh(); } - Box::into_raw(disks); + let _ = Box::into_raw(disks); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -158,7 +158,7 @@ pub extern "C" fn sysinfo_disks_refresh_list(disks: CDisks) { let disks: &mut Disks = disks.borrow_mut(); disks.refresh_list(); } - Box::into_raw(disks); + let _ = Box::into_raw(disks); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -169,7 +169,7 @@ pub extern "C" fn sysinfo_total_memory(system: CSystem) -> size_t { unsafe { let system: Box<System> = Box::from_raw(system as *mut System); let ret = system.total_memory() as size_t; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -181,7 +181,7 @@ pub extern "C" fn sysinfo_free_memory(system: CSystem) -> size_t { unsafe { let system: Box<System> = Box::from_raw(system as *mut System); let ret = system.free_memory() as size_t; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -192,7 +192,7 @@ pub extern "C" fn sysinfo_used_memory(system: CSystem) -> size_t { assert!(!system.is_null()); let system: Box<System> = unsafe { Box::from_raw(system as *mut System) }; let ret = system.used_memory() as size_t; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -203,7 +203,7 @@ pub extern "C" fn sysinfo_total_swap(system: CSystem) -> size_t { unsafe { let system: Box<System> = Box::from_raw(system as *mut System); let ret = system.total_swap() as size_t; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -215,7 +215,7 @@ pub extern "C" fn sysinfo_free_swap(system: CSystem) -> size_t { unsafe { let system: Box<System> = Box::from_raw(system as *mut System); let ret = system.free_swap() as size_t; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -227,7 +227,7 @@ pub extern "C" fn sysinfo_used_swap(system: CSystem) -> size_t { unsafe { let system: Box<System> = Box::from_raw(system as *mut System); let ret = system.used_swap() as size_t; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -258,7 +258,7 @@ pub extern "C" fn sysinfo_networks_refresh_list(networks: CNetworks) { let networks: &mut Networks = networks.borrow_mut(); networks.refresh_list(); } - Box::into_raw(networks); + let _ = Box::into_raw(networks); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -272,7 +272,7 @@ pub extern "C" fn sysinfo_networks_refresh(networks: CNetworks) { let networks: &mut Networks = networks.borrow_mut(); networks.refresh(); } - Box::into_raw(networks); + let _ = Box::into_raw(networks); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -286,7 +286,7 @@ pub extern "C" fn sysinfo_networks_received(networks: CNetworks) -> size_t { let ret = networks.iter().fold(0, |acc: size_t, (_, data)| { acc.saturating_add(data.received() as size_t) }); - Box::into_raw(networks); + let _ = Box::into_raw(networks); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -301,7 +301,7 @@ pub extern "C" fn sysinfo_networks_transmitted(networks: CNetworks) -> size_t { let ret = networks.iter().fold(0, |acc: size_t, (_, data)| { acc.saturating_add(data.transmitted() as size_t) }); - Box::into_raw(networks); + let _ = Box::into_raw(networks); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -333,7 +333,7 @@ pub extern "C" fn sysinfo_cpus_usage( } *length = cpus.len() as c_uint - 1; } - Box::into_raw(system); + let _ = Box::into_raw(system); } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -362,7 +362,7 @@ pub extern "C" fn sysinfo_processes( } entries.len() as size_t }; - Box::into_raw(system); + let _ = Box::into_raw(system); len } } else { diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -386,7 +386,7 @@ pub extern "C" fn sysinfo_process_by_pid(system: CSystem, pid: PID) -> CProcess } else { std::ptr::null() }; - Box::into_raw(system); + let _ = Box::into_raw(system); ret } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -534,7 +534,7 @@ pub extern "C" fn sysinfo_cpu_vendor_id(system: CSystem) -> RString { } else { std::ptr::null() }; - Box::into_raw(system); + let _ = Box::into_raw(system); c_string } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -554,7 +554,7 @@ pub extern "C" fn sysinfo_cpu_brand(system: CSystem) -> RString { } else { std::ptr::null() }; - Box::into_raw(system); + let _ = Box::into_raw(system); c_string } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -566,7 +566,7 @@ pub extern "C" fn sysinfo_cpu_physical_cores(system: CSystem) -> u32 { unsafe { let system: Box<System> = Box::from_raw(system as *mut System); let count = system.physical_core_count().unwrap_or(0); - Box::into_raw(system); + let _ = Box::into_raw(system); count as u32 } } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -582,7 +582,7 @@ pub extern "C" fn sysinfo_cpu_frequency(system: CSystem) -> u64 { .first() .map(|cpu| cpu.frequency()) .unwrap_or(0); - Box::into_raw(system); + let _ = Box::into_raw(system); freq } } diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -107,7 +107,7 @@ impl System { self.refresh_cpu_specifics(kind); } if let Some(kind) = refreshes.processes() { - self.refresh_processes_specifics(ProcessesToUpdate::All, kind); + self.refresh_processes_specifics(ProcessesToUpdate::All, false, kind); } } diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -262,6 +262,7 @@ impl System { /// # let mut system = System::new(); /// system.refresh_processes_specifics( /// ProcessesToUpdate::All, + /// true, /// ProcessRefreshKind::new() /// .with_memory() /// .with_cpu() diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -270,8 +271,9 @@ impl System { /// ); /// ``` /// - /// ⚠️ Unless `ProcessesToUpdate::All` is used, dead processes are not removed from - /// the set of processes kept in [`System`]. + /// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is + /// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed + /// since 7 is not part of the update. /// /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour /// by using [`set_open_files_limit`][crate::set_open_files_limit]. diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -282,11 +284,16 @@ impl System { /// use sysinfo::{ProcessesToUpdate, System}; /// /// let mut s = System::new_all(); - /// s.refresh_processes(ProcessesToUpdate::All); + /// s.refresh_processes(ProcessesToUpdate::All, true); /// ``` - pub fn refresh_processes(&mut self, processes_to_update: ProcessesToUpdate<'_>) -> usize { + pub fn refresh_processes( + &mut self, + processes_to_update: ProcessesToUpdate<'_>, + remove_dead_processes: bool, + ) -> usize { self.refresh_processes_specifics( processes_to_update, + remove_dead_processes, ProcessRefreshKind::new() .with_memory() .with_cpu() diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -299,8 +306,9 @@ impl System { /// /// Returns the number of updated processes. /// - /// ⚠️ Unless `ProcessesToUpdate::All` is used, dead processes are not removed from - /// the set of processes kept in [`System`]. + /// ⚠️ `remove_dead_processes` works as follows: if an updated process is dead, then it is + /// removed. So if you refresh pids 1, 2 and 3. If 2 and 7 are dead, only 2 will be removed + /// since 7 is not part of the update. /// /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour /// by using [`set_open_files_limit`][crate::set_open_files_limit]. diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -309,15 +317,60 @@ impl System { /// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System}; /// /// let mut s = System::new_all(); - /// s.refresh_processes_specifics(ProcessesToUpdate::All, ProcessRefreshKind::new()); + /// s.refresh_processes_specifics( + /// ProcessesToUpdate::All, + /// true, + /// ProcessRefreshKind::everything(), + /// ); /// ``` pub fn refresh_processes_specifics( &mut self, processes_to_update: ProcessesToUpdate<'_>, + remove_dead_processes: bool, refresh_kind: ProcessRefreshKind, ) -> usize { - self.inner - .refresh_processes_specifics(processes_to_update, refresh_kind) + fn update_and_remove(pid: &Pid, processes: &mut HashMap<Pid, Process>) { + let updated = if let Some(proc) = processes.get_mut(pid) { + proc.inner.switch_updated() + } else { + return; + }; + if !updated { + processes.remove(pid); + } + } + fn update(pid: &Pid, processes: &mut HashMap<Pid, Process>) { + if let Some(proc) = processes.get_mut(pid) { + proc.inner.switch_updated(); + } + } + + let nb_updated = self + .inner + .refresh_processes_specifics(processes_to_update, refresh_kind); + let processes = self.inner.processes_mut(); + match processes_to_update { + ProcessesToUpdate::All => { + if remove_dead_processes { + processes.retain(|_, v| v.inner.switch_updated()); + } else { + for proc in processes.values_mut() { + proc.inner.switch_updated(); + } + } + } + ProcessesToUpdate::Some(pids) => { + let call = if remove_dead_processes { + update_and_remove + } else { + update + }; + for pid in pids { + call(pid, processes); + } + } + } + nb_updated } /// Returns the process list. diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -1371,6 +1424,7 @@ impl Process { /// // Refresh CPU usage to get actual value. /// s.refresh_processes_specifics( /// ProcessesToUpdate::All, + /// true, /// ProcessRefreshKind::new().with_cpu() /// ); /// if let Some(process) = s.process(Pid::from(1337)) { diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -1844,6 +1898,7 @@ assert_eq!(r.", stringify!($name), "().is_some(), false); /// let mut system = System::new(); /// system.refresh_processes_specifics( /// ProcessesToUpdate::All, +/// true, /// ProcessRefreshKind::new().with_exe(UpdateKind::OnlyIfNotSet), /// ); /// ``` diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -1880,11 +1935,12 @@ impl UpdateKind { /// /// let mut system = System::new(); /// // To refresh all processes: -/// system.refresh_processes(ProcessesToUpdate::All); +/// system.refresh_processes(ProcessesToUpdate::All, true); /// /// // To refresh only the current one: /// system.refresh_processes( /// ProcessesToUpdate::Some(&[get_current_pid().unwrap()]), +/// true, /// ); /// ``` #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -1917,6 +1973,7 @@ pub enum ProcessesToUpdate<'a> { /// // We don't want to update the CPU information. /// system.refresh_processes_specifics( /// ProcessesToUpdate::All, +/// true, /// ProcessRefreshKind::everything().without_cpu(), /// ); /// diff --git a/src/unix/apple/app_store/process.rs b/src/unix/apple/app_store/process.rs --- a/src/unix/apple/app_store/process.rs +++ b/src/unix/apple/app_store/process.rs @@ -93,4 +93,8 @@ impl ProcessInner { pub(crate) fn session_id(&self) -> Option<Pid> { None } + + pub(crate) fn switch_updated(&mut self) -> bool { + false + } } diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -226,6 +226,10 @@ impl ProcessInner { } } } + + pub(crate) fn switch_updated(&mut self) -> bool { + std::mem::replace(&mut self.updated, false) + } } #[allow(deprecated)] // Because of libc::mach_absolute_time. diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -260,17 +260,16 @@ impl SystemInner { } #[allow(clippy::type_complexity)] - let (filter, filter_callback, remove_processes): ( + let (filter, filter_callback): ( &[Pid], &(dyn Fn(Pid, &[Pid]) -> bool + Sync + Send), - bool, ) = match processes_to_update { - ProcessesToUpdate::All => (&[], &empty_filter, true), + ProcessesToUpdate::All => (&[], &empty_filter), ProcessesToUpdate::Some(pids) => { if pids.is_empty() { return 0; } - (pids, &real_filter, false) + (pids, &real_filter) } }; diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -298,10 +297,6 @@ impl SystemInner { entries.into_iter().for_each(|entry| { self.process_list.insert(entry.pid(), entry); }); - if remove_processes { - self.process_list - .retain(|_, proc_| std::mem::replace(&mut proc_.inner.updated, false)); - } nb_updated.into_inner() } else { 0 diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -316,6 +311,10 @@ impl SystemInner { &self.process_list } + pub(crate) fn processes_mut(&mut self) -> &mut HashMap<Pid, Process> { + &mut self.process_list + } + pub(crate) fn process(&self, pid: Pid) -> Option<&Process> { self.process_list.get(&pid) } diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -178,6 +178,10 @@ impl ProcessInner { } } } + + pub(crate) fn switch_updated(&mut self) -> bool { + std::mem::replace(&mut self.updated, false) + } } pub(crate) unsafe fn get_process_data( diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -293,7 +297,7 @@ pub(crate) unsafe fn get_process_data( old_read_bytes: 0, written_bytes: kproc.ki_rusage.ru_oublock as _, old_written_bytes: 0, - updated: false, + updated: true, }, })) } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -131,6 +131,10 @@ impl SystemInner { &self.process_list } + pub(crate) fn processes_mut(&mut self) -> &mut HashMap<Pid, Process> { + &mut self.process_list + } + pub(crate) fn process(&self, pid: Pid) -> Option<&Process> { self.process_list.get(&pid) } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -294,17 +298,16 @@ impl SystemInner { } #[allow(clippy::type_complexity)] - let (filter, filter_callback, remove_processes): ( + let (filter, filter_callback): ( &[Pid], &(dyn Fn(&libc::kinfo_proc, &[Pid]) -> bool + Sync + Send), - bool, ) = match processes_to_update { - ProcessesToUpdate::All => (&[], &empty_filter, true), + ProcessesToUpdate::All => (&[], &empty_filter), ProcessesToUpdate::Some(pids) => { if pids.is_empty() { return 0; } - (pids, &real_filter, false) + (pids, &real_filter) } }; diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -343,12 +346,6 @@ impl SystemInner { .collect::<Vec<_>>() }; - if remove_processes { - // We remove all processes that don't exist anymore. - self.process_list - .retain(|_, v| std::mem::replace(&mut v.inner.updated, false)); - } - for process in new_processes { self.process_list.insert(process.inner.pid, process); } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -278,6 +278,10 @@ impl ProcessInner { pub(crate) fn thread_kind(&self) -> Option<ThreadKind> { self.thread_kind } + + pub(crate) fn switch_updated(&mut self) -> bool { + std::mem::replace(&mut self.updated, false) + } } pub(crate) fn compute_cpu_usage(p: &mut ProcessInner, total_time: f32, max_value: f32) { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -297,10 +301,6 @@ pub(crate) fn compute_cpu_usage(p: &mut ProcessInner, total_time: f32, max_value .min(max_value); } -pub(crate) fn unset_updated(p: &mut ProcessInner) { - p.updated = false; -} - pub(crate) fn set_time(p: &mut ProcessInner, utime: u64, stime: u64) { p.old_utime = p.utime; p.old_stime = p.stime; diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::cpu::{get_physical_core_count, CpusWrapper}; -use crate::sys::process::{compute_cpu_usage, refresh_procs, unset_updated}; +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}; diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -173,38 +173,24 @@ impl SystemInner { self.cpus.len() as f32 * 100. } - fn clear_procs(&mut self, refresh_kind: ProcessRefreshKind) { - let (total_time, compute_cpu, max_value) = if refresh_kind.cpu() { - self.cpus - .refresh_if_needed(true, CpuRefreshKind::new().with_cpu_usage()); + fn update_procs_cpu(&mut self, refresh_kind: ProcessRefreshKind) { + if !refresh_kind.cpu() { + return; + } + 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..."); - (0., false, 0.) - } else { - let (new, old) = self.cpus.get_global_raw_times(); - let total_time = if old > new { 1 } else { new - old }; - ( - total_time as f32 / self.cpus.len() as f32, - true, - self.get_max_process_cpu_usage(), - ) - } - } else { - (0., false, 0.) - }; + if self.cpus.is_empty() { + sysinfo_debug!("cannot compute processes CPU usage: no CPU found..."); + return; + } + let (new, old) = self.cpus.get_global_raw_times(); + let total_time = if old > new { 1 } else { new - old }; + let total_time = total_time as f32 / self.cpus.len() as f32; + let max_value = self.get_max_process_cpu_usage(); - self.process_list.retain(|_, proc_| { - let proc_ = &mut proc_.inner; - if !proc_.updated { - return false; - } - if compute_cpu { - compute_cpu_usage(proc_, total_time, max_value); - } - unset_updated(proc_); - true - }); + for proc_ in self.process_list.values_mut() { + compute_cpu_usage(&mut proc_.inner, total_time, max_value); + } } fn refresh_cpus(&mut self, only_update_global_cpu: bool, refresh_kind: CpuRefreshKind) { diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -291,7 +277,7 @@ impl SystemInner { refresh_kind, ); if matches!(processes_to_update, ProcessesToUpdate::All) { - self.clear_procs(refresh_kind); + self.update_procs_cpu(refresh_kind); self.cpus.set_need_cpus_update(); } nb_updated diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -305,6 +291,10 @@ impl SystemInner { &self.process_list } + pub(crate) fn processes_mut(&mut self) -> &mut HashMap<Pid, Process> { + &mut self.process_list + } + pub(crate) fn process(&self, pid: Pid) -> Option<&Process> { self.process_list.get(&pid) } diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -103,4 +103,8 @@ impl ProcessInner { pub(crate) fn session_id(&self) -> Option<Pid> { None } + + pub(crate) fn switch_updated(&mut self) -> bool { + false + } } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -16,13 +16,13 @@ pub const SUPPORTED_SIGNALS: &[crate::Signal] = supported_signals(); pub const MINIMUM_CPU_UPDATE_INTERVAL: Duration = Duration::from_millis(0); pub(crate) struct SystemInner { - processes_list: HashMap<Pid, Process>, + process_list: HashMap<Pid, Process>, } impl SystemInner { pub(crate) fn new() -> Self { Self { - processes_list: Default::default(), + process_list: Default::default(), } } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -49,7 +49,11 @@ impl SystemInner { // Need to be moved into a "common" file to avoid duplication. pub(crate) fn processes(&self) -> &HashMap<Pid, Process> { - &self.processes_list + &self.process_list + } + + pub(crate) fn processes_mut(&mut self) -> &mut HashMap<Pid, Process> { + &mut self.process_list } pub(crate) fn process(&self, _pid: Pid) -> Option<&Process> { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -443,6 +443,10 @@ impl ProcessInner { None } } + + pub(crate) fn switch_updated(&mut self) -> bool { + std::mem::replace(&mut self.updated, false) + } } #[inline] diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -10,7 +10,7 @@ use crate::utils::into_iter; use std::cell::UnsafeCell; use std::collections::HashMap; use std::ffi::{OsStr, OsString}; -use std::mem::{replace, size_of, zeroed}; +use std::mem::{size_of, zeroed}; use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::ptr; use std::sync::atomic::{AtomicUsize, Ordering}; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -199,17 +199,16 @@ impl SystemInner { } #[allow(clippy::type_complexity)] - let (filter_array, filter_callback, remove_processes): ( + let (filter_array, filter_callback): ( &[Pid], &(dyn Fn(Pid, &[Pid]) -> bool + Sync + Send), - bool, ) = match processes_to_update { - ProcessesToUpdate::All => (&[], &empty_filter, true), + ProcessesToUpdate::All => (&[], &empty_filter), ProcessesToUpdate::Some(pids) => { if pids.is_empty() { return 0; } - (pids, &real_filter, false) + (pids, &real_filter) } }; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -337,11 +336,6 @@ impl SystemInner { for p in processes.into_iter() { self.process_list.insert(p.pid(), p); } - if remove_processes { - // If it comes from `refresh_process` or `refresh_pids`, we don't remove - // dead processes. - self.process_list.retain(|_, v| replace(&mut v.inner.updated, false)); - } nb_updated.into_inner() } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -350,6 +344,10 @@ impl SystemInner { &self.process_list } + pub(crate) fn processes_mut(&mut self) -> &mut HashMap<Pid, Process> { + &mut self.process_list + } + pub(crate) fn process(&self, pid: Pid) -> Option<&Process> { self.process_list.get(&pid) }
6f1d3822765b3ba3b9fe774d8d2e3798c31fce5d
Add some way to remove a closed process I'm attaching to specific individual processes and want to know when they are closed, so I use ```rust if system.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), ProcessRefreshKind::new()) == 0 { ... } ``` to check for that situation. Unfortunately as stated by the documentation, this does not remove it from the entire list of processes. This means I need to run ```rust system.refresh_processes_specifics( ProcessesToUpdate::All, ProcessRefreshKind::new().with_exe(UpdateKind::OnlyIfNotSet), ); ``` inside to ensure it gets removed. This is very wasteful. I'd appreciate some sort of way for me to either manually remove it from the list or some argument I can pass / config I can set, so it gets removed properly. Though arguably the entire default seems questionable to me too.
0.31
1,353
Interesting: I was thinking about adding a new `remove_dead_processes` boolean field in `ProcessProcessKind` or as new parameter. Not clear yet. I suppose it would fix your case? Yeah absolutely, as long as it doesn't wastefully have to scan the entire process list or so. Sadly it kinda still needs to iterate processes or PIDs depending on the platform. Can it not reuse the information it got from just refreshing the single process? Just refreshing one process, depending on the platform, can require to go through processes/PIDs list given by the system. I guess that's fine, as long as it can directly use that information and not query it a second time, like I do currently.
6f1d3822765b3ba3b9fe774d8d2e3798c31fce5d
2024-07-24T20:46:11Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -813,3 +813,47 @@ fn test_parent_change() { // We kill the child to clean up. child.kill(); } + +// We want to ensure that if `System::refresh_process*` methods are called +// one after the other, it won't impact the CPU usage computation badly. +#[test] +fn test_multiple_single_process_refresh() { + if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") || cfg!(windows) { + // Windows never updates its parent PID so no need to check anything. + return; + } + + let file_name = "target/test_binary3"; + build_test_binary(file_name); + let mut p_a = std::process::Command::new(format!("./{file_name}")) + .arg("1") + .spawn() + .unwrap(); + let mut p_b = std::process::Command::new(format!("./{file_name}")) + .arg("1") + .spawn() + .unwrap(); + + let pid_a = Pid::from_u32(p_a.id() as _); + let pid_b = Pid::from_u32(p_b.id() as _); + + let mut s = System::new(); + let process_refresh_kind = ProcessRefreshKind::new().with_cpu(); + s.refresh_process_specifics(pid_a, process_refresh_kind); + s.refresh_process_specifics(pid_b, process_refresh_kind); + + std::thread::sleep(std::time::Duration::from_secs(1)); + s.refresh_process_specifics(pid_a, process_refresh_kind); + s.refresh_process_specifics(pid_b, process_refresh_kind); + + let cpu_a = s.process(pid_a).unwrap().cpu_usage(); + let cpu_b = s.process(pid_b).unwrap().cpu_usage(); + + p_a.kill().expect("failed to kill process a"); + p_b.kill().expect("failed to kill process b"); + + let _ = p_a.wait(); + let _ = p_b.wait(); + + assert!(cpu_b - 5. < cpu_a && cpu_b + 5. > cpu_a); +}
[ "1299" ]
GuillaumeGomez__sysinfo-1324
GuillaumeGomez/sysinfo
diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -367,6 +367,9 @@ impl System { /// exist (it will **NOT** be removed from the processes if it doesn't exist anymore). If it /// isn't listed yet, it'll be added. /// + /// ⚠️ If you need to refresh multiple processes at once, use [`refresh_pids`] instead! It has + /// much better performance. + /// /// It is the same as calling: /// /// ```no_run diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -394,6 +397,8 @@ impl System { /// let mut s = System::new_all(); /// s.refresh_process(Pid::from(1337)); /// ``` + /// + /// [`refresh_pids`]: #method.refresh_pids pub fn refresh_process(&mut self, pid: Pid) -> bool { self.refresh_process_specifics( pid, diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -409,6 +414,9 @@ impl System { /// exist (it will **NOT** be removed from the processes if it doesn't exist anymore). If it /// isn't listed yet, it'll be added. /// + /// ⚠️ If you need to refresh multiple processes at once, use [`refresh_pids_specifics`] + /// instead! It has much better performance. + /// /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour /// by using [`set_open_files_limit`][crate::set_open_files_limit]. /// diff --git a/src/common/system.rs b/src/common/system.rs --- a/src/common/system.rs +++ b/src/common/system.rs @@ -418,6 +426,8 @@ impl System { /// let mut s = System::new_all(); /// s.refresh_process_specifics(Pid::from(1337), ProcessRefreshKind::new()); /// ``` + /// + /// [`refresh_pids_specifics`]: #method.refresh_pids_specifics pub fn refresh_process_specifics( &mut self, pid: Pid, diff --git a/src/unix/apple/macos/system.rs b/src/unix/apple/macos/system.rs --- a/src/unix/apple/macos/system.rs +++ b/src/unix/apple/macos/system.rs @@ -8,6 +8,7 @@ use libc::{ processor_cpu_load_info_t, sysconf, vm_page_size, PROCESSOR_CPU_LOAD_INFO, _SC_CLK_TCK, }; use std::ptr::null_mut; +use std::time::Instant; struct ProcessorCpuLoadInfo { cpu_load: processor_cpu_load_info_t, diff --git a/src/unix/apple/macos/system.rs b/src/unix/apple/macos/system.rs --- a/src/unix/apple/macos/system.rs +++ b/src/unix/apple/macos/system.rs @@ -55,6 +56,8 @@ pub(crate) struct SystemTimeInfo { timebase_to_ns: f64, clock_per_sec: f64, old_cpu_info: ProcessorCpuLoadInfo, + last_update: Option<Instant>, + prev_time_interval: f64, } unsafe impl Send for SystemTimeInfo {} diff --git a/src/unix/apple/macos/system.rs b/src/unix/apple/macos/system.rs --- a/src/unix/apple/macos/system.rs +++ b/src/unix/apple/macos/system.rs @@ -97,40 +100,52 @@ impl SystemTimeInfo { timebase_to_ns: info.numer as f64 / info.denom as f64, clock_per_sec: nano_per_seconds / clock_ticks_per_sec as f64, old_cpu_info, + last_update: None, + prev_time_interval: 0., }) } } pub fn get_time_interval(&mut self, port: mach_port_t) -> f64 { - let mut total = 0; - let new_cpu_info = match ProcessorCpuLoadInfo::new(port) { - Some(cpu_info) => cpu_info, - None => return 0., - }; - let cpu_count = std::cmp::min(self.old_cpu_info.cpu_count, new_cpu_info.cpu_count); - unsafe { - for i in 0..cpu_count { - let new_load: &processor_cpu_load_info = &*new_cpu_info.cpu_load.offset(i as _); - let old_load: &processor_cpu_load_info = - &*self.old_cpu_info.cpu_load.offset(i as _); - for (new, old) in new_load.cpu_ticks.iter().zip(old_load.cpu_ticks.iter()) { - if new > old { - total += new.saturating_sub(*old); + let need_cpu_usage_update = self + .last_update + .map(|last_update| last_update.elapsed() > crate::MINIMUM_CPU_UPDATE_INTERVAL) + .unwrap_or(true); + if need_cpu_usage_update { + let mut total = 0; + let new_cpu_info = match ProcessorCpuLoadInfo::new(port) { + Some(cpu_info) => cpu_info, + None => return 0., + }; + let cpu_count = std::cmp::min(self.old_cpu_info.cpu_count, new_cpu_info.cpu_count); + unsafe { + for i in 0..cpu_count { + let new_load: &processor_cpu_load_info = &*new_cpu_info.cpu_load.offset(i as _); + let old_load: &processor_cpu_load_info = + &*self.old_cpu_info.cpu_load.offset(i as _); + for (new, old) in new_load.cpu_ticks.iter().zip(old_load.cpu_ticks.iter()) { + if new > old { + total += new.saturating_sub(*old); + } } } } self.old_cpu_info = new_cpu_info; + self.last_update = Some(Instant::now()); // Now we convert the ticks to nanoseconds (if the interval is less than // `MINIMUM_CPU_UPDATE_INTERVAL`, we replace it with it instead): let base_interval = total as f64 / cpu_count as f64 * self.clock_per_sec; let smallest = crate::MINIMUM_CPU_UPDATE_INTERVAL.as_secs_f64() * 1_000_000_000.0; - if base_interval < smallest { + self.prev_time_interval = if base_interval < smallest { smallest } else { base_interval / self.timebase_to_ns - } + }; + self.prev_time_interval + } else { + self.prev_time_interval } } }
296bbf02359b11eef28fc344832760b654215a22
Refreshing multiple processes on macos leads to invalid cpu usage I have a piece of code that looks like this: ```rust let mut sys = sysinfo::System::new(); let process_refresh_kind = ProcessRefreshKind::everything().without_disk_usage().without_environ(); sys.refresh_process_specifics(pid_a, process_refresh_kind); sys.refresh_process_specifics(pid_b, process_refresh_kind); loop { // Wait 1 minute std::thread::sleep(std::time::Duration::from_secs(60)); // Refresh CPU measurement sys.refresh_process_specifics(pid_a, process_refresh_kind); sys.refresh_process_specifics(pid_b, process_refresh_kind); // Get CPU usage of the two processes let cpu_a = sys.process(pid_a).map(|p| p.cpu_usage()); let cpu_b = sys.process(pid_b).map(|p| p.cpu_usage()); println!("cpu a: {:?}, cpu b: {:?}", cpu_a, cpu_b); } ``` With this code, the cpu for process A seems to be valid, but the one for process B is way too high, it can even get higher than the max value. Looking at the code, I see that the function `compute_cpu_usage` uses a `time_interval` variable. This value seems to be right on the first call to refresh (for pid A), but not on the second call (for pid B). I suppose this value is reset after each call to "refresh_process", leading to the second call computing a CPU load with a time interval that is way too small. Here is a reproducer: ```rust fn main() { let mut sys = sysinfo::System::new(); let pid_a = sysinfo::Pid::from_u32(std::process::id()); let pid_b = sysinfo::Pid::from_u32(1); let process_refresh_kind = sysinfo::ProcessRefreshKind::everything() .without_disk_usage() .without_environ(); sys.refresh_process_specifics(pid_a, process_refresh_kind); sys.refresh_process_specifics(pid_b, process_refresh_kind); loop { std::thread::sleep(std::time::Duration::from_secs(10)); sys.refresh_process_specifics(pid_a, process_refresh_kind); sys.refresh_process_specifics(pid_b, process_refresh_kind); let cpu_a = sys.process(pid_a).map(|p| p.cpu_usage()); let cpu_b = sys.process(pid_b).map(|p| p.cpu_usage()); println!("cpu a: {:?}, cpu b: {:?}", cpu_a, cpu_b); } } ``` Reversing the two PIDs reverses the one that is reported with a very high CPU usage, showing the bug. This was reproduced on 0.30.12 on macos x64.
0.30
1,324
For this kind of operations, you likely want to use [refresh_pids_specifics](https://docs.rs/sysinfo/latest/sysinfo/struct.System.html#method.refresh_pids_specifics). Although, in this case it should still work. Indeed, I didn't know about this API, and it fixes the issue. I'm leaving this issue open since there is still a bug afaict, but i'm no longer blocked by it, I let you decide what to do with it. Thanks! It definitely needs to be fixed. Gonna try to take a look in the next days.
296bbf02359b11eef28fc344832760b654215a22
2024-04-10T14:17:27Z
diff --git /dev/null b/tests/components.rs new file mode 100644 --- /dev/null +++ b/tests/components.rs @@ -0,0 +1,17 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +#[test] +fn test_components() { + use std::env::var; + + let mut c = sysinfo::Components::new(); + assert!(c.is_empty()); + + // Unfortunately, we can't get components in the CI... + if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(windows) || var("CI").is_ok() { + return; + } + + c.refresh_list(); + assert!(!c.is_empty()); +}
[ "1245" ]
GuillaumeGomez__sysinfo-1249
GuillaumeGomez/sysinfo
diff --git a/src/unix/linux/component.rs b/src/unix/linux/component.rs --- a/src/unix/linux/component.rs +++ b/src/unix/linux/component.rs @@ -374,16 +374,15 @@ impl ComponentsInner { continue; }; let entry = entry.path(); - if !file_type.is_dir() - || !entry + if !file_type.is_file() + && entry .file_name() .and_then(|x| x.to_str()) .unwrap_or("") .starts_with("hwmon") { - continue; + ComponentInner::from_hwmon(&mut self.components, &entry); } - ComponentInner::from_hwmon(&mut self.components, &entry); } } }
93f9b823c1a5cd56f271e48cf879ede312914c64
Temperatures on Linux unavailable A commit on April 7, 2024 causes temperatures on Linux to not be available. The `temperature` command in `examples/simple.rs` no longer prints anything on commit [87c627c1ff07c6a43060c397bcb401e5d72d33e0](https://github.com/GuillaumeGomez/sysinfo/commit/87c627c1ff07c6a43060c397bcb401e5d72d33e0) or later.
0.30
1,249
296bbf02359b11eef28fc344832760b654215a22
2024-01-04T18:06:14Z
diff --git a/.cirrus.yml b/.cirrus.yml --- a/.cirrus.yml +++ b/.cirrus.yml @@ -37,14 +37,14 @@ task: - FREEBSD_CI=1 cargo test --lib -j1 -- --ignored task: - name: rust 1.70 on mac m1 + name: rust 1.74 on mac m1 macos_instance: image: ghcr.io/cirruslabs/macos-monterey-base:latest setup_script: - brew update - brew install curl - curl https://sh.rustup.rs -sSf --output rustup.sh - - sh rustup.sh -y --profile=minimal --default-toolchain=1.70 + - sh rustup.sh -y --profile=minimal --default-toolchain=1.74 - source $HOME/.cargo/env - rustup --version - rustup component add clippy diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -64,7 +64,7 @@ jobs: - { os: 'ubuntu-latest', target: 'x86_64-linux-android', cross: true } - { os: 'ubuntu-latest', target: 'i686-linux-android', cross: true } toolchain: - - "1.70.0" # minimum supported rust version + - "1.74.0" # minimum supported rust version - stable - nightly steps: diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -133,7 +133,7 @@ jobs: - macos-latest - windows-latest toolchain: - - "1.70.0" # minimum supported rust version + - "1.74.0" # minimum supported rust version - stable - nightly steps: diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -6,7 +6,7 @@ description = "Library to get system information such as processes, CPUs, disks, repository = "https://github.com/GuillaumeGomez/sysinfo" license = "MIT" readme = "README.md" -rust-version = "1.70" +rust-version = "1.74" exclude = ["/test-unknown"] categories = ["filesystem", "os", "api-bindings"] edition = "2018" diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -94,3 +95,4 @@ tempfile = "3.9" [dev-dependencies] serde_json = "1.0" # Used in documentation tests. +bstr = "1.9.0" # Used in example diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -404,7 +404,10 @@ fn test_refresh_tasks() { .map(|task| task.name() == task_name) .unwrap_or(false))) .unwrap_or(false)); - assert!(s.processes_by_exact_name(task_name).next().is_some()); + assert!(s + .processes_by_exact_name(task_name.as_ref()) + .next() + .is_some()); // Let's give some time to the system to clean up... std::thread::sleep(std::time::Duration::from_secs(2)); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -420,7 +423,10 @@ fn test_refresh_tasks() { .map(|task| task.name() == task_name) .unwrap_or(false))) .unwrap_or(false)); - assert!(s.processes_by_exact_name(task_name).next().is_none()); + assert!(s + .processes_by_exact_name(task_name.as_ref()) + .next() + .is_none()); } // Checks that `refresh_process` is NOT removing dead processes. diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -564,14 +570,14 @@ fn test_process_iterator_lifetimes() { { let name = String::from(""); // errors before PR #904: name does not live long enough - process = s.processes_by_name(&name).next(); + process = s.processes_by_name(name.as_ref()).next(); } process.unwrap(); let process: Option<&sysinfo::Process>; { // worked fine before and after: &'static str lives longer than System, error couldn't appear - process = s.processes_by_name("").next(); + process = s.processes_by_name("".as_ref()).next(); } process.unwrap(); }
[ "1190" ]
GuillaumeGomez__sysinfo-1196
GuillaumeGomez/sysinfo
diff --git a/.cirrus.yml b/.cirrus.yml --- a/.cirrus.yml +++ b/.cirrus.yml @@ -1,10 +1,10 @@ task: - name: rust 1.70 on freebsd 13 + name: rust 1.74 on freebsd 13 freebsd_instance: image: freebsd-13-1-release-amd64 setup_script: - curl https://sh.rustup.rs -sSf --output rustup.sh - - sh rustup.sh -y --profile=minimal --default-toolchain=1.70 + - sh rustup.sh -y --profile=minimal --default-toolchain=1.74 - . $HOME/.cargo/env - rustup --version - rustup component add clippy diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -195,7 +195,7 @@ jobs: strategy: matrix: toolchain: - - "1.70.0" # minimum supported rust version + - "1.74.0" # minimum supported rust version - stable steps: - uses: actions/checkout@v4 diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,17 @@ version = "2.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +[[package]] +name = "bstr" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706" +dependencies = [ + "memchr", + "regex-automata", + "serde", +] + [[package]] name = "cfg-if" version = "1.0.0" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -85,6 +96,12 @@ version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" +[[package]] +name = "memchr" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" + [[package]] name = "ntapi" version = "0.4.1" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -132,6 +149,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "regex-automata" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" + [[package]] name = "rustix" version = "0.38.31" diff --git a/Cargo.lock b/Cargo.lock --- a/Cargo.lock +++ b/Cargo.lock @@ -197,9 +220,11 @@ dependencies = [ name = "sysinfo" version = "0.30.7" dependencies = [ + "bstr", "cfg-if", "core-foundation-sys", "libc", + "memchr", "ntapi", "rayon", "serde", diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,7 @@ rustdoc-args = ["--generate-link-to-definition"] [dependencies] cfg-if = "1.0" +memchr = "2.7.1" rayon = { version = "^1.8", optional = true } serde = { version = "^1.0.190", optional = true } diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ You can still use `sysinfo` on non-supported OSes, it'll simply do nothing and a empty values. You can check in your program directly if an OS is supported by checking the [`IS_SUPPORTED_SYSTEM`] constant. -The minimum-supported version of `rustc` is **1.70**. +The minimum-supported version of `rustc` is **1.74**. ## Usage diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -68,7 +68,7 @@ println!("NB CPUs: {}", sys.cpus().len()); // Display processes ID, name na disk usage: for (pid, process) in sys.processes() { - println!("[{pid}] {} {:?}", process.name(), process.disk_usage()); + println!("[{pid}] {:?} {:?}", process.name(), process.disk_usage()); } // We display all disks' information: diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -182,8 +182,8 @@ virtual systems. Apple has restrictions as to which APIs can be linked into binaries that are distributed through the app store. By default, `sysinfo` is not compatible with these restrictions. You can use the `apple-app-store` -feature flag to disable the Apple prohibited features. This also enables the `apple-sandbox` feature. -In the case of applications using the sandbox outside of the app store, the `apple-sandbox` feature +feature flag to disable the Apple prohibited features. This also enables the `apple-sandbox` feature. +In the case of applications using the sandbox outside of the app store, the `apple-sandbox` feature can be used alone to avoid causing policy violations at runtime. ### How it works diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -4,6 +4,7 @@ #![allow(unused_must_use, non_upper_case_globals)] #![allow(clippy::manual_range_contains)] +use bstr::ByteSlice; use std::io::{self, BufRead, Write}; use std::str::FromStr; use sysinfo::{Components, Disks, Networks, Pid, Signal, System, Users}; diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -242,7 +243,7 @@ fn interpret_input( &mut io::stdout(), "{}:{} status={:?}", pid, - proc_.name(), + proc_.name().as_encoded_bytes().as_bstr(), proc_.status() ); } diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -289,8 +290,12 @@ fn interpret_input( }; } else { let proc_name = tmp[1]; - for proc_ in sys.processes_by_name(proc_name) { - writeln!(&mut io::stdout(), "==== {} ====", proc_.name()); + for proc_ in sys.processes_by_name(proc_name.as_ref()) { + writeln!( + &mut io::stdout(), + "==== {} ====", + proc_.name().as_encoded_bytes().as_bstr() + ); writeln!(&mut io::stdout(), "{proc_:?}"); } } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -414,7 +414,7 @@ impl System { /// /// let s = System::new_all(); /// for (pid, process) in s.processes() { - /// println!("{} {}", pid, process.name()); + /// println!("{} {:?}", pid, process.name()); /// } /// ``` pub fn processes(&self) -> &HashMap<Pid, Process> { diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -428,7 +428,7 @@ impl System { /// /// let s = System::new_all(); /// if let Some(process) = s.process(Pid::from(1337)) { - /// println!("{}", process.name()); + /// println!("{:?}", process.name()); /// } /// ``` pub fn process(&self, pid: Pid) -> Option<&Process> { diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -450,17 +450,18 @@ impl System { /// use sysinfo::System; /// /// let s = System::new_all(); - /// for process in s.processes_by_name("htop") { - /// println!("{} {}", process.pid(), process.name()); + /// for process in s.processes_by_name("htop".as_ref()) { + /// println!("{} {:?}", process.pid(), process.name()); /// } /// ``` pub fn processes_by_name<'a: 'b, 'b>( &'a self, - name: &'b str, + name: &'b OsStr, ) -> impl Iterator<Item = &'a Process> + 'b { + let finder = memchr::memmem::Finder::new(name.as_encoded_bytes()); self.processes() .values() - .filter(move |val: &&Process| val.name().contains(name)) + .filter(move |val: &&Process| finder.find(val.name().as_encoded_bytes()).is_some()) } /// Returns an iterator of processes with exactly the given `name`. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -478,13 +479,13 @@ impl System { /// use sysinfo::System; /// /// let s = System::new_all(); - /// for process in s.processes_by_exact_name("htop") { - /// println!("{} {}", process.pid(), process.name()); + /// for process in s.processes_by_exact_name("htop".as_ref()) { + /// println!("{} {:?}", process.pid(), process.name()); /// } /// ``` pub fn processes_by_exact_name<'a: 'b, 'b>( &'a self, - name: &'b str, + name: &'b OsStr, ) -> impl Iterator<Item = &'a Process> + 'b { self.processes() .values() diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -832,7 +833,7 @@ impl System { /// /// let s = System::new_all(); /// if let Some(process) = s.process(Pid::from(1337)) { -/// println!("{}", process.name()); +/// println!("{:?}", process.name()); /// } /// ``` pub struct Process { diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -900,10 +901,10 @@ impl Process { /// /// let s = System::new_all(); /// if let Some(process) = s.process(Pid::from(1337)) { - /// println!("{}", process.name()); + /// println!("{:?}", process.name()); /// } /// ``` - pub fn name(&self) -> &str { + pub fn name(&self) -> &OsStr { self.inner.name() } diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -73,14 +73,7 @@ impl fmt::Debug for Process { impl fmt::Debug for Components { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Components {{ {} }}", - self.iter() - .map(|x| format!("{x:?}")) - .collect::<Vec<_>>() - .join(", ") - ) + f.debug_list().entries(self.iter()).finish() } } diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -109,14 +102,7 @@ impl fmt::Debug for Component { impl fmt::Debug for Networks { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Networks {{ {} }}", - self.iter() - .map(|x| format!("{x:?}")) - .collect::<Vec<_>>() - .join(", ") - ) + f.debug_list().entries(self.iter()).finish() } } diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -141,27 +127,13 @@ impl fmt::Debug for NetworkData { impl fmt::Debug for Disks { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Disks {{ {} }}", - self.iter() - .map(|x| format!("{x:?}")) - .collect::<Vec<_>>() - .join(", ") - ) + f.debug_list().entries(self.iter()).finish() } } impl fmt::Debug for Users { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "Users {{ {} }}", - self.iter() - .map(|x| format!("{x:?}")) - .collect::<Vec<_>>() - .join(", ") - ) + f.debug_list().entries(self.iter()).finish() } } diff --git a/src/unix/apple/app_store/process.rs b/src/unix/apple/app_store/process.rs --- a/src/unix/apple/app_store/process.rs +++ b/src/unix/apple/app_store/process.rs @@ -1,5 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. +use std::ffi::OsStr; use std::path::Path; use crate::{DiskUsage, Gid, Pid, ProcessStatus, Signal, Uid}; diff --git a/src/unix/apple/app_store/process.rs b/src/unix/apple/app_store/process.rs --- a/src/unix/apple/app_store/process.rs +++ b/src/unix/apple/app_store/process.rs @@ -11,8 +12,8 @@ impl ProcessInner { None } - pub(crate) fn name(&self) -> &str { - "" + pub(crate) fn name(&self) -> &OsStr { + OsStr::new("") } pub(crate) fn cmd(&self) -> &[String] { diff --git a/src/unix/apple/cpu.rs b/src/unix/apple/cpu.rs --- a/src/unix/apple/cpu.rs +++ b/src/unix/apple/cpu.rs @@ -186,7 +186,7 @@ pub(crate) unsafe fn get_cpu_frequency() -> u64 { #[cfg(any(target_os = "ios", feature = "apple-sandbox"))] { - return 0; + 0 } #[cfg(not(any(target_os = "ios", feature = "apple-sandbox")))] { diff --git a/src/unix/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/unix/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -269,6 +269,7 @@ unsafe fn get_dict_value<T, F: FnOnce(*const c_void) -> Option<T>>( ) -> Option<T> { #[cfg(target_os = "macos")] let _defined; + #[allow(clippy::infallible_destructuring_match)] let key = match key { DictKey::Extern(val) => val, #[cfg(target_os = "macos")] diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -1,6 +1,8 @@ // Take a look at the license at the top of the repository in the LICENSE file. +use std::ffi::{OsStr, OsString}; use std::mem::{self, MaybeUninit}; +use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::path::{Path, PathBuf}; use libc::{c_int, c_void, kill}; diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -12,7 +14,7 @@ use crate::sys::system::Wrap; use crate::unix::utils::cstr_to_rust_with_size; pub(crate) struct ProcessInner { - pub(crate) name: String, + pub(crate) name: OsString, pub(crate) cmd: Vec<String>, pub(crate) exe: Option<PathBuf>, pid: Pid, diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -47,7 +49,7 @@ pub(crate) struct ProcessInner { impl ProcessInner { pub(crate) fn new_empty(pid: Pid) -> Self { Self { - name: String::new(), + name: OsString::new(), pid, parent: None, cmd: Vec::new(), diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -78,7 +80,7 @@ impl ProcessInner { pub(crate) fn new(pid: Pid, parent: Option<Pid>, start_time: u64, run_time: u64) -> Self { Self { - name: String::new(), + name: OsString::new(), pid, parent, cmd: Vec::new(), diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -112,7 +114,7 @@ impl ProcessInner { unsafe { Some(kill(self.pid.0, c_signal) == 0) } } - pub(crate) fn name(&self) -> &str { + pub(crate) fn name(&self) -> &OsStr { &self.name } diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -400,12 +402,11 @@ unsafe fn get_exe_and_name_backup( ) { x if x > 0 => { buffer.set_len(x as _); - let tmp = String::from_utf8_unchecked(buffer); + let tmp = OsString::from_vec(buffer); let exe = PathBuf::from(tmp); if process.name.is_empty() { exe.file_name() - .and_then(|x| x.to_str()) - .unwrap_or("") + .unwrap_or_default() .clone_into(&mut process.name); } if exe_needs_update { diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -540,14 +541,12 @@ unsafe fn get_process_infos(process: &mut ProcessInner, refresh_kind: ProcessRef let (exe, proc_args) = get_exe(proc_args); if process.name.is_empty() { exe.file_name() - .and_then(|x| x.to_str()) - .unwrap_or("") - .to_owned() + .unwrap_or_default() .clone_into(&mut process.name); } if refresh_kind.exe().needs_update(|| process.exe.is_none()) { - process.exe = Some(exe); + process.exe = Some(exe.to_owned()); } let environ_needs_update = refresh_kind diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -565,14 +564,10 @@ unsafe fn get_process_infos(process: &mut ProcessInner, refresh_kind: ProcessRef true } -fn get_exe(data: &[u8]) -> (PathBuf, &[u8]) { +fn get_exe(data: &[u8]) -> (&Path, &[u8]) { let pos = data.iter().position(|c| *c == 0).unwrap_or(data.len()); - unsafe { - ( - Path::new(std::str::from_utf8_unchecked(&data[..pos])).to_path_buf(), - &data[pos..], - ) - } + let (exe, proc_args) = data.split_at(pos); + (Path::new(OsStr::from_bytes(exe)), proc_args) } fn get_arguments<'a>( diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -6,7 +6,7 @@ use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::OsStringExt; use std::path::{Path, PathBuf}; -use super::utils::c_buf_to_str; +use super::utils::c_buf_to_utf8_str; pub(crate) struct DiskInner { name: OsString, diff --git a/src/unix/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/unix/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -134,7 +134,7 @@ pub unsafe fn get_all_list(container: &mut Vec<Disk>) { continue; } - let mount_point = match c_buf_to_str(&fs_info.f_mntonname) { + let mount_point = match c_buf_to_utf8_str(&fs_info.f_mntonname) { Some(m) => m, None => { sysinfo_debug!("Cannot get disk mount point, ignoring it."); diff --git a/src/unix/freebsd/network.rs b/src/unix/freebsd/network.rs --- a/src/unix/freebsd/network.rs +++ b/src/unix/freebsd/network.rs @@ -80,7 +80,7 @@ impl NetworksInner { if !utils::get_sys_value(&mib, &mut data) { continue; } - if let Some(name) = utils::c_buf_to_string(&data.ifmd_name) { + if let Some(name) = utils::c_buf_to_utf8_string(&data.ifmd_name) { let data = &data.ifmd_data; match self.interfaces.entry(name) { hash_map::Entry::Occupied(mut e) => { diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -2,6 +2,7 @@ use crate::{DiskUsage, Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, Signal, Uid}; +use std::ffi::{OsStr, OsString}; use std::fmt; use std::path::{Path, PathBuf}; diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -41,7 +42,7 @@ impl fmt::Display for ProcessStatus { } pub(crate) struct ProcessInner { - pub(crate) name: String, + pub(crate) name: OsString, pub(crate) cmd: Vec<String>, pub(crate) exe: Option<PathBuf>, pub(crate) pid: Pid, diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -72,7 +73,7 @@ impl ProcessInner { unsafe { Some(libc::kill(self.pid.0, c_signal) == 0) } } - pub(crate) fn name(&self) -> &str { + pub(crate) fn name(&self) -> &OsStr { &self.name } diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -280,7 +281,7 @@ pub(crate) unsafe fn get_process_data( cwd: None, exe: None, // kvm_getargv isn't thread-safe so we get it in the main thread. - name: String::new(), + name: OsString::new(), // kvm_getargv isn't thread-safe so we get it in the main thread. cmd: Vec::new(), // kvm_getargv isn't thread-safe so we get it in the main thread. diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -14,7 +14,7 @@ use std::ptr::NonNull; use crate::sys::cpu::{physical_core_count, CpusWrapper}; use crate::sys::process::get_exe; use crate::sys::utils::{ - self, boot_time, c_buf_to_string, from_cstr_array, get_sys_value, get_sys_value_by_name, + self, boot_time, c_buf_to_os_string, from_cstr_array, get_sys_value, get_sys_value_by_name, get_system_info, init_mib, }; diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -380,7 +380,7 @@ unsafe fn add_missing_proc_info( if !cmd.is_empty() { // First, we try to retrieve the name from the command line. let p = Path::new(&cmd[0]); - if let Some(name) = p.file_name().and_then(|s| s.to_str()) { + if let Some(name) = p.file_name() { name.clone_into(&mut proc_inner.name); } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -395,7 +395,7 @@ unsafe fn add_missing_proc_info( // The name can be cut short because the `ki_comm` field size is limited, // which is why we prefer to get the name from the command line as much as // possible. - proc_inner.name = c_buf_to_string(&kproc.ki_comm).unwrap_or_default(); + proc_inner.name = c_buf_to_os_string(&kproc.ki_comm); } if refresh_kind .environ() diff --git a/src/unix/freebsd/utils.rs b/src/unix/freebsd/utils.rs --- a/src/unix/freebsd/utils.rs +++ b/src/unix/freebsd/utils.rs @@ -4,8 +4,9 @@ use crate::{Pid, Process}; use libc::{c_char, c_int, timeval}; use std::cell::UnsafeCell; use std::collections::HashMap; -use std::ffi::CStr; +use std::ffi::{CStr, OsStr, OsString}; use std::mem; +use std::os::unix::ffi::OsStrExt; use std::time::SystemTime; /// This struct is used to switch between the "old" and "new" every time you use "get_mut". diff --git a/src/unix/freebsd/utils.rs b/src/unix/freebsd/utils.rs --- a/src/unix/freebsd/utils.rs +++ b/src/unix/freebsd/utils.rs @@ -109,20 +110,37 @@ pub(crate) unsafe fn get_sys_value_array<T: Sized>(mib: &[c_int], value: &mut [T ) == 0 } -pub(crate) fn c_buf_to_str(buf: &[libc::c_char]) -> Option<&str> { +pub(crate) fn c_buf_to_utf8_str(buf: &[libc::c_char]) -> Option<&str> { unsafe { let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len()); - if let Some(pos) = buf.iter().position(|x| *x == 0) { + std::str::from_utf8(if let Some(pos) = buf.iter().position(|x| *x == 0) { // Shrink buffer to terminate the null bytes - std::str::from_utf8(&buf[..pos]).ok() + &buf[..pos] } else { - std::str::from_utf8(buf).ok() - } + buf + }) + .ok() + } +} + +pub(crate) fn c_buf_to_utf8_string(buf: &[libc::c_char]) -> Option<String> { + c_buf_to_utf8_str(buf).map(|s| s.to_owned()) +} + +pub(crate) fn c_buf_to_os_str(buf: &[libc::c_char]) -> &OsStr { + unsafe { + let buf: &[u8] = std::slice::from_raw_parts(buf.as_ptr() as _, buf.len()); + OsStr::from_bytes(if let Some(pos) = buf.iter().position(|x| *x == 0) { + // Shrink buffer to terminate the null bytes + &buf[..pos] + } else { + buf + }) } } -pub(crate) fn c_buf_to_string(buf: &[libc::c_char]) -> Option<String> { - c_buf_to_str(buf).map(|s| s.to_owned()) +pub(crate) fn c_buf_to_os_string(buf: &[libc::c_char]) -> OsString { + c_buf_to_os_str(buf).to_owned() } pub(crate) unsafe fn get_sys_value_str(mib: &[c_int], buf: &mut [libc::c_char]) -> Option<String> { diff --git a/src/unix/freebsd/utils.rs b/src/unix/freebsd/utils.rs --- a/src/unix/freebsd/utils.rs +++ b/src/unix/freebsd/utils.rs @@ -138,7 +156,7 @@ pub(crate) unsafe fn get_sys_value_str(mib: &[c_int], buf: &mut [libc::c_char]) { return None; } - c_buf_to_string(&buf[..len / mem::size_of::<libc::c_char>()]) + c_buf_to_utf8_string(&buf[..len / mem::size_of::<libc::c_char>()]) } pub(crate) unsafe fn get_sys_value_by_name<T: Sized>(name: &[u8], value: &mut T) -> bool { diff --git a/src/unix/freebsd/utils.rs b/src/unix/freebsd/utils.rs --- a/src/unix/freebsd/utils.rs +++ b/src/unix/freebsd/utils.rs @@ -180,7 +198,7 @@ pub(crate) fn get_sys_value_str_by_name(name: &[u8]) -> Option<String> { ) == 0 && size > 0 { - c_buf_to_string(&buf) + c_buf_to_utf8_string(&buf) } else { // getting the system value failed None diff --git a/src/unix/freebsd/utils.rs b/src/unix/freebsd/utils.rs --- a/src/unix/freebsd/utils.rs +++ b/src/unix/freebsd/utils.rs @@ -224,7 +242,7 @@ pub(crate) fn get_system_info(mib: &[c_int], default: Option<&str>) -> Option<St // If command fails return default default.map(|s| s.to_owned()) } else { - c_buf_to_string(&buf) + c_buf_to_utf8_string(&buf) } } } diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -1,6 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::sys::utils::{get_all_data, to_cpath}; +use crate::sys::utils::{get_all_utf8_data, to_cpath}; use crate::{Disk, DiskKind}; use libc::statvfs; diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -80,7 +80,7 @@ impl crate::DisksInner { pub(crate) fn refresh_list(&mut self) { get_all_list( &mut self.disks, - &get_all_data("/proc/mounts", 16_385).unwrap_or_default(), + &get_all_utf8_data("/proc/mounts", 16_385).unwrap_or_default(), ) } diff --git a/src/unix/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/unix/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -187,7 +187,7 @@ fn find_type_for_device_name(device_name: &OsStr) -> DiskKind { .join(trimmed) .join("queue/rotational"); // Normally, this file only contains '0' or '1' but just in case, we get 8 bytes... - match get_all_data(path, 8) + match get_all_utf8_data(path, 8) .unwrap_or_default() .trim() .parse() diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -2,18 +2,19 @@ use std::cell::UnsafeCell; use std::collections::{HashMap, HashSet}; -use std::ffi::OsStr; +use std::ffi::{OsStr, OsString}; use std::fmt; use std::fs::{self, DirEntry, File}; use std::io::Read; +use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; -use std::str::FromStr; +use std::str::{self, FromStr}; use libc::{c_ulong, gid_t, kill, uid_t}; use crate::sys::system::SystemInfo; use crate::sys::utils::{ - get_all_data, get_all_data_from_file, realpath, FileCounter, PathHandler, PathPush, + get_all_data_from_file, get_all_utf8_data, realpath, FileCounter, PathHandler, PathPush, }; use crate::{ DiskUsage, Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, Signal, ThreadKind, Uid, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -62,7 +63,6 @@ impl fmt::Display for ProcessStatus { #[repr(usize)] enum ProcIndex { Pid = 0, - ShortExe, State, ParentPid, GroupId, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -89,7 +89,7 @@ enum ProcIndex { } pub(crate) struct ProcessInner { - pub(crate) name: String, + pub(crate) name: OsString, pub(crate) cmd: Vec<String>, pub(crate) exe: Option<PathBuf>, pub(crate) pid: Pid, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -126,7 +126,7 @@ pub(crate) struct ProcessInner { impl ProcessInner { pub(crate) fn new(pid: Pid, proc_path: PathBuf) -> Self { Self { - name: String::new(), + name: OsString::new(), pid, parent: None, cmd: Vec::new(), diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -166,7 +166,7 @@ impl ProcessInner { unsafe { Some(kill(self.pid.0, c_signal) == 0) } } - pub(crate) fn name(&self) -> &str { + pub(crate) fn name(&self) -> &OsStr { &self.name } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -307,7 +307,7 @@ pub(crate) fn set_time(p: &mut ProcessInner, utime: u64, stime: u64) { } pub(crate) fn update_process_disk_activity(p: &mut ProcessInner, path: &mut PathHandler) { - let data = match get_all_data(path.join("io"), 16_384) { + let data = match get_all_utf8_data(path.join("io"), 16_384) { Ok(d) => d, Err(_) => return, }; diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -352,13 +352,13 @@ unsafe impl<'a, T> Send for Wrap<'a, T> {} unsafe impl<'a, T> Sync for Wrap<'a, T> {} #[inline(always)] -fn compute_start_time_without_boot_time(parts: &[&str], info: &SystemInfo) -> u64 { +fn compute_start_time_without_boot_time(parts: &Parts<'_>, info: &SystemInfo) -> u64 { // To be noted that the start time is invalid here, it still needs to be converted into // "real" time. - u64::from_str(parts[ProcIndex::StartTime as usize]).unwrap_or(0) / info.clock_cycle + u64::from_str(parts.str_parts[ProcIndex::StartTime as usize]).unwrap_or(0) / info.clock_cycle } -fn _get_stat_data(path: &Path, stat_file: &mut Option<FileCounter>) -> Result<String, ()> { +fn _get_stat_data(path: &Path, stat_file: &mut Option<FileCounter>) -> Result<Vec<u8>, ()> { let mut file = File::open(path.join("stat")).map_err(|_| ())?; let data = get_all_data_from_file(&mut file, 1024).map_err(|_| ())?; *stat_file = FileCounter::new(file); diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -398,11 +398,11 @@ fn update_proc_info( p: &mut ProcessInner, refresh_kind: ProcessRefreshKind, proc_path: &mut PathHandler, - parts: &[&str], + str_parts: &[&str], uptime: u64, info: &SystemInfo, ) { - get_status(p, parts[ProcIndex::State as usize]); + get_status(p, str_parts[ProcIndex::State as usize]); refresh_user_group_ids(p, proc_path, refresh_kind); if refresh_kind.exe().needs_update(|| p.exe.is_none()) { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -424,7 +424,7 @@ fn update_proc_info( p.root = realpath(proc_path.join("root")); } - update_time_and_memory(proc_path, p, parts, uptime, info, refresh_kind); + update_time_and_memory(proc_path, p, str_parts, uptime, info, refresh_kind); if refresh_kind.disk_usage() { update_process_disk_activity(p, proc_path); } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -433,7 +433,7 @@ fn update_proc_info( fn retrieve_all_new_process_info( pid: Pid, parent_pid: Option<Pid>, - parts: &[&str], + parts: &Parts<'_>, path: &Path, info: &SystemInfo, refresh_kind: ProcessRefreshKind, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -441,11 +441,11 @@ fn retrieve_all_new_process_info( ) -> Process { let mut p = ProcessInner::new(pid, path.to_owned()); let mut proc_path = PathHandler::new(path); - let name = parts[ProcIndex::ShortExe as usize]; + let name = parts.short_exe; p.parent = match parent_pid { Some(parent_pid) if parent_pid.0 != 0 => Some(parent_pid), - _ => match Pid::from_str(parts[ProcIndex::ParentPid as usize]) { + _ => match Pid::from_str(parts.str_parts[ProcIndex::ParentPid as usize]) { Ok(p) if p.0 != 0 => Some(p), _ => None, }, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -456,8 +456,8 @@ fn retrieve_all_new_process_info( .start_time_without_boot_time .saturating_add(info.boot_time); - p.name = name.into(); - if c_ulong::from_str(parts[ProcIndex::Flags as usize]) + p.name = OsStr::from_bytes(name).to_os_string(); + if c_ulong::from_str(parts.str_parts[ProcIndex::Flags as usize]) .map(|flags| flags & libc::PF_KTHREAD as c_ulong != 0) .unwrap_or(false) { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -466,7 +466,14 @@ fn retrieve_all_new_process_info( p.thread_kind = Some(ThreadKind::Userland); } - update_proc_info(&mut p, refresh_kind, &mut proc_path, parts, uptime, info); + update_proc_info( + &mut p, + refresh_kind, + &mut proc_path, + &parts.str_parts, + uptime, + info, + ); Process { inner: p } } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -508,7 +515,14 @@ pub(crate) fn _get_process_data( if start_time_without_boot_time == entry.start_time_without_boot_time { let mut proc_path = PathHandler::new(path); - update_proc_info(entry, refresh_kind, &mut proc_path, &parts, uptime, info); + update_proc_info( + entry, + refresh_kind, + &mut proc_path, + &parts.str_parts, + uptime, + info, + ); refresh_user_group_ids(entry, &mut proc_path, refresh_kind); return Ok((None, pid)); diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -545,14 +559,14 @@ pub(crate) fn _get_process_data( Ok((None, pid)) } -fn old_get_memory(entry: &mut ProcessInner, parts: &[&str], info: &SystemInfo) { +fn old_get_memory(entry: &mut ProcessInner, str_parts: &[&str], info: &SystemInfo) { // rss - entry.memory = u64::from_str(parts[ProcIndex::ResidentSetSize as usize]) + entry.memory = u64::from_str(str_parts[ProcIndex::ResidentSetSize as usize]) .unwrap_or(0) .saturating_mul(info.page_size_b); // vsz correspond to the Virtual memory size in bytes. // see: https://man7.org/linux/man-pages/man5/proc.5.html - entry.virtual_memory = u64::from_str(parts[ProcIndex::VirtualSize as usize]).unwrap_or(0); + entry.virtual_memory = u64::from_str(str_parts[ProcIndex::VirtualSize as usize]).unwrap_or(0); } fn slice_to_nb(s: &[u8]) -> u64 { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -601,7 +615,7 @@ fn get_memory(path: &Path, entry: &mut ProcessInner, info: &SystemInfo) -> bool fn update_time_and_memory( path: &mut PathHandler, entry: &mut ProcessInner, - parts: &[&str], + str_parts: &[&str], uptime: u64, info: &SystemInfo, refresh_kind: ProcessRefreshKind, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -611,13 +625,13 @@ fn update_time_and_memory( if refresh_kind.memory() { // Keeping this nested level for readability reasons. if !get_memory(path.join("statm"), entry, info) { - old_get_memory(entry, parts, info); + old_get_memory(entry, str_parts, info); } } set_time( entry, - u64::from_str(parts[ProcIndex::UserTime as usize]).unwrap_or(0), - u64::from_str(parts[ProcIndex::SystemTime as usize]).unwrap_or(0), + u64::from_str(str_parts[ProcIndex::UserTime as usize]).unwrap_or(0), + u64::from_str(str_parts[ProcIndex::SystemTime as usize]).unwrap_or(0), ); entry.run_time = uptime.saturating_sub(entry.start_time_without_boot_time); } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -776,7 +790,7 @@ fn copy_from_file(entry: &Path) -> Vec<String> { let mut out = Vec::with_capacity(10); let mut data = data.as_slice(); while let Some(pos) = data.iter().position(|c| *c == 0) { - match std::str::from_utf8(&data[..pos]).map(|s| s.trim()) { + match str::from_utf8(&data[..pos]).map(|s| s.trim()) { Ok(s) if !s.is_empty() => out.push(s.to_string()), _ => {} } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -794,7 +808,7 @@ fn copy_from_file(entry: &Path) -> Vec<String> { // Fetch tuples of real and effective UID and GID. fn get_uid_and_gid(file_path: &Path) -> Option<((uid_t, uid_t), (gid_t, gid_t))> { - let status_data = get_all_data(file_path, 16_385).ok()?; + let status_data = get_all_utf8_data(file_path, 16_385).ok()?; // We're only interested in the lines starting with Uid: and Gid: // here. From these lines, we're looking at the first and second entries to get diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -839,7 +853,12 @@ fn get_uid_and_gid(file_path: &Path) -> Option<((uid_t, uid_t), (gid_t, gid_t))> } } -fn parse_stat_file(data: &str) -> Option<Vec<&str>> { +struct Parts<'a> { + str_parts: Vec<&'a str>, + short_exe: &'a [u8], +} + +fn parse_stat_file(data: &[u8]) -> Option<Parts<'_>> { // The stat file is "interesting" to parse, because spaces cannot // be used as delimiters. The second field stores the command name // surrounded by parentheses. Unfortunately, whitespace and diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -849,16 +868,15 @@ fn parse_stat_file(data: &str) -> Option<Vec<&str>> { // in the entire string. All other fields are delimited by // whitespace. - let mut parts = Vec::with_capacity(52); - let mut data_it = data.splitn(2, ' '); - parts.push(data_it.next()?); - let mut data_it = data_it.next()?.rsplitn(2, ')'); - let data = data_it.next()?; - parts.push(data_it.next()?); - parts.extend(data.split_whitespace()); - // Remove command name '(' - if let Some(name) = parts[ProcIndex::ShortExe as usize].strip_prefix('(') { - parts[ProcIndex::ShortExe as usize] = name; - } - Some(parts) + let mut str_parts = Vec::with_capacity(51); + let mut data_it = data.splitn(2, |&b| b == b' '); + str_parts.push(str::from_utf8(data_it.next()?).ok()?); + let mut data_it = data_it.next()?.rsplitn(2, |&b| b == b')'); + let data = str::from_utf8(data_it.next()?).ok()?; + let short_exe = data_it.next()?; + str_parts.extend(data.split_whitespace()); + Some(Parts { + str_parts, + short_exe: short_exe.strip_prefix(&[b'(']).unwrap_or(short_exe), + }) } diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -2,7 +2,7 @@ use crate::sys::cpu::{get_physical_core_count, CpusWrapper}; use crate::sys::process::{_get_process_data, compute_cpu_usage, refresh_procs, unset_updated}; -use crate::sys::utils::{get_all_data, to_u64}; +use crate::sys::utils::{get_all_utf8_data, to_u64}; use crate::{Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, ProcessRefreshKind}; use libc::{self, c_char, sysconf, _SC_CLK_TCK, _SC_HOST_NAME_MAX, _SC_PAGESIZE}; diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -352,7 +352,7 @@ impl SystemInner { } pub(crate) fn uptime() -> u64 { - let content = get_all_data("/proc/uptime", 50).unwrap_or_default(); + let content = get_all_utf8_data("/proc/uptime", 50).unwrap_or_default(); content .split('.') .next() diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -508,7 +508,7 @@ impl SystemInner { } fn read_u64(filename: &str) -> Option<u64> { - get_all_data(filename, 16_635) + get_all_utf8_data(filename, 16_635) .ok() .and_then(|d| u64::from_str(d.trim()).ok()) } diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -517,7 +517,7 @@ fn read_table<F>(filename: &str, colsep: char, mut f: F) where F: FnMut(&str, u64), { - if let Ok(content) = get_all_data(filename, 16_635) { + if let Ok(content) = get_all_utf8_data(filename, 16_635) { content .split('\n') .flat_map(|line| { diff --git a/src/unix/linux/utils.rs b/src/unix/linux/utils.rs --- a/src/unix/linux/utils.rs +++ b/src/unix/linux/utils.rs @@ -7,16 +7,23 @@ use std::sync::atomic::Ordering; use crate::sys::system::remaining_files; -pub(crate) fn get_all_data_from_file(file: &mut File, size: usize) -> io::Result<String> { +pub(crate) fn get_all_data_from_file(file: &mut File, size: usize) -> io::Result<Vec<u8>> { + let mut buf = Vec::with_capacity(size); + file.rewind()?; + file.read_to_end(&mut buf)?; + Ok(buf) +} + +pub(crate) fn get_all_utf8_data_from_file(file: &mut File, size: usize) -> io::Result<String> { let mut buf = String::with_capacity(size); file.rewind()?; file.read_to_string(&mut buf)?; Ok(buf) } -pub(crate) fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<String> { +pub(crate) fn get_all_utf8_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Result<String> { let mut file = File::open(file_path.as_ref())?; - get_all_data_from_file(&mut file, size) + get_all_utf8_data_from_file(&mut file, size) } #[allow(clippy::useless_conversion)] diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -2,6 +2,7 @@ use crate::{DiskUsage, Gid, Pid, ProcessStatus, Signal, Uid}; +use std::ffi::OsStr; use std::fmt; use std::path::Path; diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -21,8 +22,8 @@ impl ProcessInner { None } - pub(crate) fn name(&self) -> &str { - "" + pub(crate) fn name(&self) -> &OsStr { + OsStr::new("") } pub(crate) fn cmd(&self) -> &[String] { diff --git a/src/windows/groups.rs b/src/windows/groups.rs --- a/src/windows/groups.rs +++ b/src/windows/groups.rs @@ -1,6 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::sys::utils::to_str; +use crate::sys::utils::to_utf8_str; use crate::{ common::{Gid, GroupInner}, windows::sid::Sid, diff --git a/src/windows/groups.rs b/src/windows/groups.rs --- a/src/windows/groups.rs +++ b/src/windows/groups.rs @@ -95,7 +95,7 @@ pub(crate) fn get_groups(groups: &mut Vec<Group>) { // Get the account name from the SID (because it's usually // a better name), but fall back to the name we were given // if this fails. - let name = to_str(entry.grpi0_name); + let name = to_utf8_str(entry.grpi0_name); groups.push(Group { inner: GroupInner::new(Gid(0), name), }); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -4,7 +4,7 @@ use crate::sys::system::is_proc_running; use crate::windows::Sid; use crate::{DiskUsage, Gid, Pid, ProcessRefreshKind, ProcessStatus, Signal, Uid}; -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::fmt; #[cfg(feature = "debug")] use std::io; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -198,7 +198,7 @@ unsafe impl Send for HandleWrapper {} unsafe impl Sync for HandleWrapper {} pub(crate) struct ProcessInner { - name: String, + name: OsString, cmd: Vec<String>, exe: Option<PathBuf>, pid: Pid, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -269,7 +269,7 @@ unsafe fn display_ntstatus_error(ntstatus: windows::core::HRESULT) { // Take a look at https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/query.htm // for explanations. -unsafe fn get_process_name(pid: Pid) -> Option<String> { +unsafe fn get_process_name(pid: Pid) -> Option<OsString> { let mut info = SYSTEM_PROCESS_ID_INFORMATION { ProcessId: pid.0 as _, ImageName: MaybeUninit::zeroed().assume_init(), diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -337,9 +337,7 @@ unsafe fn get_process_name(pid: Pid) -> Option<String> { info.ImageName.Length as usize / std::mem::size_of::<u16>(), ); let os_str = OsString::from_wide(s); - let name = Path::new(&os_str) - .file_name() - .map(|s| s.to_string_lossy().to_string()); + let name = Path::new(&os_str).file_name().map(|s| s.to_os_string()); let _err = LocalFree(HLOCAL(info.ImageName.Buffer.cast())); name } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -424,7 +422,7 @@ impl ProcessInner { parent: Option<Pid>, memory: u64, virtual_memory: u64, - name: String, + name: OsString, now: u64, refresh_kind: ProcessRefreshKind, ) -> Self { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -548,7 +546,7 @@ impl ProcessInner { } } - pub(crate) fn name(&self) -> &str { + pub(crate) fn name(&self) -> &OsStr { &self.name } diff --git a/src/windows/sid.rs b/src/windows/sid.rs --- a/src/windows/sid.rs +++ b/src/windows/sid.rs @@ -9,7 +9,7 @@ use windows::Win32::Security::{ CopySid, GetLengthSid, IsValidSid, LookupAccountSidW, SidTypeUnknown, }; -use crate::sys::utils::to_str; +use crate::sys::utils::to_utf8_str; #[doc = include_str!("../../md_doc/sid.md")] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/src/windows/sid.rs b/src/windows/sid.rs --- a/src/windows/sid.rs +++ b/src/windows/sid.rs @@ -102,7 +102,7 @@ impl Sid { return None; } - Some(to_str(PWSTR::from_raw(name.as_mut_ptr()))) + Some(to_utf8_str(PWSTR::from_raw(name.as_mut_ptr()))) } } } diff --git a/src/windows/sid.rs b/src/windows/sid.rs --- a/src/windows/sid.rs +++ b/src/windows/sid.rs @@ -115,7 +115,7 @@ impl Display for Sid { sysinfo_debug!("ConvertSidToStringSidW failed: {:?}", _err); return None; } - let result = to_str(string_sid); + let result = to_utf8_str(string_sid); let _err = LocalFree(HLOCAL(string_sid.0 as _)); Some(result) } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -12,7 +12,9 @@ use crate::utils::into_iter; use std::cell::UnsafeCell; use std::collections::HashMap; +use std::ffi::OsString; use std::mem::{size_of, zeroed}; +use std::os::windows::ffi::OsStringExt; use std::ptr; use std::time::SystemTime; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -427,14 +429,14 @@ impl SystemInner { if Self::is_windows_eleven() { return get_reg_string_value( HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", ) .map(|product_name| product_name.replace("Windows 10 ", "Windows 11 ")); } get_reg_string_value( HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", ) } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -446,7 +448,7 @@ impl SystemInner { pub(crate) fn kernel_version() -> Option<String> { get_reg_string_value( HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber", ) } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -454,7 +456,7 @@ impl SystemInner { pub(crate) fn os_version() -> Option<String> { let build_number = get_reg_string_value( HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber", ) .unwrap_or_default(); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -464,7 +466,7 @@ impl SystemInner { u32::from_le_bytes( get_reg_value_u32( HKEY_LOCAL_MACHINE, - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", + r"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentMajorVersionNumber", ) .unwrap_or_default(), diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -535,7 +537,7 @@ fn refresh_existing_process( #[allow(clippy::size_of_in_element_count)] //^ needed for "name.Length as usize / std::mem::size_of::<u16>()" -pub(crate) fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: Pid) -> String { +pub(crate) fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: Pid) -> OsString { let name = &process.ImageName; if name.Buffer.is_null() { match process_id.0 { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -543,6 +545,7 @@ pub(crate) fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: 4 => "System".to_owned(), _ => format!("<no name> Process {process_id}"), } + .into() } else { unsafe { let slice = std::slice::from_raw_parts( diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -551,7 +554,7 @@ pub(crate) fn get_process_name(process: &SYSTEM_PROCESS_INFORMATION, process_id: name.Length as usize / std::mem::size_of::<u16>(), ); - String::from_utf16_lossy(slice) + OsString::from_wide(slice) } } } diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -1,6 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::sys::utils::to_str; +use crate::sys::utils::to_utf8_str; use crate::{ common::{Gid, Uid}, windows::sid::Sid, diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -139,7 +139,7 @@ unsafe fn get_groups_for_user(username: PCWSTR) -> Vec<Group> { if !buf.0.is_null() { let entries = std::slice::from_raw_parts(buf.0, nb_entries as _); groups.extend(entries.iter().map(|entry| Group { - inner: GroupInner::new(Gid(0), to_str(entry.lgrui0_name)), + inner: GroupInner::new(Gid(0), to_utf8_str(entry.lgrui0_name)), })); } } else { diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -190,7 +190,7 @@ pub(crate) fn get_users(users: &mut Vec<User>) { // if this fails. let name = sid .account_name() - .unwrap_or_else(|| to_str(entry.usri0_name)); + .unwrap_or_else(|| to_utf8_str(entry.usri0_name)); users.push(User { inner: UserInner::new( Uid(sid), diff --git a/src/windows/utils.rs b/src/windows/utils.rs --- a/src/windows/utils.rs +++ b/src/windows/utils.rs @@ -23,7 +23,7 @@ pub(crate) fn get_now() -> u64 { .unwrap_or(0) } -pub(crate) unsafe fn to_str(p: PWSTR) -> String { +pub(crate) unsafe fn to_utf8_str(p: PWSTR) -> String { if p.is_null() { return String::new(); }
622cd8a1b3a60983c15273e82bb9fdf9e9fb6177
Process List incomplete on long names **Describe the bug** This is on 0.30.3. The issue is that the stat file on Linux is parsed under the assumption that it contains valid UTF-8. This is not necessarily the case for two reasons: 1. Process names don't need to be valid UTF-8 at all on Linux. They can contain invalid bytes. 2. Even if the process name was valid UTF-8, the assumption breaks because the process name is limited to 15 characters, which can cut a valid code point in half. This causes the stat file to not be parseable, causing the entire process not to show up in the list. So even if I wasn't using the name of the process at all, I can't find it as part of the list. **To Reproduce** I named an executable `process-name-töööö`, which cuts one of the `ö` in half. I have a fixed branch locally, but I want to discuss what the best solution is before doing a PR. My branch lossily converts the process name to a string. However this means that the [Unicode replacement character `�`](https://www.fileformat.info/info/unicode/char/fffd/index.htm) is now part of those process names. The character when encoded as UTF-8 is 3 bytes. This means that process names can now be longer than 15 bytes, or in other words, doing a name based comparison on the first 15 bytes, such as somewhat suggested in the documentation of the crate, is no longer easily possible. Maybe the solution instead is to just provide the name as an `OsStr` instead, keeping the bytes around as is. Rust recently made `OsStr` way more easily usable by allowing you to access its bytes directly.
0.30
1,196
Thanks for the detailed description! Using `OsStr` is the best solution here I think. I see that you can get a process/thread name with `pthread_getname_np` or by reading the proc `comm` file. Not sure if it's worth it though.
296bbf02359b11eef28fc344832760b654215a22
2023-12-17T22:57:54Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -365,34 +365,33 @@ mod test { #[test] fn check_system_info() { - let s = System::new(); - // We don't want to test on unsupported systems. if IS_SUPPORTED { - assert!(!s.name().expect("Failed to get system name").is_empty()); + assert!(!System::name() + .expect("Failed to get system name") + .is_empty()); - assert!(!s - .kernel_version() + assert!(!System::kernel_version() .expect("Failed to get kernel version") .is_empty()); - assert!(!s.os_version().expect("Failed to get os version").is_empty()); + assert!(!System::os_version() + .expect("Failed to get os version") + .is_empty()); - assert!(!s - .long_os_version() + assert!(!System::long_os_version() .expect("Failed to get long OS version") .is_empty()); } - assert!(!s.distribution_id().is_empty()); + assert!(!System::distribution_id().is_empty()); } #[test] fn check_host_name() { // We don't want to test on unsupported systems. if IS_SUPPORTED { - let s = System::new(); - assert!(s.host_name().is_some()); + assert!(System::host_name().is_some()); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -512,7 +511,6 @@ mod test { #[test] fn check_cpu_arch() { - let s = System::new(); - assert_eq!(s.cpu_arch().is_some(), IS_SUPPORTED); + assert_eq!(System::cpu_arch().is_some(), IS_SUPPORTED); } } diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -98,24 +98,28 @@ mod tests { #[test] fn check_hostname_has_no_nuls() { - let sys = System::new(); - - if let Some(hostname) = sys.host_name() { + if let Some(hostname) = System::host_name() { assert!(!hostname.contains('\u{0}')) } } #[test] fn check_uptime() { - let sys = System::new(); - let uptime = sys.uptime(); + let uptime = System::uptime(); if crate::IS_SUPPORTED { std::thread::sleep(std::time::Duration::from_millis(1000)); - let new_uptime = sys.uptime(); + let new_uptime = System::uptime(); assert!(uptime < new_uptime); } } + #[test] + fn check_boot_time() { + if crate::IS_SUPPORTED { + assert_ne!(System::boot_time(), 0); + } + } + // This test is used to ensure that the CPU usage computation isn't completely going off // when refreshing it too frequently (ie, multiple times in a row in a very small interval). #[test] diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -272,6 +272,8 @@ fn test_process_times() { if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { return; } + let boot_time = System::boot_time(); + assert!(boot_time > 0); let mut p = if cfg!(target_os = "windows") { std::process::Command::new("waitfor") .arg("/t") diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -300,15 +302,15 @@ fn test_process_times() { assert!(p.run_time() <= 2); assert!(p.start_time() > p.run_time()); // On linux, for whatever reason, the uptime seems to be older than the boot time, leading - // to this weird `+ 3` to ensure the test is passing as it should... + // to this weird `+ 5` to ensure the test is passing as it should... assert!( - p.start_time() + 3 + p.start_time() + 5 > SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(), ); - assert!(p.start_time() >= s.boot_time()); + assert!(p.start_time() >= boot_time); } else { panic!("Process not found!"); } diff --git a/tests/uptime.rs /dev/null --- a/tests/uptime.rs +++ /dev/null @@ -1,10 +0,0 @@ -// Take a look at the license at the top of the repository in the LICENSE file. - -#[test] -fn test_uptime() { - if sysinfo::IS_SUPPORTED { - let mut s = sysinfo::System::new(); - s.refresh_all(); - assert!(s.uptime() != 0); - } -}
[ "1138" ]
GuillaumeGomez__sysinfo-1171
GuillaumeGomez/sysinfo
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -54,10 +54,10 @@ println!("total swap : {} bytes", sys.total_swap()); println!("used swap : {} bytes", sys.used_swap()); // Display system information: -println!("System name: {:?}", sys.name()); -println!("System kernel version: {:?}", sys.kernel_version()); -println!("System OS version: {:?}", sys.os_version()); -println!("System host name: {:?}", sys.host_name()); +println!("System name: {:?}", System::name()); +println!("System kernel version: {:?}", System::kernel_version()); +println!("System OS version: {:?}", System::os_version()); +println!("System host name: {:?}", System::host_name()); // Number of CPUs: println!("NB CPUs: {}", sys.cpus().len()); diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -268,7 +268,7 @@ fn interpret_input( writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand()); } "load_avg" => { - let load_avg = sys.load_average(); + let load_avg = System::load_average(); writeln!(&mut io::stdout(), "one minute : {}%", load_avg.one); writeln!(&mut io::stdout(), "five minutes : {}%", load_avg.five); writeln!(&mut io::stdout(), "fifteen minutes: {}%", load_avg.fifteen); diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -376,11 +376,11 @@ fn interpret_input( } } "boot_time" => { - writeln!(&mut io::stdout(), "{} seconds", sys.boot_time()); + writeln!(&mut io::stdout(), "{} seconds", System::boot_time()); } "uptime" => { - let up = sys.uptime(); - let mut uptime = sys.uptime(); + let up = System::uptime(); + let mut uptime = up; let days = uptime / 86400; uptime -= days * 86400; let hours = uptime / 3600; diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -435,13 +435,11 @@ fn interpret_input( System OS version: {}\n\ System OS (long) version: {}\n\ System host name: {}", - sys.name().unwrap_or_else(|| "<unknown>".to_owned()), - sys.kernel_version() - .unwrap_or_else(|| "<unknown>".to_owned()), - sys.os_version().unwrap_or_else(|| "<unknown>".to_owned()), - sys.long_os_version() - .unwrap_or_else(|| "<unknown>".to_owned()), - sys.host_name().unwrap_or_else(|| "<unknown>".to_owned()), + System::name().unwrap_or_else(|| "<unknown>".to_owned()), + System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()), + System::os_version().unwrap_or_else(|| "<unknown>".to_owned()), + System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()), + System::host_name().unwrap_or_else(|| "<unknown>".to_owned()), ); } e => { diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -585,82 +585,56 @@ pub extern "C" fn sysinfo_cpu_frequency(system: CSystem) -> u64 { /// Equivalent of [`System::name()`][crate::System#method.name]. #[no_mangle] -pub extern "C" fn sysinfo_system_name(system: CSystem) -> RString { - assert!(!system.is_null()); - unsafe { - let system: Box<System> = Box::from_raw(system as *mut System); - let c_string = if let Some(c) = system.name().and_then(|p| CString::new(p).ok()) { - c.into_raw() as _ - } else { - std::ptr::null() - }; - Box::into_raw(system); - c_string - } +pub extern "C" fn sysinfo_system_name() -> RString { + let c_string = if let Some(c) = System::name().and_then(|p| CString::new(p).ok()) { + c.into_raw() as _ + } else { + std::ptr::null() + }; + c_string } /// Equivalent of [`System::version()`][crate::System#method.version]. #[no_mangle] -pub extern "C" fn sysinfo_system_version(system: CSystem) -> RString { - assert!(!system.is_null()); - unsafe { - let system: Box<System> = Box::from_raw(system as *mut System); - let c_string = if let Some(c) = system.os_version().and_then(|c| CString::new(c).ok()) { - c.into_raw() as _ - } else { - std::ptr::null() - }; - Box::into_raw(system); - c_string - } +pub extern "C" fn sysinfo_system_version() -> RString { + let c_string = if let Some(c) = System::os_version().and_then(|c| CString::new(c).ok()) { + c.into_raw() as _ + } else { + std::ptr::null() + }; + c_string } /// Equivalent of [`System::kernel_version()`][crate::System#method.kernel_version]. #[no_mangle] -pub extern "C" fn sysinfo_system_kernel_version(system: CSystem) -> RString { - assert!(!system.is_null()); - unsafe { - let system: Box<System> = Box::from_raw(system as *mut System); - let c_string = if let Some(c) = system.kernel_version().and_then(|c| CString::new(c).ok()) { - c.into_raw() as _ - } else { - std::ptr::null() - }; +pub extern "C" fn sysinfo_system_kernel_version() -> RString { + let c_string = if let Some(c) = System::kernel_version().and_then(|c| CString::new(c).ok()) { + c.into_raw() as _ + } else { + std::ptr::null() + }; - Box::into_raw(system); - c_string - } + c_string } /// Equivalent of [`System::host_name()`][crate::System#method.host_name]. #[no_mangle] -pub extern "C" fn sysinfo_system_host_name(system: CSystem) -> RString { - assert!(!system.is_null()); - unsafe { - let system: Box<System> = Box::from_raw(system as *mut System); - let c_string = if let Some(c) = system.host_name().and_then(|c| CString::new(c).ok()) { - c.into_raw() as _ - } else { - std::ptr::null() - }; - Box::into_raw(system); - c_string - } +pub extern "C" fn sysinfo_system_host_name() -> RString { + let c_string = if let Some(c) = System::host_name().and_then(|c| CString::new(c).ok()) { + c.into_raw() as _ + } else { + std::ptr::null() + }; + c_string } /// Equivalent of [`System::long_os_version()`][crate::System#method.long_os_version]. #[no_mangle] -pub extern "C" fn sysinfo_system_long_version(system: CSystem) -> RString { - assert!(!system.is_null()); - unsafe { - let system: Box<System> = Box::from_raw(system as *mut System); - let c_string = if let Some(c) = system.long_os_version().and_then(|c| CString::new(c).ok()) - { - c.into_raw() as _ - } else { - std::ptr::null() - }; - Box::into_raw(system); - c_string - } +pub extern "C" fn sysinfo_system_long_version() -> RString { + let c_string = if let Some(c) = System::long_os_version().and_then(|c| CString::new(c).ok()) { + c.into_raw() as _ + } else { + std::ptr::null() + }; + c_string } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -655,26 +655,28 @@ impl System { /// Returns system uptime (in seconds). /// + /// **Important**: this information is computed every time this function is called. + /// /// ```no_run /// use sysinfo::System; /// - /// let s = System::new_all(); - /// println!("System running since {} seconds", s.uptime()); + /// println!("System running since {} seconds", System::uptime()); /// ``` - pub fn uptime(&self) -> u64 { - self.inner.uptime() + pub fn uptime() -> u64 { + SystemInner::uptime() } /// Returns the time (in seconds) when the system booted since UNIX epoch. /// + /// **Important**: this information is computed every time this function is called. + /// /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("System booted at {} seconds", s.boot_time()); + /// println!("System booted at {} seconds", System::boot_time()); /// ``` - pub fn boot_time(&self) -> u64 { - self.inner.boot_time() + pub fn boot_time() -> u64 { + SystemInner::boot_time() } /// Returns the system load average value. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -686,8 +688,7 @@ impl System { /// ```no_run /// use sysinfo::System; /// - /// let s = System::new_all(); - /// let load_avg = s.load_average(); + /// let load_avg = System::load_average(); /// println!( /// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%", /// load_avg.one, diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -695,8 +696,8 @@ impl System { /// load_avg.fifteen, /// ); /// ``` - pub fn load_average(&self) -> LoadAvg { - self.inner.load_average() + pub fn load_average() -> LoadAvg { + SystemInner::load_average() } /// Returns the system name. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -706,11 +707,10 @@ impl System { /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("OS: {:?}", s.name()); + /// println!("OS: {:?}", System::name()); /// ``` - pub fn name(&self) -> Option<String> { - self.inner.name() + pub fn name() -> Option<String> { + SystemInner::name() } /// Returns the system's kernel version. diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -720,25 +720,24 @@ impl System { /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("kernel version: {:?}", s.kernel_version()); + /// println!("kernel version: {:?}", System::kernel_version()); /// ``` - pub fn kernel_version(&self) -> Option<String> { - self.inner.kernel_version() + pub fn kernel_version() -> Option<String> { + SystemInner::kernel_version() } - /// Returns the system version (e.g. for MacOS this will return 11.1 rather than the kernel version). + /// Returns the system version (e.g. for MacOS this will return 11.1 rather than the kernel + /// version). /// /// **Important**: this information is computed every time this function is called. /// /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("OS version: {:?}", s.os_version()); + /// println!("OS version: {:?}", System::os_version()); /// ``` - pub fn os_version(&self) -> Option<String> { - self.inner.os_version() + pub fn os_version() -> Option<String> { + SystemInner::os_version() } /// Returns the system long os version (e.g "MacOS 11.2 BigSur"). diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -748,11 +747,10 @@ impl System { /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("Long OS Version: {:?}", s.long_os_version()); + /// println!("Long OS Version: {:?}", System::long_os_version()); /// ``` - pub fn long_os_version(&self) -> Option<String> { - self.inner.long_os_version() + pub fn long_os_version() -> Option<String> { + SystemInner::long_os_version() } /// Returns the distribution id as defined by os-release, diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -767,37 +765,36 @@ impl System { /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("Distribution ID: {:?}", s.distribution_id()); + /// println!("Distribution ID: {:?}", System::distribution_id()); /// ``` - pub fn distribution_id(&self) -> String { - self.inner.distribution_id() + pub fn distribution_id() -> String { + SystemInner::distribution_id() } - /// Returns the system hostname based off DNS + /// Returns the system hostname based off DNS. /// /// **Important**: this information is computed every time this function is called. /// /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("Hostname: {:?}", s.host_name()); + /// println!("Hostname: {:?}", System::host_name()); /// ``` - pub fn host_name(&self) -> Option<String> { - self.inner.host_name() + pub fn host_name() -> Option<String> { + SystemInner::host_name() } /// Returns the CPU architecture (eg. x86, amd64, aarch64, ...). /// + /// **Important**: this information is computed every time this function is called. + /// /// ```no_run /// use sysinfo::System; /// - /// let s = System::new(); - /// println!("CPU Archicture: {:?}", s.cpu_arch()); + /// println!("CPU Archicture: {:?}", System::cpu_arch()); /// ``` - pub fn cpu_arch(&self) -> Option<String> { - self.inner.cpu_arch() + pub fn cpu_arch() -> Option<String> { + SystemInner::cpu_arch() } } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -2797,8 +2794,7 @@ pub struct CGroupLimits { /// ```no_run /// use sysinfo::System; /// -/// let s = System::new_all(); -/// let load_avg = s.load_average(); +/// let load_avg = System::load_average(); /// println!( /// "one minute: {}%, five minutes: {}%, fifteen minutes: {}%", /// load_avg.one, diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -22,7 +22,7 @@ impl fmt::Debug for System { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("System") .field("global CPU usage", &self.global_cpu_info().cpu_usage()) - .field("load average", &self.load_average()) + .field("load average", &Self::load_average()) .field("total memory", &self.total_memory()) .field("free memory", &self.free_memory()) .field("total swap", &self.total_swap()) diff --git a/src/serde.rs b/src/serde.rs --- a/src/serde.rs +++ b/src/serde.rs @@ -120,15 +120,15 @@ impl serde::Serialize for crate::System { state.serialize_field("free_swap", &self.free_swap())?; state.serialize_field("used_swap", &self.used_swap())?; - state.serialize_field("uptime", &self.uptime())?; - state.serialize_field("boot_time", &self.boot_time())?; - state.serialize_field("load_average", &self.load_average())?; - state.serialize_field("name", &self.name())?; - state.serialize_field("kernel_version", &self.kernel_version())?; - state.serialize_field("os_version", &self.os_version())?; - state.serialize_field("long_os_version", &self.long_os_version())?; - state.serialize_field("distribution_id", &self.distribution_id())?; - state.serialize_field("host_name", &self.host_name())?; + state.serialize_field("uptime", &Self::uptime())?; + state.serialize_field("boot_time", &Self::boot_time())?; + state.serialize_field("load_average", &Self::load_average())?; + state.serialize_field("name", &Self::name())?; + state.serialize_field("kernel_version", &Self::kernel_version())?; + state.serialize_field("os_version", &Self::os_version())?; + state.serialize_field("long_os_version", &Self::long_os_version())?; + state.serialize_field("distribution_id", &Self::distribution_id())?; + state.serialize_field("host_name", &Self::host_name())?; state.end() } diff --git a/src/sysinfo.h b/src/sysinfo.h --- a/src/sysinfo.h +++ b/src/sysinfo.h @@ -67,10 +67,10 @@ RString sysinfo_cpu_brand(CSystem system); uint64_t sysinfo_cpu_frequency(CSystem system); uint32_t sysinfo_cpu_physical_cores(CSystem system); -RString sysinfo_system_name(CSystem system); -RString sysinfo_system_kernel_version(CSystem system); -RString sysinfo_system_version(CSystem system); -RString sysinfo_system_host_name(CSystem system); -RString sysinfo_system_long_version(CSystem system); +RString sysinfo_system_name(); +RString sysinfo_system_kernel_version(); +RString sysinfo_system_version(); +RString sysinfo_system_host_name(); +RString sysinfo_system_long_version(); void sysinfo_rstring_free(RString str); diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -29,7 +29,6 @@ pub(crate) struct SystemInner { swap_free: u64, page_size_b: u64, port: mach_port_t, - boot_time: u64, #[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] clock_info: Option<crate::sys::macos::system::SystemTimeInfo>, cpus: CpusWrapper, diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -88,7 +87,6 @@ impl SystemInner { swap_free: 0, page_size_b: sysconf(_SC_PAGESIZE) as _, port, - boot_time: boot_time(), #[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] clock_info: crate::sys::macos::system::SystemTimeInfo::new(port), cpus: CpusWrapper::new(), diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -321,15 +319,15 @@ impl SystemInner { self.swap_total - self.swap_free } - pub(crate) fn uptime(&self) -> u64 { + pub(crate) fn uptime() -> u64 { unsafe { let csec = libc::time(::std::ptr::null_mut()); - libc::difftime(csec, self.boot_time as _) as u64 + libc::difftime(csec, Self::boot_time() as _) as _ } } - pub(crate) fn load_average(&self) -> LoadAvg { + pub(crate) fn load_average() -> LoadAvg { let mut loads = vec![0f64; 3]; unsafe { diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -342,17 +340,17 @@ impl SystemInner { } } - pub(crate) fn boot_time(&self) -> u64 { - self.boot_time + pub(crate) fn boot_time() -> u64 { + boot_time() } - pub(crate) fn name(&self) -> Option<String> { + pub(crate) fn name() -> Option<String> { get_system_info(libc::KERN_OSTYPE, Some("Darwin")) } - pub(crate) fn long_os_version(&self) -> Option<String> { + pub(crate) fn long_os_version() -> Option<String> { #[cfg(target_os = "macos")] - let friendly_name = match self.os_version().unwrap_or_default() { + let friendly_name = match Self::os_version().unwrap_or_default() { f_n if f_n.starts_with("14.0") => "Sonoma", f_n if f_n.starts_with("10.16") | f_n.starts_with("11.0") diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -383,25 +381,25 @@ impl SystemInner { #[cfg(target_os = "macos")] let long_name = Some(format!( "MacOS {} {}", - self.os_version().unwrap_or_default(), + Self::os_version().unwrap_or_default(), friendly_name )); #[cfg(target_os = "ios")] - let long_name = Some(format!("iOS {}", self.os_version().unwrap_or_default())); + let long_name = Some(format!("iOS {}", Self::os_version().unwrap_or_default())); long_name } - pub(crate) fn host_name(&self) -> Option<String> { + pub(crate) fn host_name() -> Option<String> { get_system_info(libc::KERN_HOSTNAME, None) } - pub(crate) fn kernel_version(&self) -> Option<String> { + pub(crate) fn kernel_version() -> Option<String> { get_system_info(libc::KERN_OSRELEASE, None) } - pub(crate) fn os_version(&self) -> Option<String> { + pub(crate) fn os_version() -> Option<String> { unsafe { // get the size for the buffer first let mut size = 0; diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -433,11 +431,11 @@ impl SystemInner { } } - pub(crate) fn distribution_id(&self) -> String { + pub(crate) fn distribution_id() -> String { std::env::consts::OS.to_owned() } - pub(crate) fn cpu_arch(&self) -> Option<String> { + pub(crate) fn cpu_arch() -> Option<String> { let mut arch_str: [u8; 32] = [0; 32]; let mut mib = [libc::CTL_HW as _, libc::HW_MACHINE as _]; diff --git a/src/unix/freebsd/cpu.rs b/src/unix/freebsd/cpu.rs --- a/src/unix/freebsd/cpu.rs +++ b/src/unix/freebsd/cpu.rs @@ -187,7 +187,7 @@ pub(crate) fn physical_core_count() -> Option<usize> { } unsafe fn get_frequency_for_cpu(cpu_nb: usize) -> u64 { - let mut frequency = 0; + let mut frequency: c_int = 0; // The information can be missing if it's running inside a VM. if !get_sys_value_by_name( diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -25,7 +25,6 @@ pub(crate) struct SystemInner { mem_used: u64, swap_total: u64, swap_used: u64, - boot_time: u64, system_info: SystemInfo, cpus: CpusWrapper, } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -39,7 +38,6 @@ impl SystemInner { mem_used: 0, swap_total: 0, swap_used: 0, - boot_time: boot_time(), system_info: SystemInfo::new(), cpus: CpusWrapper::new(), } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -186,19 +184,19 @@ impl SystemInner { self.swap_used } - pub(crate) fn uptime(&self) -> u64 { + pub(crate) fn uptime() -> u64 { unsafe { let csec = libc::time(std::ptr::null_mut()); - libc::difftime(csec, self.boot_time as _) as u64 + libc::difftime(csec, Self::boot_time() as _) as u64 } } - pub(crate) fn boot_time(&self) -> u64 { - self.boot_time + pub(crate) fn boot_time() -> u64 { + boot_time() } - pub(crate) fn load_average(&self) -> LoadAvg { + pub(crate) fn load_average() -> LoadAvg { let mut loads = vec![0f64; 3]; unsafe { libc::getloadavg(loads.as_mut_ptr(), 3); diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -210,31 +208,53 @@ impl SystemInner { } } - pub(crate) fn name(&self) -> Option<String> { - self.system_info.get_os_name() + pub(crate) fn name() -> Option<String> { + let mut os_type: [c_int; 2] = [0; 2]; + unsafe { + init_mib(b"kern.ostype\0", &mut os_type); + get_system_info(&os_type, Some("FreeBSD")) + } } - pub(crate) fn long_os_version(&self) -> Option<String> { - self.system_info.get_os_release_long() + pub(crate) fn os_version() -> Option<String> { + let mut os_release: [c_int; 2] = [0; 2]; + unsafe { + init_mib(b"kern.osrelease\0", &mut os_release); + // It returns something like "13.0-RELEASE". We want to keep everything until the "-". + get_system_info(&os_release, None) + .and_then(|s| s.split('-').next().map(|s| s.to_owned())) + } } - pub(crate) fn host_name(&self) -> Option<String> { - self.system_info.get_hostname() + pub(crate) fn long_os_version() -> Option<String> { + let mut os_release: [c_int; 2] = [0; 2]; + unsafe { + init_mib(b"kern.osrelease\0", &mut os_release); + get_system_info(&os_release, None) + } } - pub(crate) fn kernel_version(&self) -> Option<String> { - self.system_info.get_kernel_version() + pub(crate) fn host_name() -> Option<String> { + let mut hostname: [c_int; 2] = [0; 2]; + unsafe { + init_mib(b"kern.hostname\0", &mut hostname); + get_system_info(&hostname, None) + } } - pub(crate) fn os_version(&self) -> Option<String> { - self.system_info.get_os_release() + pub(crate) fn kernel_version() -> Option<String> { + let mut kern_version: [c_int; 2] = [0; 2]; + unsafe { + init_mib(b"kern.version\0", &mut kern_version); + get_system_info(&kern_version, None) + } } - pub(crate) fn distribution_id(&self) -> String { + pub(crate) fn distribution_id() -> String { std::env::consts::OS.to_owned() } - pub(crate) fn cpu_arch(&self) -> Option<String> { + pub(crate) fn cpu_arch() -> Option<String> { let mut arch_str: [u8; 32] = [0; 32]; let mib = [libc::CTL_HW as _, libc::HW_MACHINE as _]; diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -429,10 +449,6 @@ struct SystemInfo { virtual_cache_count: [c_int; 4], virtual_inactive_count: [c_int; 4], virtual_free_count: [c_int; 4], - os_type: [c_int; 2], - os_release: [c_int; 2], - kern_version: [c_int; 2], - hostname: [c_int; 2], buf_space: [c_int; 2], kd: NonNull<libc::kvm_t>, /// From FreeBSD manual: "The kernel fixed-point scale factor". It's used when computing diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -470,10 +486,6 @@ impl SystemInfo { virtual_inactive_count: Default::default(), virtual_free_count: Default::default(), buf_space: Default::default(), - os_type: Default::default(), - os_release: Default::default(), - kern_version: Default::default(), - hostname: Default::default(), kd, fscale: 0., procstat: std::ptr::null_mut(), diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -505,37 +517,10 @@ impl SystemInfo { init_mib(b"vm.stats.vm.v_free_count\0", &mut si.virtual_free_count); init_mib(b"vfs.bufspace\0", &mut si.buf_space); - init_mib(b"kern.ostype\0", &mut si.os_type); - init_mib(b"kern.osrelease\0", &mut si.os_release); - init_mib(b"kern.version\0", &mut si.kern_version); - init_mib(b"kern.hostname\0", &mut si.hostname); - si } } - fn get_os_name(&self) -> Option<String> { - get_system_info(&[self.os_type[0], self.os_type[1]], Some("FreeBSD")) - } - - fn get_kernel_version(&self) -> Option<String> { - get_system_info(&[self.kern_version[0], self.kern_version[1]], None) - } - - fn get_os_release_long(&self) -> Option<String> { - get_system_info(&[self.os_release[0], self.os_release[1]], None) - } - - fn get_os_release(&self) -> Option<String> { - // It returns something like "13.0-RELEASE". We want to keep everything until the "-". - get_system_info(&[self.os_release[0], self.os_release[1]], None) - .and_then(|s| s.split('-').next().map(|s| s.to_owned())) - } - - fn get_hostname(&self) -> Option<String> { - get_system_info(&[self.hostname[0], self.hostname[1]], Some("")) - } - /// Returns (used, total). fn get_swap_info(&self) -> (u64, u64) { // Magic number used in htop. Cannot find how they got it when reading `kvm_getswapinfo` diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -10,7 +10,7 @@ use std::cmp::min; use std::collections::HashMap; use std::ffi::CStr; use std::fs::File; -use std::io::{BufRead, BufReader, Read}; +use std::io::Read; use std::path::Path; use std::str::FromStr; use std::sync::atomic::AtomicIsize; diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -59,12 +59,12 @@ pub(crate) fn get_max_nb_fds() -> isize { } fn boot_time() -> u64 { - if let Ok(f) = File::open("/proc/stat") { - let buf = BufReader::new(f); - let line = buf - .split(b'\n') - .filter_map(|r| r.ok()) - .find(|l| l.starts_with(b"btime")); + if let Ok(buf) = File::open("/proc/stat").and_then(|mut f| { + let mut buf = Vec::new(); + f.read_to_end(&mut buf)?; + Ok(buf) + }) { + let line = buf.split(|c| *c == b'\n').find(|l| l.starts_with(b"btime")); if let Some(line) = line { return line diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -235,7 +235,7 @@ impl SystemInner { filter: Option<&[Pid]>, refresh_kind: ProcessRefreshKind, ) { - let uptime = self.uptime(); + let uptime = Self::uptime(); refresh_procs( &mut self.process_list, Path::new("/proc"), diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -253,7 +253,7 @@ impl SystemInner { pid: Pid, refresh_kind: ProcessRefreshKind, ) -> bool { - let uptime = self.uptime(); + let uptime = Self::uptime(); match _get_process_data( &Path::new("/proc/").join(pid.to_string()), &mut self.process_list, diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -348,7 +348,7 @@ impl SystemInner { self.swap_total - self.swap_free } - pub(crate) fn uptime(&self) -> u64 { + pub(crate) fn uptime() -> u64 { let content = get_all_data("/proc/uptime", 50).unwrap_or_default(); content .split('.') diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -357,11 +357,11 @@ impl SystemInner { .unwrap_or_default() } - pub(crate) fn boot_time(&self) -> u64 { - self.info.boot_time + pub(crate) fn boot_time() -> u64 { + boot_time() } - pub(crate) fn load_average(&self) -> LoadAvg { + pub(crate) fn load_average() -> LoadAvg { let mut s = String::new(); if File::open("/proc/loadavg") .and_then(|mut f| f.read_to_string(&mut s)) diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -383,7 +383,7 @@ impl SystemInner { } #[cfg(not(target_os = "android"))] - pub(crate) fn name(&self) -> Option<String> { + pub(crate) fn name() -> Option<String> { get_system_info_linux( InfoType::Name, Path::new("/etc/os-release"), diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -392,11 +392,11 @@ impl SystemInner { } #[cfg(target_os = "android")] - pub(crate) fn name(&self) -> Option<String> { + pub(crate) fn name() -> Option<String> { get_system_info_android(InfoType::Name) } - pub(crate) fn long_os_version(&self) -> Option<String> { + pub(crate) fn long_os_version() -> Option<String> { #[cfg(target_os = "android")] let system_name = "Android"; diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -406,12 +406,12 @@ impl SystemInner { Some(format!( "{} {} {}", system_name, - self.os_version().unwrap_or_default(), - self.name().unwrap_or_default() + Self::os_version().unwrap_or_default(), + Self::name().unwrap_or_default() )) } - pub(crate) fn host_name(&self) -> Option<String> { + pub(crate) fn host_name() -> Option<String> { unsafe { let hostname_max = sysconf(_SC_HOST_NAME_MAX); let mut buffer = vec![0_u8; hostname_max as usize]; diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -428,7 +428,7 @@ impl SystemInner { } } - pub(crate) fn kernel_version(&self) -> Option<String> { + pub(crate) fn kernel_version() -> Option<String> { let mut raw = std::mem::MaybeUninit::<libc::utsname>::zeroed(); unsafe { diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -450,7 +450,7 @@ impl SystemInner { } #[cfg(not(target_os = "android"))] - pub(crate) fn os_version(&self) -> Option<String> { + pub(crate) fn os_version() -> Option<String> { get_system_info_linux( InfoType::OsVersion, Path::new("/etc/os-release"), diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -459,12 +459,12 @@ impl SystemInner { } #[cfg(target_os = "android")] - pub(crate) fn os_version(&self) -> Option<String> { + pub(crate) fn os_version() -> Option<String> { get_system_info_android(InfoType::OsVersion) } #[cfg(not(target_os = "android"))] - pub(crate) fn distribution_id(&self) -> String { + pub(crate) fn distribution_id() -> String { get_system_info_linux( InfoType::DistributionID, Path::new("/etc/os-release"), diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -474,7 +474,7 @@ impl SystemInner { } #[cfg(target_os = "android")] - pub(crate) fn distribution_id(&self) -> String { + pub(crate) fn distribution_id() -> String { // Currently get_system_info_android doesn't support InfoType::DistributionID and always // returns None. This call is done anyway for consistency with non-Android implementation // and to suppress dead-code warning for DistributionID on Android. diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -482,7 +482,7 @@ impl SystemInner { .unwrap_or_else(|| std::env::consts::OS.to_owned()) } - pub(crate) fn cpu_arch(&self) -> Option<String> { + pub(crate) fn cpu_arch() -> Option<String> { let mut raw = std::mem::MaybeUninit::<libc::utsname>::uninit(); unsafe { diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -594,16 +594,18 @@ enum InfoType { #[cfg(not(target_os = "android"))] fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> Option<String> { - if let Ok(f) = File::open(path) { - let reader = BufReader::new(f); - + if let Ok(buf) = File::open(path).and_then(|mut f| { + let mut buf = String::new(); + f.read_to_string(&mut buf)?; + Ok(buf) + }) { let info_str = match info { InfoType::Name => "NAME=", InfoType::OsVersion => "VERSION_ID=", InfoType::DistributionID => "ID=", }; - for line in reader.lines().map_while(Result::ok) { + for line in buf.lines() { if let Some(stripped) = line.strip_prefix(info_str) { return Some(stripped.replace('"', "")); } diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -614,7 +616,13 @@ fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> O // VERSION_ID is not required in the `/etc/os-release` file // per https://www.linux.org/docs/man5/os-release.html // If this fails for some reason, fallback to None - let reader = BufReader::new(File::open(fallback_path).ok()?); + let buf = File::open(fallback_path) + .and_then(|mut f| { + let mut buf = String::new(); + f.read_to_string(&mut buf)?; + Ok(buf) + }) + .ok()?; let info_str = match info { InfoType::OsVersion => "DISTRIB_RELEASE=", diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -624,7 +632,7 @@ fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> O return None; } }; - for line in reader.lines().map_while(Result::ok) { + for line in buf.lines() { if let Some(stripped) = line.strip_prefix(info_str) { return Some(stripped.replace('"', "")); } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -94,15 +94,15 @@ impl SystemInner { 0 } - pub(crate) fn uptime(&self) -> u64 { + pub(crate) fn uptime() -> u64 { 0 } - pub(crate) fn boot_time(&self) -> u64 { + pub(crate) fn boot_time() -> u64 { 0 } - pub(crate) fn load_average(&self) -> LoadAvg { + pub(crate) fn load_average() -> LoadAvg { LoadAvg { one: 0., five: 0., diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -110,30 +110,30 @@ impl SystemInner { } } - pub(crate) fn name(&self) -> Option<String> { + pub(crate) fn name() -> Option<String> { None } - pub(crate) fn long_os_version(&self) -> Option<String> { + pub(crate) fn long_os_version() -> Option<String> { None } - pub(crate) fn kernel_version(&self) -> Option<String> { + pub(crate) fn kernel_version() -> Option<String> { None } - pub(crate) fn os_version(&self) -> Option<String> { + pub(crate) fn os_version() -> Option<String> { None } - pub(crate) fn distribution_id(&self) -> String { + pub(crate) fn distribution_id() -> String { std::env::consts::OS.to_owned() } - pub(crate) fn host_name(&self) -> Option<String> { + pub(crate) fn host_name() -> Option<String> { None } - pub(crate) fn cpu_arch(&self) -> Option<String> { + pub(crate) fn cpu_arch() -> Option<String> { None } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -32,10 +32,9 @@ use windows::Win32::System::Threading::GetExitCodeProcess; const WINDOWS_ELEVEN_BUILD_NUMBER: u32 = 22000; impl SystemInner { - fn is_windows_eleven(&self) -> bool { + fn is_windows_eleven() -> bool { WINDOWS_ELEVEN_BUILD_NUMBER - <= self - .kernel_version() + <= Self::kernel_version() .unwrap_or_default() .parse() .unwrap_or(0) diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -67,7 +66,6 @@ pub(crate) struct SystemInner { swap_used: u64, cpus: CpusWrapper, query: Option<Query>, - boot_time: u64, } impl SystemInner { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -80,7 +78,6 @@ impl SystemInner { swap_used: 0, cpus: CpusWrapper::new(), query: None, - boot_time: unsafe { boot_time() }, } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -410,24 +407,24 @@ impl SystemInner { self.swap_used } - pub(crate) fn uptime(&self) -> u64 { + pub(crate) fn uptime() -> u64 { unsafe { GetTickCount64() / 1_000 } } - pub(crate) fn boot_time(&self) -> u64 { - self.boot_time + pub(crate) fn boot_time() -> u64 { + unsafe { boot_time() } } - pub(crate) fn load_average(&self) -> LoadAvg { + pub(crate) fn load_average() -> LoadAvg { get_load_average() } - pub(crate) fn name(&self) -> Option<String> { + pub(crate) fn name() -> Option<String> { Some("Windows".to_owned()) } - pub(crate) fn long_os_version(&self) -> Option<String> { - if self.is_windows_eleven() { + pub(crate) fn long_os_version() -> Option<String> { + if Self::is_windows_eleven() { return get_reg_string_value( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -442,11 +439,11 @@ impl SystemInner { ) } - pub(crate) fn host_name(&self) -> Option<String> { + pub(crate) fn host_name() -> Option<String> { get_dns_hostname() } - pub(crate) fn kernel_version(&self) -> Option<String> { + pub(crate) fn kernel_version() -> Option<String> { get_reg_string_value( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -454,14 +451,14 @@ impl SystemInner { ) } - pub(crate) fn os_version(&self) -> Option<String> { + pub(crate) fn os_version() -> Option<String> { let build_number = get_reg_string_value( HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "CurrentBuildNumber", ) .unwrap_or_default(); - let major = if self.is_windows_eleven() { + let major = if Self::is_windows_eleven() { 11u32 } else { u32::from_le_bytes( diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -476,10 +473,10 @@ impl SystemInner { Some(format!("{major} ({build_number})")) } - pub(crate) fn distribution_id(&self) -> String { + pub(crate) fn distribution_id() -> String { std::env::consts::OS.to_owned() } - pub(crate) fn cpu_arch(&self) -> Option<String> { + pub(crate) fn cpu_arch() -> Option<String> { unsafe { // https://docs.microsoft.com/fr-fr/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info let info = SYSTEM_INFO::default();
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
Extract "standalone" methods from `System` If they don't need information stored in `System`, they shouldn't be a method of it.
0.29
1,171
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-12-17T17:21:49Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -474,7 +474,7 @@ fn test_wait_child() { std::process::Command::new("waitfor") .arg("/t") .arg("300") - .arg("RefreshProcess") + .arg("WaitChild") .stdout(std::process::Stdio::null()) .spawn() .unwrap() diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -736,3 +736,39 @@ fn test_process_specific_refresh() { update_specific_and_check!(exe, with_exe, , None); update_specific_and_check!(cwd, with_cwd, , None); } + +#[test] +fn test_refresh_pids() { + if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + let self_pid = sysinfo::get_current_pid().expect("failed to get current pid"); + let mut s = System::new(); + + let mut p = if cfg!(target_os = "windows") { + std::process::Command::new("waitfor") + .arg("/t") + .arg("3") + .arg("RefreshPids") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + } else { + std::process::Command::new("sleep") + .arg("3") + .stdout(std::process::Stdio::null()) + .spawn() + .unwrap() + }; + + let child_pid = Pid::from_u32(p.id() as _); + let pids = &[child_pid, self_pid]; + std::thread::sleep(std::time::Duration::from_millis(500)); + s.refresh_pids(pids); + p.kill().expect("Unable to kill process."); + + assert_eq!(s.processes().len(), 2); + for pid in s.processes().keys() { + assert!(pids.contains(pid)); + } +}
[ "1133" ]
GuillaumeGomez__sysinfo-1170
GuillaumeGomez/sysinfo
diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -265,7 +265,65 @@ impl System { /// s.refresh_processes_specifics(ProcessRefreshKind::new()); /// ``` pub fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { - self.inner.refresh_processes_specifics(refresh_kind) + self.inner.refresh_processes_specifics(None, refresh_kind) + } + + /// Gets specified processes and updates their information. + /// + /// It does the same as: + /// + /// ```no_run + /// # use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind}; + /// # let mut system = System::new(); + /// system.refresh_pids_specifics( + /// &[Pid::from(1), Pid::from(2)], + /// ProcessRefreshKind::new() + /// .with_memory() + /// .with_cpu() + /// .with_disk_usage() + /// .with_exe(UpdateKind::OnlyIfNotSet), + /// ); + /// ``` + /// + /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour + /// by using [`set_open_files_limit`][crate::set_open_files_limit]. + /// + /// Example: + /// + /// ```no_run + /// use sysinfo::System; + /// + /// let mut s = System::new_all(); + /// s.refresh_processes(); + /// ``` + pub fn refresh_pids(&mut self, pids: &[Pid]) { + self.refresh_pids_specifics( + pids, + ProcessRefreshKind::new() + .with_memory() + .with_cpu() + .with_disk_usage() + .with_exe(UpdateKind::OnlyIfNotSet), + ); + } + + /// Gets specified processes and updates the specified information. + /// + /// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour + /// by using [`set_open_files_limit`][crate::set_open_files_limit]. + /// + /// ```no_run + /// use sysinfo::{Pid, ProcessRefreshKind, System}; + /// + /// let mut s = System::new_all(); + /// s.refresh_pids_specifics(&[Pid::from(1), Pid::from(2)], ProcessRefreshKind::new()); + /// ``` + pub fn refresh_pids_specifics(&mut self, pids: &[Pid], refresh_kind: ProcessRefreshKind) { + if pids.is_empty() { + return; + } + self.inner + .refresh_processes_specifics(Some(pids), refresh_kind) } /// Refreshes *only* the process corresponding to `pid`. Returns `false` if the process doesn't diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -164,10 +164,19 @@ impl SystemInner { } #[cfg(any(target_os = "ios", feature = "apple-sandbox"))] - pub(crate) fn refresh_processes_specifics(&mut self, _refresh_kind: ProcessRefreshKind) {} + pub(crate) fn refresh_processes_specifics( + &mut self, + _filter: Option<&[Pid]>, + _refresh_kind: ProcessRefreshKind, + ) { + } #[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] - pub(crate) fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { + pub(crate) fn refresh_processes_specifics( + &mut self, + filter: Option<&[Pid]>, + refresh_kind: ProcessRefreshKind, + ) { use crate::utils::into_iter; unsafe { diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -177,6 +186,26 @@ impl SystemInner { } } if let Some(pids) = get_proc_list() { + #[inline(always)] + fn real_filter(e: Pid, filter: &[Pid]) -> bool { + filter.contains(&e) + } + + #[inline(always)] + fn empty_filter(_e: Pid, _filter: &[Pid]) -> bool { + true + } + + #[allow(clippy::type_complexity)] + let (filter, filter_callback): ( + &[Pid], + &(dyn Fn(Pid, &[Pid]) -> bool + Sync + Send), + ) = if let Some(filter) = filter { + (filter, &real_filter) + } else { + (&[], &empty_filter) + }; + let now = get_now(); let port = self.port; let time_interval = self.clock_info.as_mut().map(|c| c.get_time_interval(port)); diff --git a/src/unix/apple/system.rs b/src/unix/apple/system.rs --- a/src/unix/apple/system.rs +++ b/src/unix/apple/system.rs @@ -188,6 +217,9 @@ impl SystemInner { into_iter(pids) .flat_map(|pid| { + if !filter_callback(pid, filter) { + return None; + } match update_process(wrap, pid, time_interval, now, refresh_kind, false) { Ok(x) => x, _ => None, diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -64,8 +64,12 @@ impl SystemInner { self.cpus.refresh(refresh_kind) } - pub(crate) fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { - unsafe { self.refresh_procs(refresh_kind) } + pub(crate) fn refresh_processes_specifics( + &mut self, + filter: Option<&[Pid]>, + refresh_kind: ProcessRefreshKind, + ) { + unsafe { self.refresh_procs(filter, refresh_kind) } } pub(crate) fn refresh_process_specifics( diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -250,7 +254,7 @@ impl SystemInner { } impl SystemInner { - unsafe fn refresh_procs(&mut self, refresh_kind: ProcessRefreshKind) { + unsafe fn refresh_procs(&mut self, filter: Option<&[Pid]>, refresh_kind: ProcessRefreshKind) { let mut count = 0; let kvm_procs = libc::kvm_getprocs( self.system_info.kd.as_ptr(), diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -263,6 +267,26 @@ impl SystemInner { return; } + #[inline(always)] + fn real_filter(e: &libc::kinfo_proc, filter: &[Pid]) -> bool { + filter.contains(&Pid(e.ki_pid)) + } + + #[inline(always)] + fn empty_filter(_e: &libc::kinfo_proc, _filter: &[Pid]) -> bool { + true + } + + #[allow(clippy::type_complexity)] + let (filter, filter_callback): ( + &[Pid], + &(dyn Fn(&libc::kinfo_proc, &[Pid]) -> bool + Sync + Send), + ) = if let Some(filter) = filter { + (filter, &real_filter) + } else { + (&[], &empty_filter) + }; + let new_processes = { #[cfg(feature = "multithread")] use rayon::iter::{ParallelIterator, ParallelIterator as IterTrait}; diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -278,6 +302,9 @@ impl SystemInner { let proc_list = utils::WrapMap(UnsafeCell::new(&mut self.process_list)); IterTrait::filter_map(crate::utils::into_iter(kvm_procs), |kproc| { + if !filter_callback(kproc, filter) { + return None; + } super::process::get_process_data( kproc, &proc_list, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -675,11 +675,32 @@ pub(crate) fn refresh_procs( path: &Path, uptime: u64, info: &SystemInfo, + filter: Option<&[Pid]>, refresh_kind: ProcessRefreshKind, ) -> bool { #[cfg(feature = "multithread")] use rayon::iter::ParallelIterator; + #[inline(always)] + fn real_filter(e: &ProcAndTasks, filter: &[Pid]) -> bool { + filter.contains(&e.pid) + } + + #[inline(always)] + fn empty_filter(_e: &ProcAndTasks, _filter: &[Pid]) -> bool { + true + } + + #[allow(clippy::type_complexity)] + let (filter, filter_callback): ( + &[Pid], + &(dyn Fn(&ProcAndTasks, &[Pid]) -> bool + Sync + Send), + ) = if let Some(filter) = filter { + (filter, &real_filter) + } else { + (&[], &empty_filter) + }; + // FIXME: To prevent retrieving a task more than once (it can be listed in `/proc/[PID]/task` // subfolder and directly in `/proc` at the same time), might be interesting to use a `HashSet`. let procs = { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -697,6 +718,7 @@ pub(crate) fn refresh_procs( entries }) .flatten() + .filter(|e| filter_callback(e, filter)) .filter_map(|e| { let (mut p, _) = _get_process_data( e.path.as_path(), diff --git a/src/unix/linux/system.rs b/src/unix/linux/system.rs --- a/src/unix/linux/system.rs +++ b/src/unix/linux/system.rs @@ -230,13 +230,18 @@ impl SystemInner { self.refresh_cpus(false, refresh_kind); } - pub(crate) fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { + pub(crate) fn refresh_processes_specifics( + &mut self, + filter: Option<&[Pid]>, + refresh_kind: ProcessRefreshKind, + ) { let uptime = self.uptime(); refresh_procs( &mut self.process_list, Path::new("/proc"), uptime, &self.info, + filter, refresh_kind, ); self.clear_procs(refresh_kind); diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -27,7 +27,12 @@ impl SystemInner { pub(crate) fn refresh_cpu_specifics(&mut self, _refresh_kind: CpuRefreshKind) {} - pub(crate) fn refresh_processes_specifics(&mut self, _refresh_kind: ProcessRefreshKind) {} + pub(crate) fn refresh_processes_specifics( + &mut self, + _filter: Option<&[Pid]>, + _refresh_kind: ProcessRefreshKind, + ) { + } pub(crate) fn refresh_process_specifics( &mut self, diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -196,7 +196,11 @@ impl SystemInner { } #[allow(clippy::cast_ptr_alignment)] - pub(crate) fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { + pub(crate) fn refresh_processes_specifics( + &mut self, + filter: Option<&[Pid]>, + refresh_kind: ProcessRefreshKind, + ) { // Windows 10 notebook requires at least 512KiB of memory to make it in one go let mut buffer_size = 512 * 1024; let mut process_information: Vec<u8> = Vec::with_capacity(buffer_size); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -239,6 +243,26 @@ impl SystemInner { } } + #[inline(always)] + fn real_filter(e: Pid, filter: &[Pid]) -> bool { + filter.contains(&e) + } + + #[inline(always)] + fn empty_filter(_e: Pid, _filter: &[Pid]) -> bool { + true + } + + #[allow(clippy::type_complexity)] + let (filter, filter_callback): ( + &[Pid], + &(dyn Fn(Pid, &[Pid]) -> bool + Sync + Send), + ) = if let Some(filter) = filter { + (filter, &real_filter) + } else { + (&[], &empty_filter) + }; + // If we reach this point NtQuerySystemInformation succeeded // and the buffer contents are initialized process_information.set_len(buffer_size); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -252,7 +276,9 @@ impl SystemInner { .offset(process_information_offset) as *const SYSTEM_PROCESS_INFORMATION; - process_ids.push(Wrap(p)); + if filter_callback(Pid((*p).UniqueProcessId as _), filter) { + process_ids.push(Wrap(p)); + } // read_unaligned is necessary to avoid // misaligned pointer dereference: address must be a multiple of 0x8 but is 0x...
05d5c2cbfe823a792333841547d5c251db99fb1b
Allow to refresh multiple PIDs at once (so it can be multithreaded) Adding methods called `refresh_pids` and `refresh_pids_specifics`.
0.29
1,170
I took a look at this and on linux, I need to figure out if the `/proc/[PID]/task/` reading is really necessary. I couldn't find a reason why it was actually useful but I'll continue to investigate. More explanations about the `task` folder [here](https://github.com/htop-dev/htop/issues/1341). Not a problem, the tasks can't be listed directly in `/proc`.
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-11-29T16:35:14Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -34,7 +34,7 @@ fn test_cwd() { if let Some(p) = p { assert_eq!(p.pid(), pid); - assert_eq!(p.cwd(), std::env::current_dir().unwrap()); + assert_eq!(p.cwd().unwrap(), &std::env::current_dir().unwrap()); } else { panic!("Process not found!"); } diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -166,13 +166,14 @@ fn test_process_refresh() { .process(sysinfo::get_current_pid().expect("failed to get current pid")) .is_some()); - assert!(s.processes().iter().all(|(_, p)| p.environ().is_empty() - && p.cwd().as_os_str().is_empty() - && p.cmd().is_empty())); assert!(s .processes() .iter() - .any(|(_, p)| !p.exe().as_os_str().is_empty() && !p.name().is_empty() && p.memory() != 0)); + .all(|(_, p)| p.environ().is_empty() && p.cwd().is_none() && p.cmd().is_empty())); + assert!(s + .processes() + .iter() + .any(|(_, p)| !p.name().is_empty() && p.memory() != 0)); } #[test] diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -628,7 +629,6 @@ fn test_process_creds() { // This test ensures that only the requested information is retrieved. #[test] fn test_process_specific_refresh() { - use std::path::Path; use sysinfo::{DiskUsage, ProcessRefreshKind}; if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -645,9 +645,9 @@ fn test_process_specific_refresh() { } assert_eq!(p.environ().len(), 0); assert_eq!(p.cmd().len(), 0); - assert_eq!(p.exe(), Path::new("")); - assert_eq!(p.cwd(), Path::new("")); - assert_eq!(p.root(), Path::new("")); + assert_eq!(p.exe(), None); + assert_eq!(p.cwd(), None); + assert_eq!(p.root(), None); assert_eq!(p.memory(), 0); assert_eq!(p.virtual_memory(), 0); // These two won't be checked, too much lazyness in testing them... diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -723,8 +723,8 @@ fn test_process_specific_refresh() { target_os = "ios", feature = "apple-sandbox", )) { - update_specific_and_check!(root, with_root, , Path::new("")); + update_specific_and_check!(root, with_root, , None); } - update_specific_and_check!(exe, with_exe, , Path::new("")); - update_specific_and_check!(cwd, with_cwd, , Path::new("")); + update_specific_and_check!(exe, with_exe, , None); + update_specific_and_check!(cwd, with_cwd, , None); }
[ "1137" ]
GuillaumeGomez__sysinfo-1162
GuillaumeGomez/sysinfo
diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -462,7 +462,7 @@ pub extern "C" fn sysinfo_process_executable_path(process: CProcess) -> RString assert!(!process.is_null()); let process = process as *const Process; unsafe { - if let Some(p) = (*process).exe().to_str() { + if let Some(p) = (*process).exe().and_then(|exe| exe.to_str()) { if let Ok(c) = CString::new(p) { return c.into_raw() as _; } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -477,7 +477,7 @@ pub extern "C" fn sysinfo_process_root_directory(process: CProcess) -> RString { assert!(!process.is_null()); let process = process as *const Process; unsafe { - if let Some(p) = (*process).root().to_str() { + if let Some(p) = (*process).root().and_then(|root| root.to_str()) { if let Ok(c) = CString::new(p) { return c.into_raw() as _; } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -492,7 +492,7 @@ pub extern "C" fn sysinfo_process_current_directory(process: CProcess) -> RStrin assert!(!process.is_null()); let process = process as *const Process; unsafe { - if let Some(p) = (*process).cwd().to_str() { + if let Some(p) = (*process).cwd().and_then(|cwd| cwd.to_str()) { if let Ok(c) = CString::new(p) { return c.into_raw() as _; } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -855,7 +855,7 @@ impl Process { /// /// let s = System::new_all(); /// if let Some(process) = s.process(Pid::from(1337)) { - /// println!("{}", process.exe().display()); + /// println!("{:?}", process.exe()); /// } /// ``` /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -870,7 +870,7 @@ impl Process { /// replacement for this. /// A process [may change its `cmd[0]` value](https://man7.org/linux/man-pages/man5/proc.5.html) /// freely, making this an untrustworthy source of information. - pub fn exe(&self) -> &Path { + pub fn exe(&self) -> Option<&Path> { self.inner.exe() } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -909,10 +909,10 @@ impl Process { /// /// let s = System::new_all(); /// if let Some(process) = s.process(Pid::from(1337)) { - /// println!("{}", process.cwd().display()); + /// println!("{:?}", process.cwd()); /// } /// ``` - pub fn cwd(&self) -> &Path { + pub fn cwd(&self) -> Option<&Path> { self.inner.cwd() } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -923,10 +923,10 @@ impl Process { /// /// let s = System::new_all(); /// if let Some(process) = s.process(Pid::from(1337)) { - /// println!("{}", process.root().display()); + /// println!("{:?}", process.root()); /// } /// ``` - pub fn root(&self) -> &Path { + pub fn root(&self) -> Option<&Path> { self.inner.root() } diff --git a/src/unix/apple/app_store/process.rs b/src/unix/apple/app_store/process.rs --- a/src/unix/apple/app_store/process.rs +++ b/src/unix/apple/app_store/process.rs @@ -19,8 +19,8 @@ impl ProcessInner { &[] } - pub(crate) fn exe(&self) -> &Path { - Path::new("/") + pub(crate) fn exe(&self) -> Option<&Path> { + None } pub(crate) fn pid(&self) -> Pid { diff --git a/src/unix/apple/app_store/process.rs b/src/unix/apple/app_store/process.rs --- a/src/unix/apple/app_store/process.rs +++ b/src/unix/apple/app_store/process.rs @@ -31,12 +31,12 @@ impl ProcessInner { &[] } - pub(crate) fn cwd(&self) -> &Path { - Path::new("/") + pub(crate) fn cwd(&self) -> Option<&Path> { + None } - pub(crate) fn root(&self) -> &Path { - Path::new("/") + pub(crate) fn root(&self) -> Option<&Path> { + None } pub(crate) fn memory(&self) -> u64 { diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -14,12 +14,12 @@ use crate::unix::utils::cstr_to_rust_with_size; pub(crate) struct ProcessInner { pub(crate) name: String, pub(crate) cmd: Vec<String>, - pub(crate) exe: PathBuf, + pub(crate) exe: Option<PathBuf>, pid: Pid, parent: Option<Pid>, pub(crate) environ: Vec<String>, - cwd: PathBuf, - pub(crate) root: PathBuf, + cwd: Option<PathBuf>, + pub(crate) root: Option<PathBuf>, pub(crate) memory: u64, pub(crate) virtual_memory: u64, old_utime: u64, diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -52,9 +52,9 @@ impl ProcessInner { parent: None, cmd: Vec::new(), environ: Vec::new(), - exe: PathBuf::new(), - cwd: PathBuf::new(), - root: PathBuf::new(), + exe: None, + cwd: None, + root: None, memory: 0, virtual_memory: 0, cpu_usage: 0., diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -83,9 +83,9 @@ impl ProcessInner { parent, cmd: Vec::new(), environ: Vec::new(), - exe: PathBuf::new(), - cwd: PathBuf::new(), - root: PathBuf::new(), + exe: None, + cwd: None, + root: None, memory: 0, virtual_memory: 0, cpu_usage: 0., diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -120,8 +120,8 @@ impl ProcessInner { &self.cmd } - pub(crate) fn exe(&self) -> &Path { - self.exe.as_path() + pub(crate) fn exe(&self) -> Option<&Path> { + self.exe.as_deref() } pub(crate) fn pid(&self) -> Pid { diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -132,12 +132,12 @@ impl ProcessInner { &self.environ } - pub(crate) fn cwd(&self) -> &Path { - self.cwd.as_path() + pub(crate) fn cwd(&self) -> Option<&Path> { + self.cwd.as_deref() } - pub(crate) fn root(&self) -> &Path { - self.root.as_path() + pub(crate) fn root(&self) -> Option<&Path> { + self.root.as_deref() } pub(crate) fn memory(&self) -> u64 { diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -388,9 +388,7 @@ unsafe fn get_exe_and_name_backup( process: &mut ProcessInner, refresh_kind: ProcessRefreshKind, ) -> bool { - let exe_needs_update = refresh_kind - .exe() - .needs_update(|| process.exe.as_os_str().is_empty()); + let exe_needs_update = refresh_kind.exe().needs_update(|| process.exe.is_none()); if !process.name.is_empty() && !exe_needs_update { return false; } diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -412,7 +410,7 @@ unsafe fn get_exe_and_name_backup( .to_owned(); } if exe_needs_update { - process.exe = exe; + process.exe = Some(exe); } true } diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -432,12 +430,8 @@ unsafe fn convert_node_path_info(node: &libc::vnode_info_path) -> Option<PathBuf } unsafe fn get_cwd_root(process: &mut ProcessInner, refresh_kind: ProcessRefreshKind) { - let cwd_needs_update = refresh_kind - .cwd() - .needs_update(|| process.cwd.as_os_str().is_empty()); - let root_needs_update = refresh_kind - .root() - .needs_update(|| process.root.as_os_str().is_empty()); + let cwd_needs_update = refresh_kind.cwd().needs_update(|| process.cwd.is_none()); + let root_needs_update = refresh_kind.root().needs_update(|| process.root.is_none()); if !cwd_needs_update && !root_needs_update { return; } diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -454,14 +448,10 @@ unsafe fn get_cwd_root(process: &mut ProcessInner, refresh_kind: ProcessRefreshK return; } if cwd_needs_update { - if let Some(cwd) = convert_node_path_info(&vnodepathinfo.pvi_cdir) { - process.cwd = cwd; - } + process.cwd = convert_node_path_info(&vnodepathinfo.pvi_cdir); } if root_needs_update { - if let Some(root) = convert_node_path_info(&vnodepathinfo.pvi_rdir) { - process.root = root; - } + process.root = convert_node_path_info(&vnodepathinfo.pvi_rdir); } } diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -557,11 +547,8 @@ unsafe fn get_process_infos(process: &mut ProcessInner, refresh_kind: ProcessRef .to_owned(); } - if refresh_kind - .exe() - .needs_update(|| process.exe.as_os_str().is_empty()) - { - process.exe = exe; + if refresh_kind.exe().needs_update(|| process.exe.is_none()) { + process.exe = Some(exe); } let environ_needs_update = refresh_kind diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -43,12 +43,12 @@ impl fmt::Display for ProcessStatus { pub(crate) struct ProcessInner { pub(crate) name: String, pub(crate) cmd: Vec<String>, - pub(crate) exe: PathBuf, + pub(crate) exe: Option<PathBuf>, pub(crate) pid: Pid, parent: Option<Pid>, pub(crate) environ: Vec<String>, - pub(crate) cwd: PathBuf, - pub(crate) root: PathBuf, + pub(crate) cwd: Option<PathBuf>, + pub(crate) root: Option<PathBuf>, pub(crate) memory: u64, pub(crate) virtual_memory: u64, pub(crate) updated: bool, diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -80,8 +80,8 @@ impl ProcessInner { &self.cmd } - pub(crate) fn exe(&self) -> &Path { - self.exe.as_path() + pub(crate) fn exe(&self) -> Option<&Path> { + self.exe.as_deref() } pub(crate) fn pid(&self) -> Pid { diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -92,12 +92,12 @@ impl ProcessInner { &self.environ } - pub(crate) fn cwd(&self) -> &Path { - self.cwd.as_path() + pub(crate) fn cwd(&self) -> Option<&Path> { + self.cwd.as_deref() } - pub(crate) fn root(&self) -> &Path { - self.root.as_path() + pub(crate) fn root(&self) -> Option<&Path> { + self.root.as_deref() } pub(crate) fn memory(&self) -> u64 { diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -277,14 +277,14 @@ pub(crate) unsafe fn get_process_data( virtual_memory, memory, // procstat_getfiles - cwd: PathBuf::new(), - exe: PathBuf::new(), + cwd: None, + exe: None, // kvm_getargv isn't thread-safe so we get it in the main thread. name: String::new(), // kvm_getargv isn't thread-safe so we get it in the main thread. cmd: Vec::new(), // kvm_getargv isn't thread-safe so we get it in the main thread. - root: PathBuf::new(), + root: None, // kvm_getenvv isn't thread-safe so we get it in the main thread. environ: Vec::new(), status, diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -297,11 +297,12 @@ pub(crate) unsafe fn get_process_data( })) } -pub(crate) unsafe fn get_exe(exe: &mut PathBuf, pid: crate::Pid, refresh_kind: ProcessRefreshKind) { - if refresh_kind - .exe() - .needs_update(|| exe.as_os_str().is_empty()) - { +pub(crate) unsafe fn get_exe( + exe: &mut Option<PathBuf>, + pid: crate::Pid, + refresh_kind: ProcessRefreshKind, +) { + if refresh_kind.exe().needs_update(|| exe.is_none()) { let mut buffer = [0; libc::PATH_MAX as usize + 1]; *exe = get_sys_value_str( diff --git a/src/unix/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/unix/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -313,10 +314,6 @@ pub(crate) unsafe fn get_exe(exe: &mut PathBuf, pid: crate::Pid, refresh_kind: P ], &mut buffer, ) - .map(PathBuf::from) - .unwrap_or_else(|| { - sysinfo_debug!("Failed to get `exe` for {}", pid.0); - PathBuf::new() - }); + .map(PathBuf::from); } } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -599,12 +599,8 @@ impl SystemInfo { refresh_kind: ProcessRefreshKind, ) { let mut done = 0; - let cwd_needs_update = refresh_kind - .cwd() - .needs_update(|| proc_.cwd().as_os_str().is_empty()); - let root_needs_update = refresh_kind - .root() - .needs_update(|| proc_.root().as_os_str().is_empty()); + let cwd_needs_update = refresh_kind.cwd().needs_update(|| proc_.cwd().is_none()); + let root_needs_update = refresh_kind.root().needs_update(|| proc_.root().is_none()); if cwd_needs_update { done += 1; } diff --git a/src/unix/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/unix/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -632,14 +628,14 @@ impl SystemInfo { if tmp.fs_uflags & libc::PS_FST_UFLAG_CDIR != 0 { if cwd_needs_update && !tmp.fs_path.is_null() { if let Ok(p) = CStr::from_ptr(tmp.fs_path).to_str() { - proc_.cwd = PathBuf::from(p); + proc_.cwd = Some(PathBuf::from(p)); done -= 1; } } } else if tmp.fs_uflags & libc::PS_FST_UFLAG_RDIR != 0 { if root_needs_update && !tmp.fs_path.is_null() { if let Ok(p) = CStr::from_ptr(tmp.fs_path).to_str() { - proc_.root = PathBuf::from(p); + proc_.root = Some(PathBuf::from(p)); done -= 1; } } diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -59,12 +59,12 @@ impl fmt::Display for ProcessStatus { pub(crate) struct ProcessInner { pub(crate) name: String, pub(crate) cmd: Vec<String>, - pub(crate) exe: PathBuf, + pub(crate) exe: Option<PathBuf>, pub(crate) pid: Pid, parent: Option<Pid>, pub(crate) environ: Vec<String>, - pub(crate) cwd: PathBuf, - pub(crate) root: PathBuf, + pub(crate) cwd: Option<PathBuf>, + pub(crate) root: Option<PathBuf>, pub(crate) memory: u64, pub(crate) virtual_memory: u64, utime: u64, diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -97,9 +97,9 @@ impl ProcessInner { parent: None, cmd: Vec::new(), environ: Vec::new(), - exe: PathBuf::new(), - cwd: PathBuf::new(), - root: PathBuf::new(), + exe: None, + cwd: None, + root: None, memory: 0, virtual_memory: 0, cpu_usage: 0., diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -142,8 +142,8 @@ impl ProcessInner { &self.cmd } - pub(crate) fn exe(&self) -> &Path { - self.exe.as_path() + pub(crate) fn exe(&self) -> Option<&Path> { + self.exe.as_deref() } pub(crate) fn pid(&self) -> Pid { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -154,12 +154,12 @@ impl ProcessInner { &self.environ } - pub(crate) fn cwd(&self) -> &Path { - self.cwd.as_path() + pub(crate) fn cwd(&self) -> Option<&Path> { + self.cwd.as_deref() } - pub(crate) fn root(&self) -> &Path { - self.root.as_path() + pub(crate) fn root(&self) -> Option<&Path> { + self.root.as_deref() } pub(crate) fn memory(&self) -> u64 { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -378,19 +378,10 @@ fn update_proc_info( get_status(p, parts[2]); refresh_user_group_ids(p, proc_path, refresh_kind); - if refresh_kind - .exe() - .needs_update(|| p.exe.as_os_str().is_empty()) - { - match proc_path.join("exe").read_link() { - Ok(exe_path) => p.exe = exe_path, - Err(_error) => { - sysinfo_debug!("Failed to retrieve exe for {}: {_error:?}", p.pid().0); - // Do not use cmd[0] because it is not the same thing. - // See https://github.com/GuillaumeGomez/sysinfo/issues/697. - p.exe = PathBuf::new(); - } - } + if refresh_kind.exe().needs_update(|| p.exe.is_none()) { + // Do not use cmd[0] because it is not the same thing. + // See https://github.com/GuillaumeGomez/sysinfo/issues/697. + p.exe = realpath(proc_path.join("exe")); } if refresh_kind.cmd().needs_update(|| p.cmd.is_empty()) { diff --git a/src/unix/linux/process.rs b/src/unix/linux/process.rs --- a/src/unix/linux/process.rs +++ b/src/unix/linux/process.rs @@ -399,16 +390,10 @@ fn update_proc_info( if refresh_kind.environ().needs_update(|| p.environ.is_empty()) { p.environ = copy_from_file(proc_path.join("environ")); } - if refresh_kind - .cwd() - .needs_update(|| p.cwd.as_os_str().is_empty()) - { + if refresh_kind.cwd().needs_update(|| p.cwd.is_none()) { p.cwd = realpath(proc_path.join("cwd")); } - if refresh_kind - .root() - .needs_update(|| p.root.as_os_str().is_empty()) - { + if refresh_kind.root().needs_update(|| p.root.is_none()) { p.root = realpath(proc_path.join("root")); } diff --git a/src/unix/linux/utils.rs b/src/unix/linux/utils.rs --- a/src/unix/linux/utils.rs +++ b/src/unix/linux/utils.rs @@ -20,12 +20,12 @@ pub(crate) fn get_all_data<P: AsRef<Path>>(file_path: P, size: usize) -> io::Res } #[allow(clippy::useless_conversion)] -pub(crate) fn realpath(path: &Path) -> std::path::PathBuf { +pub(crate) fn realpath(path: &Path) -> Option<std::path::PathBuf> { match std::fs::read_link(path) { - Ok(f) => f, + Ok(path) => Some(path), Err(_e) => { sysinfo_debug!("failed to get real path for {:?}: {:?}", path, _e); - PathBuf::new() + None } } } diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -29,8 +29,8 @@ impl ProcessInner { &[] } - pub(crate) fn exe(&self) -> &Path { - Path::new("") + pub(crate) fn exe(&self) -> Option<&Path> { + None } pub(crate) fn pid(&self) -> Pid { diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -41,12 +41,12 @@ impl ProcessInner { &[] } - pub(crate) fn cwd(&self) -> &Path { - Path::new("") + pub(crate) fn cwd(&self) -> Option<&Path> { + None } - pub(crate) fn root(&self) -> &Path { - Path::new("") + pub(crate) fn root(&self) -> Option<&Path> { + None } pub(crate) fn memory(&self) -> u64 { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -201,12 +201,12 @@ unsafe impl Sync for HandleWrapper {} pub(crate) struct ProcessInner { name: String, cmd: Vec<String>, - exe: PathBuf, + exe: Option<PathBuf>, pid: Pid, user_id: Option<Uid>, environ: Vec<String>, - cwd: PathBuf, - root: PathBuf, + cwd: Option<PathBuf>, + root: Option<PathBuf>, pub(crate) memory: u64, pub(crate) virtual_memory: u64, parent: Option<Pid>, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -338,7 +338,7 @@ unsafe fn get_process_name(pid: Pid) -> Option<String> { name } -unsafe fn get_exe(process_handler: &HandleWrapper) -> PathBuf { +unsafe fn get_exe(process_handler: &HandleWrapper) -> Option<PathBuf> { let mut exe_buf = [0u16; MAX_PATH as usize + 1]; GetModuleFileNameExW( **process_handler, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -346,7 +346,7 @@ unsafe fn get_exe(process_handler: &HandleWrapper) -> PathBuf { exe_buf.as_mut_slice(), ); - PathBuf::from(null_terminated_wchar_to_string(&exe_buf)) + Some(PathBuf::from(null_terminated_wchar_to_string(&exe_buf))) } impl ProcessInner { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -375,7 +375,7 @@ impl ProcessInner { let exe = if refresh_kind.exe().needs_update(|| true) { get_exe(&process_handler) } else { - PathBuf::new() + None }; let (start_time, run_time) = get_start_and_run_time(*process_handler, now); let parent = if info.InheritedFromUniqueProcessId != 0 { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -392,8 +392,8 @@ impl ProcessInner { cmd: Vec::new(), environ: Vec::new(), exe, - cwd: PathBuf::new(), - root: PathBuf::new(), + cwd: None, + root: None, status: ProcessStatus::Run, memory: 0, virtual_memory: 0, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -427,7 +427,7 @@ impl ProcessInner { let exe = if refresh_kind.exe().needs_update(|| true) { get_exe(&handle) } else { - PathBuf::new() + None }; let (start_time, run_time) = get_start_and_run_time(*handle, now); let mut p = Self { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -439,8 +439,8 @@ impl ProcessInner { cmd: Vec::new(), environ: Vec::new(), exe, - cwd: PathBuf::new(), - root: PathBuf::new(), + cwd: None, + root: None, status: ProcessStatus::Run, memory, virtual_memory, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -463,7 +463,7 @@ impl ProcessInner { let exe = if refresh_kind.exe().needs_update(|| true) { get_executable_path(pid) } else { - PathBuf::new() + None }; Self { handle: None, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -474,8 +474,8 @@ impl ProcessInner { cmd: Vec::new(), environ: Vec::new(), exe, - cwd: PathBuf::new(), - root: PathBuf::new(), + cwd: None, + root: None, status: ProcessStatus::Run, memory, virtual_memory, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -511,10 +511,7 @@ impl ProcessInner { get_process_user_id(self, refresh_kind); get_process_params(self, refresh_kind); } - if refresh_kind - .exe() - .needs_update(|| self.exe.as_os_str().is_empty()) - { + if refresh_kind.exe().needs_update(|| self.exe.is_none()) { unsafe { self.exe = match self.handle.as_ref() { Some(handle) => get_exe(handle), diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -553,8 +550,8 @@ impl ProcessInner { &self.cmd } - pub(crate) fn exe(&self) -> &Path { - self.exe.as_path() + pub(crate) fn exe(&self) -> Option<&Path> { + self.exe.as_deref() } pub(crate) fn pid(&self) -> Pid { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -565,12 +562,12 @@ impl ProcessInner { &self.environ } - pub(crate) fn cwd(&self) -> &Path { - self.cwd.as_path() + pub(crate) fn cwd(&self) -> Option<&Path> { + self.cwd.as_deref() } - pub(crate) fn root(&self) -> &Path { - self.root.as_path() + pub(crate) fn root(&self) -> Option<&Path> { + self.root.as_deref() } pub(crate) fn memory(&self) -> u64 { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -672,23 +669,20 @@ unsafe fn get_process_times(handle: HANDLE) -> u64 { } // On Windows, the root folder is always the current drive. So we get it from its `cwd`. -fn update_root(refresh_kind: ProcessRefreshKind, cwd: &Path, root: &mut PathBuf) { - if !refresh_kind - .root() - .needs_update(|| root.as_os_str().is_empty()) - { +fn update_root(refresh_kind: ProcessRefreshKind, cwd: &Path, root: &mut Option<PathBuf>) { + if !refresh_kind.root().needs_update(|| root.is_none()) { return; } - if cwd.as_os_str().is_empty() || !cwd.has_root() { - *root = PathBuf::new(); - return; - } - let mut ancestors = cwd.ancestors().peekable(); - while let Some(path) = ancestors.next() { - if ancestors.peek().is_none() { - *root = path.into(); - break; + if cwd.has_root() { + let mut ancestors = cwd.ancestors().peekable(); + while let Some(path) = ancestors.next() { + if ancestors.peek().is_none() { + *root = Some(path.into()); + return; + } } + } else { + *root = None; } } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -868,12 +862,8 @@ unsafe fn get_process_params(process: &mut ProcessInner, refresh_kind: ProcessRe || refresh_kind .environ() .needs_update(|| process.environ.is_empty()) - || refresh_kind - .cwd() - .needs_update(|| process.cwd.as_os_str().is_empty()) - || refresh_kind - .root() - .needs_update(|| process.root.as_os_str().is_empty())) + || refresh_kind.cwd().needs_update(|| process.cwd.is_none()) + || refresh_kind.root().needs_update(|| process.root.is_none())) { return; } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -1003,15 +993,11 @@ fn get_cwd_and_root<T: RtlUserProcessParameters>( params: &T, handle: HANDLE, refresh_kind: ProcessRefreshKind, - cwd: &mut PathBuf, - root: &mut PathBuf, + cwd: &mut Option<PathBuf>, + root: &mut Option<PathBuf>, ) { - let cwd_needs_update = refresh_kind - .cwd() - .needs_update(|| cwd.as_os_str().is_empty()); - let root_needs_update = refresh_kind - .root() - .needs_update(|| root.as_os_str().is_empty()); + let cwd_needs_update = refresh_kind.cwd().needs_update(|| cwd.is_none()); + let root_needs_update = refresh_kind.root().needs_update(|| root.is_none()); if !cwd_needs_update && !root_needs_update { return; } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -1021,12 +1007,12 @@ fn get_cwd_and_root<T: RtlUserProcessParameters>( // Should always be called after we refreshed `cwd`. update_root(refresh_kind, &tmp_cwd, root); if cwd_needs_update { - *cwd = tmp_cwd; + *cwd = Some(tmp_cwd); } }, Err(_e) => { sysinfo_debug!("get_cwd_and_root failed to get data: {:?}", _e); - *cwd = PathBuf::new(); + *cwd = None; } } } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -1116,7 +1102,7 @@ fn get_proc_env<T: RtlUserProcessParameters>( } } -pub(crate) fn get_executable_path(_pid: Pid) -> PathBuf { +pub(crate) fn get_executable_path(_pid: Pid) -> Option<PathBuf> { /*let where_req = format!("ProcessId={}", pid); if let Some(ret) = run_wmi(&["process", "where", &where_req, "get", "ExecutablePath"]) { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -1127,7 +1113,7 @@ pub(crate) fn get_executable_path(_pid: Pid) -> PathBuf { return line.to_owned(); } }*/ - PathBuf::new() + None } #[inline]
8737fa06afbf879062551d77ed60b0e10c250464
Make `Process::root` return an `Option` It can be a non-available information and as such, should return an `Option` rather than an empty `Path`. (For example it's empty on mac)
0.29
1,162
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-11-29T15:55:10Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -2,28 +2,6 @@ use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind}; -#[test] -fn test_process() { - let mut s = System::new(); - assert_eq!(s.processes().len(), 0); - s.refresh_processes(); - if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { - return; - } - assert!(!s.processes().is_empty()); - assert!(s - .processes() - .values() - .all(|p| p.exe().as_os_str().is_empty())); - - let mut s = System::new(); - s.refresh_processes_specifics(ProcessRefreshKind::new().with_exe(UpdateKind::Always)); - assert!(s - .processes() - .values() - .any(|p| !p.exe().as_os_str().is_empty())); -} - #[test] fn test_cwd() { if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -188,17 +166,13 @@ fn test_process_refresh() { .process(sysinfo::get_current_pid().expect("failed to get current pid")) .is_some()); + assert!(s.processes().iter().all(|(_, p)| p.environ().is_empty() + && p.cwd().as_os_str().is_empty() + && p.cmd().is_empty())); assert!(s .processes() .iter() - .all(|(_, p)| p.exe().as_os_str().is_empty() - && p.environ().is_empty() - && p.cwd().as_os_str().is_empty() - && p.cmd().is_empty())); - assert!(s - .processes() - .iter() - .any(|(_, p)| !p.name().is_empty() && p.memory() != 0)); + .any(|(_, p)| !p.exe().as_os_str().is_empty() && !p.name().is_empty() && p.memory() != 0)); } #[test]
[ "1141" ]
GuillaumeGomez__sysinfo-1161
GuillaumeGomez/sysinfo
diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -221,13 +221,14 @@ impl System { /// It does the same as: /// /// ```no_run - /// # use sysinfo::{ProcessRefreshKind, System}; + /// # use sysinfo::{ProcessRefreshKind, System, UpdateKind}; /// # let mut system = System::new(); /// system.refresh_processes_specifics( /// ProcessRefreshKind::new() /// .with_memory() /// .with_cpu() - /// .with_disk_usage(), + /// .with_disk_usage() + /// .with_exe(UpdateKind::OnlyIfNotSet), /// ); /// ``` /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -247,7 +248,8 @@ impl System { ProcessRefreshKind::new() .with_memory() .with_cpu() - .with_disk_usage(), + .with_disk_usage() + .with_exe(UpdateKind::OnlyIfNotSet), ); } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -273,7 +275,7 @@ impl System { /// It is the same as calling: /// /// ```no_run - /// # use sysinfo::{Pid, ProcessRefreshKind, System}; + /// # use sysinfo::{Pid, ProcessRefreshKind, System, UpdateKind}; /// # let mut system = System::new(); /// # let pid = Pid::from(0); /// system.refresh_process_specifics( diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -281,7 +283,8 @@ impl System { /// ProcessRefreshKind::new() /// .with_memory() /// .with_cpu() - /// .with_disk_usage(), + /// .with_disk_usage() + /// .with_exe(UpdateKind::OnlyIfNotSet), /// ); /// ``` /// diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -302,7 +305,8 @@ impl System { ProcessRefreshKind::new() .with_memory() .with_cpu() - .with_disk_usage(), + .with_disk_usage() + .with_exe(UpdateKind::OnlyIfNotSet), ) }
9fb48e65376a6b479e8f134d38c6b38068436804
Should `exe` be included in default process retrieval (and removed from `ProcessRefreshKind`)? It seems to be a basic information that everyone might want all the time.
0.29
1,161
Another solution would be to just remove `refresh_process[es]`.
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-10-14T21:57:41Z
diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -699,19 +687,3 @@ fn parse_command_line<T: Deref<Target = str> + Borrow<str>>(cmd: &[T]) -> Vec<St } command } - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_get_path() { - let mut path = PathBuf::new(); - let mut check = true; - - do_get_env_path("PATH=tadam", &mut path, &mut check); - - assert!(!check); - assert_eq!(path, PathBuf::from("tadam")); - } -}
[ "1094" ]
GuillaumeGomez__sysinfo-1097
GuillaumeGomez/sysinfo
diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -1,6 +1,5 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use std::ffi::CStr; use std::mem::{self, MaybeUninit}; use std::ops::Deref; use std::path::{Path, PathBuf}; diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -13,6 +12,7 @@ use crate::{DiskUsage, Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, Sig use crate::sys::process::ThreadStatus; use crate::sys::system::Wrap; +use crate::unix::utils::cstr_to_rust_with_size; pub(crate) struct ProcessInner { pub(crate) name: String, diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -48,7 +48,13 @@ pub(crate) struct ProcessInner { } impl ProcessInner { - pub(crate) fn new_empty(pid: Pid, exe: PathBuf, name: String, cwd: PathBuf) -> Self { + pub(crate) fn new_empty( + pid: Pid, + exe: PathBuf, + name: String, + cwd: PathBuf, + root: PathBuf, + ) -> Self { Self { name, pid, diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -57,7 +63,7 @@ impl ProcessInner { environ: Vec::new(), exe, cwd, - root: PathBuf::new(), + root, memory: 0, virtual_memory: 0, cpu_usage: 0., diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -79,7 +85,14 @@ impl ProcessInner { } } - pub(crate) fn new(pid: Pid, parent: Option<Pid>, start_time: u64, run_time: u64) -> Self { + pub(crate) fn new( + pid: Pid, + parent: Option<Pid>, + start_time: u64, + run_time: u64, + cwd: PathBuf, + root: PathBuf, + ) -> Self { Self { name: String::new(), pid, diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -87,8 +100,8 @@ impl ProcessInner { cmd: Vec::new(), environ: Vec::new(), exe: PathBuf::new(), - cwd: PathBuf::new(), - root: PathBuf::new(), + cwd, + root, memory: 0, virtual_memory: 0, cpu_usage: 0., diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -319,17 +332,6 @@ fn check_if_pid_is_alive(pid: Pid, check_if_alive: bool) -> bool { } } -#[inline] -fn do_not_get_env_path(_: &str, _: &mut PathBuf, _: &mut bool) {} - -#[inline] -fn do_get_env_path(env: &str, root: &mut PathBuf, check: &mut bool) { - if *check && env.starts_with("PATH=") { - *check = false; - *root = Path::new(&env[5..]).to_path_buf(); - } -} - unsafe fn get_bsd_info(pid: Pid) -> Option<libc::proc_bsdinfo> { let mut info = mem::zeroed::<libc::proc_bsdinfo>(); diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -347,6 +349,18 @@ unsafe fn get_bsd_info(pid: Pid) -> Option<libc::proc_bsdinfo> { } } +unsafe fn convert_node_path_info(node: &libc::vnode_info_path) -> PathBuf { + if node.vip_vi.vi_stat.vst_dev == 0 { + return PathBuf::new(); + } + cstr_to_rust_with_size( + node.vip_path.as_ptr() as _, + Some(node.vip_path.len() * node.vip_path[0].len()), + ) + .map(PathBuf::from) + .unwrap_or_default() +} + unsafe fn create_new_process( pid: Pid, mut size: size_t, diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -362,15 +376,13 @@ unsafe fn create_new_process( &mut vnodepathinfo as *mut _ as *mut _, mem::size_of::<libc::proc_vnodepathinfo>() as _, ); - let cwd = if result > 0 { - let buffer = vnodepathinfo.pvi_cdir.vip_path; - let buffer = CStr::from_ptr(buffer.as_ptr() as _); - buffer - .to_str() - .map(PathBuf::from) - .unwrap_or_else(|_| PathBuf::new()) + let (cwd, root) = if result > 0 { + ( + convert_node_path_info(&vnodepathinfo.pvi_cdir), + convert_node_path_info(&vnodepathinfo.pvi_rdir), + ) } else { - PathBuf::new() + (PathBuf::new(), PathBuf::new()) }; let info = match info { diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -392,7 +404,7 @@ unsafe fn create_new_process( .unwrap_or("") .to_owned(); return Ok(Some(Process { - inner: ProcessInner::new_empty(pid, exe, name, cwd), + inner: ProcessInner::new_empty(pid, exe, name, cwd, root), })); } _ => {} diff --git a/src/unix/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/unix/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -488,57 +500,33 @@ unsafe fn create_new_process( } #[inline] - unsafe fn get_environ<F: Fn(&str, &mut PathBuf, &mut bool)>( - ptr: *mut u8, - mut cp: *mut u8, - size: size_t, - mut root: PathBuf, - callback: F, - ) -> (Vec<String>, PathBuf) { + unsafe fn get_environ(ptr: *mut u8, mut cp: *mut u8, size: size_t) -> Vec<String> { let mut environ = Vec::with_capacity(10); let mut start = cp; - let mut check = true; while cp < ptr.add(size) { if *cp == 0 { if cp == start { break; } let e = get_unchecked_str(cp, start); - callback(&e, &mut root, &mut check); environ.push(e); start = cp.offset(1); } cp = cp.offset(1); } - (environ, root) + environ } - let (environ, root) = if exe.is_absolute() { - if let Some(parent_path) = exe.parent() { - get_environ( - ptr, - cp, - size, - parent_path.to_path_buf(), - do_not_get_env_path, - ) - } else { - get_environ(ptr, cp, size, PathBuf::new(), do_get_env_path) - } - } else { - get_environ(ptr, cp, size, PathBuf::new(), do_get_env_path) - }; - let mut p = ProcessInner::new(pid, parent, start_time, run_time); + let environ = get_environ(ptr, cp, size); + let mut p = ProcessInner::new(pid, parent, start_time, run_time, cwd, root); p.exe = exe; p.name = name; - p.cwd = cwd; p.cmd = parse_command_line(&cmd); p.environ = environ; - p.root = root; p } else { - ProcessInner::new(pid, parent, start_time, run_time) + ProcessInner::new(pid, parent, start_time, run_time, cwd, root) }; let task_info = get_task_info(pid); diff --git a/src/unix/utils.rs b/src/unix/utils.rs --- a/src/unix/utils.rs +++ b/src/unix/utils.rs @@ -10,9 +10,9 @@ pub(crate) fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> O if c.is_null() { return None; } - let mut s = match size { - Some(len) => Vec::with_capacity(len), - None => Vec::new(), + let (mut s, max) = match size { + Some(len) => (Vec::with_capacity(len), len as isize), + None => (Vec::new(), isize::MAX), }; let mut i = 0; unsafe { diff --git a/src/unix/utils.rs b/src/unix/utils.rs --- a/src/unix/utils.rs +++ b/src/unix/utils.rs @@ -23,6 +23,9 @@ pub(crate) fn cstr_to_rust_with_size(c: *const c_char, size: Option<usize>) -> O } s.push(value); i += 1; + if i >= max { + break; + } } String::from_utf8(s).ok() }
12bb072a2dca91e271b3da45008bb162d258b02b
macos process.root() is returning the PATH env var **Describe the bug** On MacOS in nushell, I'm writing a small process information command to inspect nushell memory on demand. The code is working great on Windows but on MacOS, process.root() is returning the system PATH instead of the root folder where the executable is. I'm not really understanding why it's happening. Any ideas? Here's a snippet of how I'm getting the information. I know there's a lot of nushell code here but hopefully it's self explanatory. ```rust let span = Span::unknown(); // get the nushell process id let pid = Pid::from(std::process::id() as usize); // only refresh the process and memory information let rk = RefreshKind::new() .with_processes( ProcessRefreshKind::new() .without_cpu() .without_disk_usage() .without_user(), ) .with_memory(); // only get information requested let system = System::new_with_specifics(rk); // get the process information for the nushell pid let pinfo = system.process(pid); if let Some(p) = pinfo { Ok(Value::record( record! { "pid" => Value::int(p.pid().as_u32() as i64, span), "ppid" => Value::int(p.parent().unwrap_or(0.into()).as_u32() as i64, span), "process" => { Value::record( record! { "memory" => Value::filesize(p.memory() as i64, span), "virtual_memory" => Value::filesize(p.virtual_memory() as i64, span), "status" => Value::string(p.status().to_string(), span), // This root is returning the contents of the env var PATH on MacOS // On Windows, it returns the root path for the pid's executable "root" => Value::string(p.root().to_string_lossy().to_string(), span), "cwd" => Value::string(p.cwd().to_string_lossy().to_string(), span), "exe_path" => Value::string(p.exe().to_string_lossy().to_string(), span), "command" => Value::string(p.cmd().join(" "), span), "name" => Value::string(p.name().to_string(), span), ```
0.29
1,097
What is: > the system PATH ? Shod me the path you expect and the one you get, might be better to understand for me. Sorry for not being clearer. The system PATH is probably mischaracterized but it's supposed to mean the environment variable named PATH on unix type systems. In this image you can see the path I get for `root()` in the middle under `status` and to the right of the green text `root`. ![image](https://github.com/GuillaumeGomez/sysinfo/assets/343840/fb98deef-f724-42f9-b73c-06027700cb43) The path I expect in this image is `target/debug` Ok, so it's reading the `PATH` environment variable. Interesting.
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-09-29T14:40:58Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -659,3 +659,23 @@ fn test_process_creds() { true })); } + +// Regression test for <https://github.com/GuillaumeGomez/sysinfo/issues/1084> +#[test] +fn test_process_memory_refresh() { + if !sysinfo::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + + // Ensure the process memory is available on the first refresh. + let mut s = sysinfo::System::new(); + + // Refresh our own process + let pid = Pid::from_u32(std::process::id()); + s.refresh_process_specifics(pid, sysinfo::ProcessRefreshKind::new()); + + let proc = s.process(pid).unwrap(); + // Check that the memory values re not empty. + assert!(proc.memory() > 0); + assert!(proc.virtual_memory() > 0); +}
[ "1084" ]
GuillaumeGomez__sysinfo-1085
GuillaumeGomez/sysinfo
diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -489,6 +489,7 @@ impl ProcessInner { if refresh_kind.disk_usage() { update_disk_usage(self); } + update_memory(self); self.run_time = now.saturating_sub(self.start_time()); self.updated = true; } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -3,7 +3,7 @@ use crate::{CpuRefreshKind, LoadAvg, Pid, ProcessRefreshKind}; use crate::sys::cpu::*; -use crate::sys::process::{get_start_time, update_memory}; +use crate::sys::process::get_start_time; use crate::sys::tools::*; use crate::sys::utils::{get_now, get_reg_string_value, get_reg_value_u32}; use crate::{Process, ProcessInner}; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -473,7 +473,6 @@ fn refresh_existing_process( } else { return Some(false); } - update_memory(proc_); proc_.update(refresh_kind, nb_cpus, now); proc_.updated = false; Some(true)
a728002ac8bc33f0d868776ad4044b2931d3a7b2
process memory/virtual_memory on windows is only set on second refresh Tested on sysinfo master (f6c1a25aa22ff323087b5e35c5014d1d81f7fe7d). Here is a code showing the issue: ```rust use sysinfo::{Pid, PidExt, ProcessExt, ProcessRefreshKind, System, SystemExt}; fn main() { let mut args = std::env::args(); let pid: u32 = args.nth(1).unwrap().parse().unwrap(); let mut s = System::new(); let pid = Pid::from_u32(pid); s.refresh_process_specifics(pid, ProcessRefreshKind::new()); let proc = s.process(pid).unwrap(); println!( "memory: {}, virtual memory: {}", proc.memory(), proc.virtual_memory() ); } ``` On Linux, this displays proper values when giving a valid PID. On Windows, this displays `memory: 0, virtual memory: 0`. If a second call to `s.refresh_process_specifics` is done, then it displays proper values.
0.29
1,085
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-09-14T20:59:50Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -22,52 +22,24 @@ cfg_if::cfg_if! { #[cfg(test)] pub(crate) const MIN_USERS: usize = 0; - } else if #[cfg(any(target_os = "macos", target_os = "ios"))] { - mod apple; - use apple as sys; - pub(crate) mod users; - mod network_helper_nix; - use network_helper_nix as network_helper; + } else if #[cfg(any( + target_os = "macos", target_os = "ios", + target_os = "linux", target_os = "android", + target_os = "freebsd"))] + { + mod unix; + use unix::sys as sys; + use unix::{network_helper, users}; mod network; - pub(crate) use libc::__error as libc_errno; - #[cfg(test)] pub(crate) const MIN_USERS: usize = 1; } else if #[cfg(windows)] { mod windows; use windows as sys; - mod network_helper_win; - use network_helper_win as network_helper; - mod network; - - #[cfg(test)] - pub(crate) const MIN_USERS: usize = 1; - } else if #[cfg(any(target_os = "linux", target_os = "android"))] { - mod linux; - use linux as sys; - pub(crate) mod users; - mod network_helper_nix; - use network_helper_nix as network_helper; + use windows::network_helper; mod network; - #[cfg(target_os = "linux")] - pub(crate) use libc::__errno_location as libc_errno; - #[cfg(target_os = "android")] - pub(crate) use libc::__errno as libc_errno; - - #[cfg(test)] - pub(crate) const MIN_USERS: usize = 1; - } else if #[cfg(target_os = "freebsd")] { - mod freebsd; - use freebsd as sys; - pub(crate) mod users; - mod network_helper_nix; - use network_helper_nix as network_helper; - mod network; - - pub(crate) use libc::__error as libc_errno; - #[cfg(test)] pub(crate) const MIN_USERS: usize = 1; } else {
[ "1038" ]
GuillaumeGomez__sysinfo-1062
GuillaumeGomez/sysinfo
diff --git a/src/macros.rs b/src/macros.rs --- a/src/macros.rs +++ b/src/macros.rs @@ -60,7 +60,7 @@ macro_rules! declare_signals { #[cfg(all(unix, not(feature = "unknown-ci")))] macro_rules! retry_eintr { (set_to_0 => $($t:tt)+) => {{ - let errno = crate::libc_errno(); + let errno = crate::unix::libc_errno(); if !errno.is_null() { *errno = 0; } diff --git a/src/apple/app_store/component.rs b/src/unix/apple/app_store/component.rs --- a/src/apple/app_store/component.rs +++ b/src/unix/apple/app_store/component.rs @@ -2,7 +2,7 @@ use crate::ComponentExt; -#[doc = include_str!("../../../md_doc/component.md")] +#[doc = include_str!("../../../../md_doc/component.md")] pub struct Component {} impl ComponentExt for Component { diff --git a/src/apple/app_store/process.rs b/src/unix/apple/app_store/process.rs --- a/src/apple/app_store/process.rs +++ b/src/unix/apple/app_store/process.rs @@ -4,7 +4,7 @@ use std::path::Path; use crate::{DiskUsage, Gid, Pid, ProcessExt, ProcessStatus, Signal, Uid}; -#[doc = include_str!("../../../md_doc/process.md")] +#[doc = include_str!("../../../../md_doc/process.md")] pub struct Process; impl ProcessExt for Process { diff --git a/src/apple/cpu.rs b/src/unix/apple/cpu.rs --- a/src/apple/cpu.rs +++ b/src/unix/apple/cpu.rs @@ -103,7 +103,7 @@ impl Drop for CpuData { } } -#[doc = include_str!("../../md_doc/cpu.md")] +#[doc = include_str!("../../../md_doc/cpu.md")] pub struct Cpu { name: String, cpu_usage: f32, diff --git a/src/apple/disk.rs b/src/unix/apple/disk.rs --- a/src/apple/disk.rs +++ b/src/unix/apple/disk.rs @@ -19,7 +19,7 @@ use std::os::unix::ffi::OsStrExt; use std::path::{Path, PathBuf}; use std::ptr; -#[doc = include_str!("../../md_doc/disk.md")] +#[doc = include_str!("../../../md_doc/disk.md")] pub struct Disk { pub(crate) type_: DiskKind, pub(crate) name: OsString, diff --git a/src/apple/macos/component/arm.rs b/src/unix/apple/macos/component/arm.rs --- a/src/apple/macos/component/arm.rs +++ b/src/unix/apple/macos/component/arm.rs @@ -8,7 +8,7 @@ use core_foundation_sys::string::{ kCFStringEncodingUTF8, CFStringCreateWithBytes, CFStringGetCStringPtr, }; -use crate::apple::inner::ffi::{ +use crate::sys::inner::ffi::{ kHIDPage_AppleVendor, kHIDUsage_AppleVendor_TemperatureSensor, kIOHIDEventTypeTemperature, matching, IOHIDEventFieldBase, IOHIDEventGetFloatValue, IOHIDEventSystemClientCopyServices, IOHIDEventSystemClientCreate, IOHIDEventSystemClientSetMatching, IOHIDServiceClientCopyEvent, diff --git a/src/apple/macos/component/arm.rs b/src/unix/apple/macos/component/arm.rs --- a/src/apple/macos/component/arm.rs +++ b/src/unix/apple/macos/component/arm.rs @@ -109,7 +109,7 @@ impl Components { unsafe impl Send for Components {} unsafe impl Sync for Components {} -#[doc = include_str!("../../../../md_doc/component.md")] +#[doc = include_str!("../../../../../md_doc/component.md")] pub struct Component { service: CFReleaser<__IOHIDServiceClient>, temperature: f32, diff --git a/src/apple/macos/component/x86.rs b/src/unix/apple/macos/component/x86.rs --- a/src/apple/macos/component/x86.rs +++ b/src/unix/apple/macos/component/x86.rs @@ -77,7 +77,7 @@ impl Components { } } -#[doc = include_str!("../../../../md_doc/component.md")] +#[doc = include_str!("../../../../../md_doc/component.md")] pub struct Component { temperature: f32, max: f32, diff --git a/src/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -14,7 +14,7 @@ use crate::{DiskUsage, Gid, Pid, ProcessExt, ProcessRefreshKind, ProcessStatus, use crate::sys::process::ThreadStatus; use crate::sys::system::Wrap; -#[doc = include_str!("../../../md_doc/process.md")] +#[doc = include_str!("../../../../md_doc/process.md")] pub struct Process { pub(crate) name: String, pub(crate) cmd: Vec<String>, diff --git a/src/apple/macos/process.rs b/src/unix/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/unix/apple/macos/process.rs @@ -316,7 +316,7 @@ fn check_if_pid_is_alive(pid: Pid, check_if_alive: bool) -> bool { return true; } // `kill` failed but it might not be because the process is dead. - let errno = crate::libc_errno(); + let errno = crate::unix::libc_errno(); // If errno is equal to ESCHR, it means the process is dead. !errno.is_null() && *errno != libc::ESRCH } diff --git a/src/apple/network.rs b/src/unix/apple/network.rs --- a/src/apple/network.rs +++ b/src/unix/apple/network.rs @@ -164,7 +164,7 @@ impl NetworksExt for Networks { } } -#[doc = include_str!("../../md_doc/network_data.md")] +#[doc = include_str!("../../../md_doc/network_data.md")] #[derive(PartialEq, Eq)] pub struct NetworkData { current_in: u64, diff --git a/src/apple/system.rs b/src/unix/apple/system.rs --- a/src/apple/system.rs +++ b/src/unix/apple/system.rs @@ -74,7 +74,7 @@ declare_signals! { _ => None, } -#[doc = include_str!("../../md_doc/system.md")] +#[doc = include_str!("../../../md_doc/system.md")] pub struct System { process_list: HashMap<Pid, Process>, mem_total: u64, diff --git a/src/apple/system.rs b/src/unix/apple/system.rs --- a/src/apple/system.rs +++ b/src/unix/apple/system.rs @@ -327,7 +327,7 @@ impl SystemExt for System { } fn refresh_users_list(&mut self) { - self.users = crate::apple::users::get_users_list(); + self.users = crate::sys::users::get_users_list(); } // COMMON PART diff --git a/src/freebsd/component.rs b/src/unix/freebsd/component.rs --- a/src/freebsd/component.rs +++ b/src/unix/freebsd/component.rs @@ -3,7 +3,7 @@ use super::utils::get_sys_value_by_name; use crate::ComponentExt; -#[doc = include_str!("../../md_doc/component.md")] +#[doc = include_str!("../../../md_doc/component.md")] pub struct Component { id: Vec<u8>, label: String, diff --git a/src/freebsd/cpu.rs b/src/unix/freebsd/cpu.rs --- a/src/freebsd/cpu.rs +++ b/src/unix/freebsd/cpu.rs @@ -132,7 +132,7 @@ impl CpusWrapper { } } -#[doc = include_str!("../../md_doc/cpu.md")] +#[doc = include_str!("../../../md_doc/cpu.md")] pub struct Cpu { pub(crate) cpu_usage: f32, name: String, diff --git a/src/freebsd/disk.rs b/src/unix/freebsd/disk.rs --- a/src/freebsd/disk.rs +++ b/src/unix/freebsd/disk.rs @@ -7,7 +7,7 @@ use std::path::{Path, PathBuf}; use super::utils::c_buf_to_str; -#[doc = include_str!("../../md_doc/disk.md")] +#[doc = include_str!("../../../md_doc/disk.md")] pub struct Disk { name: OsString, c_mount_point: Vec<libc::c_char>, diff --git a/src/freebsd/network.rs b/src/unix/freebsd/network.rs --- a/src/freebsd/network.rs +++ b/src/unix/freebsd/network.rs @@ -113,7 +113,7 @@ impl Networks { } } -#[doc = include_str!("../../md_doc/network_data.md")] +#[doc = include_str!("../../../md_doc/network_data.md")] pub struct NetworkData { /// Total number of bytes received over interface. ifi_ibytes: u64, diff --git a/src/freebsd/process.rs b/src/unix/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/unix/freebsd/process.rs @@ -40,7 +40,7 @@ impl fmt::Display for ProcessStatus { } } -#[doc = include_str!("../../md_doc/process.md")] +#[doc = include_str!("../../../md_doc/process.md")] pub struct Process { pub(crate) name: String, pub(crate) cmd: Vec<String>, diff --git a/src/freebsd/system.rs b/src/unix/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/unix/freebsd/system.rs @@ -57,7 +57,7 @@ declare_signals! { _ => None, } -#[doc = include_str!("../../md_doc/system.md")] +#[doc = include_str!("../../../md_doc/system.md")] pub struct System { process_list: HashMap<Pid, Process>, mem_total: u64, diff --git a/src/linux/component.rs b/src/unix/linux/component.rs --- a/src/linux/component.rs +++ b/src/unix/linux/component.rs @@ -11,7 +11,7 @@ use std::fs::{read_dir, File}; use std::io::Read; use std::path::{Path, PathBuf}; -#[doc = include_str!("../../md_doc/component.md")] +#[doc = include_str!("../../../md_doc/component.md")] #[derive(Default)] pub struct Component { /// Optional associated device of a `Component`. diff --git a/src/linux/cpu.rs b/src/unix/linux/cpu.rs --- a/src/linux/cpu.rs +++ b/src/unix/linux/cpu.rs @@ -305,7 +305,7 @@ impl CpuValues { } } -#[doc = include_str!("../../md_doc/cpu.md")] +#[doc = include_str!("../../../md_doc/cpu.md")] pub struct Cpu { old_values: CpuValues, new_values: CpuValues, diff --git a/src/linux/disk.rs b/src/unix/linux/disk.rs --- a/src/linux/disk.rs +++ b/src/unix/linux/disk.rs @@ -16,7 +16,7 @@ macro_rules! cast { }; } -#[doc = include_str!("../../md_doc/disk.md")] +#[doc = include_str!("../../../md_doc/disk.md")] #[derive(PartialEq, Eq)] pub struct Disk { type_: DiskKind, diff --git a/src/linux/network.rs b/src/unix/linux/network.rs --- a/src/linux/network.rs +++ b/src/unix/linux/network.rs @@ -126,7 +126,7 @@ impl NetworksExt for Networks { } } -#[doc = include_str!("../../md_doc/network_data.md")] +#[doc = include_str!("../../../md_doc/network_data.md")] pub struct NetworkData { /// Total number of bytes received over interface. rx_bytes: u64, diff --git a/src/linux/process.rs b/src/unix/linux/process.rs --- a/src/linux/process.rs +++ b/src/unix/linux/process.rs @@ -56,7 +56,7 @@ impl fmt::Display for ProcessStatus { } } -#[doc = include_str!("../../md_doc/process.md")] +#[doc = include_str!("../../../md_doc/process.md")] pub struct Process { pub(crate) name: String, pub(crate) cmd: Vec<String>, diff --git a/src/linux/system.rs b/src/unix/linux/system.rs --- a/src/linux/system.rs +++ b/src/unix/linux/system.rs @@ -147,7 +147,7 @@ declare_signals! { Signal::Sys => libc::SIGSYS, } -#[doc = include_str!("../../md_doc/system.md")] +#[doc = include_str!("../../../md_doc/system.md")] pub struct System { process_list: Process, mem_total: u64, diff --git /dev/null b/src/unix/mod.rs new file mode 100644 --- /dev/null +++ b/src/unix/mod.rs @@ -0,0 +1,28 @@ +// Take a look at the license at the top of the repository in the LICENSE file. + +cfg_if::cfg_if! { + if #[cfg(any(target_os = "macos", target_os = "ios"))] { + pub(crate) mod apple; + pub(crate) use apple as sys; + + pub(crate) use libc::__error as libc_errno; + } else if #[cfg(any(target_os = "linux", target_os = "android"))] { + pub(crate) mod linux; + pub(crate) use linux as sys; + + #[cfg(target_os = "linux")] + pub(crate) use libc::__errno_location as libc_errno; + #[cfg(target_os = "android")] + pub(crate) use libc::__errno as libc_errno; + } else if #[cfg(target_os = "freebsd")] { + pub(crate) mod freebsd; + pub(crate) use freebsd as sys; + + pub(crate) use libc::__error as libc_errno; + } else { + compile_error!("Invalid cfg!"); + } +} + +pub(crate) mod network_helper; +pub(crate) mod users; diff --git a/src/users.rs b/src/unix/users.rs --- a/src/users.rs +++ b/src/unix/users.rs @@ -9,7 +9,7 @@ use libc::{getgrgid_r, getgrouplist}; use std::fs::File; use std::io::Read; -#[doc = include_str!("../md_doc/user.md")] +#[doc = include_str!("../../md_doc/user.md")] pub struct User { pub(crate) uid: Uid, pub(crate) gid: Gid, diff --git a/src/windows/mod.rs b/src/windows/mod.rs --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -4,6 +4,7 @@ mod component; mod cpu; mod disk; mod network; +pub(crate) mod network_helper; mod process; mod sid; mod system;
ffd95c1a84cee358f3a73411f38599357d323619
Move unix-like targets into a unix sub-folder to have better folder hierarchy FreeBSD, linux and macOS should be moved into it alongside `src/users.rs` and `src/network_helper_nix.rs`.
0.29
1,062
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-07-21T16:30:34Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -275,7 +275,7 @@ mod test { .all(|(_, proc_)| proc_.cpu_usage() == 0.0)); // Wait a bit to update CPU usage values - std::thread::sleep(std::time::Duration::from_millis(100)); + std::thread::sleep(System::MINIMUM_CPU_UPDATE_INTERVAL); s.refresh_processes(); assert!(s .processes() diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -297,7 +297,7 @@ mod test { for _ in 0..10 { s.refresh_cpu(); // Wait a bit to update CPU usage values - std::thread::sleep(std::time::Duration::from_millis(100)); + std::thread::sleep(System::MINIMUM_CPU_UPDATE_INTERVAL); if s.cpus().iter().any(|c| c.cpu_usage() > 0.0) { // All good! return;
[ "881" ]
GuillaumeGomez__sysinfo-1017
GuillaumeGomez/sysinfo
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -97,9 +97,9 @@ loop { for cpu in sys.cpus() { print!("{}% ", cpu.cpu_usage()); } - // Sleeping for 500 ms to let time for the system to run for long + // Sleeping to let time for the system to run for long // enough to have useful information. - std::thread::sleep(std::time::Duration::from_millis(500)); + std::thread::sleep(System::MINIMUM_CPU_UPDATE_INTERVAL); } ``` diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -24,6 +24,9 @@ use ntapi::ntpebteb::PEB; use ntapi::ntwow64::{PEB32, PRTL_USER_PROCESS_PARAMETERS32, RTL_USER_PROCESS_PARAMETERS32}; use once_cell::sync::Lazy; +use ntapi::ntexapi::{ + NtQuerySystemInformation, SystemProcessIdInformation, SYSTEM_PROCESS_ID_INFORMATION, +}; use ntapi::ntpsapi::{ NtQueryInformationProcess, ProcessBasicInformation, ProcessCommandLineInformation, ProcessWow64Information, PROCESSINFOCLASS, PROCESS_BASIC_INFORMATION, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -33,22 +36,22 @@ use winapi::shared::basetsd::SIZE_T; use winapi::shared::minwindef::{DWORD, FALSE, FILETIME, LPVOID, MAX_PATH, TRUE, ULONG}; use winapi::shared::ntdef::{NT_SUCCESS, UNICODE_STRING}; use winapi::shared::ntstatus::{ - STATUS_BUFFER_OVERFLOW, STATUS_BUFFER_TOO_SMALL, STATUS_INFO_LENGTH_MISMATCH, + STATUS_BUFFER_OVERFLOW, STATUS_BUFFER_TOO_SMALL, STATUS_INFO_LENGTH_MISMATCH, STATUS_SUCCESS, }; use winapi::shared::winerror::ERROR_INSUFFICIENT_BUFFER; use winapi::um::errhandlingapi::GetLastError; use winapi::um::handleapi::CloseHandle; use winapi::um::heapapi::{GetProcessHeap, HeapAlloc, HeapFree}; use winapi::um::memoryapi::{ReadProcessMemory, VirtualQueryEx}; +use winapi::um::minwinbase::LMEM_FIXED; use winapi::um::processthreadsapi::{ GetProcessTimes, GetSystemTimes, OpenProcess, OpenProcessToken, ProcessIdToSessionId, }; use winapi::um::psapi::{ - EnumProcessModulesEx, GetModuleBaseNameW, GetModuleFileNameExW, GetProcessMemoryInfo, - LIST_MODULES_ALL, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX, + GetModuleFileNameExW, GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX, }; use winapi::um::securitybaseapi::GetTokenInformation; -use winapi::um::winbase::{GetProcessIoCounters, CREATE_NO_WINDOW}; +use winapi::um::winbase::{GetProcessIoCounters, LocalAlloc, LocalFree, CREATE_NO_WINDOW}; use winapi::um::winnt::{ TokenUser, HANDLE, HEAP_ZERO_MEMORY, IO_COUNTERS, MEMORY_BASIC_INFORMATION, PROCESS_QUERY_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_VM_READ, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -236,27 +239,105 @@ static WINDOWS_8_1_OR_NEWER: Lazy<bool> = Lazy::new(|| unsafe { || version_info.dwMajorVersion == 6 && version_info.dwMinorVersion >= 3 }); -unsafe fn get_process_name(process_handler: &HandleWrapper, h_mod: *mut c_void) -> String { - let mut process_name = [0u16; MAX_PATH + 1]; - - GetModuleBaseNameW( - **process_handler, - h_mod as _, - process_name.as_mut_ptr(), - MAX_PATH as DWORD + 1, +#[cfg(feature = "debug")] +unsafe fn display_ntstatus_error(ntstatus: winapi::shared::ntdef::NTSTATUS) { + let mut buffer: LPVOID = null_mut(); + let x = &[ + 'N' as u16, 'T' as u16, 'D' as u16, 'L' as u16, 'L' as u16, '.' as u16, 'D' as u16, + 'L' as u16, 'L' as u16, 0, + ]; + let handler = winapi::um::libloaderapi::LoadLibraryW(x.as_ptr()); + + winapi::um::winbase::FormatMessageW( + winapi::um::winbase::FORMAT_MESSAGE_ALLOCATE_BUFFER + | winapi::um::winbase::FORMAT_MESSAGE_FROM_SYSTEM + | winapi::um::winbase::FORMAT_MESSAGE_FROM_HMODULE, + handler as _, + ntstatus as _, + winapi::shared::ntdef::MAKELANGID( + winapi::shared::ntdef::LANG_NEUTRAL, + winapi::shared::ntdef::SUBLANG_DEFAULT, + ) as _, + &mut buffer as *mut _ as *mut _, + 0, + null_mut(), ); - null_terminated_wchar_to_string(&process_name) + let msg = buffer as *const u16; + for x in 0.. { + if *msg.offset(x) == 0 { + let slice = std::slice::from_raw_parts(msg as *const u16, x as usize); + let s = null_terminated_wchar_to_string(slice); + sysinfo_debug!( + "Couldn't get process infos: NtQuerySystemInformation returned {}: {}", + ntstatus, + s, + ); + break; + } + } + LocalFree(buffer); + winapi::um::libloaderapi::FreeLibrary(handler); } -unsafe fn get_h_mod(process_handler: &HandleWrapper, h_mod: &mut *mut c_void) -> bool { - let mut cb_needed = 0; - EnumProcessModulesEx( - **process_handler, - h_mod as *mut *mut c_void as _, - size_of::<DWORD>() as DWORD, - &mut cb_needed, - LIST_MODULES_ALL, - ) != 0 +unsafe fn get_process_name(pid: Pid) -> Option<String> { + let mut info = SYSTEM_PROCESS_ID_INFORMATION { + ProcessId: pid.0 as _, + ImageName: UNICODE_STRING { + Length: 0, + // `MaximumLength` MUST BE a power of 2. + MaximumLength: 1 << 7, // 128 + Buffer: null_mut(), + }, + }; + + for i in 0.. { + info.ImageName.Buffer = LocalAlloc(LMEM_FIXED, info.ImageName.MaximumLength as _) as *mut _; + if info.ImageName.Buffer.is_null() { + sysinfo_debug!("Couldn't get process infos: LocalAlloc failed"); + return None; + } + let ntstatus = NtQuerySystemInformation( + SystemProcessIdInformation, + &mut info as *mut _ as *mut _, + size_of::<SYSTEM_PROCESS_ID_INFORMATION>() as _, + null_mut(), + ); + if ntstatus == STATUS_SUCCESS { + break; + } else if ntstatus == STATUS_INFO_LENGTH_MISMATCH { + if !info.ImageName.Buffer.is_null() { + LocalFree(info.ImageName.Buffer as *mut _); + } + if i > 2 { + // Too many iterations, we should have the correct length at this point normally, + // aborting name retrieval. + sysinfo_debug!( + "NtQuerySystemInformation returned `STATUS_INFO_LENGTH_MISMATCH` too many times" + ); + return None; + } + // New length has been set into `MaximumLength` so we just continue the loop. + } else { + if !info.ImageName.Buffer.is_null() { + LocalFree(info.ImageName.Buffer as *mut _); + } + + #[cfg(feature = "debug")] + { + display_ntstatus_error(ntstatus); + } + return None; + } + } + + if info.ImageName.Buffer.is_null() { + return None; + } + + let s = std::slice::from_raw_parts(info.ImageName.Buffer, info.ImageName.Length as _); + let name = String::from_utf16_lossy(s); + LocalFree(info.ImageName.Buffer as _); + Some(name) } unsafe fn get_exe(process_handler: &HandleWrapper) -> PathBuf { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -291,14 +372,8 @@ impl Process { return None; } let info = info.assume_init(); - let mut h_mod = null_mut(); - - let name = if get_h_mod(&process_handler, &mut h_mod) { - get_process_name(&process_handler, h_mod) - } else { - String::new() - }; + let name = get_process_name(pid).unwrap_or_default(); let exe = get_exe(&process_handler); let mut root = exe.clone(); root.pop(); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -26,7 +26,6 @@ use ntapi::ntexapi::{ }; use winapi::ctypes::wchar_t; use winapi::shared::minwindef::{FALSE, TRUE}; -use winapi::shared::ntdef::{PVOID, ULONG}; use winapi::shared::ntstatus::{STATUS_INFO_LENGTH_MISMATCH, STATUS_SUCCESS}; use winapi::um::minwinbase::STILL_ACTIVE; use winapi::um::processthreadsapi::GetExitCodeProcess; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -236,8 +235,8 @@ impl SystemExt for System { unsafe { let ntstatus = NtQuerySystemInformation( SystemProcessInformation, - process_information.as_mut_ptr() as PVOID, - buffer_size as ULONG, + process_information.as_mut_ptr() as *mut _, + buffer_size as _, &mut cb_needed, );
ab2d268ca4bad60be367a4893161b520955aae4a
Process data inconsistency between `refresh_processes_specifics` and `refresh_process_specifics` Thanks for all your work on sysinfo! I have found a way to get inconsistent data (or at least inconsistent process names) regarding a given process: * `system.refresh_processes_specifics()` (without any PID given) uses `NtQuerySystemInformation` and uses `SYSTEM_PROCESS_INFORMATION.ImageName` as their process names * `system.refresh_process_specifics(pid)` uses `OpenProcess`/`NtQueryInformationProcess`/`EnumProcessModulesEx`/`GetModuleBaseNameW` These two code paths may end up getting different results. See this minimal reproducer: ```rust use sysinfo::{Pid, PidExt, System, SystemExt, ProcessExt}; fn main() { let mut system = System::default(); system.refresh_processes_specifics(Default::default()); for (pid, process) in system.processes() { let proc_name = process.name(); if proc_name.contains("msiexec") { println!(" * {}\t{}\t{}\t{:?}", pid, proc_name, get_specific_proc_name(process.pid().as_u32()), process.cmd() ); } } } fn get_specific_proc_name(pid: u32) -> String { let s_pid = Pid::from_u32(pid); let mut system = System::default(); system.refresh_process_specifics(s_pid, Default::default()); let proc = system.process(s_pid).unwrap(); proc.name().to_string() } ``` This can display ``` * 1512 msiexec.exe msiexec.exe ["C:\\Windows\\System32\\msiexec.exe", "/i", "P:\\webex\\meetings.msi"] * 4576 msiexec.exe MsiExec.exe ["C:\\Windows\\syswow64\\MsiExec.exe", "-Embedding", "CF3EB87457D3F802DE535DC782B0A689", "C"] * 4876 msiexec.exe msiexec.exe ["C:\\Windows\\system32\\msiexec.exe", "/V"] ``` Mind the lower/uppercase inconsistency for process 4576 (which may be due to the erroneous command-line for a file that is actually named a lowercase `C:\\Windows\\syswow64\\msiexec.exe`) This is not a critical issue, because: * Windows is not supposed to be case-sensitive for process names (I suppose?) * sysinfo documentation discourages against re-creating several `System` instances. Re-using the same instance would probably detect it knows this PID already and avoid the whole `OpenProcess`/`NtQueryInformationProcess`/`EnumProcessModulesEx`/`GetModuleBaseNameW` * it does not look this happens often (I had a hard time re-producing it, as the easiest reproducer I made involves running a 32-bit MSI on a 64-bit machine. But still, having two different code paths to get the same data may look like something to avoid (if ever that would be possible). What's your opinion on this? I may try to fix it myself in case you'd like me to (although I'm not familiar (yet?) with sysinfo).
0.29
1,017
First, thanks for the issue and the very complete explanations. Both `refresh_process` and `refresh_processes` should gather coherent data. So if you're motivated to write a fix, it's very welcome! OK, I'll try to have a look at it. Which path do you think would make most sense? * using `NtQuerySystemInformation` to only get the list of PIDs, then using the OpenProcess/NtQueryInformationProcess/EnumProcessModulesEx/GetModuleBaseNameW route for each PID, * or doing it the other way round, and use an NT API to retrieve a `SYSTEM_PROCESS_INFORMATION` for a single PID? I haven't read at Microsoft's documentation yet, maybe the second solution is not possible at all. And maybe the first one would be too CPU-intensive? What do you think? I'd favour the solution which is the less CPU intensive as it is already quite big (a lot more than I'd liked it to be). Hm, it turns out the OpenProcess/NtQueryInformationProcess/EnumProcessModulesEx/GetModuleBaseNameW way is not as reliable, as it sometimes even fails at retrieving a process name. Here is the list of all the processes currently running on my machine where both process names mismatch: ``` PID NT API name Win32 API name cmdline * 4 System [] * 10204 csrss.exe [] * 220 Registry [] * 2384 Memory Compression [] * 2536 svchost.exe [] * 3388 MsMpEng.exe [] * 4900 dllhost.exe DllHost.exe ["C:\\Windows\\system32\\DllHost.exe", "/Processid:{973D20D7-562D-44B9-B70B-5A0F49CCDF3F}"] * 5020 SecurityHealthService.exe [] * 5148 NisSrv.exe [] * 568 smss.exe [] * 676 csrss.exe [] * 7376 svchost.exe [] * 748 wininit.exe [] * 756 csrss.exe [] * 7680 SgrmBroker.exe [] * 892 services.exe [] * 9572 explorer.exe Explorer.EXE ["C:\\Windows\\Explorer.EXE"] * 9584 vctip.exe VCTIP.EXE ["C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools\\VC\\Tools\\MSVC\\14.33.31629\\bin\\HostX64\\x64\\VCTIP.EXE"] ``` So, I'll probably use NT APIs as much as I can (well, in case I can find a suitable one that gives information for a single process) Something important to be noted: windows files are case insensitive. So it should be the same whether or not you have capital letters in it. At this point it's just display. That's right (that's one of the notes I wrote in my initial post as well). However, having variable process names could cause trouble when trying to match names (that is how I discovered this bug). I am now working around by comparing case-insentively, but having a consistent output from sysinfo would be better anyway. Absolutely! It's a shame that windows API provide non-coherent names... ## Summary of what we currently have * a way to **batch-list** processes (`refresh_processes_specifics`). It uses [`NtQuerySystemInformation`](https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation), which, in one call, returns a list of complete [`SYSTEM_PROCESS_INFORMATION`](https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/WindowsProgramming/struct.SYSTEM_PROCESS_INFORMATION.html) objects. That's nice, complete and exact. * a way to fetch a **single** process (`refresh_process_specifics`). It uses `OpenProcess`, then various APIs for various data that we want to collect: `GetModuleBaseNameW`, `GetProcessTimes`, `NtQueryInformationProcess` with various request types, etc. This returns: * **incorrect** data (case can be modified, that was the reason I opened this issue) * **incomplete** data (which I discovered later on, which may be worse than the original issue) : * even run as admin, some process names are not retrieved: processes such as `services.exe` or some (but not all) `svchost.exe` have an empty string as `proc.name()` * processes have 0 as `proc.memory` and `proc.virtual_memory`. So, we're using inconsistent APIs. ## What other APIs are there? I looked up at possible Microsoft APIs to list and get infos about processes For single process retrieval: * I could not find any other way that the one you are using, so I have no idea how to improve it. There are other options for batch retrieval, but the current `NtQuerySystemInformation` works well, so we have no reason to change: * [`CreateToolhelp32Snapshot`](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot) (which gives access to handles to processes) * [`WTSEnumerateProcessesExW`](https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/nf-wtsapi32-wtsenumerateprocessesexw) which gives access to PIDs through [`WTS_PROCESS_INFO_EXA`](https://learn.microsoft.com/en-us/windows/win32/api/wtsapi32/ns-wtsapi32-wts_process_info_exa) * the currently used `NtQuerySystemInformation`, which works well. * `EnumProcesses`, that [merely calls `NtQuerySystemInformation` and throws away everything but the PID](https://doxygen.reactos.org/de/d86/dll_2win32_2psapi_2psapi_8c.html#ac21851d57723fb163a7025b404a84408). ## What are possible solutions? Since we cannot improve data obtained for a single process, we'll have to do it the other way round (list all processes and filter out the only one that interests us). * Using `CreateToolhelp32Snapshot` gives handles, so this won't give any benefit over the current situation (that already uses handles for single processes) * Using `WTSEnumerateProcessesExW`. But the `WTS_PROCESS_INFO_EXA` it gives lack info about virtual memory or parent ID. So I'm not sure that's really interesting to use it. * `EnumProcesses` is basically a trimmed-down (but slower) version of `NtQuerySystemInformation` * use `NtQuerySystemInformation` this way: ``` fn refresh_process_specifics(pid) -> Process { let procs: Vec<SYSTEM_PROCESS_INFORMATION> = Vec::new(); NtQuerySystemInformation(SystemProcessInformation, &mut proc); procs.filter(|p| p.UniqueProcessId == pid) } ``` Advantages: * consistency between `refresh_processes_specifics` and `refresh_process_specifics` * more data is available (we always populate process names, memory, virtual_memory) Disadvantages: we ask Windows to collect data for all processes and only keep one :-/ Obviously, this is slower. Here is a bench to call `refresh_process_specifics(a_given_pid)` ``` test bench_current_implementation ... bench: 361,260 ns/iter (+/- 75,058) test bench_using_NtQuerySystemInformation ... bench: 1,336,271 ns/iter (+/- 742,860) ``` With all this said (sorry for this long message, I wrote it as I researched, but now you have all the info): how much are you willing to trade performance for correctness? I have a PR ready to be published on GitHub, just tell me whether or not it is interesting to you. I think performance impact is too important to make this solution viable unfortunately. What I suggest is to simply mention that the process name comparison on windows should be done case insensitively. That could be an easy addition. The issue is not limited to case unfortunately, as I wrote there is also the "missing data" problem (missing names on some processes, missing memory/virtual_memory on every process). I'll do an MR to document this There is also an issue of right access. Some system calls require more so I didn't use them. But if you can find a way to get the same information without having a huge performance regression or needing more rights, then I'm all for it. NtQuerySystemInformation can be used to retrieve a process name by PID with class SystemProcessIdInformation which is described here https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/query.htm Thanks for the information! Of course if you're interested into adding it... ;)
3cc9cc814d21b7977a0e7bb8260a7b64529e6a1b
2023-05-05T14:53:18Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -615,3 +615,47 @@ fn test_process_cpu_usage() { assert!(process.cpu_usage() <= max_usage); } } + +#[test] +fn test_process_creds() { + use sysinfo::{ProcessExt, System, SystemExt}; + + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + + let mut sys = System::new_all(); + sys.refresh_all(); + + // Just ensure there is at least one process on the system whose credentials can be retrieved. + assert!(sys.processes().values().any(|process| { + if process.user_id().is_none() { + return false; + } + + #[cfg(not(windows))] + { + if process.group_id().is_none() + || process.effective_user_id().is_none() + || process.effective_group_id().is_none() + { + return false; + } + } + + true + })); + + // On Windows, make sure no process has real group ID and no effective IDs. + #[cfg(windows)] + assert!(sys.processes().values().all(|process| { + if process.group_id().is_some() + || process.effective_user_id().is_some() + || process.effective_group_id().is_some() + { + return false; + } + + true + })); +}
[ "970" ]
GuillaumeGomez__sysinfo-977
GuillaumeGomez/sysinfo
diff --git a/src/apple/app_store/process.rs b/src/apple/app_store/process.rs --- a/src/apple/app_store/process.rs +++ b/src/apple/app_store/process.rs @@ -76,10 +76,18 @@ impl ProcessExt for Process { None } + fn effective_user_id(&self) -> Option<&Uid> { + None + } + fn group_id(&self) -> Option<Gid> { None } + fn effective_group_id(&self) -> Option<Gid> { + None + } + fn wait(&self) {} fn session_id(&self) -> Option<Pid> { diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -33,7 +33,9 @@ pub struct Process { pub(crate) updated: bool, cpu_usage: f32, user_id: Option<Uid>, + effective_user_id: Option<Uid>, group_id: Option<Gid>, + effective_group_id: Option<Gid>, pub(crate) process_status: ProcessStatus, /// Status of process (running, stopped, waiting, etc). `None` means `sysinfo` doesn't have /// enough rights to get this information. diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -66,7 +68,9 @@ impl Process { start_time: 0, run_time: 0, user_id: None, + effective_user_id: None, group_id: None, + effective_group_id: None, process_status: ProcessStatus::Unknown(0), status: None, old_read_bytes: 0, diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -95,7 +99,9 @@ impl Process { start_time, run_time, user_id: None, + effective_user_id: None, group_id: None, + effective_group_id: None, process_status: ProcessStatus::Unknown(0), status: None, old_read_bytes: 0, diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -181,10 +187,18 @@ impl ProcessExt for Process { self.user_id.as_ref() } + fn effective_user_id(&self) -> Option<&Uid> { + self.effective_user_id.as_ref() + } + fn group_id(&self) -> Option<Gid> { self.group_id } + fn effective_group_id(&self) -> Option<Gid> { + self.effective_group_id + } + fn wait(&self) { let mut status = 0; // attempt waiting diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -526,8 +540,10 @@ unsafe fn create_new_process( p.memory = task_info.pti_resident_size; p.virtual_memory = task_info.pti_virtual_size; - p.user_id = Some(Uid(info.pbi_uid)); - p.group_id = Some(Gid(info.pbi_gid)); + p.user_id = Some(Uid(info.pbi_ruid)); + p.effective_user_id = Some(Uid(info.pbi_uid)); + p.group_id = Some(Gid(info.pbi_rgid)); + p.effective_group_id = Some(Gid(info.pbi_gid)); p.process_status = ProcessStatus::from(info.pbi_status); if refresh_kind.disk_usage() { update_proc_disk_activity(&mut p); diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -58,7 +58,9 @@ pub struct Process { run_time: u64, pub(crate) status: ProcessStatus, user_id: Uid, + effective_user_id: Uid, group_id: Gid, + effective_group_id: Gid, read_bytes: u64, old_read_bytes: u64, written_bytes: u64, diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -140,10 +142,18 @@ impl ProcessExt for Process { Some(&self.user_id) } + fn effective_user_id(&self) -> Option<&Uid> { + Some(&self.effective_user_id) + } + fn group_id(&self) -> Option<Gid> { Some(self.group_id) } + fn effective_group_id(&self) -> Option<Gid> { + Some(self.effective_group_id) + } + fn wait(&self) { let mut status = 0; // attempt waiting diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -259,7 +269,9 @@ pub(crate) unsafe fn get_process_data( pid: Pid(kproc.ki_pid), parent, user_id: Uid(kproc.ki_ruid), + effective_user_id: Uid(kproc.ki_uid), group_id: Gid(kproc.ki_rgid), + effective_group_id: Gid(kproc.ki_svgid), start_time, run_time: now.saturating_sub(start_time), cpu_usage, diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -5,7 +5,6 @@ use std::collections::HashMap; use std::fmt; use std::fs::{self, File}; use std::io::Read; -use std::mem::MaybeUninit; use std::path::{Path, PathBuf}; use std::str::FromStr; diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -79,7 +78,9 @@ pub struct Process { pub(crate) updated: bool, cpu_usage: f32, user_id: Option<Uid>, + effective_user_id: Option<Uid>, group_id: Option<Gid>, + effective_group_id: Option<Gid>, pub(crate) status: ProcessStatus, /// Tasks run by this process. pub tasks: HashMap<Pid, Process>, diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -113,7 +114,9 @@ impl Process { start_time: 0, run_time: 0, user_id: None, + effective_user_id: None, group_id: None, + effective_group_id: None, status: ProcessStatus::Unknown(0), tasks: if pid.0 == 0 { HashMap::with_capacity(1000) diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -204,10 +207,18 @@ impl ProcessExt for Process { self.user_id.as_ref() } + fn effective_user_id(&self) -> Option<&Uid> { + self.effective_user_id.as_ref() + } + fn group_id(&self) -> Option<Gid> { self.group_id } + fn effective_group_id(&self) -> Option<Gid> { + self.effective_group_id + } + fn wait(&self) { let mut status = 0; // attempt waiting diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -337,9 +348,13 @@ fn get_status(p: &mut Process, part: &str) { } fn refresh_user_group_ids<P: PathPush>(p: &mut Process, path: &mut P) { - if let Some((user_id, group_id)) = get_uid_and_gid(path.join("status")) { + if let Some(((user_id, effective_user_id), (group_id, effective_group_id))) = + get_uid_and_gid(path.join("status")) + { p.user_id = Some(Uid(user_id)); + p.effective_user_id = Some(Uid(effective_user_id)); p.group_id = Some(Gid(group_id)); + p.effective_group_id = Some(Gid(effective_group_id)); } } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -643,43 +658,38 @@ fn copy_from_file(entry: &Path) -> Vec<String> { } } -fn get_uid_and_gid(file_path: &Path) -> Option<(uid_t, gid_t)> { - use std::os::unix::ffi::OsStrExt; - - unsafe { - let mut sstat: MaybeUninit<libc::stat> = MaybeUninit::uninit(); - - let mut file_path: Vec<u8> = file_path.as_os_str().as_bytes().to_vec(); - file_path.push(0); - if libc::stat(file_path.as_ptr() as *const _, sstat.as_mut_ptr()) == 0 { - let sstat = sstat.assume_init(); - - return Some((sstat.st_uid, sstat.st_gid)); - } - } - +// Fetch tuples of real and effective UID and GID. +fn get_uid_and_gid(file_path: &Path) -> Option<((uid_t, uid_t), (gid_t, gid_t))> { let status_data = get_all_data(file_path, 16_385).ok()?; // We're only interested in the lines starting with Uid: and Gid: - // here. From these lines, we're looking at the second entry to get - // the effective u/gid. + // here. From these lines, we're looking at the first and second entries to get + // the real u/gid. - let f = |h: &str, n: &str| -> Option<uid_t> { + let f = |h: &str, n: &str| -> (Option<uid_t>, Option<uid_t>) { if h.starts_with(n) { - h.split_whitespace().nth(2).unwrap_or("0").parse().ok() + let mut ids = h.split_whitespace(); + let real = ids.nth(1).unwrap_or("0").parse().ok(); + let effective = ids.next().unwrap_or("0").parse().ok(); + + (real, effective) } else { - None + (None, None) } }; let mut uid = None; + let mut effective_uid = None; let mut gid = None; + let mut effective_gid = None; for line in status_data.lines() { - if let Some(u) = f(line, "Uid:") { - debug_assert!(uid.is_none()); - uid = Some(u); - } else if let Some(g) = f(line, "Gid:") { - debug_assert!(gid.is_none()); - gid = Some(g); + if let (Some(real), Some(effective)) = f(line, "Uid:") { + debug_assert!(uid.is_none() && effective_uid.is_none()); + uid = Some(real); + effective_uid = Some(effective); + } else if let (Some(real), Some(effective)) = f(line, "Gid:") { + debug_assert!(gid.is_none() && effective_gid.is_none()); + gid = Some(real); + effective_gid = Some(effective); } else { continue; } diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -687,8 +697,10 @@ fn get_uid_and_gid(file_path: &Path) -> Option<(uid_t, gid_t)> { break; } } - match (uid, gid) { - (Some(u), Some(g)) => Some((u, g)), + match (uid, effective_uid, gid, effective_gid) { + (Some(uid), Some(effective_uid), Some(gid), Some(effective_gid)) => { + Some(((uid, effective_uid), (gid, effective_gid))) + } _ => None, } } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -403,6 +403,26 @@ pub trait ProcessExt: Debug { /// ``` fn user_id(&self) -> Option<&Uid>; + /// Returns the user ID of the effective owner of this process or `None` if this information + /// couldn't be retrieved. If you want to get the [`User`] from it, take a look at + /// [`SystemExt::get_user_by_id`]. + /// + /// If you run something with `sudo`, the real user ID of the launched process will be the ID of + /// the user you are logged in as but effective user ID will be `0` (i-e root). + /// + /// ⚠️ It always returns `None` on Windows. + /// + /// ```no_run + /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// + /// if let Some(process) = s.process(Pid::from(1337)) { + /// eprintln!("User id for process 1337: {:?}", process.effective_user_id()); + /// } + /// ``` + fn effective_user_id(&self) -> Option<&Uid>; + /// Returns the process group ID of the process. /// /// ⚠️ It always returns `None` on Windows. diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -418,6 +438,24 @@ pub trait ProcessExt: Debug { /// ``` fn group_id(&self) -> Option<Gid>; + /// Returns the effective group ID of the process. + /// + /// If you run something with `sudo`, the real group ID of the launched process will be the + /// primary group ID you are logged in as but effective group ID will be `0` (i-e root). + /// + /// ⚠️ It always returns `None` on Windows. + /// + /// ```no_run + /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// + /// if let Some(process) = s.process(Pid::from(1337)) { + /// eprintln!("User id for process 1337: {:?}", process.effective_group_id()); + /// } + /// ``` + fn effective_group_id(&self) -> Option<Gid>; + /// Wait for process termination. /// /// ```no_run diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -86,10 +86,18 @@ impl ProcessExt for Process { None } + fn effective_user_id(&self) -> Option<&Uid> { + None + } + fn group_id(&self) -> Option<Gid> { None } + fn effective_group_id(&self) -> Option<Gid> { + None + } + fn wait(&self) {} fn session_id(&self) -> Option<Pid> { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -525,10 +525,18 @@ impl ProcessExt for Process { self.user_id.as_ref() } + fn effective_user_id(&self) -> Option<&Uid> { + None + } + fn group_id(&self) -> Option<Gid> { None } + fn effective_group_id(&self) -> Option<Gid> { + None + } + fn wait(&self) { if let Some(handle) = self.get_handle() { while is_proc_running(handle) {
41367e7f05b6fcafee328db5ba5859a00b2e2156
Wrong userid for process sometimes returned on Linux **Describe the bug** sysinfo version 0.28.3, platform is Amazon Linux 2 (also reproed on Ubuntu) `sysinfo` always reports a userid of `root` on Linux for processes with the `dumpable` attribute set to a value other than `1`. This is because it attempts to get the UID by `stat`-ing `/proc/[pid]/status` [here](https://github.com/GuillaumeGomez/sysinfo/blob/master/src/linux/process.rs#L654) and picking the owner of that file. The problem with this is that `/proc/[pid]/status` isn't always owned by the process's owner. From the [docs](https://man7.org/linux/man-pages/man5/proc.5.html) for `proc`: > The files inside each `/proc/[pid]` directory are normally owned by the effective user and effective group ID of the process. However, as a security measure, the ownership is made root:root if the process's "dumpable" attribute is set to a value other than 1. See [here](https://man7.org/linux/man-pages/man2/prctl.2.html) for docs on a few scenarios in which this flag can get unset. Note that the `/proc/[pid]` directory itself is always owned by the process owner, so `stat`-ing that instead would be a good alternative. **To Reproduce** I put together a small repository with a repro https://github.com/nsunderland1/sysinfo_bug The meat of it is in `main.rs` https://github.com/nsunderland1/sysinfo_bug/blob/main/src/main.rs ```rust use std::ops::Deref; use sysinfo::{ProcessExt, ProcessRefreshKind, RefreshKind, System, SystemExt}; fn main() { // The user passes a UID from the command line let my_new_uid: u32 = std::env::args().nth(1).unwrap().parse().unwrap(); // It shouldn't match the current process's effective UID assert_ne!(nix::unistd::Uid::effective().as_raw(), my_new_uid); // Now use seteuid to change our effective UID to it nix::unistd::seteuid(nix::unistd::Uid::from_raw(my_new_uid)).unwrap(); // Sanity check that it worked assert_eq!(nix::unistd::Uid::effective().as_raw(), my_new_uid); // Now check the effective UID using sysinfo let system = System::new_with_specifics( RefreshKind::new().with_processes(ProcessRefreshKind::new().with_user()), ); let my_pid = sysinfo::get_current_pid().unwrap(); let my_uid_but_wrong = system.process(my_pid).unwrap().user_id().unwrap(); // This assertion will fail, as sysinfo will report a UID of 0 (root) assert_eq!(*my_uid_but_wrong.deref(), my_new_uid); } ```
0.28
977
Thanks for the detailed report. Interested into sending a fix maybe? So turns out on Linux, `sysinfo` gives you the effective UID and GID only, leaving behind real, saved and filesystem IDs. However, on FreeBSD it gives you real IDs instead. :( I actually don't know what the last ones are even so I'd ignore them (until and unless someone asks for them) but it would be good to: 1. return the same ID for all OS. I think this should be the real ID (looking at all relevant APIs and proc entries on Linux, this seems like the right thing to do) so we should fix the Linux impl. 2. add API to get the effective IDs (or real if we go with the opposite approach in 1). 3. document clearly which IDs existing getters give you. It should return real UIDs by default. So the current implementation on linux is wrong. The idea was to add methods to get `effective_uid`. And yes, making it explicit in the documentation would be really nice! > The idea was to add methods to get `effective_uid` Glad we agree. I guess you'd want it to return an `Option` so on Windows it returns None? FWIW, I think on Windows it should just return the same as `uid` since it's not that Windows doesn't have effective UID but rather that it does not differentiates between the two. Up to you though. Yes I'd prefer for the `effective_uid` method to return `None` on Windows to have one unified API. The documentation on the trait will mention it.
41367e7f05b6fcafee328db5ba5859a00b2e2156
2023-01-17T12:46:36Z
diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -164,7 +164,7 @@ mod tests { for pid in &pids { sys.refresh_process_specifics(*pid, ProcessRefreshKind::new().with_cpu()); } - // To ensure that linux doesn't give too high numbers. + // To ensure that Linux doesn't give too high numbers. assert!( sys.process(pids[2]).unwrap().cpu_usage() < sys.cpus().len() as f32 * 100., "using ALL CPU: failed at iteration {}",
[ "905" ]
GuillaumeGomez__sysinfo-924
GuillaumeGomez/sysinfo
diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# sysinfo ![img_github_ci] [![][img_crates]][crates] [![][img_doc]][doc] +# sysinfo [![][img_crates]][crates] [![][img_doc]][doc] `sysinfo` is a crate used to get a system's information. diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -206,7 +206,6 @@ If you appreciate my work and want to support me, you can do it with [github sponsors](https://github.com/sponsors/GuillaumeGomez) or with [patreon](https://www.patreon.com/GuillaumeGomez). -[img_github_ci]: https://github.com/GuillaumeGomez/sysinfo/actions/workflows/CI.yml/badge.svg [img_crates]: https://img.shields.io/crates/v/sysinfo.svg [img_doc]: https://img.shields.io/badge/rust-documentation-blue.svg diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -259,8 +259,8 @@ pub extern "C" fn sysinfo_networks_transmitted(system: CSystem) -> size_t { /// Equivalent of [`System::cpus_usage()`][crate::System#method.cpus_usage]. /// -/// * `length` will contain the number of cpu usage added into `procs`. -/// * `procs` will be allocated if it's null and will contain of cpu usage. +/// * `length` will contain the number of CPU usage added into `procs`. +/// * `procs` will be allocated if it's null and will contain of CPU usage. #[no_mangle] pub extern "C" fn sysinfo_cpus_usage( system: CSystem, diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -291,7 +291,7 @@ pub extern "C" fn sysinfo_cpus_usage( /// Equivalent of [`System::processes()`][crate::System#method.processes]. Returns an /// array ended by a null pointer. Must be freed. /// -/// # /!\ WARNING /!\ +/// # ⚠️ WARNING ⚠️ /// /// While having this method returned processes, you should *never* call any refresh method! #[no_mangle] diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -323,7 +323,7 @@ pub extern "C" fn sysinfo_processes( /// Equivalent of [`System::process()`][crate::System#method.process]. /// -/// # /!\ WARNING /!\ +/// # ⚠️ WARNING ⚠️ /// /// While having this method returned process, you should *never* call any /// refresh method! diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -344,7 +344,7 @@ pub extern "C" fn sysinfo_process_by_pid(system: CSystem, pid: pid_t) -> CProces /// Equivalent of iterating over [`Process::tasks()`][crate::Process#method.tasks]. /// -/// # /!\ WARNING /!\ +/// # ⚠️ WARNING ⚠️ /// /// While having this method processes, you should *never* call any refresh method! #[cfg(target_os = "linux")] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -88,10 +88,10 @@ mod system; mod traits; mod utils; -/// This function is only used on linux targets, on the other platforms it does nothing and returns +/// This function is only used on Linux targets, on the other platforms it does nothing and returns /// `false`. /// -/// On linux, to improve performance, we keep a `/proc` file open for each process we index with +/// On Linux, to improve performance, we keep a `/proc` file open for each process we index with /// a maximum number of files open equivalent to half of the system limit. /// /// The problem is that some users might need all the available file descriptors so we need to diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -31,7 +31,7 @@ pub struct Component { /// - Read in: `temp[1-*]_input`. /// - Unit: read as millidegree Celsius converted to Celsius. temperature: Option<f32>, - /// Maximum value computed by sysinfo + /// Maximum value computed by `sysinfo`. max: Option<f32>, /// Max threshold provided by the chip/kernel /// - Read in:`temp[1-*]_max` diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -60,7 +60,7 @@ pub struct Component { sensor_type: Option<TermalSensorType>, /// Component Label /// - /// For formating detail see `Component::label` function docstring. + /// For formatting detail see `Component::label` function docstring. /// /// ## Linux implementation details /// diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -89,7 +89,7 @@ pub struct Component { /// File to read current temperature shall be `temp[1-*]_input` /// It may be absent but we don't continue if absent. input_file: Option<PathBuf>, - /// `temp[1-*]_highest file` to read if disponnible highest value. + /// `temp[1-*]_highest file` to read if available highest value. highest_file: Option<PathBuf>, } diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -132,14 +132,14 @@ fn get_temperature_from_file(file: &Path) -> Option<f32> { convert_temp_celsius(temp) } -/// Takes a raw temperature in mili-celsius and convert it to celsius +/// Takes a raw temperature in mili-celsius and convert it to celsius. #[inline] fn convert_temp_celsius(temp: Option<i32>) -> Option<f32> { temp.map(|n| (n as f32) / 1000f32) } /// Information about thermal sensor. It may be unavailable as it's -/// kernel module and chip dependant. +/// kernel module and chip dependent. enum TermalSensorType { /// 1: CPU embedded diode CPUEmbeddedDiode, diff --git a/src/linux/component.rs b/src/linux/component.rs --- a/src/linux/component.rs +++ b/src/linux/component.rs @@ -228,7 +228,7 @@ impl Component { /// - Optional: max threshold value defined in `tempN_max` /// - Optional: critical threshold value defined in `tempN_crit` /// - /// Where `N` is a u32 associated to a sensor like `temp1_max`, `temp1_input`. + /// Where `N` is a `u32` associated to a sensor like `temp1_max`, `temp1_input`. /// /// ## Doc to Linux kernel API. /// diff --git a/src/linux/cpu.rs b/src/linux/cpu.rs --- a/src/linux/cpu.rs +++ b/src/linux/cpu.rs @@ -533,10 +533,10 @@ pub(crate) fn get_physical_core_count() -> Option<usize> { /// Obtain the implementer of this CPU core. /// -/// This has been obtained from util-linux’s lscpu implementation, see +/// This has been obtained from util-linux's lscpu implementation, see /// https://github.com/util-linux/util-linux/blob/7076703b529d255600631306419cca1b48ab850a/sys-utils/lscpu-arm.c#L240 /// -/// This list will have to be updated every time a new vendor appears, please keep it synchronised +/// This list will have to be updated every time a new vendor appears, please keep it synchronized /// with util-linux and update the link above with the commit you have used. fn get_arm_implementer(implementer: u32) -> Option<&'static str> { Some(match implementer { diff --git a/src/linux/cpu.rs b/src/linux/cpu.rs --- a/src/linux/cpu.rs +++ b/src/linux/cpu.rs @@ -564,10 +564,10 @@ fn get_arm_implementer(implementer: u32) -> Option<&'static str> { /// Obtain the part of this CPU core. /// -/// This has been obtained from util-linux’s lscpu implementation, see +/// This has been obtained from util-linux's lscpu implementation, see /// https://github.com/util-linux/util-linux/blob/7076703b529d255600631306419cca1b48ab850a/sys-utils/lscpu-arm.c#L34 /// -/// This list will have to be updated every time a new core appears, please keep it synchronised +/// This list will have to be updated every time a new core appears, please keep it synchronized /// with util-linux and update the link above with the commit you have used. fn get_arm_part(implementer: u32, part: u32) -> Option<&'static str> { Some(match (implementer, part) { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -29,7 +29,7 @@ pub(crate) static mut REMAINING_FILES: once_cell::sync::Lazy<Arc<Mutex<isize>>> rlim_max: 0, }; if libc::getrlimit(libc::RLIMIT_NOFILE, &mut limits) != 0 { - // Most linux system now defaults to 1024. + // Most Linux system now defaults to 1024. return Arc::new(Mutex::new(1024 / 2)); } // We save the value in case the update fails. diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -56,7 +56,7 @@ pub(crate) fn get_max_nb_fds() -> isize { rlim_max: 0, }; if libc::getrlimit(libc::RLIMIT_NOFILE, &mut limits) != 0 { - // Most linux system now defaults to 1024. + // Most Linux system now defaults to 1024. 1024 / 2 } else { limits.rlim_max as isize / 2 diff --git a/src/network_helper_nix.rs b/src/network_helper_nix.rs --- a/src/network_helper_nix.rs +++ b/src/network_helper_nix.rs @@ -3,11 +3,11 @@ use crate::common::MacAddr; use std::ptr::null_mut; -/// this iterator yields an interface name and address +/// This iterator yields an interface name and address. pub(crate) struct InterfaceAddressIterator { - /// Pointer to the current ifaddrs struct + /// Pointer to the current `ifaddrs` struct. ifap: *mut libc::ifaddrs, - /// Pointer to the first element in linked list + /// Pointer to the first element in linked list. buf: *mut libc::ifaddrs, } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -170,7 +170,7 @@ pub trait ProcessExt: Debug { /// /// **⚠️ Important ⚠️** /// - /// On **linux**, there are two things to know about processes' name: + /// On **Linux**, there are two things to know about processes' name: /// 1. It is limited to 15 characters. /// 2. It is not always the exe name. /// diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -223,7 +223,7 @@ pub trait ProcessExt: Debug { /// freely, making this an untrustworthy source of information. fn exe(&self) -> &Path; - /// Returns the pid of the process. + /// Returns the PID of the process. /// /// ```no_run /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -295,7 +295,7 @@ pub trait ProcessExt: Debug { /// ``` fn virtual_memory(&self) -> u64; - /// Returns the parent pid. + /// Returns the parent PID. /// /// ```no_run /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -307,7 +307,7 @@ pub trait ProcessExt: Debug { /// ``` fn parent(&self) -> Option<Pid>; - /// Returns the status of the processus. + /// Returns the status of the process. /// /// ```no_run /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -344,13 +344,16 @@ pub trait ProcessExt: Debug { fn run_time(&self) -> u64; /// Returns the total CPU usage (in %). Notice that it might be bigger than 100 if run on a - /// multicore machine. + /// multi-core machine. /// - /// If you want a value between 0% and 100%, divide the returned value by the number of CPU - /// CPUs. + /// If you want a value between 0% and 100%, divide the returned value by the number of CPUs. /// - /// **Warning**: If you want accurate CPU usage number, better leave a bit of time - /// between two calls of this method (200 ms for example, take a look at + /// ⚠️ To start to have accurate CPU usage, a process needs to be refreshed **twice** because + /// CPU usage computation is based on time diff (process time on a given time period divided by + /// total system time on the same time period). + /// + /// ⚠️ If you want accurate CPU usage number, better leave a bit of time + /// between two calls of this method (take a look at /// [`SystemExt::MINIMUM_CPU_UPDATE_INTERVAL`] for more information). /// /// ```no_run diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -544,8 +547,8 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// /// Why is this constant even needed? /// - /// If refreshed too often (200ms on macOS, 1s onFreeBSD), the CPU usage of processes will be - /// `0` whereas on Linux it'll always be the maximum value (`number of CPUs * 100`). + /// If refreshed too often, the CPU usage of processes will be `0` whereas on Linux it'll + /// always be the maximum value (`number of CPUs * 100`). const MINIMUM_CPU_UPDATE_INTERVAL: Duration; /// Creates a new [`System`] instance with nothing loaded. If you want to diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -832,7 +835,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// /// ## Linux /// - /// ⚠️ On linux, the [NFS](https://en.wikipedia.org/wiki/Network_File_System) file + /// ⚠️ On Linux, the [NFS](https://en.wikipedia.org/wiki/Network_File_System) file /// systems are ignored and the information of a mounted NFS **cannot** be obtained /// via [`SystemExt::refresh_disks_list`]. This is due to the fact that I/O function /// `statvfs` used by [`SystemExt::refresh_disks_list`] is blocking and diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -915,7 +918,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// ``` fn processes(&self) -> &HashMap<Pid, Process>; - /// Returns the process corresponding to the given pid or `None` if no such process exists. + /// Returns the process corresponding to the given `pid` or `None` if no such process exists. /// /// ```no_run /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -934,7 +937,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// /// **⚠️ Important ⚠️** /// - /// On **linux**, there are two things to know about processes' name: + /// On **Linux**, there are two things to know about processes' name: /// 1. It is limited to 15 characters. /// 2. It is not always the exe name. /// diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -965,7 +968,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// /// **⚠️ Important ⚠️** /// - /// On **linux**, there are two things to know about processes' name: + /// On **Linux**, there are two things to know about processes' name: /// 1. It is limited to 15 characters. /// 2. It is not always the exe name. /// diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -989,7 +992,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { ) } - /// Returns "global" cpus information (aka the addition of all the CPUs). + /// Returns "global" CPUs information (aka the addition of all the CPUs). /// /// To have up-to-date information, you need to call [`SystemExt::refresh_cpu`] or /// [`SystemExt::refresh_specifics`] with `cpu` enabled. diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1006,7 +1009,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// Returns the list of the CPUs. /// - /// By default, the list of cpus is empty until you call [`SystemExt::refresh_cpu`] or + /// By default, the list of CPUs is empty until you call [`SystemExt::refresh_cpu`] or /// [`SystemExt::refresh_specifics`] with `cpu` enabled. /// /// ```no_run diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1604,7 +1607,7 @@ pub trait ComponentExt: Debug { /// /// ## Linux /// - /// May be computed by sysinfo from kernel. + /// May be computed by `sysinfo` from kernel. /// Returns `f32::NAN` if it failed to retrieve it. fn max(&self) -> f32; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1637,7 +1640,7 @@ pub trait ComponentExt: Debug { /// /// ## Linux /// - /// Since components informations are retrieved thanks to `hwmon`, + /// Since components information is retrieved thanks to `hwmon`, /// the labels are generated as follows. /// Note: it may change and it was inspired by `sensors` own formatting. /// diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. -/// Converts the value into a parallel iterator (if the multithread feature is enabled) -/// Uses the rayon::iter::IntoParallelIterator trait +/// Converts the value into a parallel iterator (if the multi-thread feature is enabled). +/// Uses the `rayon::iter::IntoParallelIterator` trait. #[cfg(all( all( any( diff --git a/src/utils.rs b/src/utils.rs --- a/src/utils.rs +++ b/src/utils.rs @@ -23,8 +23,8 @@ where val.into_par_iter() } -/// Converts the value into a sequential iterator (if the multithread feature is disabled) -/// Uses the std::iter::IntoIterator trait +/// Converts the value into a sequential iterator (if the multithread feature is disabled). +/// Uses the `std::iter::IntoIterator` trait. #[cfg(all( all( any( diff --git a/src/windows/cpu.rs b/src/windows/cpu.rs --- a/src/windows/cpu.rs +++ b/src/windows/cpu.rs @@ -30,7 +30,7 @@ use winapi::um::winnt::{ PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX, PVOID, WT_EXECUTEDEFAULT, }; -// This formula comes from linux's include/linux/sched/loadavg.h +// This formula comes from Linux's include/linux/sched/loadavg.h // https://github.com/torvalds/linux/blob/345671ea0f9258f410eb057b9ced9cefbbe5dc78/include/linux/sched/loadavg.h#L20-L23 #[allow(clippy::excessive_precision)] const LOADAVG_FACTOR_1F: f64 = 0.9200444146293232478931553241; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -596,7 +596,7 @@ unsafe fn get_process_times(handle: HANDLE) -> u64 { #[inline] fn compute_start(process_times: u64) -> u64 { // 11_644_473_600 is the number of seconds between the Windows epoch (1601-01-01) and - // the linux epoch (1970-01-01). + // the Linux epoch (1970-01-01). process_times / 10_000_000 - 11_644_473_600 } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -960,7 +960,7 @@ fn check_sub(a: u64, b: u64) -> u64 { } /// Before changing this function, you must consider the following: -/// https://github.com/GuillaumeGomez/sysinfo/issues/459 +/// <https://github.com/GuillaumeGomez/sysinfo/issues/459> pub(crate) fn compute_cpu_usage(p: &mut Process, nb_cpus: u64) { unsafe { let mut ftime: FILETIME = zeroed();
2e28eea78967c43e8a8edbb6a61b7cdb988007ce
process.cpu_usage() is 0 When I use the following code to get the cpu usage of each process, it returns 0, both on windwos and mac ``` use sysinfo::{NetworkExt, NetworksExt, ProcessExt, System, SystemExt}; fn main() { let mut sys = System::new_all(); sys.refresh_all(); for (pid, process) in sys.processes() { println!("[{}] {} {} ", pid, process.name(), process.cpu_usage()); } } ``` sysinfo: 0.27.1 mac intel/arm64 windows
0.27
924
It's something I'm working on in https://github.com/GuillaumeGomez/sysinfo/pull/903. I need to add a timeout to not refresh the system time too often. > It's something I'm working on in #903. I need to add a timeout to not refresh the system time too often. Looking forward to updating as soon as possible. Start of the year so super busy. Will try to do it this week-end. > Start of the year so super busy. Will try to do it this week-end. 哈哈哈哈哈 Sorry, just realized this is not a bug at all: to compute CPU usage, we need to make a diff which means we need to refresh **twice**. I'll update the documentation to reflect this.
2e28eea78967c43e8a8edbb6a61b7cdb988007ce
2023-01-16T16:45:43Z
diff --git a/src/system.rs b/src/system.rs --- a/src/system.rs +++ b/src/system.rs @@ -129,10 +129,9 @@ mod tests { return; } - let mut sys = System::new(); - sys.refresh_processes_specifics(ProcessRefreshKind::new().with_cpu()); - sys.refresh_cpu(); + let mut sys = System::new_all(); assert!(!sys.cpus().is_empty()); + sys.refresh_processes_specifics(ProcessRefreshKind::new().with_cpu()); let stop = Arc::new(AtomicBool::new(false)); // Spawning a few threads to ensure that it will actually have an impact on the CPU usage. diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -543,3 +543,23 @@ fn test_process_iterator_lifetimes() { } process.unwrap(); } + +// Regression test for <https://github.com/GuillaumeGomez/sysinfo/issues/918>. +#[test] +fn test_process_cpu_usage() { + use sysinfo::{ProcessExt, System, SystemExt}; + + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + + let mut sys = System::new_all(); + std::thread::sleep(System::MINIMUM_CPU_UPDATE_INTERVAL); + sys.refresh_all(); + + let max_usage = sys.cpus().len() as f32 * 100.; + + for process in sys.processes().values() { + assert!(process.cpu_usage() <= max_usage); + } +}
[ "918" ]
GuillaumeGomez__sysinfo-919
GuillaumeGomez/sysinfo
diff --git a/src/apple/cpu.rs b/src/apple/cpu.rs --- a/src/apple/cpu.rs +++ b/src/apple/cpu.rs @@ -207,7 +207,7 @@ pub(crate) fn init_cpus( let frequency = if refresh_kind.frequency() { get_cpu_frequency() } else { - 0 + global_cpu.frequency }; unsafe { diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -221,7 +221,8 @@ pub(crate) fn compute_cpu_usage( ) { if let Some(time_interval) = time_interval { let total_existing_time = p.old_stime.saturating_add(p.old_utime); - if time_interval > 0.000001 { + let mut updated_cpu_usage = false; + if time_interval > 0.000001 && total_existing_time > 0 { let total_current_time = task_info .pti_total_system .saturating_add(task_info.pti_total_user); diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -229,8 +230,10 @@ pub(crate) fn compute_cpu_usage( let total_time_diff = total_current_time.saturating_sub(total_existing_time); if total_time_diff > 0 { p.cpu_usage = (total_time_diff as f64 / time_interval * 100.) as f32; + updated_cpu_usage = true; } - } else { + } + if !updated_cpu_usage { p.cpu_usage = 0.; } p.old_stime = task_info.pti_total_system;
a02d518033cf8712a13bce82cc09b1b8dda4006a
oddly high CPU usage values on macOS systems after 0.27.4 I was recently updating some stuff to 0.27.4, when I noticed that there were some process CPU usages that were fine before were way too high now, up in the thousands, which seems really weird. I first thought I was perhaps not updating correctly, or that I forgot to divide by the number of cores, but that doesn't seem to be the case. Example program: ```rust use sysinfo::{ProcessExt, System, SystemExt}; fn main() { let mut sys = System::new_all(); sys.refresh_all(); let num_processors = sys.cpus().len() as f64; println!("num processors: {num_processors}"); for (pid, process) in sys.processes() { let usage = process.cpu_usage() as f64; println!("pid: {}, name: {} usage: {}, normalized: {}", pid, process.name(), usage, usage / num_processors); } } ``` Truncated output on an M1 Max Macbook Pro (I experienced a similar issue on an x86 macOS VM so it doesn't seem to be M1 related): ``` num processors: 10 pid: 64216, name: Google Chrome Helper (Renderer) usage: 0, normalized: 0 pid: 29928, name: aned usage: 0, normalized: 0 pid: 710, name: colorsync.useragent usage: 0, normalized: 0 (...) pid: 8893, name: suggestd usage: 36761.8046875, normalized: 3676.18046875 pid: 63106, name: cloudphotod usage: 7.886623859405518, normalized: 0.7886623859405517 pid: 43588, name: mdworker_shared usage: 0.5809944868087769, normalized: 0.058099448680877686 pid: 32653, name: softwareupdated usage: 0, normalized: 0 pid: 816, name: Python usage: 2294.884521484375, normalized: 229.4884521484375 (...) ``` You can see that for some reason, `suggestd` even after normalization by dividing over the number of cores is showing about 3600%, or Python is reporting 229%. Checking usage on Activity Monitor, these things should *not* be running that hard, either, and nowhere near the top as these stats would indicate, which makes it seem even more confusing to get as an output. Running this on 0.27.3 gives all zeros, while 0.27.4 onward gives this new behaviour, which IMO is even more surprising of a behaviour to experience than just 0, which 0.27.4 was supposed to fix. If I'm just missing a proper way of handling the output of `cpu_usage` that has changed since the last version I was on (0.26.7), then please let me know.
0.27
919
The problem before `0.27.4` was that the system time (used to compute CPU usage) was recomputed every time `refresh_process` was called. So for each process updated through this method, the CPU usage was 0 or very close to 0, which was wrong. So I added a minimum update time (which is stored in [this constant](https://docs.rs/sysinfo/latest/sysinfo/trait.SystemExt.html#associatedconstant.MINIMUM_CPU_UPDATE_INTERVAL)) which is [200ms on macOS](https://docs.rs/sysinfo/latest/x86_64-apple-darwin/src/sysinfo/apple/system.rs.html#143). However, I think there is a missing part in your code. So maybe the issue is in `sysinfo`. Can you provide a more complete code please? Unfortunately, there isn't more code - that's all I wrote. I was just adapting the example code in #905. Ah I see. Try to add a `sleep` with the value provided by the constant I linked before calling `refresh_all` just to check. Unfortunately, seems like the problem is still there, even if I slap `sleep`s around. I'm using 0.27.6, with my `Cargo.toml` just being: ```toml [package] name = "test_sysinfo" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] sysinfo = "0.27.6" ``` Code: ```rust use sysinfo::{ProcessExt, System, SystemExt}; fn main() { let mut sys = System::new_all(); let min_dur = System::MINIMUM_CPU_UPDATE_INTERVAL; println!("Sleeping for {} seconds", min_dur.as_secs_f64()); std::thread::sleep(min_dur); sys.refresh_all(); println!("Sleeping again for {} seconds", min_dur.as_secs_f64()); std::thread::sleep(min_dur); let num_processors = sys.cpus().len() as f64; println!("num processors: {num_processors}"); for (pid, process) in sys.processes() { let usage = process.cpu_usage() as f64; println!( "pid: {}, name: {} usage: {}, normalized: {}", pid, process.name(), usage, usage / num_processors ); } } ``` Shortened output of running `cargo run`: ``` Sleeping for 0.2 seconds Sleeping again for 0.2 seconds num processors: 10 pid: 64096, name: Google Chrome Helper (Renderer) usage: 39.36622619628906, normalized: 3.9366226196289063 pid: 31224, name: com.apple.AppStoreDaemon.StorePrivilegedTaskService usage: 0, normalized: 0 (...) pid: 665, name: iTerm2 usage: 7294.37841796875, normalized: 729.437841796875 pid: 394, name: contextstored usage: 0, normalized: 0 pid: 50024, name: Code Helper usage: 125.6988296508789, normalized: 12.56988296508789 pid: 18031, name: biomesyncd usage: 10.827007293701172, normalized: 1.0827007293701172 (...) pid: 49969, name: Code Helper (Renderer) usage: 2.5994529724121094, normalized: 0.25994529724121096 pid: 35641, name: plugin-container usage: 8020.38330078125, normalized: 802.038330078125 pid: 59582, name: com.apple.NRD.UpdateBrainService usage: 0, normalized: 0 (...) pid: 49966, name: Code Helper (Renderer) usage: 363.4837646484375, normalized: 36.34837646484375 pid: 24433, name: mdworker usage: 4.426096439361572, normalized: 0.4426096439361572 pid: 24588, name: Code Helper usage: 4322.203125, normalized: 432.2203125 (...) ``` There are still some values that are returning percentages that cannot possibly make sense, even after dividing over the number of cores. I ran it with `cargo run --release` as well, just in the unlikely case Cargo was doing something weird, and the issue is still there, with stuff like: ``` (...) pid: 35640, name: plugin-container usage: 29989.283203125, normalized: 2998.9283203125 pid: 49969, name: Code Helper (Renderer) usage: 3.438371419906616, normalized: 0.3438371419906616 pid: 24433, name: mdworker usage: 4.426096439361572, normalized: 0.4426096439361572 pid: 610, name: distnoted usage: 981.2070922851563, normalized: 98.12070922851562 pid: 514, name: colorsyncd usage: 0, normalized: 0 pid: 612, name: securityd_service usage: 0, normalized: 0 pid: 317, name: fseventsd usage: 0, normalized: 0 pid: 64168, name: Google Chrome Helper (Renderer) usage: 75.51575469970703, normalized: 7.551575469970703 pid: 708, name: fontworker usage: 5.670442581176758, normalized: 0.5670442581176758 pid: 1607, name: QuickLookUIService usage: 7.426414966583252, normalized: 0.7426414966583252 pid: 24590, name: Code Helper (Renderer) usage: 1311.937255859375, normalized: 131.1937255859375 pid: 493, name: systemstatusd usage: 0, normalized: 0 (...) ``` We've got values there over 100% even after dividing, and processes that are most definitely not taking 90+% CPU usage but apparently they are. There is definitely something wrong going on. Checking what's wrong.
2e28eea78967c43e8a8edbb6a61b7cdb988007ce
2022-12-07T10:58:49Z
diff --git a/tests/code_checkers/docs.rs b/tests/code_checkers/docs.rs --- a/tests/code_checkers/docs.rs +++ b/tests/code_checkers/docs.rs @@ -38,8 +38,7 @@ fn check_md_doc_path(p: &Path, md_line: &str, ty_line: &str) -> bool { show_error( p, &format!( - "Invalid markdown file name `{}`, should have been `{}`", - md_name, correct + "Invalid markdown file name `{md_name}`, should have been `{correct}`", ), ); return false; diff --git a/tests/code_checkers/headers.rs b/tests/code_checkers/headers.rs --- a/tests/code_checkers/headers.rs +++ b/tests/code_checkers/headers.rs @@ -39,8 +39,7 @@ pub fn check_license_header(content: &str, p: &Path) -> TestResult { show_error( p, &format!( - "Expected license header at the top of the file (`{}`), found: `{}`", - header, s + "Expected license header at the top of the file (`{header}`), found: `{s}`", ), ); TestResult { diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -141,6 +141,57 @@ fn test_environ() { } } +// Test to ensure that a process with a lot of environment variables doesn't get truncated. +// More information in <https://github.com/GuillaumeGomez/sysinfo/issues/886>. +#[test] +fn test_big_environ() { + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + const SIZE: usize = 30_000; + let mut big_env = String::with_capacity(SIZE); + for _ in 0..SIZE { + big_env.push('a'); + } + let mut p = if cfg!(target_os = "windows") { + std::process::Command::new("waitfor") + .arg("/t") + .arg("3") + .arg("EnvironSignal") + .stdout(std::process::Stdio::null()) + .env("FOO", &big_env) + .spawn() + .unwrap() + } else { + std::process::Command::new("sleep") + .arg("3") + .stdout(std::process::Stdio::null()) + .env("FOO", &big_env) + .spawn() + .unwrap() + }; + + let pid = Pid::from_u32(p.id() as _); + std::thread::sleep(std::time::Duration::from_secs(1)); + let mut s = sysinfo::System::new(); + s.refresh_processes(); + p.kill().expect("Unable to kill process."); + + let processes = s.processes(); + let p = processes.get(&pid); + + if let Some(p) = p { + assert_eq!(p.pid(), pid); + // FIXME: instead of ignoring the test on CI, try to find out what's wrong... + if std::env::var("APPLE_CI").is_err() { + let env = format!("FOO={big_env}"); + assert!(p.environ().iter().any(|e| *e == env)); + } + } else { + panic!("Process not found!"); + } +} + #[test] fn test_process_refresh() { let mut s = sysinfo::System::new();
[ "886" ]
GuillaumeGomez__sysinfo-887
GuillaumeGomez/sysinfo
diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -342,11 +342,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { let minutes = uptime / 60; writeln!( &mut io::stdout(), - "{} days {} hours {} minutes ({} seconds in total)", - days, - hours, - minutes, - up, + "{days} days {hours} hours {minutes} minutes ({up} seconds in total)", ); } x if x.starts_with("refresh") => { diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -365,11 +361,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { if sys.refresh_process(pid) { writeln!(&mut io::stdout(), "Process `{pid}` updated successfully"); } else { - writeln!( - &mut io::stdout(), - "Process `{}` couldn't be updated...", - pid - ); + writeln!(&mut io::stdout(), "Process `{pid}` couldn't be updated..."); } } else { writeln!(&mut io::stdout(), "Invalid [pid] received..."); diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -377,9 +369,8 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { } else { writeln!( &mut io::stdout(), - "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \ + "\"{x}\": Unknown command. Enter 'help' if you want to get the commands' \ list.", - x ); } } diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -410,9 +401,8 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { e => { writeln!( &mut io::stdout(), - "\"{}\": Unknown command. Enter 'help' if you want to get the commands' \ + "\"{e}\": Unknown command. Enter 'help' if you want to get the commands' \ list.", - e ); } } diff --git a/src/linux/cpu.rs b/src/linux/cpu.rs --- a/src/linux/cpu.rs +++ b/src/linux/cpu.rs @@ -427,8 +427,7 @@ impl CpuExt for Cpu { pub(crate) fn get_cpu_frequency(cpu_core_index: usize) -> u64 { let mut s = String::new(); if File::open(format!( - "/sys/devices/system/cpu/cpu{}/cpufreq/scaling_cur_freq", - cpu_core_index + "/sys/devices/system/cpu/cpu{cpu_core_index}/cpufreq/scaling_cur_freq", )) .and_then(|mut f| f.read_to_string(&mut s)) .is_ok() diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -620,10 +620,12 @@ pub(crate) fn refresh_procs( fn copy_from_file(entry: &Path) -> Vec<String> { match File::open(entry) { Ok(mut f) => { - let mut data = vec![0; 16_384]; + let mut data = Vec::with_capacity(16_384); - if let Ok(size) = f.read(&mut data) { - data.truncate(size); + if let Err(_e) = f.read_to_end(&mut data) { + sysinfo_debug!("Failed to read file in `copy_from_file`: {:?}", _e); + Vec::new() + } else { let mut out = Vec::with_capacity(20); let mut start = 0; for (pos, x) in data.iter().enumerate() { diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -639,11 +641,12 @@ fn copy_from_file(entry: &Path) -> Vec<String> { } } out - } else { - Vec::new() } } - Err(_) => Vec::new(), + Err(_e) => { + sysinfo_debug!("Failed to open file in `copy_from_file`: {:?}", _e); + Vec::new() + } } }
abe8e369d0cee1cf85ddc2d864da875c6312d524
linux: environ is truncated for long environ ``` $ wc -c /proc/882252/environ 30417 /proc/882252/environ ``` environ for this process is truncated approximately half way through
0.26
887
suspicious size matching truncation: https://github.com/GuillaumeGomez/sysinfo/blob/master/src/linux/process.rs#L623 Nice catch! It should indeed add a size check when reading the file.
abe8e369d0cee1cf85ddc2d864da875c6312d524
2022-12-01T12:55:37Z
diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -962,4 +991,23 @@ mod tests { fn check_display_impl_process_status() { println!("{} {:?}", ProcessStatus::Parked, ProcessStatus::Idle); } + + // This test exists to ensure that the `TryFrom<usize>` and `FromStr` traits are implemented + // on `Uid`, `Gid` and `Pid`. + #[test] + fn check_uid_gid_from_impls() { + use std::convert::TryFrom; + use std::str::FromStr; + + assert!(crate::Uid::try_from(0usize).is_ok()); + assert!(crate::Uid::from_str("0").is_ok()); + + assert!(crate::Gid::try_from(0usize).is_ok()); + assert!(crate::Gid::from_str("0").is_ok()); + + assert!(crate::Pid::try_from(0usize).is_ok()); + // If it doesn't panic, it's fine. + let _ = crate::Pid::from(0); + assert!(crate::Pid::from_str("0").is_ok()); + } }
[ "883" ]
GuillaumeGomez__sysinfo-884
GuillaumeGomez/sysinfo
diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -2,7 +2,7 @@ use crate::{NetworkData, Networks, NetworksExt, UserExt}; -use std::convert::From; +use std::convert::{From, TryFrom}; use std::fmt; use std::str::FromStr; diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -14,7 +14,7 @@ use std::str::FromStr; /// let p = Pid::from_u32(0); /// let value: u32 = p.as_u32(); /// ``` -pub trait PidExt<T>: Copy + From<T> + FromStr + fmt::Display { +pub trait PidExt: Copy + From<usize> + FromStr + fmt::Display { /// Allows to convert [`Pid`][crate::Pid] into [`u32`]. /// /// ``` diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -41,19 +41,19 @@ macro_rules! pid_decl { #[repr(transparent)] pub struct Pid(pub(crate) $typ); - impl From<$typ> for Pid { - fn from(v: $typ) -> Self { - Self(v) + impl From<usize> for Pid { + fn from(v: usize) -> Self { + Self(v as _) } } - impl From<Pid> for $typ { + impl From<Pid> for usize { fn from(v: Pid) -> Self { - v.0 + v.0 as _ } } - impl PidExt<$typ> for Pid { + impl PidExt for Pid { fn as_u32(self) -> u32 { - self.0 as u32 + self.0 as _ } fn from_u32(v: u32) -> Self { Self(v as _) diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -664,7 +664,7 @@ pub struct LoadAvg { } macro_rules! xid { - ($(#[$outer:meta])+ $name:ident, $type:ty) => { + ($(#[$outer:meta])+ $name:ident, $type:ty $(, $trait:ty)?) => { $(#[$outer])+ #[repr(transparent)] #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -677,18 +677,51 @@ macro_rules! xid { &self.0 } } + + $( + impl TryFrom<usize> for $name { + type Error = <$type as TryFrom<usize>>::Error; + + fn try_from(t: usize) -> Result<Self, <$type as TryFrom<usize>>::Error> { + Ok(Self(<$type>::try_from(t)?)) + } + } + + impl $trait for $name { + type Err = <$type as FromStr>::Err; + + fn from_str(t: &str) -> Result<Self, <$type as FromStr>::Err> { + Ok(Self(<$type>::from_str(t)?)) + } + } + )? }; } macro_rules! uid { - ($(#[$outer:meta])+ $type:ty) => { - xid!($(#[$outer])+ Uid, $type); + ($type:ty$(, $trait:ty)?) => { + xid!( + /// A user id wrapping a platform specific type. + /// + /// ⚠️ On windows, `Uid` is actually wrapping a `Box<str>` due to some + /// Windows limitations around their users ID. For the time being, `Uid` + /// is the user name on this platform. + Uid, + $type + $(, $trait)? + ); }; } macro_rules! gid { - ($(#[$outer:meta])+ $type:ty) => { - xid!($(#[$outer])+ #[derive(Copy)] Gid, $type); + ($type:ty) => { + xid!( + /// A group id wrapping a platform specific type. + #[derive(Copy)] + Gid, + $type, + FromStr + ); }; } diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -703,33 +736,29 @@ cfg_if::cfg_if! { target_os = "ios", ) ))] { - uid!( - /// A user id wrapping a platform specific type. - libc::uid_t - ); - gid!( - /// A group id wrapping a platform specific type. - libc::gid_t - ); + uid!(libc::uid_t, FromStr); + gid!(libc::gid_t); } else if #[cfg(windows)] { - uid!( - /// A user id wrapping a platform specific type. - Box<str> - ); - gid!( - /// A group id wrapping a platform specific type. - u32 - ); - } else { - uid!( - /// A user id wrapping a platform specific type. - u32 - ); - gid!( - /// A group id wrapping a platform specific type. - u32 - ); + uid!(Box<str>); + gid!(u32); + // Manual implementation outside of the macro... + impl FromStr for Uid { + type Err = <String as FromStr>::Err; + + fn from_str(t: &str) -> Result<Self, <String as FromStr>::Err> { + Ok(Self(t.into())) + } + } + impl TryFrom<usize> for Uid { + type Error = <u32 as TryFrom<usize>>::Error; + fn try_from(t: usize) -> Result<Self, <u32 as TryFrom<usize>>::Error> { + Ok(Self(t.to_string().into_boxed_str())) + } + } + } else { + uid!(u32, FromStr); + gid!(u32); } }
8be83e1cfbc75e8594b14332a8786978540ff6ff
Uid::from() Hey guys! Is Uid::from() method is implemented yet? Cause right now Pid::from() forking fine, but Uid::from() required Uid object anyway.
0.26
884
No it's not as no one asked for it. I'll add it today. Thanks are lot! Same for Group please Noted! :laughing: I'll actually go through the newtypes to be sure I don't forget one. Great, thanks!
abe8e369d0cee1cf85ddc2d864da875c6312d524
2022-11-23T15:28:42Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -293,6 +293,17 @@ fn test_process_times() { } } +// Checks that `session_id` is working. +#[test] +fn test_process_session_id() { + if !sysinfo::System::IS_SUPPORTED || cfg!(feature = "apple-sandbox") { + return; + } + let mut s = sysinfo::System::new(); + s.refresh_processes(); + assert!(s.processes().values().any(|p| p.session_id().is_some())); +} + // Checks that `refresh_processes` is removing dead processes. #[test] fn test_refresh_processes() {
[ "783" ]
GuillaumeGomez__sysinfo-878
GuillaumeGomez/sysinfo
diff --git a/md_doc/pid.md b/md_doc/pid.md --- a/md_doc/pid.md +++ b/md_doc/pid.md @@ -1,4 +1,4 @@ -Process id +Process ID. Can be used as an integer type by simple casting. For example: diff --git a/src/apple/app_store/process.rs b/src/apple/app_store/process.rs --- a/src/apple/app_store/process.rs +++ b/src/apple/app_store/process.rs @@ -81,4 +81,8 @@ impl ProcessExt for Process { } fn wait(&self) {} + + fn session_id(&self) -> Option<Pid> { + None + } } diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -198,6 +198,17 @@ impl ProcessExt for Process { } } } + + fn session_id(&self) -> Option<Pid> { + unsafe { + let session_id = libc::getsid(self.pid.0); + if session_id < 0 { + None + } else { + Some(Pid(session_id)) + } + } + } } #[allow(deprecated)] // Because of libc::mach_absolute_time. diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -157,6 +157,17 @@ impl ProcessExt for Process { } } } + + fn session_id(&self) -> Option<Pid> { + unsafe { + let session_id = libc::getsid(self.pid.0); + if session_id < 0 { + None + } else { + Some(Pid(session_id)) + } + } + } } pub(crate) unsafe fn get_process_data( diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -233,6 +233,17 @@ impl ProcessExt for Process { } } } + + fn session_id(&self) -> Option<Pid> { + unsafe { + let session_id = libc::getsid(self.pid.0); + if session_id < 0 { + None + } else { + Some(Pid(session_id)) + } + } + } } pub(crate) fn compute_cpu_usage(p: &mut Process, total_time: f32, max_value: f32) { diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -408,7 +408,7 @@ pub trait ProcessExt: Debug { /// let mut s = System::new_all(); /// /// if let Some(process) = s.process(Pid::from(1337)) { - /// eprintln!("Group id for process 1337: {:?}", process.group_id()); + /// eprintln!("Group ID for process 1337: {:?}", process.group_id()); /// } /// ``` fn group_id(&self) -> Option<Gid>; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -427,6 +427,21 @@ pub trait ProcessExt: Debug { /// } /// ``` fn wait(&self); + + /// Returns the session ID for the current process or `None` if it couldn't be retrieved. + /// + /// ⚠️ This information is computed every time this method is called. + /// + /// ```no_run + /// use sysinfo::{Pid, ProcessExt, System, SystemExt}; + /// + /// let mut s = System::new_all(); + /// + /// if let Some(process) = s.process(Pid::from(1337)) { + /// eprintln!("Session ID for process 1337: {:?}", process.session_id()); + /// } + /// ``` + fn session_id(&self) -> Option<Pid>; } /// Contains all the methods of the [`Cpu`][crate::Cpu] struct. diff --git a/src/unknown/process.rs b/src/unknown/process.rs --- a/src/unknown/process.rs +++ b/src/unknown/process.rs @@ -91,4 +91,8 @@ impl ProcessExt for Process { } fn wait(&self) {} + + fn session_id(&self) -> Option<Pid> { + None + } } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -2,7 +2,9 @@ use crate::sys::system::is_proc_running; use crate::sys::utils::to_str; -use crate::{DiskUsage, Gid, Pid, ProcessExt, ProcessRefreshKind, ProcessStatus, Signal, Uid}; +use crate::{ + DiskUsage, Gid, Pid, PidExt, ProcessExt, ProcessRefreshKind, ProcessStatus, Signal, Uid, +}; use std::ffi::OsString; use std::fmt; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -39,7 +41,7 @@ use winapi::um::handleapi::CloseHandle; use winapi::um::heapapi::{GetProcessHeap, HeapAlloc, HeapFree}; use winapi::um::memoryapi::{ReadProcessMemory, VirtualQueryEx}; use winapi::um::processthreadsapi::{ - GetProcessTimes, GetSystemTimes, OpenProcess, OpenProcessToken, + GetProcessTimes, GetSystemTimes, OpenProcess, OpenProcessToken, ProcessIdToSessionId, }; use winapi::um::psapi::{ EnumProcessModulesEx, GetModuleBaseNameW, GetModuleFileNameExW, GetProcessMemoryInfo, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -563,6 +565,17 @@ impl ProcessExt for Process { sysinfo_debug!("can't wait on this process so returning"); } } + + fn session_id(&self) -> Option<Pid> { + unsafe { + let mut out = 0; + if ProcessIdToSessionId(self.pid.as_u32(), &mut out) != 0 { + return Some(Pid(out as _)); + } + sysinfo_debug!("ProcessIdToSessionId failed, error: {:?}", GetLastError()); + None + } + } } #[inline]
0818da38903a7597cb315a1a2bb5392fe0d2e336
[Feature Request] Process session id A session id is used to group processes within a session. For mac/bsd/linix it can be obtained from the [getsid](https://docs.rs/libc/0.2.124/i686-unknown-linux-gnu/libc/fn.getsid.html) system call For windows it can be found in the [SYSTEM_PROCESS_INFORMATION](https://microsoft.github.io/windows-docs-rs/doc/windows/Win32/System/WindowsProgramming/struct.SYSTEM_PROCESS_INFORMATION.html) struct from NtQuerySystemInformation which is already being called. It can be obtained individually from [ProcessIdToSessionId](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-processidtosessionid) but this may sometimes give access denied.
0.26
878
For windows, we can wrap it into an `Option` like we do for the other process IDs. Interested into sending a PR?
abe8e369d0cee1cf85ddc2d864da875c6312d524
2022-09-25T00:36:37Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -328,9 +328,10 @@ mod test { #[test] fn check_system_info() { + let s = System::new(); + // We don't want to test on unsupported systems. if System::IS_SUPPORTED { - let s = System::new(); assert!(!s.name().expect("Failed to get system name").is_empty()); assert!(!s diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -345,6 +346,8 @@ mod test { .expect("Failed to get long OS version") .is_empty()); } + + assert!(!s.distribution_id().is_empty()); } #[test] diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -798,6 +829,7 @@ mod test { fn lsb_release_fallback_android() { assert!(get_system_info_android(InfoType::OsVersion).is_some()); assert!(get_system_info_android(InfoType::Name).is_some()); + assert!(get_system_info_android(InfoType::DistributionID).is_none()); } #[test]
[ "843" ]
GuillaumeGomez__sysinfo-844
GuillaumeGomez/sysinfo
diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -605,6 +605,10 @@ impl SystemExt for System { } } } + + fn distribution_id(&self) -> String { + std::env::consts::OS.to_owned() + } } impl Default for System { diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -361,6 +361,10 @@ impl SystemExt for System { fn os_version(&self) -> Option<String> { self.system_info.get_os_release() } + + fn distribution_id(&self) -> String { + std::env::consts::OS.to_owned() + } } impl Default for System { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -697,6 +697,25 @@ impl SystemExt for System { fn os_version(&self) -> Option<String> { get_system_info_android(InfoType::OsVersion) } + + #[cfg(not(target_os = "android"))] + fn distribution_id(&self) -> String { + get_system_info_linux( + InfoType::DistributionID, + Path::new("/etc/os-release"), + Path::new(""), + ) + .unwrap_or_else(|| std::env::consts::OS.to_owned()) + } + + #[cfg(target_os = "android")] + fn distribution_id(&self) -> String { + // Currently get_system_info_android doesn't support InfoType::DistributionID and always + // returns None. This call is done anyway for consistency with non-Android implementation + // and to suppress dead-code warning for DistributionID on Android. + get_system_info_android(InfoType::DistributionID) + .unwrap_or_else(|| std::env::consts::OS.to_owned()) + } } impl Default for System { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -722,6 +741,9 @@ enum InfoType { /// - Linux: The distributions name Name, OsVersion, + /// Machine-parseable ID of a distribution, see + /// https://www.freedesktop.org/software/systemd/man/os-release.html#ID= + DistributionID, } #[cfg(not(target_os = "android"))] diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -732,6 +754,7 @@ fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> O let info_str = match info { InfoType::Name => "NAME=", InfoType::OsVersion => "VERSION_ID=", + InfoType::DistributionID => "ID=", }; for line in reader.lines().flatten() { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -750,6 +773,10 @@ fn get_system_info_linux(info: InfoType, path: &Path, fallback_path: &Path) -> O let info_str = match info { InfoType::OsVersion => "DISTRIB_RELEASE=", InfoType::Name => "DISTRIB_ID=", + InfoType::DistributionID => { + // lsb-release is inconsistent with os-release and unsupported. + return None; + } }; for line in reader.lines().flatten() { if let Some(stripped) = line.strip_prefix(info_str) { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -765,6 +792,10 @@ fn get_system_info_android(info: InfoType) -> Option<String> { let name: &'static [u8] = match info { InfoType::Name => b"ro.product.model\0", InfoType::OsVersion => b"ro.build.version.release\0", + InfoType::DistributionID => { + // Not supported. + return None; + } }; let mut value_buffer = vec![0u8; libc::PROP_VALUE_MAX as usize]; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -844,6 +876,10 @@ DISTRIB_DESCRIPTION="Ubuntu 20.10" get_system_info_linux(InfoType::Name, &tmp1, Path::new("")), Some("Ubuntu".to_owned()) ); + assert_eq!( + get_system_info_linux(InfoType::DistributionID, &tmp1, Path::new("")), + Some("ubuntu".to_owned()) + ); // Check for the "fallback" path: "/etc/lsb-release" assert_eq!( diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -854,5 +890,9 @@ DISTRIB_DESCRIPTION="Ubuntu 20.10" get_system_info_linux(InfoType::Name, Path::new(""), &tmp2), Some("Ubuntu".to_owned()) ); + assert_eq!( + get_system_info_linux(InfoType::DistributionID, Path::new(""), &tmp2), + None + ); } } diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -1235,6 +1235,23 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// ``` fn long_os_version(&self) -> Option<String>; + /// Returns the distribution id as defined by os-release, + /// or [`std::env::consts::OS`]. + /// + /// See also + /// - https://www.freedesktop.org/software/systemd/man/os-release.html#ID= + /// - https://doc.rust-lang.org/std/env/consts/constant.OS.html + /// + /// **Important**: this information is computed every time this function is called. + /// + /// ```no_run + /// use sysinfo::{System, SystemExt}; + /// + /// let s = System::new(); + /// println!("Distribution ID: {:?}", s.distribution_id()); + /// ``` + fn distribution_id(&self) -> String; + /// Returns the system hostname based off DNS /// /// **Important**: this information is computed every time this function is called. diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -166,6 +166,10 @@ impl SystemExt for System { None } + fn distribution_id(&self) -> String { + std::env::consts::OS.to_owned() + } + fn host_name(&self) -> Option<String> { None } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -496,6 +496,10 @@ impl SystemExt for System { }; Some(format!("{} ({})", major, build_number)) } + + fn distribution_id(&self) -> String { + std::env::consts::OS.to_owned() + } } impl Default for System {
d5ad6dff70a2e019f8f7ff83e34775c8a20d94bb
Machine-parseable equivalent to System::name() Hi, [os-release](https://www.freedesktop.org/software/systemd/man/os-release.html) documents `NAME=` as a human-presentable name of a distro, and `ID=` as a machine-readable identifier. `System::name()` currently relies on `os-release.NAME`, which makes it less than ideal for distro identification. Is there a way to get `os-release.ID` specifically? I didn't find it in [system.rs](https://github.com/GuillaumeGomez/sysinfo/blame/master/src/linux/system.rs), I would appreciate a pointer if it's available through sysinfo. Thank you for your consideration.
0.26
844
It can be added. The question as always is: "what should it return for other OSes?". On linux you have different distributions so it makes sense, but I think it's the only case. For windows you only have windows, same for macOS. For FreeBSD it could make sense too? Personally I think it can be the OS name if /etc/os-release is not available. We could use `std::env::consts::OS` as a fallback. I believe this can be the right choice because - [os-release](https://www.freedesktop.org/software/systemd/man/os-release.html#ID=) specifies `If not set, a default of "ID=linux" may be used` - `std::env::consts::OS == "linux"` on Linux, which matches the specification above. - We can extrapolate this to other OSes that don't usually have /etc/os-release, even though [os-release](https://www.freedesktop.org/software/systemd/man/os-release.html) specification doesn't cover them. On Rust names like `windows` and `macos` that come from `std::env::consts::OS` should be pretty well understood. We could probably document this fallback as part of the API. I don't have a strong opinion on how to name this, I would propose `distro_id()` or something similar, both to highlight that it's mostly useful as a distro concept, and that it uses `ID`, machine-readable name, not `NAME`, human-readable name. I imagine this can be used later as match ...distro_id() { "arch" => ... do ArchLinux things, "ubuntu" => ... do Ubuntu things, "linux" => failed to determine which distro, generic code, "windows" => windows code, } If in the future Windows/MacOS distro will start making sense, it will be possible to extend this as well. **Alternatively** we can return `Option::None` if distro name is unavailable and let the user decide what they actually want to do. Whether fallback to the OS name, error out, or do something else entirely. This may be useful if a user wants to implement a distro-specific. sysinfo already uses Option<String> extensively so it will be consistent. **Caveat** I am not sure how to handle lsb-release as it has Capitalised names, e.g. `Ubuntu` instead of `ubuntu`. There is some code in sysinfo that falls back to lsb-release, but maybe we should just ignore lsb-release completely. What do you think? Thank you for the prompt response by the way! Sounds good to me. For windows and macOS, we can just return "windows" and "macOS" and live with it. For the method name, I'd go for "distribution_name". What do you think? If you're motivated, a PR is very welcome. :) I will be happy to work on a PR. > I'd go for "distribution_name" I would prefer "distribution_id" to highlight the stable nature of the field. I will send you a PR and let's discuss there. Thank you!
abe8e369d0cee1cf85ddc2d864da875c6312d524
2022-09-03T12:49:44Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -469,4 +469,19 @@ mod test { (new_total - total).abs() ); } + + // We ensure that the `Process` cmd information is retrieved as expected. + #[test] + fn check_cmd_line() { + if !System::IS_SUPPORTED { + return; + } + let mut sys = System::new(); + sys.refresh_processes_specifics(ProcessRefreshKind::new()); + + assert!(sys + .processes() + .iter() + .any(|(_, process)| !process.cmd().is_empty())); + } }
[ "833" ]
GuillaumeGomez__sysinfo-835
GuillaumeGomez/sysinfo
diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -353,6 +353,7 @@ fn retrieve_all_new_process_info( if refresh_kind.user() { refresh_user_group_ids(&mut p, &mut tmp); + tmp.pop(); } if proc_list.pid.0 != 0 { diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -367,7 +368,6 @@ fn retrieve_all_new_process_info( } else { p.name = name.into(); - tmp.pop(); tmp.push("cmdline"); p.cmd = copy_from_file(&tmp); diff --git a/src/linux/process.rs b/src/linux/process.rs --- a/src/linux/process.rs +++ b/src/linux/process.rs @@ -547,65 +547,65 @@ pub(crate) fn refresh_procs( info: &SystemInfo, refresh_kind: ProcessRefreshKind, ) -> bool { - if let Ok(d) = fs::read_dir(path) { - let folders = d - .filter_map(|entry| { - let entry = entry.ok()?; - let entry = entry.path(); - - if entry.is_dir() { - Some(entry) - } else { - None - } + let d = match fs::read_dir(path) { + Ok(d) => d, + Err(_) => return false, + }; + let folders = d + .filter_map(|entry| { + let entry = entry.ok()?; + let entry = entry.path(); + + if entry.is_dir() { + Some(entry) + } else { + None + } + }) + .collect::<Vec<_>>(); + if pid.0 == 0 { + let proc_list = Wrap(UnsafeCell::new(proc_list)); + + #[cfg(feature = "multithread")] + use rayon::iter::ParallelIterator; + + into_iter(folders) + .filter_map(|e| { + let (p, _) = _get_process_data( + e.as_path(), + proc_list.get(), + pid, + uptime, + info, + refresh_kind, + ) + .ok()?; + p }) - .collect::<Vec<_>>(); - if pid.0 == 0 { - let proc_list = Wrap(UnsafeCell::new(proc_list)); - - #[cfg(feature = "multithread")] - use rayon::iter::ParallelIterator; - - into_iter(folders) - .filter_map(|e| { - let (p, _) = _get_process_data( - e.as_path(), - proc_list.get(), - pid, - uptime, - info, - refresh_kind, - ) - .ok()?; - p - }) - .collect::<Vec<_>>() - } else { - let mut updated_pids = Vec::with_capacity(folders.len()); - let new_tasks = folders - .iter() - .filter_map(|e| { - let (p, pid) = - _get_process_data(e.as_path(), proc_list, pid, uptime, info, refresh_kind) - .ok()?; - updated_pids.push(pid); - p - }) - .collect::<Vec<_>>(); - // Sub-tasks are not cleaned up outside so we do it here directly. - proc_list - .tasks - .retain(|&pid, _| updated_pids.iter().any(|&x| x == pid)); - new_tasks - } - .into_iter() - .for_each(|e| { - proc_list.tasks.insert(e.pid(), e); - }); - true + .collect::<Vec<_>>() } else { - false - } + let mut updated_pids = Vec::with_capacity(folders.len()); + let new_tasks = folders + .iter() + .filter_map(|e| { + let (p, pid) = + _get_process_data(e.as_path(), proc_list, pid, uptime, info, refresh_kind) + .ok()?; + updated_pids.push(pid); + p + }) + .collect::<Vec<_>>(); + // Sub-tasks are not cleaned up outside so we do it here directly. + proc_list + .tasks + .retain(|&pid, _| updated_pids.iter().any(|&x| x == pid)); + new_tasks + } + .into_iter() + .for_each(|e| { + proc_list.tasks.insert(e.pid(), e); + }); + true } fn copy_from_file(entry: &Path) -> Vec<String> {
c7046eb4e189afcfb140057caa581d835e1cc51d
Obtaining linux command line requires ProcessRefreshKind::with_user() to be set It seems retrieving process user information must be turned on when loading processes in linux for the command line to be retrieved. ### Expected Refreshing a new System with ProcessRefreshKind::new() loads the process command line data as none of the ProcessRefreshKind options seem to pertain to it ### Actual Refreshing a new System requires ProcessRefreshKind user retrieval to be turned on to obtain information about the process command line. ### Sample ``` // Does not include command line let mut sys = System::new(); sys.refresh_processes_specifics(ProcessRefreshKind::new()); for (pid, process) in sys.processes() { println!("A [{}] {} {:?}", pid, process.name(), process.cmd()); } // Does not include command line let mut sys = System::new(); sys.refresh_processes_specifics(ProcessRefreshKind::everything().without_user()); for (pid, process) in sys.processes() { println!("B [{}] {} {:?}", pid, process.name(), process.cmd()); } // Includes command line let mut sys = System::new(); sys.refresh_processes_specifics(ProcessRefreshKind::new().with_user()); for (pid, process) in sys.processes() { println!("C [{}] {} {:?}", pid, process.name(), process.cmd()); } ``` Version: 0.26.1 OS: RHEL8
0.26
835
This is intriguing. Thanks for opening this issue! I'll try to take a look in the next days but don't hesitate to check before if you want.
abe8e369d0cee1cf85ddc2d864da875c6312d524
2022-06-10T12:16:28Z
diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -444,4 +444,23 @@ mod test { assert_ne!(proc_.frequency(), 0); } } + + // In case `Process::updated` is misused, `System::refresh_processes` might remove them + // so this test ensures that it doesn't happen. + #[test] + fn check_refresh_process_update() { + if !System::IS_SUPPORTED { + return; + } + let mut s = System::new_all(); + let total = s.processes().len() as isize; + s.refresh_processes(); + let new_total = s.processes().len() as isize; + // There should be almost no difference in the processes count. + assert!( + (new_total - total).abs() < 5, + "{} < 5", + (new_total - total).abs() + ); + } }
[ "767" ]
GuillaumeGomez__sysinfo-768
GuillaumeGomez/sysinfo
diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -30,7 +30,7 @@ pub struct Process { old_stime: u64, start_time: u64, run_time: u64, - updated: bool, + pub(crate) updated: bool, cpu_usage: f32, user_id: Option<Uid>, group_id: Option<Gid>, diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -236,7 +236,6 @@ pub(crate) fn compute_cpu_usage( }; } } - p.updated = true; } /*pub fn set_time(p: &mut Process, utime: u64, stime: u64) { diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -247,18 +246,6 @@ pub(crate) fn compute_cpu_usage( p.updated = true; }*/ -#[inline] -pub(crate) fn has_been_updated(p: &mut Process) -> bool { - let old = p.updated; - p.updated = false; - old -} - -#[inline] -pub(crate) fn force_update(p: &mut Process) { - p.updated = true; -} - unsafe fn get_task_info(pid: Pid) -> libc::proc_taskinfo { let mut task_info = mem::zeroed::<libc::proc_taskinfo>(); // If it doesn't work, we just don't have memory information for this process diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -274,12 +261,22 @@ unsafe fn get_task_info(pid: Pid) -> libc::proc_taskinfo { } #[inline] -fn check_if_pid_is_alive(pid: Pid) -> bool { - unsafe { kill(pid.0, 0) == 0 } - // For the full complete check, it'd need to be (but that seems unneeded): - // unsafe { - // *libc::__errno_location() == libc::ESRCH - // } +fn check_if_pid_is_alive(pid: Pid, check_if_alive: bool) -> bool { + // In case we are iterating all pids we got from `proc_listallpids`, then + // there is no point checking if the process is alive since it was returned + // from this function. + if !check_if_alive { + return true; + } + unsafe { + if kill(pid.0, 0) == 0 { + return true; + } + // `kill` failed but it might not be because the process is dead. + let errno = libc::__error(); + // If errno is equal to ESCHR, it means the process is dead. + !errno.is_null() && *errno != libc::ESRCH + } } #[inline] diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -300,6 +297,7 @@ pub(crate) fn update_process( time_interval: Option<f64>, now: u64, refresh_kind: ProcessRefreshKind, + check_if_alive: bool, ) -> Result<Option<Process>, ()> { let mut proc_args = Vec::with_capacity(size as usize); diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -307,8 +305,8 @@ pub(crate) fn update_process( if let Some(ref mut p) = (*wrap.0.get()).get_mut(&pid) { if p.memory == 0 { // We don't have access to this process' information. - force_update(p); - return if check_if_pid_is_alive(pid) { + return if check_if_pid_is_alive(pid, check_if_alive) { + p.updated = true; Ok(None) } else { Err(()) diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -331,7 +329,8 @@ pub(crate) fn update_process( ) } else { // It very likely means that the process is dead... - return if check_if_pid_is_alive(pid) { + return if check_if_pid_is_alive(pid, check_if_alive) { + p.updated = true; Ok(None) } else { Err(()) diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -347,6 +346,7 @@ pub(crate) fn update_process( if refresh_kind.disk_usage() { update_proc_disk_activity(p); } + p.updated = true; return Ok(None); } diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -126,16 +126,6 @@ pub(crate) struct Wrap<'a>(pub UnsafeCell<&'a mut HashMap<Pid, Process>>); unsafe impl<'a> Send for Wrap<'a> {} unsafe impl<'a> Sync for Wrap<'a> {} -#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] -impl System { - fn clear_procs(&mut self) { - use crate::sys::macos::process; - - self.process_list - .retain(|_, proc_| process::has_been_updated(proc_)); - } -} - fn boot_time() -> u64 { let mut boot_time = timeval { tv_sec: 0, diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -356,6 +346,7 @@ impl SystemExt for System { time_interval, now, refresh_kind, + false, ) { Ok(x) => x, _ => None, diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -366,7 +357,8 @@ impl SystemExt for System { entries.into_iter().for_each(|entry| { self.process_list.insert(entry.pid(), entry); }); - self.clear_procs(); + self.process_list + .retain(|_, proc_| std::mem::replace(&mut proc_.updated, false)); } } diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -390,6 +382,7 @@ impl SystemExt for System { time_interval, now, refresh_kind, + true, ) } { Ok(Some(p)) => { diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -249,6 +249,6 @@ pub(crate) unsafe fn get_process_data( old_read_bytes: 0, written_bytes: kproc.ki_rusage.ru_oublock as _, old_written_bytes: 0, - updated: true, + updated: false, })) } diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -377,10 +377,6 @@ impl System { #[cfg(not(feature = "multithread"))] use std::iter::Iterator as IterTrait; - crate::utils::into_iter(&mut self.process_list).for_each(|(_, proc_)| { - proc_.updated = false; - }); - let fscale = self.system_info.fscale; let page_size = self.system_info.page_size as isize; let now = super::utils::get_now(); diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -404,7 +400,8 @@ impl System { }; // We remove all processes that don't exist anymore. - self.process_list.retain(|_, v| v.updated); + self.process_list + .retain(|_, v| std::mem::replace(&mut v.updated, false)); for (kproc, proc_) in procs { self.add_missing_proc_info(kd, kproc, proc_);
ad49264fca17c996547c173e4d8ef792c95b16d5
macOS: it's necessary to call `refresh_processes` twice to get them all Using `sysinfo 0.24.2` (also seen on `0.23.13`), with the following code: ```rust use sysinfo::{System, SystemExt}; fn main() { let mut s = System::new_all(); s.refresh_processes(); dbg!(s.processes().len()); s.refresh_processes(); dbg!(s.processes().len()); } ``` Then calling ```bash ps aux | wc -l; cargo run -q; ps aux | wc -l ``` I get: ``` 452 [src/main.rs:6] s.processes().len() = 272 [src/main.rs:8] s.processes().len() = 450 452 ``` The result is the same when running as root or not.
0.24
768
Thanks for the report. I'll try to take a look when I have some time. After some more investigation, the `System::new_all()` gets them all, but then the first `.refresh_processes()` truncate the list and the second fills it again: I added `println!` calls in `refresh_processes_specifics()`: ``` ---- System::new_all() ---- ENTERING: refresh_processes_specifics: self.process_list.len() = 0 refresh_processes_specifics: proc_listallpids = 556 refresh_processes_specifics: pids.len() = 537 refresh_processes_specifics: entries.len() = 536 EXITING: refresh_processes_specifics: self.process_list.len() = 536 ---- s.refresh_processes() ---- ENTERING: refresh_processes_specifics: self.process_list.len() = 536 refresh_processes_specifics: proc_listallpids = 556 refresh_processes_specifics: pids.len() = 537 refresh_processes_specifics: entries.len() = 0 EXITING: refresh_processes_specifics: self.process_list.len() = 313 [src/main.rs:8] s.processes().len() = 313 ---- s.refresh_processes() ---- ENTERING: refresh_processes_specifics: self.process_list.len() = 313 refresh_processes_specifics: proc_listallpids = 556 refresh_processes_specifics: pids.len() = 537 refresh_processes_specifics: entries.len() = 223 EXITING: refresh_processes_specifics: self.process_list.len() = 536 [src/main.rs:11] s.processes().len() = 536 ``` Oh I see! Very likely the `update` field that is messing up with it.
ad49264fca17c996547c173e4d8ef792c95b16d5
2022-06-07T09:09:59Z
diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -615,3 +625,19 @@ fn parse_command_line<T: Deref<Target = str> + Borrow<str>>(cmd: &[T]) -> Vec<St } command } + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_get_path() { + let mut path = PathBuf::new(); + let mut check = true; + + do_get_env_path("PATH=tadam", &mut path, &mut check); + + assert!(!check); + assert_eq!(path, PathBuf::from("tadam")); + } +}
[ "760" ]
GuillaumeGomez__sysinfo-763
GuillaumeGomez/sysinfo
diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -247,12 +247,14 @@ pub(crate) fn compute_cpu_usage( p.updated = true; }*/ +#[inline] pub(crate) fn has_been_updated(p: &mut Process) -> bool { let old = p.updated; p.updated = false; old } +#[inline] pub(crate) fn force_update(p: &mut Process) { p.updated = true; } diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -271,6 +273,7 @@ unsafe fn get_task_info(pid: Pid) -> libc::proc_taskinfo { task_info } +#[inline] fn check_if_pid_is_alive(pid: Pid) -> bool { unsafe { kill(pid.0, 0) == 0 } // For the full complete check, it'd need to be (but that seems unneeded): diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -279,6 +282,17 @@ fn check_if_pid_is_alive(pid: Pid) -> bool { // } } +#[inline] +fn do_not_get_env_path(_: &str, _: &mut PathBuf, _: &mut bool) {} + +#[inline] +fn do_get_env_path(env: &str, root: &mut PathBuf, check: &mut bool) { + if *check && env.starts_with("PATH=") { + *check = false; + *root = Path::new(&env[5..]).to_path_buf(); + } +} + pub(crate) fn update_process( wrap: &Wrap, pid: Pid, diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -471,16 +485,6 @@ pub(crate) fn update_process( cp = cp.offset(1); } - #[inline] - fn do_nothing(_: &str, _: &mut PathBuf, _: &mut bool) {} - #[inline] - fn do_something(env: &str, root: &mut PathBuf, check: &mut bool) { - if *check && env.starts_with("PATH=") { - *check = false; - *root = Path::new(&env[6..]).to_path_buf(); - } - } - #[inline] unsafe fn get_environ<F: Fn(&str, &mut PathBuf, &mut bool)>( ptr: *mut u8, diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -509,12 +513,18 @@ pub(crate) fn update_process( let (environ, root) = if exe.is_absolute() { if let Some(parent_path) = exe.parent() { - get_environ(ptr, cp, size, parent_path.to_path_buf(), do_nothing) + get_environ( + ptr, + cp, + size, + parent_path.to_path_buf(), + do_not_get_env_path, + ) } else { - get_environ(ptr, cp, size, PathBuf::new(), do_something) + get_environ(ptr, cp, size, PathBuf::new(), do_get_env_path) } } else { - get_environ(ptr, cp, size, PathBuf::new(), do_something) + get_environ(ptr, cp, size, PathBuf::new(), do_get_env_path) }; let mut p = Process::new(pid, parent, start_time, run_time);
f1557bb62eb1b6135fe2e5e7b6f406f84dac3691
Fix path panic The following lines in `src/apple/macos/process.rs` would be buggy: ``` fn do_something(env: &str, root: &mut PathBuf, check: &mut bool) { if *check && env.starts_with("PATH=") { *check = false; *root = Path::new(&env[6..]).to_path_buf(); } } ``` The length of "PATH=" is 5 so we need to change 6 to 5. Also we should handle the corner case of empty PATH. So I would propose to changing into the following: ``` fn do_something(env: &str, root: &mut PathBuf, check: &mut bool) { if *check && env.starts_with("PATH=") && env.len() > 5 { *check = false; *root = Path::new(&env[5..]).to_path_buf(); } } ``` Would also appreciate a new package can be released with the fix as soon as possible.
0.24
763
Interested into sending a fix?
ad49264fca17c996547c173e4d8ef792c95b16d5
2022-06-03T22:53:19Z
diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -316,18 +314,18 @@ mod test { let sys = System::new_with_specifics( crate::RefreshKind::new().with_cpu(CpuRefreshKind::new().with_cpu_usage()), ); - let processors = sys.processors(); - assert!(!processors.is_empty(), "no processor found"); + let cpus = sys.cpus(); + assert!(!cpus.is_empty(), "no CPU found"); if let Some(line) = stdout.lines().find(|l| l.contains("machdep.cpu.vendor")) { let sysctl_value = line.split(":").skip(1).next().unwrap(); - assert_eq!(processors[0].vendor_id(), sysctl_value.trim()); + assert_eq!(cpus[0].vendor_id(), sysctl_value.trim()); } if let Some(line) = stdout .lines() .find(|l| l.contains("machdep.cpu.brand_string")) { let sysctl_value = line.split(":").skip(1).next().unwrap(); - assert_eq!(processors[0].brand(), sysctl_value.trim()); + assert_eq!(cpus[0].brand(), sysctl_value.trim()); } } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -251,7 +251,7 @@ mod test { .processes() .iter() .all(|(_, proc_)| proc_.cpu_usage() >= 0.0 - && proc_.cpu_usage() <= (s.processors().len() as f32) * 100.0)); + && proc_.cpu_usage() <= (s.cpus().len() as f32) * 100.0)); assert!(s .processes() .iter() diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -365,11 +365,11 @@ mod test { } #[test] - fn check_processors_number() { + fn check_cpus_number() { let mut s = System::new(); // This information isn't retrieved by default. - assert!(s.processors().is_empty()); + assert!(s.cpus().is_empty()); if System::IS_SUPPORTED { // The physical cores count is recomputed every time the function is called, so the // information must be relevant even with nothing initialized. diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -378,20 +378,20 @@ mod test { .expect("failed to get number of physical cores"); s.refresh_cpu(); - // The processors shouldn't be empty anymore. - assert!(!s.processors().is_empty()); + // The cpus shouldn't be empty anymore. + assert!(!s.cpus().is_empty()); // In case we are running inside a VM, it's possible to not have a physical core, only // logical ones, which is why we don't test `physical_cores_count > 0`. let physical_cores_count2 = s .physical_core_count() .expect("failed to get number of physical cores"); - assert!(physical_cores_count2 <= s.processors().len()); + assert!(physical_cores_count2 <= s.cpus().len()); assert_eq!(physical_cores_count, physical_cores_count2); } else { assert_eq!(s.physical_core_count(), None); } - assert!(s.physical_core_count().unwrap_or(0) <= s.processors().len()); + assert!(s.physical_core_count().unwrap_or(0) <= s.cpus().len()); } #[test] diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -418,11 +418,11 @@ mod test { } let mut s = System::new(); s.refresh_processes(); - for proc_ in s.processors() { + for proc_ in s.cpus() { assert_eq!(proc_.frequency(), 0); } s.refresh_cpu(); - for proc_ in s.processors() { + for proc_ in s.cpus() { assert_ne!(proc_.frequency(), 0); } } diff --git a/tests/processor.rs b/tests/cpu.rs --- a/tests/processor.rs +++ b/tests/cpu.rs @@ -1,21 +1,21 @@ // Take a look at the license at the top of the repository in the LICENSE file. -// This test is used to ensure that the processors are not loaded by default. +// This test is used to ensure that the CPUs are not loaded by default. #[test] -fn test_processor() { - use sysinfo::{ProcessorExt, SystemExt}; +fn test_cpu() { + use sysinfo::{CpuExt, SystemExt}; if sysinfo::System::IS_SUPPORTED { let mut s = sysinfo::System::new(); - assert!(s.processors().is_empty()); + assert!(s.cpus().is_empty()); s.refresh_cpu(); - assert!(!s.processors().is_empty()); + assert!(!s.cpus().is_empty()); let s = sysinfo::System::new_all(); - assert!(!s.processors().is_empty()); + assert!(!s.cpus().is_empty()); - assert!(!s.processors()[0].brand().chars().any(|c| c == '\0')); + assert!(!s.cpus()[0].brand().chars().any(|c| c == '\0')); } }
[ "736" ]
GuillaumeGomez__sysinfo-754
GuillaumeGomez/sysinfo
diff --git a/Cargo.toml b/Cargo.toml --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "sysinfo" version = "0.23.15" authors = ["Guillaume Gomez <guillaume1.gomez@gmail.com>"] -description = "Library to get system information such as processes, processors, disks, components and networks" +description = "Library to get system information such as processes, CPUs, disks, components and networks" repository = "https://github.com/GuillaumeGomez/sysinfo" license = "MIT" readme = "README.md" diff --git a/README.md b/README.md --- a/README.md +++ b/README.md @@ -75,8 +75,8 @@ println!("System kernel version: {:?}", sys.kernel_version()); println!("System OS version: {:?}", sys.os_version()); println!("System host name: {:?}", sys.host_name()); -// Number of processors: -println!("NB processors: {}", sys.processors().len()); +// Number of CPUs: +println!("NB CPUs: {}", sys.cpus().len()); // Display processes ID, name na disk usage: for (pid, process) in sys.processes() { diff --git a/examples/simple.c b/examples/simple.c --- a/examples/simple.c +++ b/examples/simple.c @@ -69,9 +69,9 @@ int main() { printf("networks transmitted: %ld\n", sysinfo_get_networks_transmitted(system)); unsigned int len = 0, i = 0; float *procs = NULL; - sysinfo_get_processors_usage(system, &len, &procs); + sysinfo_get_cpus_usage(system, &len, &procs); while (i < len) { - printf("Processor #%d usage: %f%%\n", i, procs[i]); + printf("CPU #%d usage: %f%%\n", i, procs[i]); i += 1; } free(procs); diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -9,7 +9,7 @@ use std::io::{self, BufRead, Write}; use std::str::FromStr; use sysinfo::Signal::*; use sysinfo::{ - NetworkExt, NetworksExt, Pid, ProcessExt, ProcessorExt, Signal, System, SystemExt, UserExt, + CpuExt, NetworkExt, NetworksExt, Pid, ProcessExt, Signal, System, SystemExt, UserExt, }; const signals: &[Signal] = &[ diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -80,7 +80,7 @@ fn print_help() { ); writeln!( &mut io::stdout(), - "processors : Displays processors state" + "cpus : Displays CPUs state" ); writeln!( &mut io::stdout(), diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -112,19 +112,16 @@ fn print_help() { ); writeln!( &mut io::stdout(), - "vendor_id : Displays processor vendor id" - ); - writeln!( - &mut io::stdout(), - "brand : Displays processor brand" + "vendor_id : Displays CPU vendor id" ); + writeln!(&mut io::stdout(), "brand : Displays CPU brand"); writeln!( &mut io::stdout(), "load_avg : Displays system load average" ); writeln!( &mut io::stdout(), - "frequency : Displays processor frequency" + "frequency : Displays CPU frequency" ); writeln!(&mut io::stdout(), "users : Displays all users"); writeln!( diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -159,7 +156,7 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { nb += 1; } } - "processors" => { + "cpus" => { // Note: you should refresh a few times before using this, so that usage statistics // can be ascertained writeln!( diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -172,9 +169,9 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { writeln!( &mut io::stdout(), "total process usage: {}%", - sys.global_processor_info().cpu_usage() + sys.global_cpu_info().cpu_usage() ); - for proc_ in sys.processors() { + for proc_ in sys.cpus() { writeln!(&mut io::stdout(), "{:?}", proc_); } } diff --git a/examples/simple.rs b/examples/simple.rs --- a/examples/simple.rs +++ b/examples/simple.rs @@ -200,18 +197,18 @@ fn interpret_input(input: &str, sys: &mut System) -> bool { writeln!( &mut io::stdout(), "{} MHz", - sys.global_processor_info().frequency() + sys.global_cpu_info().frequency() ); } "vendor_id" => { writeln!( &mut io::stdout(), "vendor ID: {}", - sys.processors()[0].vendor_id() + sys.cpus()[0].vendor_id() ); } "brand" => { - writeln!(&mut io::stdout(), "brand: {}", sys.processors()[0].brand()); + writeln!(&mut io::stdout(), "brand: {}", sys.cpus()[0].brand()); } "load_avg" => { let load_avg = sys.load_average(); diff --git /dev/null b/md_doc/cpu.md new file mode 100644 --- /dev/null +++ b/md_doc/cpu.md @@ -0,0 +1,1 @@ +Struct containing information of a CPU. diff --git a/md_doc/processor.md /dev/null --- a/md_doc/processor.md +++ /dev/null @@ -1,1 +0,0 @@ -Struct containing information of a processor. diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -2,7 +2,7 @@ use crate::sys::system::get_sys_value; -use crate::{CpuRefreshKind, ProcessorExt}; +use crate::{CpuExt, CpuRefreshKind}; use libc::{c_char, host_processor_info, mach_task_self}; use std::mem; diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -22,21 +22,21 @@ impl<T> Deref for UnsafePtr<T> { } } -pub(crate) struct ProcessorData { +pub(crate) struct CpuData { pub cpu_info: UnsafePtr<i32>, pub num_cpu_info: u32, } -impl ProcessorData { - pub fn new(cpu_info: *mut i32, num_cpu_info: u32) -> ProcessorData { - ProcessorData { +impl CpuData { + pub fn new(cpu_info: *mut i32, num_cpu_info: u32) -> CpuData { + CpuData { cpu_info: UnsafePtr(cpu_info), num_cpu_info, } } } -impl Drop for ProcessorData { +impl Drop for CpuData { fn drop(&mut self) { if !self.cpu_info.0.is_null() { let prev_cpu_info_size = std::mem::size_of::<i32>() as u32 * self.num_cpu_info; diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -52,28 +52,28 @@ impl Drop for ProcessorData { } } -#[doc = include_str!("../../md_doc/processor.md")] -pub struct Processor { +#[doc = include_str!("../../md_doc/cpu.md")] +pub struct Cpu { name: String, cpu_usage: f32, - processor_data: Arc<ProcessorData>, + cpu_data: Arc<CpuData>, frequency: u64, vendor_id: String, brand: String, } -impl Processor { +impl Cpu { pub(crate) fn new( name: String, - processor_data: Arc<ProcessorData>, + cpu_data: Arc<CpuData>, frequency: u64, vendor_id: String, brand: String, - ) -> Processor { - Processor { + ) -> Cpu { + Cpu { name, cpu_usage: 0f32, - processor_data, + cpu_data, frequency, vendor_id, brand, diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -84,13 +84,13 @@ impl Processor { self.cpu_usage = cpu_usage; } - pub(crate) fn update(&mut self, cpu_usage: f32, processor_data: Arc<ProcessorData>) { + pub(crate) fn update(&mut self, cpu_usage: f32, cpu_data: Arc<CpuData>) { self.cpu_usage = cpu_usage; - self.processor_data = processor_data; + self.cpu_data = cpu_data; } - pub(crate) fn data(&self) -> Arc<ProcessorData> { - Arc::clone(&self.processor_data) + pub(crate) fn data(&self) -> Arc<CpuData> { + Arc::clone(&self.cpu_data) } pub(crate) fn set_frequency(&mut self, frequency: u64) { diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -98,7 +98,7 @@ impl Processor { } } -impl ProcessorExt for Processor { +impl CpuExt for Cpu { fn cpu_usage(&self) -> f32 { self.cpu_usage } diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -107,7 +107,7 @@ impl ProcessorExt for Processor { &self.name } - /// Returns the processor frequency in MHz. + /// Returns the CPU frequency in MHz. fn frequency(&self) -> u64 { self.frequency } diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -150,12 +150,12 @@ fn get_idle(cpu_info: *mut i32, offset: isize) -> i32 { unsafe { *cpu_info.offset(offset + libc::CPU_STATE_IDLE as isize) } } -pub(crate) fn compute_processor_usage(proc_: &Processor, cpu_info: *mut i32, offset: isize) -> f32 { +pub(crate) fn compute_usage_of_cpu(proc_: &Cpu, cpu_info: *mut i32, offset: isize) -> f32 { let old_cpu_info = proc_.data().cpu_info.0; let in_use; let total; - // In case we are initializing processors, there is no "old value" yet. + // In case we are initializing cpus, there is no "old value" yet. if old_cpu_info == cpu_info { in_use = get_in_use(cpu_info, offset); total = in_use + get_idle(cpu_info, offset); diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -166,9 +166,9 @@ pub(crate) fn compute_processor_usage(proc_: &Processor, cpu_info: *mut i32, off in_use as f32 / total as f32 * 100. } -pub(crate) fn update_processor_usage<F: FnOnce(Arc<ProcessorData>, *mut i32) -> (f32, usize)>( +pub(crate) fn update_cpu_usage<F: FnOnce(Arc<CpuData>, *mut i32) -> (f32, usize)>( port: libc::mach_port_t, - global_processor: &mut Processor, + global_cpu: &mut Cpu, f: F, ) { let mut num_cpu_u = 0u32; diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -186,20 +186,18 @@ pub(crate) fn update_processor_usage<F: FnOnce(Arc<ProcessorData>, *mut i32) -> &mut num_cpu_info as *mut u32, ) == libc::KERN_SUCCESS { - let (total_percentage, len) = f( - Arc::new(ProcessorData::new(cpu_info, num_cpu_info)), - cpu_info, - ); + let (total_percentage, len) = + f(Arc::new(CpuData::new(cpu_info, num_cpu_info)), cpu_info); total_cpu_usage = total_percentage / len as f32; } - global_processor.set_cpu_usage(total_cpu_usage); + global_cpu.set_cpu_usage(total_cpu_usage); } } -pub(crate) fn init_processors( +pub(crate) fn init_cpus( port: libc::mach_port_t, - processors: &mut Vec<Processor>, - global_processor: &mut Processor, + cpus: &mut Vec<Cpu>, + global_cpu: &mut Cpu, refresh_kind: CpuRefreshKind, ) { let mut num_cpu = 0; diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -223,11 +221,11 @@ pub(crate) fn init_processors( num_cpu = 1; } } - update_processor_usage(port, global_processor, |proc_data, cpu_info| { + update_cpu_usage(port, global_cpu, |proc_data, cpu_info| { let mut percentage = 0f32; let mut offset = 0; for i in 0..num_cpu { - let mut p = Processor::new( + let mut p = Cpu::new( format!("{}", i + 1), Arc::clone(&proc_data), frequency, diff --git a/src/apple/processor.rs b/src/apple/cpu.rs --- a/src/apple/processor.rs +++ b/src/apple/cpu.rs @@ -235,21 +233,21 @@ pub(crate) fn init_processors( brand.clone(), ); if refresh_kind.cpu_usage() { - let cpu_usage = compute_processor_usage(&p, cpu_info, offset); + let cpu_usage = compute_usage_of_cpu(&p, cpu_info, offset); p.set_cpu_usage(cpu_usage); percentage += p.cpu_usage(); } - processors.push(p); + cpus.push(p); offset += libc::CPU_STATE_MAX as isize; } - (percentage, processors.len()) + (percentage, cpus.len()) }); // We didn't set them above to avoid cloning them unnecessarily. - global_processor.brand = brand; - global_processor.vendor_id = vendor_id; - global_processor.frequency = frequency; + global_cpu.brand = brand; + global_cpu.vendor_id = vendor_id; + global_cpu.frequency = frequency; } fn get_sysctl_str(s: &[u8]) -> String { diff --git a/src/apple/mod.rs b/src/apple/mod.rs --- a/src/apple/mod.rs +++ b/src/apple/mod.rs @@ -14,18 +14,18 @@ pub(crate) use self::ios as inner; pub(crate) mod app_store; pub mod component; +pub mod cpu; pub mod disk; mod ffi; pub mod network; pub mod process; -pub mod processor; pub mod system; pub mod users; mod utils; pub use self::component::Component; +pub use self::cpu::Cpu; pub use self::disk::Disk; pub use self::network::{NetworkData, Networks}; pub use self::process::Process; -pub use self::processor::Processor; pub use self::system::System; diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -1,17 +1,17 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::component::Component; +use crate::sys::cpu::*; use crate::sys::disk::*; #[cfg(target_os = "macos")] use crate::sys::ffi; use crate::sys::network::Networks; use crate::sys::process::*; -use crate::sys::processor::*; #[cfg(target_os = "macos")] use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease}; use crate::{ - CpuRefreshKind, LoadAvg, Pid, ProcessRefreshKind, ProcessorExt, RefreshKind, SystemExt, User, + CpuExt, CpuRefreshKind, LoadAvg, Pid, ProcessRefreshKind, RefreshKind, SystemExt, User, }; #[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -84,8 +84,8 @@ pub struct System { mem_available: u64, swap_total: u64, swap_free: u64, - global_processor: Processor, - processors: Vec<Processor>, + global_cpu: Cpu, + cpus: Vec<Cpu>, page_size_kb: u64, components: Vec<Component>, // Used to get CPU information, not supported on iOS, or inside the default macOS sandbox. diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -184,14 +184,14 @@ impl SystemExt for System { mem_available: 0, swap_total: 0, swap_free: 0, - global_processor: Processor::new( + global_cpu: Cpu::new( "0".to_owned(), - Arc::new(ProcessorData::new(std::ptr::null_mut(), 0)), + Arc::new(CpuData::new(std::ptr::null_mut(), 0)), 0, String::new(), String::new(), ), - processors: Vec::new(), + cpus: Vec::new(), page_size_kb: sysconf(_SC_PAGESIZE) as u64 / 1_000, components: Vec::with_capacity(2), #[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))] diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -291,41 +291,32 @@ impl SystemExt for System { } fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind) { - let processors = &mut self.processors; - if processors.is_empty() { - init_processors( - self.port, - processors, - &mut self.global_processor, - refresh_kind, - ); + let cpus = &mut self.cpus; + if cpus.is_empty() { + init_cpus(self.port, cpus, &mut self.global_cpu, refresh_kind); self.got_cpu_frequency = refresh_kind.frequency(); return; } if refresh_kind.frequency() && !self.got_cpu_frequency { let frequency = get_cpu_frequency(); - for proc_ in processors.iter_mut() { + for proc_ in cpus.iter_mut() { proc_.set_frequency(frequency); } self.got_cpu_frequency = true; } if refresh_kind.cpu_usage() { - update_processor_usage( - self.port, - &mut self.global_processor, - |proc_data, cpu_info| { - let mut percentage = 0f32; - let mut offset = 0; - for proc_ in processors.iter_mut() { - let cpu_usage = compute_processor_usage(proc_, cpu_info, offset); - proc_.update(cpu_usage, Arc::clone(&proc_data)); - percentage += proc_.cpu_usage(); - - offset += libc::CPU_STATE_MAX as isize; - } - (percentage, processors.len()) - }, - ); + update_cpu_usage(self.port, &mut self.global_cpu, |proc_data, cpu_info| { + let mut percentage = 0f32; + let mut offset = 0; + for proc_ in cpus.iter_mut() { + let cpu_usage = compute_usage_of_cpu(proc_, cpu_info, offset); + proc_.update(cpu_usage, Arc::clone(&proc_data)); + percentage += proc_.cpu_usage(); + + offset += libc::CPU_STATE_MAX as isize; + } + (percentage, cpus.len()) + }); } } diff --git a/src/apple/system.rs b/src/apple/system.rs --- a/src/apple/system.rs +++ b/src/apple/system.rs @@ -436,12 +427,12 @@ impl SystemExt for System { self.process_list.get(&pid) } - fn global_processor_info(&self) -> &Processor { - &self.global_processor + fn global_cpu_info(&self) -> &Cpu { + &self.global_cpu } - fn processors(&self) -> &[Processor] { - &self.processors + fn cpus(&self) -> &[Cpu] { + &self.cpus } fn physical_core_count(&self) -> Option<usize> { diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -1,6 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::{NetworkExt, NetworksExt, Pid, Process, ProcessExt, ProcessorExt, System, SystemExt}; +use crate::{CpuExt, NetworkExt, NetworksExt, Pid, Process, ProcessExt, System, SystemExt}; use libc::{self, c_char, c_float, c_uint, c_void, pid_t, size_t}; use std::borrow::BorrowMut; use std::ffi::CString; diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -11,7 +11,7 @@ pub type CSystem = *mut c_void; pub type CProcess = *const c_void; /// C string returned from `CString::into_raw`. pub type RString = *const c_char; -/// Callback used by [`get_processes`][crate::System#method.processes]. +/// Callback used by [`processes`][crate::System#method.processes]. pub type ProcessLoop = extern "C" fn(pid: pid_t, process: CProcess, data: *mut c_void) -> bool; /// Equivalent of [`System::new()`][crate::System#method.new]. diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -157,9 +157,9 @@ pub extern "C" fn sysinfo_refresh_disks_list(system: CSystem) { } } -/// Equivalent of [`System::get_total_memory()`][crate::System#method.total_memory]. +/// Equivalent of [`System::total_memory()`][crate::System#method.total_memory]. #[no_mangle] -pub extern "C" fn sysinfo_get_total_memory(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_total_memory(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -169,9 +169,9 @@ pub extern "C" fn sysinfo_get_total_memory(system: CSystem) -> size_t { } } -/// Equivalent of [`System::get_free_memory()`][crate::System#method.free_memory]. +/// Equivalent of [`System::free_memory()`][crate::System#method.free_memory]. #[no_mangle] -pub extern "C" fn sysinfo_get_free_memory(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_free_memory(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -181,9 +181,9 @@ pub extern "C" fn sysinfo_get_free_memory(system: CSystem) -> size_t { } } -/// Equivalent of [`System::get_used_memory()`][crate::System#method.used_memory]. +/// Equivalent of [`System::used_memory()`][crate::System#method.used_memory]. #[no_mangle] -pub extern "C" fn sysinfo_get_used_memory(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_used_memory(system: CSystem) -> size_t { assert!(!system.is_null()); let system: Box<System> = unsafe { Box::from_raw(system as *mut System) }; let ret = system.used_memory() as size_t; diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -191,9 +191,9 @@ pub extern "C" fn sysinfo_get_used_memory(system: CSystem) -> size_t { ret } -/// Equivalent of [`System::get_total_swap()`][crate::System#method.total_swap]. +/// Equivalent of [`System::total_swap()`][crate::System#method.total_swap]. #[no_mangle] -pub extern "C" fn sysinfo_get_total_swap(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_total_swap(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -203,9 +203,9 @@ pub extern "C" fn sysinfo_get_total_swap(system: CSystem) -> size_t { } } -/// Equivalent of [`System::get_free_swap()`][crate::System#method.free_swap]. +/// Equivalent of [`System::free_swap()`][crate::System#method.free_swap]. #[no_mangle] -pub extern "C" fn sysinfo_get_free_swap(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_free_swap(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -215,9 +215,9 @@ pub extern "C" fn sysinfo_get_free_swap(system: CSystem) -> size_t { } } -/// Equivalent of [`System::get_used_swap()`][crate::System#method.used_swap]. +/// Equivalent of [`System::used_swap()`][crate::System#method.used_swap]. #[no_mangle] -pub extern "C" fn sysinfo_get_used_swap(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_used_swap(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -228,9 +228,9 @@ pub extern "C" fn sysinfo_get_used_swap(system: CSystem) -> size_t { } /// Equivalent of -/// `system::get_networks().iter().fold(0, |acc, (_, data)| acc + data.received() as size_t)`. +/// `system::networks().iter().fold(0, |acc, (_, data)| acc + data.received() as size_t)`. #[no_mangle] -pub extern "C" fn sysinfo_get_networks_received(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_networks_received(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -244,9 +244,9 @@ pub extern "C" fn sysinfo_get_networks_received(system: CSystem) -> size_t { } /// Equivalent of -/// `system::get_networks().iter().fold(0, |acc, (_, data)| acc + data.transmitted() as size_t)`. +/// `system::networks().iter().fold(0, |acc, (_, data)| acc + data.transmitted() as size_t)`. #[no_mangle] -pub extern "C" fn sysinfo_get_networks_transmitted(system: CSystem) -> size_t { +pub extern "C" fn sysinfo_networks_transmitted(system: CSystem) -> size_t { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -259,12 +259,12 @@ pub extern "C" fn sysinfo_get_networks_transmitted(system: CSystem) -> size_t { } } -/// Equivalent of [`System::get_processors_usage()`][crate::System#method.processors_usage]. +/// Equivalent of [`System::cpus_usage()`][crate::System#method.cpus_usage]. /// /// * `length` will contain the number of cpu usage added into `procs`. /// * `procs` will be allocated if it's null and will contain of cpu usage. #[no_mangle] -pub extern "C" fn sysinfo_get_processors_usage( +pub extern "C" fn sysinfo_cpus_usage( system: CSystem, length: *mut c_uint, procs: *mut *mut c_float, diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -276,28 +276,28 @@ pub extern "C" fn sysinfo_get_processors_usage( unsafe { let system: Box<System> = Box::from_raw(system as *mut System); { - let processors = system.processors(); + let cpus = system.cpus(); if (*procs).is_null() { - (*procs) = libc::malloc(::std::mem::size_of::<c_float>() * processors.len()) - as *mut c_float; + (*procs) = + libc::malloc(::std::mem::size_of::<c_float>() * cpus.len()) as *mut c_float; } - for (pos, processor) in processors.iter().skip(1).enumerate() { - (*(*procs).offset(pos as isize)) = processor.cpu_usage(); + for (pos, cpu) in cpus.iter().skip(1).enumerate() { + (*(*procs).offset(pos as isize)) = cpu.cpu_usage(); } - *length = processors.len() as c_uint - 1; + *length = cpus.len() as c_uint - 1; } Box::into_raw(system); } } -/// Equivalent of [`System::get_processes()`][crate::System#method.processes]. Returns an +/// Equivalent of [`System::processes()`][crate::System#method.processes]. Returns an /// array ended by a null pointer. Must be freed. /// /// # /!\ WARNING /!\ /// /// While having this method returned processes, you should *never* call any refresh method! #[no_mangle] -pub extern "C" fn sysinfo_get_processes( +pub extern "C" fn sysinfo_processes( system: CSystem, fn_pointer: Option<ProcessLoop>, data: *mut c_void, diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -323,14 +323,14 @@ pub extern "C" fn sysinfo_get_processes( } } -/// Equivalent of [`System::get_process()`][crate::System#method.process]. +/// Equivalent of [`System::process()`][crate::System#method.process]. /// /// # /!\ WARNING /!\ /// /// While having this method returned process, you should *never* call any /// refresh method! #[no_mangle] -pub extern "C" fn sysinfo_get_process_by_pid(system: CSystem, pid: pid_t) -> CProcess { +pub extern "C" fn sysinfo_process_by_pid(system: CSystem, pid: pid_t) -> CProcess { assert!(!system.is_null()); unsafe { let system: Box<System> = Box::from_raw(system as *mut System); diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -351,7 +351,7 @@ pub extern "C" fn sysinfo_get_process_by_pid(system: CSystem, pid: pid_t) -> CPr /// While having this method processes, you should *never* call any refresh method! #[cfg(target_os = "linux")] #[no_mangle] -pub extern "C" fn sysinfo_process_get_tasks( +pub extern "C" fn sysinfo_process_tasks( process: CProcess, fn_pointer: Option<ProcessLoop>, data: *mut c_void, diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -374,7 +374,7 @@ pub extern "C" fn sysinfo_process_get_tasks( /// Equivalent of [`Process::pid()`][crate::Process#method.pid]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_pid(process: CProcess) -> pid_t { +pub extern "C" fn sysinfo_process_pid(process: CProcess) -> pid_t { assert!(!process.is_null()); let process = process as *const Process; unsafe { (*process).pid().0 } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -384,7 +384,7 @@ pub extern "C" fn sysinfo_process_get_pid(process: CProcess) -> pid_t { /// /// In case there is no known parent, it returns `0`. #[no_mangle] -pub extern "C" fn sysinfo_process_get_parent_pid(process: CProcess) -> pid_t { +pub extern "C" fn sysinfo_process_parent_pid(process: CProcess) -> pid_t { assert!(!process.is_null()); let process = process as *const Process; unsafe { (*process).parent().unwrap_or(Pid(0)).0 } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -392,7 +392,7 @@ pub extern "C" fn sysinfo_process_get_parent_pid(process: CProcess) -> pid_t { /// Equivalent of [`Process::cpu_usage()`][crate::Process#method.cpu_usage]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_cpu_usage(process: CProcess) -> c_float { +pub extern "C" fn sysinfo_process_cpu_usage(process: CProcess) -> c_float { assert!(!process.is_null()); let process = process as *const Process; unsafe { (*process).cpu_usage() } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -400,7 +400,7 @@ pub extern "C" fn sysinfo_process_get_cpu_usage(process: CProcess) -> c_float { /// Equivalent of [`Process::memory()`][crate::Process#method.memory]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_memory(process: CProcess) -> size_t { +pub extern "C" fn sysinfo_process_memory(process: CProcess) -> size_t { assert!(!process.is_null()); let process = process as *const Process; unsafe { (*process).memory() as usize } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -408,7 +408,7 @@ pub extern "C" fn sysinfo_process_get_memory(process: CProcess) -> size_t { /// Equivalent of [`Process::virtual_memory()`][crate::Process#method.virtual_memory]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_virtual_memory(process: CProcess) -> size_t { +pub extern "C" fn sysinfo_process_virtual_memory(process: CProcess) -> size_t { assert!(!process.is_null()); let process = process as *const Process; unsafe { (*process).virtual_memory() as usize } diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -416,7 +416,7 @@ pub extern "C" fn sysinfo_process_get_virtual_memory(process: CProcess) -> size_ /// Equivalent of [`Process::exe()`][crate::Process#method.exe]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_executable_path(process: CProcess) -> RString { +pub extern "C" fn sysinfo_process_executable_path(process: CProcess) -> RString { assert!(!process.is_null()); let process = process as *const Process; unsafe { diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -431,7 +431,7 @@ pub extern "C" fn sysinfo_process_get_executable_path(process: CProcess) -> RStr /// Equivalent of [`Process::root()`][crate::Process#method.root]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_root_directory(process: CProcess) -> RString { +pub extern "C" fn sysinfo_process_root_directory(process: CProcess) -> RString { assert!(!process.is_null()); let process = process as *const Process; unsafe { diff --git a/src/c_interface.rs b/src/c_interface.rs --- a/src/c_interface.rs +++ b/src/c_interface.rs @@ -446,7 +446,7 @@ pub extern "C" fn sysinfo_process_get_root_directory(process: CProcess) -> RStri /// Equivalent of [`Process::cwd()`][crate::Process#method.cwd]. #[no_mangle] -pub extern "C" fn sysinfo_process_get_current_directory(process: CProcess) -> RString { +pub extern "C" fn sysinfo_process_current_directory(process: CProcess) -> RString { assert!(!process.is_null()); let process = process as *const Process; unsafe { diff --git a/src/common.rs b/src/common.rs --- a/src/common.rs +++ b/src/common.rs @@ -290,14 +290,14 @@ on Windows as other platforms get this information alongside the Process informa /// extra computation. /// /// ``` -/// use sysinfo::{ProcessorExt, CpuRefreshKind, System, SystemExt}; +/// use sysinfo::{CpuExt, CpuRefreshKind, System, SystemExt}; /// /// let mut system = System::new(); /// /// // We don't want to update all the CPU information. /// system.refresh_cpu_specifics(CpuRefreshKind::everything().without_frequency()); /// -/// for cpu in system.processors() { +/// for cpu in system.cpus() { /// assert_eq!(cpu.frequency(), 0); /// } /// ``` diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -1,15 +1,15 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::{ - Component, ComponentExt, Disk, DiskExt, NetworkData, NetworkExt, Networks, NetworksExt, - Process, ProcessExt, Processor, ProcessorExt, System, SystemExt, + Component, ComponentExt, Cpu, CpuExt, Disk, DiskExt, NetworkData, NetworkExt, Networks, + NetworksExt, Process, ProcessExt, System, SystemExt, }; use std::fmt; -impl fmt::Debug for Processor { +impl fmt::Debug for Cpu { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Processor") + f.debug_struct("Cpu") .field("name", &self.name()) .field("CPU usage", &self.cpu_usage()) .field("frequency", &self.frequency()) diff --git a/src/debug.rs b/src/debug.rs --- a/src/debug.rs +++ b/src/debug.rs @@ -22,16 +22,13 @@ impl fmt::Debug for Processor { impl fmt::Debug for System { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("System") - .field( - "global CPU usage", - &self.global_processor_info().cpu_usage(), - ) + .field("global CPU usage", &self.global_cpu_info().cpu_usage()) .field("load average", &self.load_average()) .field("total memory", &self.total_memory()) .field("free memory", &self.free_memory()) .field("total swap", &self.total_swap()) .field("free swap", &self.free_swap()) - .field("nb CPUs", &self.processors().len()) + .field("nb CPUs", &self.cpus().len()) .field("nb network interfaces", &self.networks().iter().count()) .field("nb processes", &self.processes().len()) .field("nb disks", &self.disks().len()) diff --git a/src/freebsd/processor.rs b/src/freebsd/cpu.rs --- a/src/freebsd/processor.rs +++ b/src/freebsd/cpu.rs @@ -1,18 +1,18 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::ProcessorExt; +use crate::CpuExt; -#[doc = include_str!("../../md_doc/processor.md")] -pub struct Processor { +#[doc = include_str!("../../md_doc/cpu.md")] +pub struct Cpu { pub(crate) cpu_usage: f32, name: String, pub(crate) vendor_id: String, pub(crate) frequency: u64, } -impl Processor { - pub(crate) fn new(name: String, vendor_id: String, frequency: u64) -> Processor { - Processor { +impl Cpu { + pub(crate) fn new(name: String, vendor_id: String, frequency: u64) -> Cpu { + Cpu { cpu_usage: 0., name, vendor_id, diff --git a/src/freebsd/processor.rs b/src/freebsd/cpu.rs --- a/src/freebsd/processor.rs +++ b/src/freebsd/cpu.rs @@ -21,7 +21,7 @@ impl Processor { } } -impl ProcessorExt for Processor { +impl CpuExt for Cpu { fn cpu_usage(&self) -> f32 { self.cpu_usage } diff --git a/src/freebsd/mod.rs b/src/freebsd/mod.rs --- a/src/freebsd/mod.rs +++ b/src/freebsd/mod.rs @@ -1,16 +1,16 @@ // Take a look at the license at the top of the repository in the LICENSE file. pub mod component; +pub mod cpu; pub mod disk; pub mod network; pub mod process; -pub mod processor; pub mod system; mod utils; pub use self::component::Component; +pub use self::cpu::Cpu; pub use self::disk::Disk; pub use self::network::{NetworkData, Networks}; pub use self::process::Process; -pub use self::processor::Processor; pub use self::system::System; diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::{ - sys::{component::Component, Disk, Networks, Process, Processor}, + sys::{component::Component, Cpu, Disk, Networks, Process}, CpuRefreshKind, LoadAvg, Pid, ProcessRefreshKind, RefreshKind, SystemExt, User, }; diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -63,8 +63,8 @@ pub struct System { mem_used: u64, swap_total: u64, swap_used: u64, - global_processor: Processor, - processors: Vec<Processor>, + global_cpu: Cpu, + cpus: Vec<Cpu>, components: Vec<Component>, disks: Vec<Disk>, networks: Networks, diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -88,8 +88,8 @@ impl SystemExt for System { mem_used: 0, swap_total: 0, swap_used: 0, - global_processor: Processor::new(String::new(), String::new(), 0), - processors: Vec::with_capacity(system_info.nb_cpus as _), + global_cpu: Cpu::new(String::new(), String::new(), 0), + cpus: Vec::with_capacity(system_info.nb_cpus as _), components: Vec::with_capacity(2), disks: Vec::with_capacity(1), networks: Networks::new(), diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -114,10 +114,10 @@ impl SystemExt for System { } fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind) { - if self.processors.is_empty() { + if self.cpus.is_empty() { let mut frequency = 0; - // We get the processor vendor ID in here. + // We get the CPU vendor ID in here. let vendor_id = get_sys_value_str_by_name(b"hw.model\0").unwrap_or_else(|| "<unknown>".to_owned()); for pos in 0..self.system_info.nb_cpus { diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -126,16 +126,16 @@ impl SystemExt for System { frequency = get_frequency_for_cpu(pos); } } - self.processors.push(Processor::new( + self.cpus.push(Cpu::new( format!("cpu {}", pos), vendor_id.clone(), frequency, )); } - self.global_processor.vendor_id = vendor_id; + self.global_cpu.vendor_id = vendor_id; self.got_cpu_frequency = refresh_kind.frequency(); } else if refresh_kind.frequency() && !self.got_cpu_frequency { - for (pos, proc_) in self.processors.iter_mut().enumerate() { + for (pos, proc_) in self.cpus.iter_mut().enumerate() { unsafe { proc_.frequency = get_frequency_for_cpu(pos as _); } diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -144,15 +144,15 @@ impl SystemExt for System { } if refresh_kind.cpu_usage() { self.system_info - .get_cpu_usage(&mut self.global_processor, &mut self.processors); + .get_cpu_usage(&mut self.global_cpu, &mut self.cpus); } } fn refresh_components_list(&mut self) { - if self.processors.is_empty() { + if self.cpus.is_empty() { self.refresh_cpu(); } - self.components = unsafe { super::component::get_components(self.processors.len()) }; + self.components = unsafe { super::component::get_components(self.cpus.len()) }; } fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -242,12 +242,12 @@ impl SystemExt for System { &mut self.networks } - fn global_processor_info(&self) -> &Processor { - &self.global_processor + fn global_cpu_info(&self) -> &Cpu { + &self.global_cpu } - fn processors(&self) -> &[Processor] { - &self.processors + fn cpus(&self) -> &[Cpu] { + &self.cpus } fn physical_core_count(&self) -> Option<usize> { diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -503,7 +503,7 @@ struct SystemInfo { mib_cp_times: [c_int; 2], // For the global CPU usage. cp_time: utils::VecSwitcher<libc::c_ulong>, - // For each processor CPU usage. + // For each CPU usage. cp_times: utils::VecSwitcher<libc::c_ulong>, /// From FreeBSD manual: "The kernel fixed-point scale factor". It's used when computing /// processes' CPU usage. diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -708,23 +708,19 @@ impl SystemInfo { } } - fn get_cpu_usage(&mut self, global: &mut Processor, processors: &mut [Processor]) { + fn get_cpu_usage(&mut self, global: &mut Cpu, cpus: &mut [Cpu]) { unsafe { get_sys_value_array(&self.mib_cp_time, self.cp_time.get_mut()); get_sys_value_array(&self.mib_cp_times, self.cp_times.get_mut()); } - fn fill_processor( - proc_: &mut Processor, - new_cp_time: &[libc::c_ulong], - old_cp_time: &[libc::c_ulong], - ) { + fn fill_cpu(proc_: &mut Cpu, new_cp_time: &[libc::c_ulong], old_cp_time: &[libc::c_ulong]) { let mut total_new: u64 = 0; let mut total_old: u64 = 0; let mut cp_diff: libc::c_ulong = 0; for i in 0..(libc::CPUSTATES as usize) { - // We obviously don't want to get the idle part of the processor usage, otherwise + // We obviously don't want to get the idle part of the CPU usage, otherwise // we would always be at 100%... if i != libc::CP_IDLE as usize { cp_diff += new_cp_time[i] - old_cp_time[i]; diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -741,13 +737,13 @@ impl SystemInfo { } } - fill_processor(global, self.cp_time.get_new(), self.cp_time.get_old()); + fill_cpu(global, self.cp_time.get_new(), self.cp_time.get_old()); let old_cp_times = self.cp_times.get_old(); let new_cp_times = self.cp_times.get_new(); - for (pos, proc_) in processors.iter_mut().enumerate() { + for (pos, proc_) in cpus.iter_mut().enumerate() { let index = pos * libc::CPUSTATES as usize; - fill_processor(proc_, &new_cp_times[index..], &old_cp_times[index..]); + fill_cpu(proc_, &new_cp_times[index..], &old_cp_times[index..]); } } diff --git a/src/lib.rs b/src/lib.rs --- a/src/lib.rs +++ b/src/lib.rs @@ -62,9 +62,9 @@ pub use common::{ get_current_pid, CpuRefreshKind, DiskType, DiskUsage, Gid, LoadAvg, NetworksIter, Pid, PidExt, ProcessRefreshKind, ProcessStatus, RefreshKind, Signal, Uid, User, }; -pub use sys::{Component, Disk, NetworkData, Networks, Process, Processor, System}; +pub use sys::{Component, Cpu, Disk, NetworkData, Networks, Process, System}; pub use traits::{ - ComponentExt, DiskExt, NetworkExt, NetworksExt, ProcessExt, ProcessorExt, SystemExt, UserExt, + ComponentExt, CpuExt, DiskExt, NetworkExt, NetworksExt, ProcessExt, SystemExt, UserExt, }; #[cfg(feature = "c-interface")] diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -6,7 +6,7 @@ use std::collections::HashSet; use std::fs::File; use std::io::Read; -use crate::ProcessorExt; +use crate::CpuExt; /// Struct containing values to compute a CPU usage. #[derive(Clone, Copy)] diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -112,8 +112,8 @@ impl CpuValues { } } -#[doc = include_str!("../../md_doc/processor.md")] -pub struct Processor { +#[doc = include_str!("../../md_doc/cpu.md")] +pub struct Cpu { old_values: CpuValues, new_values: CpuValues, pub(crate) name: String, diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -125,7 +125,7 @@ pub struct Processor { pub(crate) brand: String, } -impl Processor { +impl Cpu { pub(crate) fn new_with_values( name: &str, user: u64, diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -141,8 +141,8 @@ impl Processor { frequency: u64, vendor_id: String, brand: String, - ) -> Processor { - Processor { + ) -> Cpu { + Cpu { name: name.to_owned(), old_values: CpuValues::new(), new_values: CpuValues::new_with_values( diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -194,7 +194,7 @@ impl Processor { } } -impl ProcessorExt for Processor { +impl CpuExt for Cpu { fn cpu_usage(&self) -> f32 { self.cpu_usage } diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -217,7 +217,7 @@ impl ProcessorExt for Processor { } } -pub(crate) fn get_raw_times(p: &Processor) -> (u64, u64) { +pub(crate) fn get_raw_times(p: &Cpu) -> (u64, u64) { (p.total_time, p.old_total_time) } diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -266,31 +266,31 @@ pub(crate) fn get_physical_core_count() -> Option<usize> { } macro_rules! add_core { - ($core_ids_and_physical_ids:ident, $core_id:ident, $physical_id:ident, $processor:ident) => {{ + ($core_ids_and_physical_ids:ident, $core_id:ident, $physical_id:ident, $cpu:ident) => {{ if !$core_id.is_empty() && !$physical_id.is_empty() { $core_ids_and_physical_ids.insert(format!("{} {}", $core_id, $physical_id)); - } else if !$processor.is_empty() { + } else if !$cpu.is_empty() { // On systems with only physical cores like raspberry, there is no "core id" or - // "physical id" fields. So if one of them is missing, we simply use the "processor" + // "physical id" fields. So if one of them is missing, we simply use the "CPU" // info and count it as a physical core. - $core_ids_and_physical_ids.insert($processor.to_owned()); + $core_ids_and_physical_ids.insert($cpu.to_owned()); } $core_id = ""; $physical_id = ""; - $processor = ""; + $cpu = ""; }}; } let mut core_ids_and_physical_ids: HashSet<String> = HashSet::new(); let mut core_id = ""; let mut physical_id = ""; - let mut processor = ""; + let mut cpu = ""; for line in s.lines() { if line.is_empty() { - add_core!(core_ids_and_physical_ids, core_id, physical_id, processor); + add_core!(core_ids_and_physical_ids, core_id, physical_id, cpu); } else if line.starts_with("processor") { - processor = line + cpu = line .splitn(2, ':') .last() .map(|x| x.trim()) diff --git a/src/linux/processor.rs b/src/linux/cpu.rs --- a/src/linux/processor.rs +++ b/src/linux/cpu.rs @@ -309,7 +309,7 @@ pub(crate) fn get_physical_core_count() -> Option<usize> { .unwrap_or_default(); } } - add_core!(core_ids_and_physical_ids, core_id, physical_id, processor); + add_core!(core_ids_and_physical_ids, core_id, physical_id, cpu); Some(core_ids_and_physical_ids.len()) } diff --git a/src/linux/mod.rs b/src/linux/mod.rs --- a/src/linux/mod.rs +++ b/src/linux/mod.rs @@ -1,16 +1,16 @@ // Take a look at the license at the top of the repository in the LICENSE file. pub mod component; +pub mod cpu; pub mod disk; pub mod network; pub mod process; -pub mod processor; pub mod system; pub(crate) mod utils; pub use self::component::Component; +pub use self::cpu::Cpu; pub use self::disk::Disk; pub use self::network::{NetworkData, Networks}; pub use self::process::Process; -pub use self::processor::Processor; pub use self::system::System; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -1,9 +1,9 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::component::{self, Component}; +use crate::sys::cpu::*; use crate::sys::disk; use crate::sys::process::*; -use crate::sys::processor::*; use crate::sys::utils::get_all_data; use crate::{ CpuRefreshKind, Disk, LoadAvg, Networks, Pid, ProcessRefreshKind, RefreshKind, SystemExt, User, diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -166,17 +166,17 @@ pub struct System { mem_slab_reclaimable: u64, swap_total: u64, swap_free: u64, - global_processor: Processor, - processors: Vec<Processor>, + global_cpu: Cpu, + cpus: Vec<Cpu>, components: Vec<Component>, disks: Vec<Disk>, networks: Networks, users: Vec<User>, - /// Field set to `false` in `update_processors` and to `true` in `refresh_processes_specifics`. + /// Field set to `false` in `update_cpus` and to `true` in `refresh_processes_specifics`. /// - /// The reason behind this is to avoid calling the `update_processors` more than necessary. + /// The reason behind this is to avoid calling the `update_cpus` more than necessary. /// For example when running `refresh_all` or `refresh_specifics`. - need_processors_update: bool, + need_cpus_update: bool, info: SystemInfo, got_cpu_frequency: bool, } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -188,23 +188,23 @@ impl System { /// To prevent that, we compute ahead of time this maximum value and ensure that processes' /// CPU usage don't go over it. fn get_max_process_cpu_usage(&self) -> f32 { - self.processors.len() as f32 * 100. + self.cpus.len() as f32 * 100. } fn clear_procs(&mut self, refresh_kind: ProcessRefreshKind) { let (total_time, compute_cpu, max_value) = if refresh_kind.cpu() { - if self.need_processors_update { - self.refresh_processors(true, CpuRefreshKind::new().with_cpu_usage()); + if self.need_cpus_update { + self.refresh_cpus(true, CpuRefreshKind::new().with_cpu_usage()); } - if self.processors.is_empty() { - sysinfo_debug!("cannot compute processes CPU usage: no processor found..."); + if self.cpus.is_empty() { + sysinfo_debug!("cannot compute processes CPU usage: no CPU found..."); (0., false, 0.) } else { - let (new, old) = get_raw_times(&self.global_processor); + let (new, old) = get_raw_times(&self.global_cpu); let total_time = if old > new { 1 } else { new - old }; ( - total_time as f32 / self.processors.len() as f32, + total_time as f32 / self.cpus.len() as f32, true, self.get_max_process_cpu_usage(), ) diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -225,17 +225,13 @@ impl System { }); } - fn refresh_processors( - &mut self, - only_update_global_processor: bool, - refresh_kind: CpuRefreshKind, - ) { + fn refresh_cpus(&mut self, only_update_global_cpu: bool, refresh_kind: CpuRefreshKind) { if let Ok(f) = File::open("/proc/stat") { - self.need_processors_update = false; + self.need_cpus_update = false; let buf = BufReader::new(f); let mut i: usize = 0; - let first = self.processors.is_empty(); + let first = self.cpus.is_empty(); let mut it = buf.split(b'\n'); let (vendor_id, brand) = if first { get_vendor_id_and_brand() diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -250,12 +246,11 @@ impl System { } let mut parts = line.split(|x| *x == b' ').filter(|s| !s.is_empty()); if first { - self.global_processor.name = - to_str!(parts.next().unwrap_or(&[])).to_owned(); + self.global_cpu.name = to_str!(parts.next().unwrap_or(&[])).to_owned(); } else { parts.next(); } - self.global_processor.set( + self.global_cpu.set( parts.next().map(to_u64).unwrap_or(0), parts.next().map(to_u64).unwrap_or(0), parts.next().map(to_u64).unwrap_or(0), diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -268,7 +263,7 @@ impl System { parts.next().map(to_u64).unwrap_or(0), ); } - if first || !only_update_global_processor { + if first || !only_update_global_cpu { while let Some(Ok(line)) = it.next() { if &line[..3] != b"cpu" { break; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -276,7 +271,7 @@ impl System { let mut parts = line.split(|x| *x == b' ').filter(|s| !s.is_empty()); if first { - self.processors.push(Processor::new_with_values( + self.cpus.push(Cpu::new_with_values( to_str!(parts.next().unwrap_or(&[])), parts.next().map(to_u64).unwrap_or(0), parts.next().map(to_u64).unwrap_or(0), diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -294,7 +289,7 @@ impl System { )); } else { parts.next(); // we don't want the name again - self.processors[i].set( + self.cpus[i].set( parts.next().map(to_u64).unwrap_or(0), parts.next().map(to_u64).unwrap_or(0), parts.next().map(to_u64).unwrap_or(0), diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -331,12 +326,12 @@ impl System { } #[cfg(not(feature = "multithread"))] - fn iter_mut<'a>(val: &'a mut Vec<Processor>) -> std::slice::IterMut<'a, Processor> { + fn iter_mut<'a>(val: &'a mut Vec<Cpu>) -> std::slice::IterMut<'a, Cpu> { val.iter_mut() } // `get_cpu_frequency` is very slow, so better run it in parallel. - self.global_processor.frequency = iter_mut(&mut self.processors) + self.global_cpu.frequency = iter_mut(&mut self.cpus) .enumerate() .map(|(pos, proc_)| { proc_.frequency = get_cpu_frequency(pos); diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -349,8 +344,8 @@ impl System { } if first { - self.global_processor.vendor_id = vendor_id; - self.global_processor.brand = brand; + self.global_cpu.vendor_id = vendor_id; + self.global_cpu.brand = brand; } } } diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -373,7 +368,7 @@ impl SystemExt for System { mem_slab_reclaimable: 0, swap_total: 0, swap_free: 0, - global_processor: Processor::new_with_values( + global_cpu: Cpu::new_with_values( "", 0, 0, diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -389,12 +384,12 @@ impl SystemExt for System { String::new(), String::new(), ), - processors: Vec::with_capacity(4), + cpus: Vec::with_capacity(4), components: Vec::new(), disks: Vec::with_capacity(2), networks: Networks::new(), users: Vec::new(), - need_processors_update: true, + need_cpus_update: true, info, got_cpu_frequency: false, }; diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -432,7 +427,7 @@ impl SystemExt for System { } fn refresh_cpu_specifics(&mut self, refresh_kind: CpuRefreshKind) { - self.refresh_processors(false, refresh_kind); + self.refresh_cpus(false, refresh_kind); } fn refresh_processes_specifics(&mut self, refresh_kind: ProcessRefreshKind) { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -446,7 +441,7 @@ impl SystemExt for System { refresh_kind, ); self.clear_procs(refresh_kind); - self.need_processors_update = true; + self.need_cpus_update = true; } fn refresh_process_specifics(&mut self, pid: Pid, refresh_kind: ProcessRefreshKind) -> bool { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -468,18 +463,18 @@ impl SystemExt for System { }; if found { if refresh_kind.cpu() { - self.refresh_processors(true, CpuRefreshKind::new().with_cpu_usage()); + self.refresh_cpus(true, CpuRefreshKind::new().with_cpu_usage()); - if self.processors.is_empty() { - sysinfo_debug!("Cannot compute process CPU usage: no processors found..."); + if self.cpus.is_empty() { + sysinfo_debug!("Cannot compute process CPU usage: no cpus found..."); return found; } - let (new, old) = get_raw_times(&self.global_processor); + let (new, old) = get_raw_times(&self.global_cpu); let total_time = (if old >= new { 1 } else { new - old }) as f32; let max_cpu_usage = self.get_max_process_cpu_usage(); if let Some(p) = self.process_list.tasks.get_mut(&pid) { - compute_cpu_usage(p, total_time / self.processors.len() as f32, max_cpu_usage); + compute_cpu_usage(p, total_time / self.cpus.len() as f32, max_cpu_usage); p.updated = false; } } else if let Some(p) = self.process_list.tasks.get_mut(&pid) { diff --git a/src/linux/system.rs b/src/linux/system.rs --- a/src/linux/system.rs +++ b/src/linux/system.rs @@ -517,12 +512,12 @@ impl SystemExt for System { &mut self.networks } - fn global_processor_info(&self) -> &Processor { - &self.global_processor + fn global_cpu_info(&self) -> &Cpu { + &self.global_cpu } - fn processors(&self) -> &[Processor] { - &self.processors + fn cpus(&self) -> &[Cpu] { + &self.cpus } fn physical_core_count(&self) -> Option<usize> { diff --git a/src/sysinfo.h b/src/sysinfo.h --- a/src/sysinfo.h +++ b/src/sysinfo.h @@ -27,7 +27,7 @@ size_t sysinfo_get_free_swap(CSystem system); size_t sysinfo_get_used_swap(CSystem system); size_t sysinfo_get_network_income(CSystem system); size_t sysinfo_get_network_outcome(CSystem system); -void sysinfo_get_processors_usage(CSystem system, unsigned int *length, float **procs); +void sysinfo_get_cpus_usage(CSystem system, unsigned int *length, float **cpus); size_t sysinfo_get_processes(CSystem system, bool (*fn_pointer)(pid_t, CProcess, void*), void *data); #ifdef __linux__ diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -2,7 +2,7 @@ use crate::{ common::{Gid, Uid}, - sys::{Component, Disk, Networks, Process, Processor}, + sys::{Component, Cpu, Disk, Networks, Process}, }; use crate::{ CpuRefreshKind, DiskType, DiskUsage, LoadAvg, NetworksIter, Pid, ProcessRefreshKind, diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -334,7 +334,7 @@ pub trait ProcessExt: Debug { /// multicore machine. /// /// If you want a value between 0% and 100%, divide the returned value by the number of CPU - /// processors. + /// CPUs. /// /// **Warning**: If you want accurate CPU usage number, better leave a bit of time /// between two calls of this method (200 ms for example). diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -402,67 +402,67 @@ pub trait ProcessExt: Debug { fn group_id(&self) -> Option<Gid>; } -/// Contains all the methods of the [`Processor`][crate::Processor] struct. -pub trait ProcessorExt: Debug { - /// Returns this processor's usage. +/// Contains all the methods of the [`Cpu`][crate::Cpu] struct. +pub trait CpuExt: Debug { + /// Returns this CPU's usage. /// /// Note: You'll need to refresh it at least twice (diff between the first and the second is /// how CPU usage is computed) at first if you want to have a non-zero value. /// /// ```no_run - /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// use sysinfo::{CpuExt, System, SystemExt}; /// /// let s = System::new(); - /// for processor in s.processors() { - /// println!("{}%", processor.cpu_usage()); + /// for cpu in s.cpus() { + /// println!("{}%", cpu.cpu_usage()); /// } /// ``` fn cpu_usage(&self) -> f32; - /// Returns this processor's name. + /// Returns this CPU's name. /// /// ```no_run - /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// use sysinfo::{CpuExt, System, SystemExt}; /// /// let s = System::new(); - /// for processor in s.processors() { - /// println!("{}", processor.name()); + /// for cpu in s.cpus() { + /// println!("{}", cpu.name()); /// } /// ``` fn name(&self) -> &str; - /// Returns the processor's vendor id. + /// Returns the CPU's vendor id. /// /// ```no_run - /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// use sysinfo::{CpuExt, System, SystemExt}; /// /// let s = System::new(); - /// for processor in s.processors() { - /// println!("{}", processor.vendor_id()); + /// for cpu in s.cpus() { + /// println!("{}", cpu.vendor_id()); /// } /// ``` fn vendor_id(&self) -> &str; - /// Returns the processor's brand. + /// Returns the CPU's brand. /// /// ```no_run - /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// use sysinfo::{CpuExt, System, SystemExt}; /// /// let s = System::new(); - /// for processor in s.processors() { - /// println!("{}", processor.brand()); + /// for cpu in s.cpus() { + /// println!("{}", cpu.brand()); /// } /// ``` fn brand(&self) -> &str; - /// Returns the processor's frequency. + /// Returns the CPU's frequency. /// /// ```no_run - /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// use sysinfo::{CpuExt, System, SystemExt}; /// /// let s = System::new(); - /// for processor in s.processors() { - /// println!("{}", processor.frequency()); + /// for cpu in s.cpus() { + /// println!("{}", cpu.frequency()); /// } /// ``` fn frequency(&self) -> u64; diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -494,7 +494,7 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { /// ``` const SUPPORTED_SIGNALS: &'static [Signal]; - /// Creates a new [`System`] instance with nothing loaded except the processors list. If you + /// Creates a new [`System`] instance with nothing loaded except the cpus list. If you /// want to load components, network interfaces or the disks, you'll have to use the /// `refresh_*_list` methods. [`SystemExt::refresh_networks_list`] for example. /// diff --git a/src/traits.rs b/src/traits.rs --- a/src/traits.rs +++ b/src/traits.rs @@ -911,46 +911,46 @@ pub trait SystemExt: Sized + Debug + Default + Send + Sync { ) } - /// Returns "global" processors information (aka the addition of all the processors). + /// Returns "global" cpus information (aka the addition of all the CPUs). /// /// To have up-to-date information, you need to call [`SystemExt::refresh_cpu`] or /// [`SystemExt::refresh_specifics`] with `cpu` enabled. /// /// ```no_run - /// use sysinfo::{CpuRefreshKind, ProcessorExt, RefreshKind, System, SystemExt}; + /// use sysinfo::{CpuRefreshKind, CpuExt, RefreshKind, System, SystemExt}; /// /// let s = System::new_with_specifics( /// RefreshKind::new().with_cpu(CpuRefreshKind::everything()), /// ); - /// println!("{}%", s.global_processor_info().cpu_usage()); + /// println!("{}%", s.global_cpu_info().cpu_usage()); /// ``` - fn global_processor_info(&self) -> &Processor; + fn global_cpu_info(&self) -> &Cpu; - /// Returns the list of the processors. + /// Returns the list of the CPUs. /// - /// By default, the list of processors is empty until you call [`SystemExt::refresh_cpu`] or + /// By default, the list of cpus is empty until you call [`SystemExt::refresh_cpu`] or /// [`SystemExt::refresh_specifics`] with `cpu` enabled. /// /// ```no_run - /// use sysinfo::{CpuRefreshKind, ProcessorExt, RefreshKind, System, SystemExt}; + /// use sysinfo::{CpuRefreshKind, CpuExt, RefreshKind, System, SystemExt}; /// /// let s = System::new_with_specifics( /// RefreshKind::new().with_cpu(CpuRefreshKind::everything()), /// ); - /// for processor in s.processors() { - /// println!("{}%", processor.cpu_usage()); + /// for cpu in s.cpus() { + /// println!("{}%", cpu.cpu_usage()); /// } /// ``` - fn processors(&self) -> &[Processor]; + fn cpus(&self) -> &[Cpu]; - /// Returns the number of physical cores on the processor or `None` if it couldn't get it. + /// Returns the number of physical cores on the CPU or `None` if it couldn't get it. /// /// In case there are multiple CPUs, it will combine the physical core count of all the CPUs. /// /// **Important**: this information is computed every time this function is called. /// /// ```no_run - /// use sysinfo::{ProcessorExt, System, SystemExt}; + /// use sysinfo::{CpuExt, System, SystemExt}; /// /// let s = System::new(); /// println!("{:?}", s.physical_core_count()); diff --git a/src/unknown/processor.rs b/src/unknown/cpu.rs --- a/src/unknown/processor.rs +++ b/src/unknown/cpu.rs @@ -1,17 +1,17 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::ProcessorExt; +use crate::CpuExt; -#[doc = include_str!("../../md_doc/processor.md")] -pub struct Processor {} +#[doc = include_str!("../../md_doc/cpu.md")] +pub struct Cpu {} -impl Processor { - pub(crate) fn new() -> Processor { - Processor {} +impl Cpu { + pub(crate) fn new() -> Cpu { + Cpu {} } } -impl ProcessorExt for Processor { +impl CpuExt for Cpu { fn cpu_usage(&self) -> f32 { 0.0 } diff --git a/src/unknown/mod.rs b/src/unknown/mod.rs --- a/src/unknown/mod.rs +++ b/src/unknown/mod.rs @@ -1,15 +1,15 @@ // Take a look at the license at the top of the repository in the LICENSE file. pub mod component; +pub mod cpu; pub mod disk; pub mod network; pub mod process; -pub mod processor; pub mod system; pub use self::component::Component; +pub use self::cpu::Cpu; pub use self::disk::Disk; pub use self::network::{NetworkData, Networks}; pub use self::process::Process; -pub use self::processor::Processor; pub use self::system::System; diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::{ - sys::{component::Component, Disk, Networks, Process, Processor}, + sys::{component::Component, Cpu, Disk, Networks, Process}, CpuRefreshKind, LoadAvg, Pid, ProcessRefreshKind, RefreshKind, SystemExt, User, }; diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -16,7 +16,7 @@ declare_signals! { pub struct System { processes_list: HashMap<Pid, Process>, networks: Networks, - global_processor: Processor, + global_cpu: Cpu, } impl SystemExt for System { diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -27,7 +27,7 @@ impl SystemExt for System { System { processes_list: Default::default(), networks: Networks::new(), - global_processor: Processor::new(), + global_cpu: Cpu::new(), } } diff --git a/src/unknown/system.rs b/src/unknown/system.rs --- a/src/unknown/system.rs +++ b/src/unknown/system.rs @@ -67,11 +67,11 @@ impl SystemExt for System { &mut self.networks } - fn global_processor_info(&self) -> &Processor { - &self.global_processor + fn global_cpu_info(&self) -> &Cpu { + &self.global_cpu } - fn processors(&self) -> &[Processor] { + fn cpus(&self) -> &[Cpu] { &[] } diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -1,7 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use crate::sys::tools::KeyHandler; -use crate::{CpuRefreshKind, LoadAvg, ProcessorExt}; +use crate::{CpuExt, CpuRefreshKind, LoadAvg}; use std::collections::HashMap; use std::io::Error; diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -91,13 +91,13 @@ unsafe fn init_load_avg() -> Mutex<Option<LoadAvg>> { let mut counter: PDH_HCOUNTER = mem::zeroed(); if PdhAddEnglishCounterA( query, - b"\\System\\Processor Queue Length\0".as_ptr() as _, + b"\\System\\Cpu Queue Length\0".as_ptr() as _, 0, &mut counter, ) != ERROR_SUCCESS as _ { PdhCloseQuery(query); - sysinfo_debug!("init_load_avg: failed to get processor queue length"); + sysinfo_debug!("init_load_avg: failed to get CPU queue length"); return Mutex::new(None); } diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -240,42 +240,37 @@ impl Query { } } -pub(crate) struct ProcessorsWrapper { - global: Processor, - processors: Vec<Processor>, +pub(crate) struct CpusWrapper { + global: Cpu, + cpus: Vec<Cpu>, got_cpu_frequency: bool, } -impl ProcessorsWrapper { +impl CpusWrapper { pub fn new() -> Self { Self { - global: Processor::new_with_values( - "Total CPU".to_owned(), - String::new(), - String::new(), - 0, - ), - processors: Vec::new(), + global: Cpu::new_with_values("Total CPU".to_owned(), String::new(), String::new(), 0), + cpus: Vec::new(), got_cpu_frequency: false, } } - pub fn global_processor(&self) -> &Processor { + pub fn global_cpu(&self) -> &Cpu { &self.global } - pub fn global_processor_mut(&mut self) -> &mut Processor { + pub fn global_cpu_mut(&mut self) -> &mut Cpu { &mut self.global } - pub fn processors(&self) -> &[Processor] { - &self.processors + pub fn cpus(&self) -> &[Cpu] { + &self.cpus } fn init_if_needed(&mut self, refresh_kind: CpuRefreshKind) { - if self.processors.is_empty() { - let (processors, vendor_id, brand) = super::tools::init_processors(refresh_kind); - self.processors = processors; + if self.cpus.is_empty() { + let (cpus, vendor_id, brand) = super::tools::init_cpus(refresh_kind); + self.cpus = cpus; self.global.vendor_id = vendor_id; self.global.brand = brand; self.got_cpu_frequency = refresh_kind.frequency(); diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -284,32 +279,29 @@ impl ProcessorsWrapper { pub fn len(&mut self) -> usize { self.init_if_needed(CpuRefreshKind::new()); - self.processors.len() + self.cpus.len() } - pub fn iter_mut( - &mut self, - refresh_kind: CpuRefreshKind, - ) -> impl Iterator<Item = &mut Processor> { + pub fn iter_mut(&mut self, refresh_kind: CpuRefreshKind) -> impl Iterator<Item = &mut Cpu> { self.init_if_needed(refresh_kind); - self.processors.iter_mut() + self.cpus.iter_mut() } pub fn get_frequencies(&mut self) { if self.got_cpu_frequency { return; } - let frequencies = get_frequencies(self.processors.len()); + let frequencies = get_frequencies(self.cpus.len()); - for (processor, frequency) in self.processors.iter_mut().zip(frequencies) { - processor.set_frequency(frequency); + for (cpu, frequency) in self.cpus.iter_mut().zip(frequencies) { + cpu.set_frequency(frequency); } self.got_cpu_frequency = true; } } -#[doc = include_str!("../../md_doc/processor.md")] -pub struct Processor { +#[doc = include_str!("../../md_doc/cpu.md")] +pub struct Cpu { name: String, cpu_usage: f32, key_used: Option<KeyHandler>, diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -318,7 +310,7 @@ pub struct Processor { frequency: u64, } -impl ProcessorExt for Processor { +impl CpuExt for Cpu { fn cpu_usage(&self) -> f32 { self.cpu_usage } diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -340,14 +332,14 @@ impl ProcessorExt for Processor { } } -impl Processor { +impl Cpu { pub(crate) fn new_with_values( name: String, vendor_id: String, brand: String, frequency: u64, - ) -> Processor { - Processor { + ) -> Cpu { + Cpu { name, cpu_usage: 0f32, key_used: None, diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -466,18 +458,18 @@ pub(crate) fn get_vendor_id_and_brand(info: &SYSTEM_INFO) -> (String, String) { (get_vendor_id_not_great(info), String::new()) } -pub(crate) fn get_key_used(p: &mut Processor) -> &mut Option<KeyHandler> { +pub(crate) fn get_key_used(p: &mut Cpu) -> &mut Option<KeyHandler> { &mut p.key_used } // From https://stackoverflow.com/a/43813138: // -// If your PC has 64 or fewer logical processors installed, the above code will work fine. However, -// if your PC has more than 64 logical processors installed, use GetActiveProcessorCount() or -// GetLogicalProcessorInformation() to determine the total number of logical processors installed. -pub(crate) fn get_frequencies(nb_processors: usize) -> Vec<u64> { - let size = nb_processors * mem::size_of::<PROCESSOR_POWER_INFORMATION>(); - let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_processors); +// If your PC has 64 or fewer logical cpus installed, the above code will work fine. However, +// if your PC has more than 64 logical cpus installed, use GetActiveCpuCount() or +// GetLogicalCpuInformation() to determine the total number of logical cpus installed. +pub(crate) fn get_frequencies(nb_cpus: usize) -> Vec<u64> { + let size = nb_cpus * mem::size_of::<PROCESSOR_POWER_INFORMATION>(); + let mut infos: Vec<PROCESSOR_POWER_INFORMATION> = Vec::with_capacity(nb_cpus); unsafe { if CallNtPowerInformation( diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -488,7 +480,7 @@ pub(crate) fn get_frequencies(nb_processors: usize) -> Vec<u64> { size as _, ) == 0 { - infos.set_len(nb_processors); + infos.set_len(nb_cpus); // infos.Number return infos .into_iter() diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -497,15 +489,15 @@ pub(crate) fn get_frequencies(nb_processors: usize) -> Vec<u64> { } } sysinfo_debug!("get_frequencies: CallNtPowerInformation failed"); - vec![0; nb_processors] + vec![0; nb_cpus] } pub(crate) fn get_physical_core_count() -> Option<usize> { - // we cannot use the number of processors here to pre calculate the buf size - // GetLogicalProcessorInformationEx with RelationProcessorCore passed to it not only returns + // we cannot use the number of cpus here to pre calculate the buf size + // GetLogicalCpuInformationEx with RelationProcessorCore passed to it not only returns // the logical cores but also numa nodes // - // GetLogicalProcessorInformationEx: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformationex + // GetLogicalCpuInformationEx: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformationex let mut needed_size = 0; unsafe { diff --git a/src/windows/processor.rs b/src/windows/cpu.rs --- a/src/windows/processor.rs +++ b/src/windows/cpu.rs @@ -526,7 +518,7 @@ pub(crate) fn get_physical_core_count() -> Option<usize> { Some(value) if value == ERROR_INSUFFICIENT_BUFFER as _ => {} _ => { sysinfo_debug!( - "get_physical_core_count: GetLogicalProcessorInformationEx failed" + "get_physical_core_count: GetLogicalCpuInformationEx failed" ); return None; } diff --git a/src/windows/mod.rs b/src/windows/mod.rs --- a/src/windows/mod.rs +++ b/src/windows/mod.rs @@ -1,21 +1,20 @@ // Take a look at the license at the top of the repository in the LICENSE file. mod component; +mod cpu; mod disk; #[macro_use] mod macros; mod network; mod process; -mod processor; mod system; mod tools; mod users; mod utils; pub use self::component::Component; +pub use self::cpu::Cpu; pub use self::disk::Disk; pub use self::network::{NetworkData, Networks}; pub use self::process::Process; -pub use self::processor::Processor; pub use self::system::System; -pub(crate) use self::users::to_str; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -1,5 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. +use crate::sys::utils::to_str; use crate::{DiskUsage, Gid, Pid, ProcessExt, ProcessRefreshKind, ProcessStatus, Signal, Uid}; use std::ffi::OsString; diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -148,9 +149,7 @@ unsafe fn get_process_user_id( ); None } else { - Some(Uid( - crate::windows::to_str(name.as_mut_ptr()).into_boxed_str() - )) + Some(Uid(to_str(name.as_mut_ptr()).into_boxed_str())) } } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -436,11 +435,11 @@ impl Process { pub(crate) fn update( &mut self, refresh_kind: crate::ProcessRefreshKind, - nb_processors: u64, + nb_cpus: u64, now: u64, ) { if refresh_kind.cpu() { - compute_cpu_usage(self, nb_processors); + compute_cpu_usage(self, nb_cpus); } if refresh_kind.disk_usage() { update_disk_usage(self); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -903,7 +902,7 @@ fn check_sub(a: u64, b: u64) -> u64 { /// Before changing this function, you must consider the following: /// https://github.com/GuillaumeGomez/sysinfo/issues/459 -pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64) { +pub(crate) fn compute_cpu_usage(p: &mut Process, nb_cpus: u64) { unsafe { let mut ftime: FILETIME = zeroed(); let mut fsys: FILETIME = zeroed(); diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -974,7 +973,7 @@ pub(crate) fn compute_cpu_usage(p: &mut Process, nb_processors: u64) { } else { denominator }) as f32 - * nb_processors as f32; + * nb_cpus as f32; p.cpu_calc_values.old_process_user_cpu = user; p.cpu_calc_values.old_process_sys_cpu = sys; p.cpu_calc_values.old_system_user_cpu = global_user_time; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -7,9 +7,9 @@ use crate::{ use winapi::um::winreg::HKEY_LOCAL_MACHINE; use crate::sys::component::{self, Component}; +use crate::sys::cpu::*; use crate::sys::disk::{get_disks, Disk}; use crate::sys::process::{update_memory, Process}; -use crate::sys::processor::*; use crate::sys::tools::*; use crate::sys::users::get_users; use crate::sys::utils::get_now; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -55,7 +55,7 @@ pub struct System { mem_available: u64, swap_total: u64, swap_used: u64, - processors: ProcessorsWrapper, + cpus: CpusWrapper, components: Vec<Component>, disks: Vec<Disk>, query: Option<Query>, diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -93,7 +93,7 @@ impl SystemExt for System { mem_available: 0, swap_total: 0, swap_used: 0, - processors: ProcessorsWrapper::new(), + cpus: CpusWrapper::new(), components: Vec::new(), disks: Vec::with_capacity(2), query: None, diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -110,14 +110,14 @@ impl SystemExt for System { self.query = Query::new(); if let Some(ref mut query) = self.query { add_english_counter( - r"\Processor(_Total)\% Processor Time".to_string(), + r"\Cpu(_Total)\% Processor Time".to_string(), query, - get_key_used(self.processors.global_processor_mut()), + get_key_used(self.cpus.global_cpu_mut()), "tot_0".to_owned(), ); - for (pos, proc_) in self.processors.iter_mut(refresh_kind).enumerate() { + for (pos, proc_) in self.cpus.iter_mut(refresh_kind).enumerate() { add_english_counter( - format!(r"\Processor({})\% Processor Time", pos), + format!(r"\Cpu({})\% Processor Time", pos), query, get_key_used(proc_), format!("{}_0", pos), diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -128,7 +128,7 @@ impl SystemExt for System { if let Some(ref mut query) = self.query { query.refresh(); let mut used_time = None; - if let Some(ref key_used) = *get_key_used(self.processors.global_processor_mut()) { + if let Some(ref key_used) = *get_key_used(self.cpus.global_cpu_mut()) { used_time = Some( query .get(&key_used.unique_id) diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -136,11 +136,9 @@ impl SystemExt for System { ); } if let Some(used_time) = used_time { - self.processors - .global_processor_mut() - .set_cpu_usage(used_time); + self.cpus.global_cpu_mut().set_cpu_usage(used_time); } - for p in self.processors.iter_mut(refresh_kind) { + for p in self.cpus.iter_mut(refresh_kind) { let mut used_time = None; if let Some(ref key_used) = *get_key_used(p) { used_time = Some( diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -154,7 +152,7 @@ impl SystemExt for System { } } if refresh_kind.frequency() { - self.processors.get_frequencies(); + self.cpus.get_frequencies(); } } } diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -195,7 +193,7 @@ impl SystemExt for System { } let now = get_now(); if let Some(mut p) = Process::new_from_pid(pid, now, refresh_kind) { - p.update(refresh_kind, self.processors.len() as u64, now); + p.update(refresh_kind, self.cpus.len() as u64, now); p.updated = false; self.process_list.insert(pid, p); true diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -250,8 +248,8 @@ impl SystemExt for System { process_information_offset += pi.NextEntryOffset as isize; } let process_list = Wrap(UnsafeCell::new(&mut self.process_list)); - let nb_processors = if refresh_kind.cpu() { - self.processors.len() as u64 + let nb_cpus = if refresh_kind.cpu() { + self.cpus.len() as u64 } else { 0 }; diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -268,7 +266,7 @@ impl SystemExt for System { if let Some(proc_) = (*process_list.0.get()).get_mut(&pid) { proc_.memory = (pi.WorkingSetSize as u64) / 1_000; proc_.virtual_memory = (pi.VirtualSize as u64) / 1_000; - proc_.update(refresh_kind, nb_processors, now); + proc_.update(refresh_kind, nb_cpus, now); return None; } let name = get_process_name(&pi, pid); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -285,7 +283,7 @@ impl SystemExt for System { now, refresh_kind, ); - p.update(refresh_kind, nb_processors, now); + p.update(refresh_kind, nb_cpus, now); Some(p) }) .collect::<Vec<_>>(); diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -329,12 +327,12 @@ impl SystemExt for System { self.process_list.get(&pid) } - fn global_processor_info(&self) -> &Processor { - self.processors.global_processor() + fn global_cpu_info(&self) -> &Cpu { + self.cpus.global_cpu() } - fn processors(&self) -> &[Processor] { - self.processors.processors() + fn cpus(&self) -> &[Cpu] { + self.cpus.cpus() } fn physical_core_count(&self) -> Option<usize> { diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -479,7 +477,7 @@ fn refresh_existing_process(s: &mut System, pid: Pid, refresh_kind: ProcessRefre return false; } update_memory(entry); - entry.update(refresh_kind, s.processors.len() as u64, get_now()); + entry.update(refresh_kind, s.cpus.len() as u64, get_now()); entry.updated = false; true } else { diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -1,6 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. -use crate::sys::processor::{self, Processor, Query}; +use crate::sys::cpu::{self, Cpu, Query}; use crate::CpuRefreshKind; use std::mem::zeroed; diff --git a/src/windows/tools.rs b/src/windows/tools.rs --- a/src/windows/tools.rs +++ b/src/windows/tools.rs @@ -17,20 +17,20 @@ impl KeyHandler { } } -pub(crate) fn init_processors(refresh_kind: CpuRefreshKind) -> (Vec<Processor>, String, String) { +pub(crate) fn init_cpus(refresh_kind: CpuRefreshKind) -> (Vec<Cpu>, String, String) { unsafe { let mut sys_info: SYSTEM_INFO = zeroed(); GetSystemInfo(&mut sys_info); - let (vendor_id, brand) = processor::get_vendor_id_and_brand(&sys_info); - let nb_processors = sys_info.dwNumberOfProcessors as usize; + let (vendor_id, brand) = cpu::get_vendor_id_and_brand(&sys_info); + let nb_cpus = sys_info.dwNumberOfProcessors as usize; let frequencies = if refresh_kind.frequency() { - processor::get_frequencies(nb_processors) + cpu::get_frequencies(nb_cpus) } else { - vec![0; nb_processors] + vec![0; nb_cpus] }; - let mut ret = Vec::with_capacity(nb_processors + 1); + let mut ret = Vec::with_capacity(nb_cpus + 1); for (nb, frequency) in frequencies.iter().enumerate() { - ret.push(Processor::new_with_values( + ret.push(Cpu::new_with_values( format!("CPU {}", nb + 1), vendor_id.clone(), brand.clone(), diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -1,5 +1,6 @@ // Take a look at the license at the top of the repository in the LICENSE file. +use crate::sys::utils::to_str; use crate::{ common::{Gid, Uid}, User, diff --git a/src/windows/users.rs b/src/windows/users.rs --- a/src/windows/users.rs +++ b/src/windows/users.rs @@ -21,23 +22,6 @@ use winapi::um::ntlsa::{ }; use winapi::um::winnt::{LPWSTR, PLUID}; -pub(crate) unsafe fn to_str(p: LPWSTR) -> String { - let mut i = 0; - - loop { - let c = *p.offset(i); - if c == 0 { - break; - } - i += 1; - } - let s = std::slice::from_raw_parts(p, i as _); - String::from_utf16(s).unwrap_or_else(|_e| { - sysinfo_debug!("Failed to convert to UTF-16 string: {}", _e); - String::new() - }) -} - // FIXME: once this is mreged in winapi, it can be removed. #[allow(non_upper_case_globals)] const NERR_Success: NET_API_STATUS = 0; diff --git a/src/windows/utils.rs b/src/windows/utils.rs --- a/src/windows/utils.rs +++ b/src/windows/utils.rs @@ -1,6 +1,7 @@ // Take a look at the license at the top of the repository in the LICENSE file. use winapi::shared::minwindef::FILETIME; +use winapi::um::winnt::LPWSTR; use std::time::SystemTime; diff --git a/src/windows/utils.rs b/src/windows/utils.rs --- a/src/windows/utils.rs +++ b/src/windows/utils.rs @@ -16,3 +17,20 @@ pub(crate) fn get_now() -> u64 { .map(|n| n.as_secs()) .unwrap_or(0) } + +pub(crate) unsafe fn to_str(p: LPWSTR) -> String { + let mut i = 0; + + loop { + let c = *p.offset(i); + if c == 0 { + break; + } + i += 1; + } + let s = std::slice::from_raw_parts(p, i as _); + String::from_utf16(s).unwrap_or_else(|_e| { + sysinfo_debug!("Failed to convert to UTF-16 string: {}", _e); + String::new() + }) +}
6f1c70092ee030535cc2939960baf41ce331a4b2
Rename `processors` method into `cpus` and `Processor` type into `Cpu` `ProcessorExt` into `CpuExt` too.
0.23
754
6f1c70092ee030535cc2939960baf41ce331a4b2
2022-05-20T16:09:59Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -375,7 +375,7 @@ fn test_refresh_process() { // Let's give some time to the system to clean up... std::thread::sleep(std::time::Duration::from_secs(1)); - s.refresh_process(pid); + assert!(!s.refresh_process(pid)); // Checks that the process is still listed. assert!(s.process(pid).is_some()); }
[ "741" ]
GuillaumeGomez__sysinfo-743
GuillaumeGomez/sysinfo
diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -302,6 +302,14 @@ unsafe fn get_task_info(pid: Pid) -> libc::proc_taskinfo { task_info } +fn check_if_pid_is_alive(pid: Pid) -> bool { + unsafe { kill(pid.0, 0) == 0 } + // For the full complete check, it'd need to be (but that seems unneeded): + // unsafe { + // *libc::__errno_location() == libc::ESRCH + // } +} + pub(crate) fn update_process( wrap: &Wrap, pid: Pid, diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -317,7 +325,11 @@ pub(crate) fn update_process( if p.memory == 0 { // We don't have access to this process' information. force_update(p); - return Ok(None); + return if check_if_pid_is_alive(pid) { + Ok(None) + } else { + Err(()) + }; } let task_info = get_task_info(pid); let mut thread_info = mem::zeroed::<libc::proc_threadinfo>(); diff --git a/src/apple/macos/process.rs b/src/apple/macos/process.rs --- a/src/apple/macos/process.rs +++ b/src/apple/macos/process.rs @@ -335,7 +347,12 @@ pub(crate) fn update_process( Some(ThreadStatus::from(thread_info.pth_run_state)), ) } else { - (0, 0, None) + // It very likely means that the process is dead... + return if check_if_pid_is_alive(pid) { + Ok(None) + } else { + Err(()) + }; }; p.status = thread_status; if refresh_kind.cpu() { diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -144,10 +144,10 @@ pub(crate) unsafe fn get_process_data( fscale: f32, now: u64, refresh_kind: ProcessRefreshKind, -) -> Option<Process> { +) -> Result<Option<Process>, ()> { if kproc.ki_pid != 1 && (kproc.ki_flag as libc::c_int & libc::P_SYSTEM) != 0 { // We filter out the kernel threads. - return None; + return Err(()); } // We now get the values needed for both new and existing process. diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -186,7 +186,7 @@ pub(crate) unsafe fn get_process_data( proc_.written_bytes = kproc.ki_rusage.ru_oublock as _; } - return None; + return Ok(None); } // This is a new process, we need to get more information! diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -217,7 +217,7 @@ pub(crate) unsafe fn get_process_data( // .unwrap_or_else(PathBuf::new); let start_time = kproc.ki_start.tv_sec as u64; - Some(Process { + Ok(Some(Process { pid: Pid(kproc.ki_pid), parent, uid: kproc.ki_ruid, diff --git a/src/freebsd/process.rs b/src/freebsd/process.rs --- a/src/freebsd/process.rs +++ b/src/freebsd/process.rs @@ -244,5 +244,5 @@ pub(crate) unsafe fn get_process_data( written_bytes: kproc.ki_rusage.ru_oublock as _, old_written_bytes: 0, updated: true, - }) + })) } diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -172,17 +172,7 @@ impl SystemExt for System { macro_rules! multi_iter { ($name:ident, $($iter:tt)+) => { - $name = crate::utils::into_iter(procs).$($iter)+.and_then(|kproc| { - super::process::get_process_data( - kproc, - &proc_list, - page_size, - fscale, - now, - refresh_kind, - ) - .map(|p| (kproc, p)) - }); + $name = crate::utils::into_iter(procs).$($iter)+; } } diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -192,14 +182,25 @@ impl SystemExt for System { #[cfg(feature = "multithread")] multi_iter!(ret, find_any(|kproc| kproc.ki_pid == pid.0)); - if let Some((kproc, proc_)) = ret { - self.add_missing_proc_info(self.system_info.kd.as_ptr(), kproc, proc_); - true + let kproc = if let Some(kproc) = ret { + kproc } else { - self.process_list - .get(&pid) - .map(|p| p.updated) - .unwrap_or(false) + return false; + }; + match super::process::get_process_data( + kproc, + &proc_list, + page_size, + fscale, + now, + refresh_kind, + ) { + Ok(Some(proc_)) => { + self.add_missing_proc_info(self.system_info.kd.as_ptr(), kproc, proc_); + true + } + Ok(None) => true, + Err(_) => false, } } } diff --git a/src/freebsd/system.rs b/src/freebsd/system.rs --- a/src/freebsd/system.rs +++ b/src/freebsd/system.rs @@ -387,7 +388,8 @@ impl System { now, refresh_kind, ) - .map(|p| (kproc, p)) + .ok() + .and_then(|p| p.map(|p| (kproc, p))) }) .collect::<Vec<_>>() };
13182f50f11646ee958d78a042539491eff6fbdd
refresh_process_specifics won't return false after the process has died Reproducer: ```rust #[test] fn test_repro() { let mut sys = System::new(); let mut cmd = std::process::Command::new("cat").spawn().unwrap(); let cmd_pid = (cmd.id() as i32).into(); sys.refresh_process_specifics(cmd_pid, ProcessRefreshKind::new()); let job_process_start_time = sys.process(cmd_pid).unwrap().start_time(); cmd.kill().unwrap(); let still_alive = sys.refresh_process_specifics(cmd_pid, ProcessRefreshKind::new()); assert!(!still_alive); } ``` The above code works on linux and windows, but on macos, still_alive will return true, despite the subprocess being dead. I believe the problem is that [update_process](https://github.com/GuillaumeGomez/sysinfo/blob/2cdf1f1d3d7f142a52522d2f1d62ba7400641266/src/apple/macos/process.rs#L305) never actually checks if the process is still alive. It checks if it exists within the `wrap` (which seems to be a sort of cache of processes that are still alive), and if it is, will _always_ end up returning `Ok(None)`, which is interpreted by `refresh_process_specifics` as "the process is still alive" (see https://github.com/GuillaumeGomez/sysinfo/blob/2cdf1f1d3d7f142a52522d2f1d62ba7400641266/src/apple/system.rs#L383). I think there should be a check somewhere that looks if the pid is still alive somehow.
0.23
743
This [test](https://github.com/GuillaumeGomez/sysinfo/blob/master/tests/process.rs#L341-L381) checks exactly that. Generally, the system doesn't remove processes right away. So maybe wait a bit before checking it again? What could be nice would be to update the documentation about this behaviour though so users aren't surprised. :) I don't think that's what's going on, because simply doing `sys = System::new()` before the `sys.refresh_process_specifics` fixes the problem. And again, looking at the code in `update_process`, I don't see any code anywhere that actually checks if the process is still alive. Also, your test fails to test the result of `refresh_process`, which is what my test does. [this line](https://github.com/GuillaumeGomez/sysinfo/blob/master/tests/process.rs#L378) should have its result checked to make sure it is `== false`, so it matches [the documentation](https://docs.rs/sysinfo/latest/sysinfo/trait.SystemExt.html#method.refresh_process), which states: > Returns false if the process doesn’t exist. You are right, the test is incomplete and should run an `assert` on this call. Do you want to send a fix?
6f1c70092ee030535cc2939960baf41ce331a4b2
2022-03-29T15:35:01Z
diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -322,6 +322,9 @@ fn test_refresh_processes() { s.refresh_processes(); assert!(s.process(pid).is_some()); + // Check that the process name is not empty. + assert!(!s.process(pid).unwrap().name().is_empty()); + p.kill().expect("Unable to kill process."); // We need this, otherwise the process will still be around as a zombie on linux. let _ = p.wait(); diff --git a/tests/process.rs b/tests/process.rs --- a/tests/process.rs +++ b/tests/process.rs @@ -363,6 +366,9 @@ fn test_refresh_process() { s.refresh_process(pid); assert!(s.process(pid).is_some()); + // Check that the process name is not empty. + assert!(!s.process(pid).unwrap().name().is_empty()); + p.kill().expect("Unable to kill process."); // We need this, otherwise the process will still be around as a zombie on linux. let _ = p.wait();
[ "711" ]
GuillaumeGomez__sysinfo-712
GuillaumeGomez/sysinfo
diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -178,10 +178,7 @@ unsafe fn get_exe(process_handler: HANDLE, h_mod: *mut c_void) -> PathBuf { impl Process { pub(crate) fn new_from_pid(pid: Pid, now: u64) -> Option<Process> { unsafe { - let process_handler = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid.0 as _); - if process_handler.is_null() { - return None; - } + let process_handler = get_process_handler(pid)?; let mut info: MaybeUninit<PROCESS_BASIC_INFORMATION> = MaybeUninit::uninit(); if NtQueryInformationProcess( process_handler, diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -195,16 +192,53 @@ impl Process { return None; } let info = info.assume_init(); - Some(Process::new_with_handle( + let mut h_mod = null_mut(); + + let name = if get_h_mod(process_handler, &mut h_mod) { + get_process_name(process_handler, h_mod) + } else { + String::new() + }; + + let exe = get_exe(process_handler, h_mod); + let mut root = exe.clone(); + root.pop(); + let (cmd, environ, cwd) = match get_process_params(process_handler) { + Ok(args) => args, + Err(_e) => { + sysinfo_debug!("Failed to get process parameters: {}", _e); + (Vec::new(), Vec::new(), PathBuf::new()) + } + }; + let (start_time, run_time) = get_start_and_run_time(process_handler, now); + let parent = if info.InheritedFromUniqueProcessId as usize != 0 { + Some(Pid(info.InheritedFromUniqueProcessId as _)) + } else { + None + }; + Some(Process { + handle: PtrWrapper(process_handler), + name, pid, - if info.InheritedFromUniqueProcessId as usize != 0 { - Some(Pid(info.InheritedFromUniqueProcessId as _)) - } else { - None - }, - process_handler, - now, - )) + parent, + cmd, + environ, + exe, + cwd, + root, + status: ProcessStatus::Run, + memory: 0, + virtual_memory: 0, + cpu_usage: 0., + cpu_calc_values: CPUsageCalculationValues::new(), + start_time, + run_time, + updated: true, + old_read_bytes: 0, + old_written_bytes: 0, + read_bytes: 0, + written_bytes: 0, + }) } } diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -220,8 +254,11 @@ impl Process { let mut h_mod = null_mut(); unsafe { - get_h_mod(handle, &mut h_mod); - let exe = get_exe(handle, h_mod); + let exe = if get_h_mod(handle, &mut h_mod) { + get_exe(handle, h_mod) + } else { + PathBuf::new() + }; let mut root = exe.clone(); root.pop(); let (cmd, environ, cwd) = match get_process_params(handle) { diff --git a/src/windows/process.rs b/src/windows/process.rs --- a/src/windows/process.rs +++ b/src/windows/process.rs @@ -283,58 +320,6 @@ impl Process { } } - fn new_with_handle( - pid: Pid, - parent: Option<Pid>, - process_handler: HANDLE, - now: u64, - ) -> Process { - let mut h_mod = null_mut(); - - unsafe { - let name = if get_h_mod(process_handler, &mut h_mod) { - get_process_name(process_handler, h_mod) - } else { - String::new() - }; - - let exe = get_exe(process_handler, h_mod); - let mut root = exe.clone(); - root.pop(); - let (cmd, environ, cwd) = match get_process_params(process_handler) { - Ok(args) => args, - Err(_e) => { - sysinfo_debug!("Failed to get process parameters: {}", _e); - (Vec::new(), Vec::new(), PathBuf::new()) - } - }; - let (start_time, run_time) = get_start_and_run_time(process_handler, now); - Process { - handle: PtrWrapper(process_handler), - name, - pid, - parent, - cmd, - environ, - exe, - cwd, - root, - status: ProcessStatus::Run, - memory: 0, - virtual_memory: 0, - cpu_usage: 0., - cpu_calc_values: CPUsageCalculationValues::new(), - start_time, - run_time, - updated: true, - old_read_bytes: 0, - old_written_bytes: 0, - read_bytes: 0, - written_bytes: 0, - } - } - } - pub(crate) fn update( &mut self, refresh_kind: crate::ProcessRefreshKind, diff --git a/src/windows/system.rs b/src/windows/system.rs --- a/src/windows/system.rs +++ b/src/windows/system.rs @@ -253,8 +253,8 @@ impl SystemExt for System { #[cfg(feature = "multithread")] use rayon::iter::ParallelIterator; - // TODO: instead of using parallel iterator only here, would be better to be able - // to run it over `process_information` directly! + // TODO: instead of using parallel iterator only here, would be better to be + // able to run it over `process_information` directly! let processes = into_iter(process_ids) .filter_map(|pi| { let pi = *pi.0;
bcaba0720be731ba78b4585a3a0578145eb5aed4
Windows: missing process name with refresh_process_specifics(pid, ..) On Windows, `System::refresh_process_specifics()` and `System::refresh_processes_specifics()` are NOT equivalent. The first one fails to retrieve the process name. The following produce an empty name. ```rust let mut system = System::default(); let pid = Pid::from_u32(/*...*/); system.refresh_process_specifics(pid, Default::default()); let p = system.process(pid).unwrap(); let name = p.name(); ``` And the following produce the right name. ```rust let mut system = System::default(); let pid = Pid::from_u32(/*...*/); system.refresh_processes_specifics(Default::default()); let p = system.process(pid).unwrap(); let name = p.name(); ```
0.23
712
6f1c70092ee030535cc2939960baf41ce331a4b2