sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::mem::{self, MaybeUninit};

use libc::c_void;

use crate::sys::process::ThreadStatus;
use crate::sys::system::Wrap;
use crate::{Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, Uid};

use super::ProcessInner;
use super::cpu::compute_cpu_usage;
use super::info::{
    check_if_pid_is_alive, get_bsd_info, get_cwd_root, get_exe_and_name_backup, get_parent,
    get_process_infos, get_task_info,
};

unsafe fn create_new_process(
    pid: Pid,
    now: u64,
    refresh_kind: ProcessRefreshKind,
    info: Option<libc::proc_bsdinfo>,
    timebase_to_ms: f64,
) -> Result<Option<Process>, ()> {
    let info = match info {
        Some(info) => info,
        None => {
            let mut p = ProcessInner::new_empty(pid);
            unsafe {
                if get_exe_and_name_backup(&mut p, refresh_kind, false) {
                    get_cwd_root(&mut p, refresh_kind);
                    return Ok(Some(Process { inner: p }));
                }
                // Without even the name, there is no point in keeping it.
                return Err(());
            }
        }
    };

    let parent = get_parent(&info);

    let start_time = info.pbi_start_tvsec;
    let run_time = now.saturating_sub(start_time);

    let mut p = ProcessInner::new(pid, parent, start_time, run_time);
    unsafe {
        if !get_process_infos(&mut p, refresh_kind)
            && !get_exe_and_name_backup(&mut p, refresh_kind, false)
        {
            // Without even the name, there is no point in keeping it.
            return Err(());
        }
        get_cwd_root(&mut p, refresh_kind);

        if refresh_kind.cpu() || refresh_kind.memory() {
            let task_info = get_task_info(pid);

            p.old_stime = task_info.pti_total_system;
            p.old_utime = task_info.pti_total_user;
            if refresh_kind.cpu() {
                p.accumulated_cpu_time = (task_info
                    .pti_total_user
                    .saturating_add(task_info.pti_total_system)
                    as f64
                    * timebase_to_ms) as u64;
            }
            if refresh_kind.memory() {
                p.memory = task_info.pti_resident_size;
                p.virtual_memory = task_info.pti_virtual_size;
            }
        }

        p.user_id = Some(Uid(info.pbi_ruid));
        p.effective_user_id = Some(Uid(info.pbi_uid));
        p.group_id = Some(Gid(info.pbi_rgid));
        p.effective_group_id = Some(Gid(info.pbi_gid));
        p.process_status = ProcessStatus::from(info.pbi_status);
        if refresh_kind.disk_usage() {
            update_proc_disk_activity(&mut p);
        }
        Ok(Some(Process { inner: p }))
    }
}

pub(crate) fn update_process(
    wrap: &Wrap,
    pid: Pid,
    time_interval: Option<f64>,
    now: u64,
    refresh_kind: ProcessRefreshKind,
    check_if_alive: bool,
    timebase_to_ms: f64,
) -> Result<Option<Process>, ()> {
    unsafe {
        if let Some(ref mut p) = (*wrap.0.get()).get_mut(&pid) {
            let p = &mut p.inner;

            let mut extra_checked = false;

            if let Some(info) = get_bsd_info(pid) {
                if info.pbi_start_tvsec != p.start_time {
                    // Do not remove it, just replace it.
                    p.updated = true;
                    // Ensure the name and exe path are updated.
                    p.name.clear();
                    p.exe = None;
                    // The owner of this PID changed.
                    return create_new_process(pid, now, refresh_kind, Some(info), timebase_to_ms);
                }
                let parent = get_parent(&info);
                // Update the parent if it changed.
                if p.parent != parent {
                    p.parent = parent;
                }
            } else {
                // Odd that this information is unavailable.
                if !get_exe_and_name_backup(p, refresh_kind, true) {
                    // It is not actually alive, so un-update it so it will be removed.
                    p.updated = false;
                    return Ok(None);
                }
                extra_checked = true;
            }

            if !get_process_infos(p, refresh_kind) && !extra_checked {
                get_exe_and_name_backup(p, refresh_kind, false);
            }
            get_cwd_root(p, refresh_kind);

            if refresh_kind.disk_usage() {
                update_proc_disk_activity(p);
            }

            let mut thread_info = mem::zeroed::<libc::proc_threadinfo>();
            let (user_time, system_time, thread_status) = if libc::proc_pidinfo(
                pid.0,
                libc::PROC_PIDTHREADINFO,
                0,
                &mut thread_info as *mut libc::proc_threadinfo as *mut c_void,
                mem::size_of::<libc::proc_threadinfo>() as _,
            ) != 0
            {
                (
                    thread_info.pth_user_time,
                    thread_info.pth_system_time,
                    Some(ThreadStatus::from(thread_info.pth_run_state)),
                )
            } else {
                // This very likely means the process is dead.
                if check_if_pid_is_alive(pid, check_if_alive) {
                    (0, 0, Some(ThreadStatus::Running))
                } else {
                    return Err(());
                }
            };
            p.status = thread_status;
            p.run_time = now.saturating_sub(p.start_time);

            if refresh_kind.cpu() || refresh_kind.memory() {
                let task_info = get_task_info(pid);

                if refresh_kind.cpu() {
                    compute_cpu_usage(p, task_info, system_time, user_time, time_interval);
                    p.accumulated_cpu_time = (task_info
                        .pti_total_user
                        .saturating_add(task_info.pti_total_system)
                        as f64
                        * timebase_to_ms) as u64;
                }
                if refresh_kind.memory() {
                    p.memory = task_info.pti_resident_size;
                    p.virtual_memory = task_info.pti_virtual_size;
                }
            }
            p.updated = true;
            Ok(None)
        } else {
            create_new_process(pid, now, refresh_kind, get_bsd_info(pid), timebase_to_ms)
        }
    }
}

fn update_proc_disk_activity(p: &mut ProcessInner) {
    p.old_read_bytes = p.read_bytes;
    p.old_written_bytes = p.written_bytes;

    let mut pidrusage = MaybeUninit::<libc::rusage_info_v2>::uninit();

    unsafe {
        let retval = libc::proc_pid_rusage(
            p.pid().0 as _,
            libc::RUSAGE_INFO_V2,
            pidrusage.as_mut_ptr() as _,
        );

        if retval < 0 {
            sinf_debug!("proc_pid_rusage failed: {:?}", retval);
        } else {
            let pidrusage = pidrusage.assume_init();
            p.read_bytes = pidrusage.ri_diskio_bytesread;
            p.written_bytes = pidrusage.ri_diskio_byteswritten;
        }
    }
}