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

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

use crate::platform::bsd::sysctl::{boot_time, init_mib};
use crate::sys::cpu::CpusWrapper;
use crate::sys::process::get_exe;
use crate::sys::utils::{
    self, c_buf_to_os_string, c_buf_to_utf8_string, from_cstr_array, get_sys_value,
    get_sys_value_by_name, get_sys_value_str,
};

use libc::c_int;

#[doc = "Minimum interval used internally by `sinf` when refreshing CPU time. The value differs between operating systems."]
pub const MINIMUM_CPU_UPDATE_INTERVAL: Duration = Duration::from_millis(200);

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

mod inner;

#[derive(Debug)]
struct Zfs {
    enabled: bool,
    mib_arcstats_size: [c_int; 5],
}

impl Zfs {
    fn new() -> Self {
        let mut zfs = Self {
            enabled: false,
            mib_arcstats_size: Default::default(),
        };
        unsafe {
            init_mib(
                b"kstat.zfs.misc.arcstats.size\0",
                &mut zfs.mib_arcstats_size,
            );
            let mut arc_size: u64 = 0;
            if get_sys_value(&zfs.mib_arcstats_size, &mut arc_size) {
                zfs.enabled = arc_size != 0;
            }
        }
        zfs
    }

    fn arc_size(&self) -> Option<u64> {
        if self.enabled {
            let mut arc_size: u64 = 0;
            unsafe {
                get_sys_value(&self.mib_arcstats_size, &mut arc_size);
                Some(arc_size)
            }
        } else {
            None
        }
    }
}

/// Simplifies access to system information.
#[derive(Debug)]
struct SystemInfo {
    hw_physical_memory: [c_int; 2],
    page_size: c_int,
    virtual_page_count: [c_int; 4],
    virtual_wire_count: [c_int; 4],
    virtual_active_count: [c_int; 4],
    virtual_cache_count: [c_int; 4],
    virtual_inactive_count: [c_int; 4],
    virtual_free_count: [c_int; 4],
    buf_space: [c_int; 2],
    kd: Option<NonNull<libc::kvm_t>>,
    /// From the FreeBSD manual: "The kernel fixed-point scale factor".
    fscale: f32,
    procstat: *mut libc::procstat,
    zfs: Zfs,
}

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

impl SystemInfo {
    fn new() -> Self {
        unsafe {
            let mut si = SystemInfo {
                hw_physical_memory: Default::default(),
                page_size: 0,
                virtual_page_count: Default::default(),
                virtual_wire_count: Default::default(),
                virtual_active_count: Default::default(),
                virtual_cache_count: Default::default(),
                virtual_inactive_count: Default::default(),
                virtual_free_count: Default::default(),
                buf_space: Default::default(),
                kd: None,
                fscale: 0.,
                procstat: std::ptr::null_mut(),
                zfs: Zfs::new(),
            };
            let mut fscale: c_int = 0;
            if !get_sys_value_by_name(b"kern.fscale\0", &mut fscale) {
                // Default value used by htop.
                fscale = 2048;
            }
            si.fscale = fscale as f32;

            if !get_sys_value_by_name(b"vm.stats.vm.v_page_size\0", &mut si.page_size) {
                sinf_debug!(
                    "failed to get page size, memory information retrieval will be limited"
                );
                si.page_size = 0;
            }

            init_mib(b"hw.physmem\0", &mut si.hw_physical_memory);
            init_mib(b"vm.stats.vm.v_page_count\0", &mut si.virtual_page_count);
            init_mib(b"vm.stats.vm.v_wire_count\0", &mut si.virtual_wire_count);
            init_mib(
                b"vm.stats.vm.v_active_count\0",
                &mut si.virtual_active_count,
            );
            init_mib(b"vm.stats.vm.v_cache_count\0", &mut si.virtual_cache_count);
            init_mib(
                b"vm.stats.vm.v_inactive_count\0",
                &mut si.virtual_inactive_count,
            );
            init_mib(b"vm.stats.vm.v_free_count\0", &mut si.virtual_free_count);
            init_mib(b"vfs.bufspace\0", &mut si.buf_space);

            si
        }
    }

    fn get_kd(&mut self) -> Option<NonNull<libc::kvm_t>> {
        if self.kd.is_none() {
            let mut errbuf =
                MaybeUninit::<[libc::c_char; libc::_POSIX2_LINE_MAX as usize]>::uninit();

            unsafe {
                self.kd = NonNull::new(libc::kvm_openfiles(
                    std::ptr::null(),
                    c"/dev/null".as_ptr() as *const _,
                    std::ptr::null(),
                    0,
                    errbuf.as_mut_ptr() as *mut _,
                ));
            }
            if self.kd.is_none() {
                sinf_debug!("`kvm_openfiles` failed, system information retrieval will be limited");
            }
        }
        self.kd
    }

