Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Clean up cpu_arch functions code #1136

Merged
merged 1 commit into from
Nov 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ windows = { version = "0.51", features = [
"Win32_System_WindowsProgramming",
"Win32_System_Wmi",
"Win32_UI_Shell",
] }
]}

[target.'cfg(not(any(target_os = "unknown", target_arch = "wasm32")))'.dependencies]
libc = "^0.2.150"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`] constant.

The minimum-supported version of `rustc` is **1.65**.
The minimum-supported version of `rustc` is **1.69**.

## Usage

Expand Down
2 changes: 1 addition & 1 deletion src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -702,7 +702,7 @@ impl System {
self.inner.host_name()
}

/// Returns the CPU architecture (eg. x86, amd64, aarch64, ...)
/// Returns the CPU architecture (eg. x86, amd64, aarch64, ...).
///
/// ```no_run
/// use sysinfo::System;
Expand Down
44 changes: 20 additions & 24 deletions src/unix/apple/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use crate::{Cpu, CpuRefreshKind, LoadAvg, Pid, Process, ProcessRefreshKind};

use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::ffi::CStr;
use std::mem;
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use std::time::SystemTime;
Expand Down Expand Up @@ -407,7 +408,25 @@ impl SystemInner {
}

pub(crate) fn cpu_arch(&self) -> Option<String> {
get_cpu_arch()
let mut arch_str: [u8; 32] = [0; 32];
let mut mib = [libc::CTL_HW as _, libc::HW_MACHINE as _];

unsafe {
if get_sys_value(
mem::size_of::<[u8; 32]>(),
arch_str.as_mut_ptr() as *mut _,
&mut mib,
) {
CStr::from_bytes_until_nul(&arch_str)
.ok()
.and_then(|res| match res.to_str() {
Ok(arch) => Some(arch.to_string()),
Err(_) => None,
})
} else {
None
}
}
}
}

Expand Down Expand Up @@ -455,26 +474,3 @@ fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> {
}
}
}

pub(crate) fn get_cpu_arch() -> Option<String> {
use std::ffi::CStr;
let mut arch_str: [u8; 32] = [0; 32];

unsafe {
let mut mib = [libc::CTL_HW as _, libc::HW_MACHINE as _];
if get_sys_value(
mem::size_of::<[u8; 32]>(),
arch_str.as_mut_ptr() as *mut _,
&mut mib,
) {
CStr::from_bytes_until_nul(&arch_str)
.map(|res| match res.to_str() {
Ok(arch) => Some(arch.to_string()),
Err(_) => None,
})
.unwrap_or_else(|_| None)
} else {
None
}
}
}
36 changes: 16 additions & 20 deletions src/unix/freebsd/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,23 @@ impl SystemInner {
pub(crate) fn distribution_id(&self) -> String {
std::env::consts::OS.to_owned()
}

pub(crate) fn cpu_arch(&self) -> Option<String> {
get_cpu_arch()
let mut arch_str: [u8; 32] = [0; 32];
let mib = [libc::CTL_HW as _, libc::HW_MACHINE as _];

unsafe {
if get_sys_value(&mib, &mut arch_str) {
CStr::from_bytes_until_nul(&arch_str)
.ok()
.and_then(|res| match res.to_str() {
Ok(arch) => Some(arch.to_string()),
Err(_) => None,
})
} else {
None
}
}
}
}

Expand Down Expand Up @@ -598,22 +613,3 @@ impl Drop for SystemInfo {
}
}
}

