sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::cell::UnsafeCell;
use std::collections::{HashMap, HashSet};
use std::ffi::{CStr, CString, OsStr, OsString};
use std::fs::{DirEntry, read_dir};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
#[cfg(feature = "gpu")]
use std::time::Instant;

use libc::{c_ulong, gid_t, pid_t, uid_t};

use crate::sys::system::SystemInfo;
use crate::sys::utils::{read_file_into, read_path_into};
use crate::{
    Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, ProcessesToUpdate, ThreadKind, Uid,
    UpdateKind,
};

use super::inner::{set_time, update_process_disk_activity};
use super::{ProcDir, ProcIndex, ProcessBuffers, ProcessInner, Wrap};

pub(super) struct ProcAndTasks {
    pid: Pid,
    parent_pid: Option<Pid>,
    path: CString,
    tasks: Option<HashSet<Pid>>,
    is_thread: bool,
    ids: Option<Ids>,
}

#[cfg(feature = "multithread")]
#[inline]
pub(super) fn iter<T>(val: T) -> rayon::iter::IterBridge<T>
where
    T: rayon::iter::ParallelBridge,
{
    val.par_bridge()
}

#[cfg(not(feature = "multithread"))]
#[inline]
pub(super) fn iter<T>(val: T) -> T
where
    T: Iterator,
{
    val
}

/// Reads the whole `/proc` folder.
pub(crate) fn refresh_procs(
    proc_list: &mut HashMap<Pid, Process>,
    proc_path: &Path,
    uptime: u64,
    info: &SystemInfo,
    processes_to_update: ProcessesToUpdate<'_>,
    refresh_kind: ProcessRefreshKind,
) -> usize {
    #[cfg(feature = "multithread")]
    use rayon::iter::ParallelIterator;

    let nb_updated = AtomicUsize::new(0);
    #[cfg(feature = "gpu")]
    let now = Instant::now();
    let mut buffers = ProcessBuffers::new(refresh_kind);

    // This code visits processes listed in `/proc` and tasks listed in `/proc/[PID]/task`.
    let procs = {
        let pid_iter: Box<dyn Iterator<Item = (PathBuf, Pid)> + Send> = match processes_to_update {
            ProcessesToUpdate::All => match read_dir(proc_path) {
                Ok(proc_entries) => Box::new(proc_entries.filter_map(filter_pid_entries)),
                Err(_err) => {
                    sinf_debug!("Failed to read folder {proc_path:?}: {_err:?}");
                    return 0;
                }
            },
            ProcessesToUpdate::Some(pids) => Box::new(
                pids.iter()
                    .map(|pid| (proc_path.join(pid.to_string()), *pid)),
            ),
        };

        let proc_list = Wrap(UnsafeCell::new(proc_list));

        let get_process_data = |buffers: &mut ProcessBuffers, e: ProcAndTasks| {
            let proc_list = proc_list.get();
            let new_process = _get_process_data(
                &e.path,
                proc_list,
                e.pid,
                e.is_thread,
                e.parent_pid,
                uptime,
                info,
                refresh_kind,
                e.tasks,
                e.ids,
                buffers,
                #[cfg(feature = "gpu")]
                now,
            )
            .ok()?;
            nb_updated.fetch_add(1, Ordering::Relaxed);
            new_process
        };
        let get_procs = |buffers: &mut ProcessBuffers, (path, pid): (PathBuf, Pid)| {
            get_proc_and_tasks(path, pid, refresh_kind, processes_to_update, buffers)
        };

        // Each rayon job receives its own buffers.
        #[cfg(feature = "multithread")]
        let procs = iter(pid_iter)
            .map_init(|| ProcessBuffers::new(refresh_kind), get_procs)
            .flatten()
            .map_init(|| ProcessBuffers::new(refresh_kind), get_process_data)
            .flatten();
        #[cfg(not(feature = "multithread"))]
        let procs = {
            let mut procs_buffers = ProcessBuffers::new(refresh_kind);
            let buffers = &mut buffers;
            iter(pid_iter)
                .flat_map(move |e| get_procs(&mut procs_buffers, e))
                .filter_map(move |e| get_process_data(buffers, e))
        };
        procs.collect::<Vec<_>>()
    };
    for proc_ in procs {
        proc_list.insert(proc_.pid(), proc_);
    }
    #[cfg(feature = "gpu")]
    if refresh_kind.gpu_usage() || refresh_kind.gpu_memory() {
        super::gpu::update_threads_gpu_info(proc_list, refresh_kind, now, &mut buffers);
    }
    nb_updated.into_inner()
}