    /// Returns (used, total).
    fn get_swap_info(&mut self) -> (u64, u64) {
        // FreeBSD documentation: https://man.freebsd.org/cgi/man.cgi?query=kvm_getswapinfo&sektion=3&n=1
        let mut swap = MaybeUninit::<libc::kvm_swap>::uninit();
        let Some(kd) = self.get_kd() else {
            return (0, 0);
        };
        unsafe {
            let nswap = libc::kvm_getswapinfo(kd.as_ptr(), swap.as_mut_ptr(), 1, 0);
            if nswap < 0 {
                return (0, 0);
            }
            let swap = swap.assume_init();
            (
                (swap.ksw_used as u64).saturating_mul(self.page_size as u64),
                (swap.ksw_total as u64).saturating_mul(self.page_size as u64),
            )
        }
    }

    fn get_total_memory(&self) -> u64 {
        let mut nb_pages: libc::c_uint = 0;
        unsafe {
            if get_sys_value(&self.virtual_page_count, &mut nb_pages) {
                return u64::from(nb_pages).saturating_mul(self.page_size as _);
            }

            // Fallback: this includes all available memory, not only the memory available to users.
            let mut total_memory: libc::c_ulong = 0;
            get_sys_value(&self.hw_physical_memory, &mut total_memory);
            total_memory as u64
        }
    }

    fn get_used_memory(&self) -> u64 {
        let mut mem_active: libc::c_uint = 0;
        let mut mem_wire: libc::c_uint = 0;

        unsafe {
            get_sys_value(&self.virtual_active_count, &mut mem_active);
            get_sys_value(&self.virtual_wire_count, &mut mem_wire);

            let mut mem_wire = u64::from(mem_wire).saturating_mul(self.page_size as _);
            // Subtract "ZFS ARC" from "wired memory": it belongs to cache, but the kernel reports it as "wired memory".
            if let Some(arc_size) = self.zfs.arc_size() {
                mem_wire = mem_wire.saturating_sub(arc_size);
            }
            u64::from(mem_active)
                .saturating_mul(self.page_size as _)
                .saturating_add(mem_wire)
        }
    }

    fn get_free_memory(&self) -> u64 {
        let mut free_mem: libc::c_uint = 0;

        unsafe {
            get_sys_value(&self.virtual_free_count, &mut free_mem);

            u64::from(free_mem).saturating_mul(self.page_size as _)
        }
    }

    fn get_available_memory(&self) -> u64 {
        let mut buffers_mem: libc::c_long = 0;
        let mut inactive_mem: libc::c_uint = 0;
        let mut cached_mem: libc::c_uint = 0;
        let mut free_mem: libc::c_uint = 0;

        unsafe {
            get_sys_value(&self.buf_space, &mut buffers_mem); // In bytes.
            get_sys_value(&self.virtual_inactive_count, &mut inactive_mem);
            get_sys_value(&self.virtual_cache_count, &mut cached_mem);
            get_sys_value(&self.virtual_free_count, &mut free_mem);

            (buffers_mem as u64)
                .saturating_add(u64::from(inactive_mem).saturating_mul(self.page_size as _))
                .saturating_add(u64::from(cached_mem).saturating_mul(self.page_size as _))
                .saturating_add(u64::from(free_mem).saturating_mul(self.page_size as _))
        }
    }

    #[allow(clippy::collapsible_if)] // Kept for readability.
    unsafe fn get_proc_missing_info(
        &mut self,
        kproc: &libc::kinfo_proc,
        proc_: &mut ProcessInner,
        refresh_kind: ProcessRefreshKind,
    ) {
        let mut done = 0;
        let cwd_needs_update = refresh_kind.cwd().needs_update(|| proc_.cwd().is_none());
        let root_needs_update = refresh_kind.root().needs_update(|| proc_.root().is_none());
        if cwd_needs_update {
            done += 1;
        }
        if root_needs_update {
            done += 1;
        }
        if done == 0 {
            return;
        }
        if self.procstat.is_null() {
            unsafe {
                self.procstat = libc::procstat_open_sysctl();
                if self.procstat.is_null() {
                    sinf_debug!("procstat_open_sysctl failed");
                    return;
                }
            }
        }
        unsafe {
            let head =
                libc::procstat_getfiles(self.procstat, kproc as *const _ as usize as *mut _, 0);
            if head.is_null() {
                return;
            }
            let mut entry = (*head).stqh_first;
            while !entry.is_null() && done > 0 {
                {
                    let tmp = &*entry;
                    if tmp.fs_uflags & libc::PS_FST_UFLAG_CDIR != 0 {
                        if cwd_needs_update && !tmp.fs_path.is_null() {
                            if let Ok(p) = CStr::from_ptr(tmp.fs_path).to_str() {
                                proc_.cwd = Some(PathBuf::from(p));
                                done -= 1;
                            }
                        }
                    } else if tmp.fs_uflags & libc::PS_FST_UFLAG_RDIR != 0 {
                        if root_needs_update && !tmp.fs_path.is_null() {
                            if let Ok(p) = CStr::from_ptr(tmp.fs_path).to_str() {
                                proc_.root = Some(PathBuf::from(p));
                                done -= 1;
                            }
                        }
                    }
                }
                entry = (*entry).next.stqe_next;
            }
            libc::procstat_freefiles(self.procstat, head);
        }
    }
}

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

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

    unsafe {
        // First call to obtain 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 {
            // Size the buffer appropriately.
            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)
}