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, Process, ProcessRefreshKind,
    ProcessesToUpdate,
};

use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::ffi::CStr;
use std::mem::MaybeUninit;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, SystemTime};

use crate::sys::cpu::CpusWrapper;
use crate::sys::utils::{self, c_buf_to_utf8_string, get_sys_value, get_sys_value_by_name};

use super::ffi;
use crate::platform::bsd::sysctl::{boot_time, init_mib};

use libc::c_int;

#[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(250);

pub(crate) struct SystemInner {
    process_list: HashMap<Pid, Process>,
    mem_total: u64,
    mem_free: u64,
    mem_used: u64,
    mem_available: u64,
    swap_total: u64,
    swap_used: u64,
    system_info: SystemInfo,
    cpus: CpusWrapper,
}

/// Provides convenient access to system information.
#[derive(Debug)]
pub(crate) struct SystemInfo {
    pub(crate) page_size: u64,
    pub(crate) kd: Option<NonNull<ffi::kvm_t>>,
    /// From the NetBSD manual: "The kernel fixed-point scale factor".
    pub(crate) fscale: f32,
    /// NetBSD exposes only the total blocks in and out per process, not the block size.
    pub(crate) block_size: u64,
}

// Required because `kd: *mut libc::kvm_t` is not thread-safe.
unsafe impl Send for SystemInfo {}
unsafe impl Sync for SystemInfo {}

mod inner;

impl SystemInfo {
    fn new() -> Self {
        unsafe {
            let mut errbuf = MaybeUninit::<[libc::c_char; ffi::_POSIX2_LINE_MAX]>::uninit();
            let kd = NonNull::new(ffi::kvm_openfiles(
                std::ptr::null(),
                std::ptr::null(),
                std::ptr::null(),
                ffi::KVM_NO_FILES,
                errbuf.as_mut_ptr() as *mut _,
            ));
            if kd.is_none() {
                sinf_debug!("kvm_openfiles failed, cannot retrieve processes information");
            }

            let mut si = SystemInfo {
                page_size: 0,
                kd,
                fscale: 0.,
                block_size: 512,
            };
            let mut fscale: c_int = 0;
            if !get_sys_value(&[libc::CTL_KERN, libc::KERN_FSCALE], &mut fscale) || fscale < 0 {
                sinf_debug!("failed to get fscale, cannot retrieve CPU usage information");
            } else {
                si.fscale = fscale as f32;
            }

            let page_size = libc::sysconf(libc::_SC_PAGESIZE);
            if page_size < 0 {
                sinf_debug!("failed to get page size, cannot retrieve memory information");
            } else {
                si.page_size = page_size as _;
            }

            let mut block_size: libc::c_long = 0;
            // `getbsize` is not thread-safe because it returns a `static char*`.
            ffi::getbsize(std::ptr::null_mut(), &mut block_size);
            if block_size > 0 {
                si.block_size = block_size as u64;
            }

            si
        }
    }
}

impl Drop for SystemInfo {
    fn drop(&mut self) {
        unsafe {
            if let Some(kd) = self.kd {
                ffi::kvm_close(kd.as_ptr());
            }
        }
    }
}

fn get_system_info(mib: &[c_int]) -> Option<String> {
    let mut size = 0;

    unsafe {
        // First call, used to get the size.
        libc::sysctl(
            mib.as_ptr(),
            mib.len() as _,
            std::ptr::null_mut(),
            &mut size,
            std::ptr::null_mut(),
            0,
        );

        // Exit early if the size was not updated.
        if size != 0 {
            // Set the buffer to the correct size.
            let mut buf: Vec<libc::c_char> = vec![0; size as _];

            if libc::sysctl(
                mib.as_ptr(),
                mib.len() as _,
                buf.as_mut_ptr() as _,
                &mut size,
                std::ptr::null_mut(),
                0,
            ) != -1
            {
                return c_buf_to_utf8_string(&buf);
            }
        }
    }
    None
}

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