sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use crate::{
    Cpu, CpuRefreshKind, Error, LoadAvg, MemoryRefreshKind, Pid, ProcessRefreshKind,
    ProcessesToUpdate,
};

use crate::sys::cpu::*;
use crate::{Process, ProcessInner};

use std::collections::HashMap;
use std::ffi::OsStr;
use std::mem::{size_of, zeroed};
use std::os::windows::ffi::OsStrExt;
use std::time::{Duration, SystemTime};

use windows::Win32::Foundation::{self, HANDLE, STILL_ACTIVE};
use windows::Win32::System::Diagnostics::ToolHelp::{
    CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
};
use windows::Win32::System::ProcessStatus::{K32GetPerformanceInfo, PERFORMANCE_INFORMATION};
use windows::Win32::System::Registry::{
    HKEY, HKEY_LOCAL_MACHINE, KEY_READ, REG_NONE, RegCloseKey, RegOpenKeyExW, RegQueryValueExW,
};
use windows::Win32::System::SystemInformation::{self, GetSystemInfo};
use windows::Win32::System::SystemInformation::{
    ComputerNamePhysicalDnsHostname, GetComputerNameExW, GetTickCount64, GlobalMemoryStatusEx,
    MEMORYSTATUSEX, SYSTEM_INFO,
};
use windows::Win32::System::Threading::GetExitCodeProcess;
use windows::core::{Owned, PCWSTR, PWSTR};

declare_signals! {
    (),
    Signal::Kill => (),
    _ => None,
}

#[doc = "Returns the list of the supported signals on this system (used by [`Process::kill_with`][crate::Process::kill_with])."]
pub const SUPPORTED_SIGNALS: &[crate::Signal] = supported_signals();
#[doc = "This is the minimum interval time used internally by `sinf` to refresh the CPU time. This value differs from one OS to another."]
pub const MINIMUM_CPU_UPDATE_INTERVAL: Duration = Duration::from_millis(200);

const WINDOWS_ELEVEN_BUILD_NUMBER: u32 = 22000;

/// Calculates the system boot time in seconds with improved precision.
/// It works in nanoseconds throughout to avoid rounding errors in the uptime
/// calculation, converting to seconds only at the end for stable results. The
/// result is capped within u64 limits to handle edge cases.
unsafe fn boot_time() -> Result<u64, Error> {
    let n = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map_err(|err| Error::Other(Box::new(err)))?;
    let system_time_ns = n.as_nanos();
    let tick_count_ns = unsafe { GetTickCount64() } as u128 * 1_000_000;
    let boot_time_sec = system_time_ns.saturating_sub(tick_count_ns) / 1_000_000_000;
    Ok(boot_time_sec.try_into().unwrap_or(u64::MAX))
}

pub(crate) struct SystemInner {
    process_list: HashMap<Pid, Process>,
    mem_total: u64,
    mem_available: u64,
    swap_total: u64,
    swap_used: u64,
    cpus: CpusWrapper,
    query: Option<Query>,
    #[cfg(feature = "gpu")]
    pub(crate) gpu_query: Option<Query>,
}

mod cpu;
mod info;
mod inner;
mod memory;
mod process;

pub(crate) fn is_proc_running(handle: HANDLE) -> bool {
    let mut exit_code = 0;
    unsafe { GetExitCodeProcess(handle, &mut exit_code) }.is_ok()
        && exit_code == STILL_ACTIVE.0 as u32
}

fn get_dns_hostname() -> Result<String, Error> {
    let mut buffer_size = 0;
    // Call this first to obtain the buffer size, because the DNS name can be longer than MAX_COMPUTERNAME_LENGTH.
    unsafe {
        let _err = GetComputerNameExW(ComputerNamePhysicalDnsHostname, None, &mut buffer_size);

        // Allocate the buffer with the required 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 GetComputerNameExW(
            ComputerNamePhysicalDnsHostname,
            Some(PWSTR::from_raw(buffer.as_mut_ptr())),
            &mut buffer_size,
        )
        .is_ok()
        {
            if let Some(pos) = buffer.iter().position(|c| *c == 0) {
                buffer.resize(pos, 0);
            }

            if let Ok(info) = String::from_utf16(&buffer) {
                return Ok(info);
            }
        }
    }

    sinf_debug!("Failed to get computer hostname");
    Err(Error::Other("failed to retrieve host name".into()))
}

fn get_now() -> u64 {
    SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|n| n.as_secs())
        .unwrap_or(0)
}

mod registry;
use self::registry::{get_reg_string_value, get_reg_value_u32};

#[cfg(test)]
mod tests;