pub(crate) fn get_cpu_arch() -> Option<String> {
use std::ffi::CStr;
let mut arch_str: [u8; 32] = [0; 32];

unsafe {
let mib = [libc::CTL_HW as _, libc::HW_MACHINE as _];
if get_sys_value(&mib, &mut arch_str) {
CStr::from_bytes_until_nul(&arch_str)
.map(|res| match res.to_str() {
Ok(arch) => Some(arch.to_string()),
Err(_) => None,
})
.unwrap_or_else(|_| None)
} else {
None
}
}
}
42 changes: 20 additions & 22 deletions src/unix/linux/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use crate::{Cpu, CpuRefreshKind, LoadAvg, Pid, Process, ProcessInner, ProcessRef
use libc::{self, c_char, sysconf, _SC_CLK_TCK, _SC_HOST_NAME_MAX, _SC_PAGESIZE};
use std::cmp::min;
use std::collections::HashMap;
use std::ffi::CStr;
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
use std::path::Path;
Expand Down Expand Up @@ -480,8 +481,26 @@ impl SystemInner {
get_system_info_android(InfoType::DistributionID)
.unwrap_or_else(|| std::env::consts::OS.to_owned())
}

pub(crate) fn cpu_arch(&self) -> Option<String> {
get_cpu_arch()
let mut raw = std::mem::MaybeUninit::<libc::utsname>::uninit();

unsafe {
if libc::uname(raw.as_mut_ptr()) != 0 {
return None;
}
let info = raw.assume_init();
// Converting `&[i8]` to `&[u8]`.
let machine: &[u8] =
std::slice::from_raw_parts(info.machine.as_ptr() as *const _, info.machine.len());

CStr::from_bytes_until_nul(machine)
.ok()
.and_then(|res| match res.to_str() {
Ok(arch) => Some(arch.to_string()),
Err(_) => None,
})
}
}
}

Expand Down Expand Up @@ -643,27 +662,6 @@ fn get_system_info_android(info: InfoType) -> Option<String> {
}
}

fn get_cpu_arch() -> Option<String> {
let mut raw = std::mem::MaybeUninit::<libc::utsname>::zeroed();

unsafe {
if libc::uname(raw.as_mut_ptr()) == 0 {
let info = raw.assume_init();

let machine = info
.machine
.iter()
.filter(|c| **c != 0)
.map(|c| *c as u8 as char)
.collect::<String>();

Some(machine)
} else {
None
}
}
}

#[cfg(test)]
mod test {
#[cfg(target_os = "android")]
Expand Down
37 changes: 21 additions & 16 deletions src/windows/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,27 @@ impl SystemInner {
std::env::consts::OS.to_owned()
}
pub(crate) fn cpu_arch(&self) -> Option<String> {
get_cpu_arch()
unsafe {
// https://docs.microsoft.com/fr-fr/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
let info = SYSTEM_INFO::default();
match info.Anonymous.Anonymous.wProcessorArchitecture {
SystemInformation::PROCESSOR_ARCHITECTURE_ALPHA => Some("alpha".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ALPHA64 => Some("alpha64".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_AMD64 => Some("x86_64".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ARM => Some("arm".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 => Some("arm".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ARM64 => Some("arm64".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_IA32_ON_ARM64
| SystemInformation::PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 => {
Some("ia32".to_string())
}
SystemInformation::PROCESSOR_ARCHITECTURE_IA64 => Some("ia64".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_INTEL => Some("x86".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_MIPS => Some("mips".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_PPC => Some("powerpc".to_string()),
_ => None,
}
}
}
}

Expand Down Expand Up @@ -544,18 +564,3 @@ fn get_dns_hostname() -> Option<String> {
sysinfo_debug!("Failed to get computer hostname");
None
}

fn get_cpu_arch() -> Option<String> {
// https://docs.microsoft.com/fr-fr/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info
unsafe {
let info = SYSTEM_INFO::default();
match info.Anonymous.Anonymous.wProcessorArchitecture {
SystemInformation::PROCESSOR_ARCHITECTURE_INTEL => Some("x86".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ARM => Some("arm".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_AMD64 => Some("x86_64".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ARM64 => Some("arm64".to_string()),
SystemInformation::PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64 => Some("arm".to_string()),
_ => None,
}
}
}
1 change: 0 additions & 1 deletion tests/cpu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ fn test_cpu() {
assert!(s.cpus().iter().any(|c| !c.brand().is_empty()));
}
assert!(s.cpus().iter().any(|c| !c.vendor_id().is_empty()));
assert!(s.cpu_arch().is_some());
}

#[test]
Expand Down