sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::ffi::OsString;
use std::mem;
use std::os::unix::ffi::OsStringExt;
use std::path::PathBuf;

use libc::{c_int, c_void, kill};

use crate::{Pid, ProcessRefreshKind};

mod cmdline;
mod paths;

use self::cmdline::{get_arguments, get_environ, get_exe};
pub(super) use self::paths::get_cwd_root;
use super::ProcessInner;

pub(super) unsafe fn get_task_info(pid: Pid) -> libc::proc_taskinfo {
    unsafe {
        let mut task_info = mem::zeroed::<libc::proc_taskinfo>();
        // If this fails, no memory information is available for this process, which is acceptable.
        libc::proc_pidinfo(
            pid.0,
            libc::PROC_PIDTASKINFO,
            0,
            &mut task_info as *mut libc::proc_taskinfo as *mut c_void,
            mem::size_of::<libc::proc_taskinfo>() as _,
        );
        task_info
    }
}

#[inline]
pub(super) fn check_if_pid_is_alive(pid: Pid, check_if_alive: bool) -> bool {
    // When iterating over all PIDs returned by `proc_listallpids`, there is no point in checking whether the process is alive, because it was just returned by that function.
    if !check_if_alive {
        return true;
    }
    unsafe {
        if kill(pid.0, 0) == 0 {
            return true;
        }
        // `kill` failed, but not necessarily because the process is dead.
        let errno = crate::platform::unix::libc_errno();
        // An errno equal to ESRCH means the process is dead.
        !errno.is_null() && *errno != libc::ESRCH
    }
}

pub(super) unsafe fn get_bsd_info(pid: Pid) -> Option<libc::proc_bsdinfo> {
    unsafe {
        let mut info = mem::zeroed::<libc::proc_bsdinfo>();

        if libc::proc_pidinfo(
            pid.0,
            libc::PROC_PIDTBSDINFO,
            0,
            &mut info as *mut _ as *mut _,
            mem::size_of::<libc::proc_bsdinfo>() as _,
        ) != mem::size_of::<libc::proc_bsdinfo>() as c_int
        {
            None
        } else {
            Some(info)
        }
    }
}

pub(super) fn get_parent(info: &libc::proc_bsdinfo) -> Option<Pid> {
    match info.pbi_ppid as i32 {
        0 => None,
        p => Some(Pid(p)),
    }
}

/// Less efficient way to retrieve `exe` and `name`.
pub(super) unsafe fn get_exe_and_name_backup(
    process: &mut ProcessInner,
    refresh_kind: ProcessRefreshKind,
    force_check: bool,
) -> bool {
    let exe_needs_update = refresh_kind.exe().needs_update(|| process.exe.is_none());
    if !process.name.is_empty() && !exe_needs_update && !force_check {
        return true;
    }
    let mut buffer: Vec<u8> = Vec::with_capacity(libc::PROC_PIDPATHINFO_MAXSIZE as _);
    unsafe {
        match libc::proc_pidpath(
            process.pid.0,
            buffer.as_mut_ptr() as *mut _,
            libc::PROC_PIDPATHINFO_MAXSIZE as _,
        ) {
            x if x > 0 => {
                buffer.set_len(x as _);
                let tmp = OsString::from_vec(buffer);
                let exe = PathBuf::from(tmp);
                if process.name.is_empty() {
                    exe.file_name()
                        .unwrap_or_default()
                        .clone_into(&mut process.name);
                }
                if exe_needs_update {
                    process.exe = Some(exe);
                }
                true
            }
            _ => false,
        }
    }
}

pub(super) unsafe fn get_process_infos(
    process: &mut ProcessInner,
    refresh_kind: ProcessRefreshKind,
) -> bool {
    // Layout of the `sysctl` KERN_PROCARGS2 buffer.
    let mut mib: [libc::c_int; 3] = [libc::CTL_KERN, libc::KERN_PROCARGS2, process.pid.0 as _];
    let mut arg_max = 0;
    unsafe {
        // First retrieve the size needed for the data (in `arg_max`).
        if libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as _,
            std::ptr::null_mut(),
            &mut arg_max,
            std::ptr::null_mut(),
            0,
        ) == -1
        {
            sinf_debug!(
                "couldn't get arguments and environment size for PID {}",
                process.pid.0
            );
            return false; // Not enough rights, presumably.
        }

        let mut proc_args: Vec<u8> = Vec::with_capacity(arg_max as _);
        if libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as _,
            proc_args.as_mut_slice().as_mut_ptr() as *mut _,
            &mut arg_max,
            std::ptr::null_mut(),
            0,
        ) == -1
        {
            sinf_debug!(
                "couldn't get arguments and environment for PID {}",
                process.pid.0
            );
            return false; // The failure reason is not observable here.
        }

        proc_args.set_len(arg_max);

        if proc_args.is_empty() {
            return false;
        }
        // Copy the number of arguments (`argc`) into `n_args`.
        let mut n_args: c_int = 0;
        libc::memcpy(
            &mut n_args as *mut _ as *mut _,
            proc_args.as_slice().as_ptr() as *const _,
            mem::size_of::<c_int>(),
        );

        // Skip `argc`.
        let proc_args = &proc_args[mem::size_of::<c_int>()..];

        let (exe, proc_args) = get_exe(proc_args);
        if process.name.is_empty() {
            exe.file_name()
                .unwrap_or_default()
                .clone_into(&mut process.name);
        }

        if refresh_kind.exe().needs_update(|| process.exe.is_none()) {
            process.exe = Some(exe.to_owned());
        }

        let environ_needs_update = refresh_kind
            .environ()
            .needs_update(|| process.environ.is_empty());
        let cmd_needs_update = refresh_kind.cmd().needs_update(|| process.cmd.is_empty());
        if !environ_needs_update && !cmd_needs_update {
            // Nothing else to do.
            return true;
        }
        let proc_args = get_arguments(&mut process.cmd, proc_args, n_args, cmd_needs_update);
        if environ_needs_update {
            get_environ(&mut process.environ, proc_args);
        }
        true
    }
}