sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use super::*;

use super::ids::{Ids, refresh_user_group_ids};
use super::memory::update_time_and_memory;
use super::parse::{parse_stat_file, split_content};

/// Reads the `stat` file into `buffers.buf`.
pub(super) fn _get_stat_data(
    proc_dir: &mut ProcDir<'_>,
    buffers: &mut ProcessBuffers,
) -> Result<(), ()> {
    let Some(mut file) = proc_dir.open(c"stat") else {
        return Err(());
    };
    read_file_into(&mut file, &mut buffers.buf).map_err(|_| ())?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
pub(super) fn update_proc_info(
    p: &mut ProcessInner,
    parent_pid: Option<Pid>,
    refresh_kind: ProcessRefreshKind,
    proc_dir: &mut ProcDir<'_>,
    parts: &Parts,
    uptime: u64,
    info: &SystemInfo,
    ids: Option<Ids>,
    buffers: &mut ProcessBuffers,
    #[cfg(feature = "gpu")] now: Instant,
) {
    fn copy_from_file(proc_dir: &mut ProcDir<'_>, name: &CStr, buf: &mut Vec<u8>) -> Vec<OsString> {
        if proc_dir.read_into(name, buf) {
            split_content(buf)
        } else {
            Vec::new()
        }
    }

    fn update_optional_path(target: &mut Option<PathBuf>, new_val: Option<&[u8]>) {
        if let Some(new_val) = new_val
            && target
                .as_ref()
                .is_none_or(|target| target.as_os_str().as_bytes() != new_val)
        {
            *target = Some(PathBuf::from(OsStr::from_bytes(new_val)));
        }
    }

    update_parent_pid(p, parent_pid, parts);

    p.status = parts.status;
    refresh_user_group_ids(p, ids, refresh_kind);

    if refresh_kind.exe().needs_update(|| p.exe.is_none()) {
        // Do not use `cmd[0]`; it is not equivalent.
        let new_exe = proc_dir.read_link(c"exe", &mut buffers.buf).map(|exe| {
            // When the target executable is modified or removed, Linux appends ` (deleted)` to the path.
            exe.strip_suffix(b" (deleted)").unwrap_or(exe)
        });
        update_optional_path(&mut p.exe, new_exe);
    }

    if refresh_kind.cmd().needs_update(|| p.cmd.is_empty()) {
        let new_cmd = copy_from_file(proc_dir, c"cmdline", &mut buffers.buf);
        if !new_cmd.is_empty() || p.cmd.is_empty() {
            p.cmd = new_cmd;
        }
    }
    if refresh_kind.environ().needs_update(|| p.environ.is_empty()) {
        let new_environ = copy_from_file(proc_dir, c"environ", &mut buffers.buf);
        if !new_environ.is_empty() || p.environ.is_empty() {
            p.environ = new_environ;
        }
    }
    if refresh_kind.cwd().needs_update(|| p.cwd.is_none()) {
        update_optional_path(&mut p.cwd, proc_dir.read_link(c"cwd", &mut buffers.buf));
    }
    if refresh_kind.root().needs_update(|| p.root.is_none()) {
        update_optional_path(&mut p.root, proc_dir.read_link(c"root", &mut buffers.buf));
    }

    update_time_and_memory(
        proc_dir,
        p,
        parts,
        uptime,
        info,
        refresh_kind,
        &mut buffers.buf,
    );
    if refresh_kind.disk_usage() {
        update_process_disk_activity(p, proc_dir, &mut buffers.buf);
    }
    // Must run after `update_time_and_memory`.
    if refresh_kind.cpu() {
        // CPU times are reported in ticks scaled by HZ, which is fixed externally at 100 ticks per second.
        p.accumulated_cpu_time =
            p.utime.saturating_add(p.stime).saturating_mul(1_000) / info.clock_cycle;
    }
    #[cfg(feature = "gpu")]
    if (refresh_kind.gpu_usage() || refresh_kind.gpu_memory())
        // Kernel threads have no file descriptors, so there are no GPU ones to find.
        && p.thread_kind != Some(ThreadKind::Kernel)
    {
        p.gpu_info.share_parent_fd_table = p.thread_kind == Some(ThreadKind::Userland)
            && p.parent
                .is_some_and(|parent| super::super::gpu::same_fd_table(parent, p.pid));
        // When a thread shares its parent's file descriptor table, its GPU information is copied from the parent once all processes have been updated.
        if !p.gpu_info.share_parent_fd_table {
            super::super::gpu::compute_gpu_usage(
                proc_dir,
                &mut p.gpu_info,
                now,
                refresh_kind,
                buffers,
            );
        }
    }
    p.updated = true;
    // A process may be marked nonexistent (for example, while hidden by `hidepid=invisible`) and become readable again later.
    p.exists = true;
}

pub(super) fn update_parent_pid(p: &mut ProcessInner, parent_pid: Option<Pid>, parts: &Parts) {
    p.parent = match parent_pid {
        Some(parent_pid) if parent_pid.0 != 0 => Some(parent_pid),
        _ => match parts.parent_pid {
            Some(p) if p != 0 => Some(Pid(p)),
            _ => None,
        },
    };
}

#[allow(clippy::too_many_arguments)]
pub(super) fn retrieve_all_new_process_info(
    is_thread: bool,
    pid: Pid,
    parent_pid: Option<Pid>,
    parts: &mut Parts,
    proc_dir: &mut ProcDir<'_>,
    info: &SystemInfo,
    refresh_kind: ProcessRefreshKind,
    uptime: u64,
    ids: Option<Ids>,
    buffers: &mut ProcessBuffers,
    #[cfg(feature = "gpu")] now: Instant,
) -> Process {
    let mut p = ProcessInner::new(
        pid,
        PathBuf::from(OsStr::from_bytes(proc_dir.path.to_bytes())),
    );

    // The start time is not yet valid here; it still needs conversion into real time.
    let start_time_without_boot_time = parts.start_time / info.clock_cycle;
    p.start_time_raw = parts.start_time;
    p.start_time_without_boot_time = start_time_without_boot_time;
    p.start_time = p
        .start_time_without_boot_time
        .saturating_add(info.boot_time);

    p.name = std::mem::take(&mut parts.short_exe);
    if parts
        .flags
        .is_some_and(|flags| flags & libc::PF_KTHREAD as c_ulong != 0)
    {
        p.thread_kind = Some(ThreadKind::Kernel);
    } else if is_thread {
        p.thread_kind = Some(ThreadKind::Userland);
    }

    update_proc_info(
        &mut p,
        parent_pid,
        refresh_kind,
        proc_dir,
        parts,
        uptime,
        info,
        ids,
        buffers,
        #[cfg(feature = "gpu")]
        now,
    );

    Process { inner: p }
}

#[allow(clippy::too_many_arguments)]
pub(super) fn update_existing_process(
    is_thread: bool,
    proc: &mut Process,
    proc_dir: &mut ProcDir<'_>,
    parent_pid: Option<Pid>,
    uptime: u64,
    info: &SystemInfo,
    refresh_kind: ProcessRefreshKind,
    tasks: Option<HashSet<Pid>>,
    ids: Option<Ids>,
    buffers: &mut ProcessBuffers,
    #[cfg(feature = "gpu")] now: Instant,
) -> Result<Option<Process>, ()> {
    let entry = &mut proc.inner;
    // The file descriptor may be invalid if the original process terminated and another took its place.
    _get_stat_data(proc_dir, buffers)?;
    entry.tasks = tasks;

    // `parts` borrows the `stat` buffer while `buffers` is still needed, so it is taken out and put back afterwards.
    let Some(mut parts) = parse_stat_file(&buffers.buf, Some(entry.start_time_raw)) else {
        return Err(());
    };

    // A new process may reuse this PID after the original one terminates.
    if parts.start_time == entry.start_time_raw {
        // If the entry was first discovered without thread information (for example, in `ProcessesToUpdate::All` mode), set `thread_kind` now.
        if is_thread && entry.thread_kind.is_none() {
            entry.thread_kind = Some(ThreadKind::Userland);
        }

        update_proc_info(
            entry,
            parent_pid,
            refresh_kind,
            proc_dir,
            &parts,
            uptime,
            info,
            ids,
            buffers,
            #[cfg(feature = "gpu")]
            now,
        );
        return Ok(None);
    }
    // Reaching this point means the PID still exists but belongs to a different process.
    let p = retrieve_all_new_process_info(
        is_thread,
        entry.pid,
        parent_pid,
        &mut parts,
        proc_dir,
        info,
        refresh_kind,
        uptime,
        ids,
        buffers,
        #[cfg(feature = "gpu")]
        now,
    );
    *proc = p;
    // The PID is already in the `HashMap`, so it is not added again.
    Ok(None)
}

#[allow(clippy::too_many_arguments)]
pub(super) fn _get_process_data(
    path: &CStr,
    proc_list: &mut HashMap<Pid, Process>,
    pid: Pid,
    is_thread: bool,
    parent_pid: Option<Pid>,
    uptime: u64,
    info: &SystemInfo,
    refresh_kind: ProcessRefreshKind,
    tasks: Option<HashSet<Pid>>,
    ids: Option<Ids>,
    buffers: &mut ProcessBuffers,
    #[cfg(feature = "gpu")] now: Instant,
) -> Result<Option<Process>, ()> {
    let mut proc_dir = ProcDir::new(path);
    if let Some(ref mut entry) = proc_list.get_mut(&pid) {
        return update_existing_process(
            is_thread,
            entry,
            &mut proc_dir,
            parent_pid,
            uptime,
            info,
            refresh_kind,
            tasks,
            ids,
            buffers,
            #[cfg(feature = "gpu")]
            now,
        );
    }
    _get_stat_data(&mut proc_dir, buffers)?;
    // `parts` borrows the `stat` buffer while `buffers` is still needed, so it is taken out and put back afterwards.
    let Some(mut parts) = parse_stat_file(&buffers.buf, None) else {
        return Err(());
    };

    let mut new_process = retrieve_all_new_process_info(
        is_thread,
        pid,
        parent_pid,
        &mut parts,
        &mut proc_dir,
        info,
        refresh_kind,
        uptime,
        ids,
        buffers,
        #[cfg(feature = "gpu")]
        now,
    );
    new_process.inner.tasks = tasks;
    Ok(Some(new_process))
}