pub(super) fn filter_pid_entries(
    entry: Result<DirEntry, std::io::Error>,
) -> Option<(PathBuf, Pid)> {
    if let Ok(entry) = entry
        && entry.file_type().is_ok_and(|file_type| file_type.is_dir())
        && let Some(pid) = parse_ascii_checked_usize(entry.file_name().as_bytes())
    {
        Some((entry.path(), Pid::from(pid)))
    } else {
        None
    }
}

pub(super) fn get_proc_and_tasks(
    path: PathBuf,
    pid: Pid,
    refresh_kind: ProcessRefreshKind,
    processes_to_update: ProcessesToUpdate<'_>,
    buffers: &mut ProcessBuffers,
) -> Vec<ProcAndTasks> {
    let mut parent_pid = None;
    let mut is_thread = false;

    let (ids, tgid) = match get_uid_and_gid_and_tgid(&path, buffers) {
        Some((ids, tgid)) => (Some(ids), Some(tgid)),
        None => (None, None),
    };
    let is_a_task = tgid.is_some_and(|tgid| tgid != pid);
    // Threads have no meaningful tasks, so `procs` and `tasks` are not fetched.
    let (mut procs, tasks) = if refresh_kind.tasks() && !is_a_task {
        let update_processes_list = processes_to_update == ProcessesToUpdate::All;
        // The `status` file provides user information and the tgid.
        let retrieve_ids = update_processes_list && refresh_kind.user() != UpdateKind::Never;
        let mut procs = get_proc_tasks(&path, pid, retrieve_ids, buffers);
        let tasks = procs.iter().map(|ProcAndTasks { pid, .. }| *pid).collect();

        if !update_processes_list {
            // Do not add the tasks to the list of processes to update.
            procs.clear();
        }
        (procs, Some(tasks))
    } else {
        (Vec::new(), None)
    };

    // When the process's tgid differs from its pid, it is a task (thread).
    if is_a_task {
        parent_pid = tgid;
        is_thread = true;
    }

    procs.push(ProcAndTasks {
        is_thread,
        pid,
        parent_pid,
        path: to_c_string(path),
        tasks,
        ids,
    });

    procs
}

pub(super) fn to_c_string(path: PathBuf) -> CString {
    let mut path = path.into_os_string().into_vec();
    path.push(0);
    // SAFETY: Paths cannot contain NUL bytes, and a NUL was appended.
    unsafe { CString::from_vec_with_nul_unchecked(path) }
}

pub(super) fn get_proc_tasks(
    path: &Path,
    parent_pid: Pid,
    retrieve_ids: bool,
    buffers: &mut ProcessBuffers,
) -> Vec<ProcAndTasks> {
    let task_path = path.join("task");

    read_dir(&task_path)
        .ok()
        .map(|task_entries| {
            task_entries
                .filter_map(filter_pid_entries)
                // Tasks list their own PID in the task folder, so it must be filtered out.
                .filter(|(_, pid)| *pid != parent_pid)
                .map(|(path, pid)| {
                    let ids = if retrieve_ids {
                        get_uid_and_gid_and_tgid(&path, buffers).map(|(ids, _)| ids)
                    } else {
                        None
                    };
                    ProcAndTasks {
                        pid,
                        is_thread: true,
                        path: to_c_string(path),
                        parent_pid: Some(parent_pid),
                        tasks: None,
                        ids,
                    }
                })
                .collect()
        })
        .unwrap_or_default()
}

mod ids;
mod memory;
mod parse;
mod update;

use self::ids::{Ids, get_uid_and_gid_and_tgid};
#[cfg(feature = "gpu")]
pub(super) use self::parse::parse_ascii_checked_u64;
#[cfg(any(test, all(feature = "fuzzing", target_os = "linux")))]
pub(super) use self::parse::split_content;
pub(super) use self::parse::{Parts, parse_ascii_checked_usize, parse_stat_file};
use self::update::_get_process_data;