Dataset Viewer
Auto-converted to Parquet Duplicate
created_at
stringlengths
20
20
test_patch
stringlengths
226
26.3k
issue_numbers
sequencelengths
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\n--- a/README.md\n+++ b/README.md\n@@ -15,7 +15,7 @@ Support the(...TRUNCATED)
[ "215" ]
GuillaumeGomez__sysinfo-245
GuillaumeGomez/sysinfo
"diff --git a/Cargo.toml b/Cargo.toml\n--- a/Cargo.toml\n+++ b/Cargo.toml\n@@ -16,17 +16,15 @@ build(...TRUNCATED)
4ae1791d21f84f911ca8a77e3ebc19996b7de808
"Feature Request: support retrieve CPU number and load info\nThanks for providing the awesome librar(...TRUNCATED)
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 (...TRUNCATED)
4ae1791d21f84f911ca8a77e3ebc19996b7de808
2019-06-24T15:31:47Z
"diff --git a/src/system.rs b/src/system.rs\n--- a/src/system.rs\n+++ b/src/system.rs\n@@ -25,14 +25(...TRUNCATED)
[ "182" ]
GuillaumeGomez__sysinfo-183
GuillaumeGomez/sysinfo
"diff --git a/Cargo.toml b/Cargo.toml\n--- a/Cargo.toml\n+++ b/Cargo.toml\n@@ -1,6 +1,6 @@\n [packag(...TRUNCATED)
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\n--- a/src/sysinfo.rs\n+++ b/src/sysinfo.rs\n@@ -54,7 (...TRUNCATED)
[ "76" ]
GuillaumeGomez__sysinfo-178
GuillaumeGomez/sysinfo
"diff --git a/.travis.yml b/.travis.yml\n--- a/.travis.yml\n+++ b/.travis.yml\n@@ -55,7 +55,7 @@ scr(...TRUNCATED)
bf0691f89ac36af1418a522591cc012ce584d0aa
"`sysinfo::System::new()` slow?\nA simple program creating a `sysinfo::System` takes several times l(...TRUNCATED)
0.8
178
"Even more than reasonable: it sounds great! I'll gladly accept any patch improving the speed of thi(...TRUNCATED)
5744eb9221c99229f38375d776ee681032ca4f86
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
1