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::HashSet;
use std::ffi::{CStr, OsString};
use std::fs::File;
use std::io::Read;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::path::PathBuf;
#[cfg(feature = "gpu")]
use std::time::Instant;

use crate::{Gid, Pid, ProcessRefreshKind, ProcessStatus, ThreadKind, Uid};

#[allow(dead_code)]
#[repr(usize)]
enum ProcIndex {
    Pid = 0,
    State,
    ParentPid,
    GroupId,
    SessionId,
    Tty,
    ForegroundProcessGroupId,
    Flags,
    MinorFaults,
    ChildrenMinorFaults,
    MajorFaults,
    ChildrenMajorFaults,
    UserTime,
    SystemTime,
    ChildrenUserTime,
    ChildrenKernelTime,
    Priority,
    Nice,
    NumberOfThreads,
    IntervalTimerSigalarm,
    StartTime,
    VirtualSize,
    ResidentSetSize,
    // More fields exist; only the listed ones are used.
}

#[cfg(feature = "gpu")]
#[derive(Default)]
struct GpuInfo {
    last_update: Option<Instant>,
    gpu_time: u64,
    gpu_usage: Option<f32>,
    memory: Option<u64>,
    /// `true` when the thread shares its parent process's fd table.
    share_parent_fd_table: bool,
}

pub(crate) struct ProcessInner {
    pub(crate) name: OsString,
    pub(crate) cmd: Vec<OsString>,
    pub(crate) exe: Option<PathBuf>,
    pub(crate) pid: Pid,
    parent: Option<Pid>,
    pub(crate) environ: Vec<OsString>,
    pub(crate) cwd: Option<PathBuf>,
    pub(crate) root: Option<PathBuf>,
    pub(crate) memory: u64,
    pub(crate) virtual_memory: u64,
    utime: u64,
    stime: u64,
    old_utime: u64,
    old_stime: u64,
    start_time_without_boot_time: u64,
    start_time: u64,
    start_time_raw: u64,
    run_time: u64,
    pub(crate) updated: bool,
    cpu_usage: f32,
    user_id: Option<Uid>,
    effective_user_id: Option<Uid>,
    group_id: Option<Gid>,
    effective_group_id: Option<Gid>,
    pub(crate) status: ProcessStatus,
    pub(crate) tasks: Option<HashSet<Pid>>,
    old_read_bytes: u64,
    old_written_bytes: u64,
    read_bytes: u64,
    written_bytes: u64,
    thread_kind: Option<ThreadKind>,
    proc_path: PathBuf,
    accumulated_cpu_time: u64,
    exists: bool,
    #[cfg(feature = "gpu")]
    gpu_info: GpuInfo,
}

struct ProcessBuffers {
    buf: Vec<u8>,
    /// Builds the paths of the files to read.
    path: PathBuf,
    #[cfg(feature = "gpu")]
    dents: Vec<u8>,
}

impl ProcessBuffers {
    #[allow(clippy::uninit_vec)]
    fn new(
        #[cfg_attr(not(feature = "gpu"), allow(unused_variables))] refresh_kind: ProcessRefreshKind,
    ) -> Self {
        Self {
            buf: Vec::with_capacity(16_384),
            path: PathBuf::new(),
            #[cfg(feature = "gpu")]
            dents: {
                if refresh_kind.gpu_usage() || refresh_kind.gpu_memory() {
                    let mut data = Vec::with_capacity(std::mem::size_of::<libc::dirent64>() * 20);
                    // SAFETY: syscalls write `data`, so no explicit initialization is needed.
                    unsafe {
                        data.set_len(data.capacity());
                    }
                    data
                } else {
                    Vec::new()
                }
            },
        }
    }
}

/// Accesses the files of a `/proc/<pid>` folder.
struct ProcDir<'a> {
    path: &'a CStr,
    dir_fd: Option<OwnedFd>,
}

impl<'a> ProcDir<'a> {
    fn new(path: &'a CStr) -> Self {
        Self { path, dir_fd: None }
    }

    fn dir_fd(&mut self) -> Option<&OwnedFd> {
        if let Some(ref dir_fd) = self.dir_fd {
            return Some(dir_fd);
        }
        let fd = retry_eintr!(unsafe {
            libc::open(
                self.path.as_ptr(),
                libc::O_RDONLY
                    | libc::O_PATH
                    | libc::O_DIRECTORY
                    | libc::O_CLOEXEC
                    | libc::O_NOFOLLOW,
            )
        });
        if fd < 0 {
            sinf_debug!(
                "failed to open {:?}: {:?}",
                self.path,
                std::io::Error::last_os_error()
            );
            return None;
        }
        // SAFETY: `fd` was just opened and is not owned elsewhere.
        self.dir_fd = unsafe { Some(OwnedFd::from_raw_fd(fd)) };
        self.dir_fd.as_ref()
    }

    fn open(&mut self, name: &CStr) -> Option<File> {
        let dir_fd = self.dir_fd()?;
        let fd = retry_eintr!(unsafe {
            libc::openat(
                dir_fd.as_raw_fd(),
                name.as_ptr(),
                libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW,
            )
        });
        if fd < 0 {
            sinf_debug!(
                "Failed to open file {name:?}: {:?}",
                std::io::Error::last_os_error()
            );
            None
        } else {
            // SAFETY: `fd` was just opened and is not owned elsewhere.
            Some(unsafe { File::from_raw_fd(fd) })
        }
    }

    /// Reads the whole content of `name` into `buf`, replacing its previous content.
    fn read_into(&mut self, name: &CStr, buf: &mut Vec<u8>) -> bool {
        let Some(mut file) = self.open(name) else {
            return false;
        };
        buf.clear();
        if let Err(_err) = file.read_to_end(buf) {
            sinf_debug!("Failed to read file: {_err:?}");
            false
        } else {
            true
        }
    }

    /// Reads the target of the link `name` into `buf`, replacing its previous content.
    fn read_link<'b>(&mut self, name: &CStr, buf: &'b mut Vec<u8>) -> Option<&'b [u8]> {
        let dir_fd = self.dir_fd()?;
        buf.clear();
        if buf.len() < 256 {
            buf.reserve(256);
        }
        loop {
            let read = unsafe {
                libc::readlinkat(
                    dir_fd.as_raw_fd(),
                    name.as_ptr(),
                    buf.as_mut_ptr() as *mut _,
                    buf.capacity(),
                )
            };
            if read < 0 {
                sinf_debug!(
                    "failed to read link {name:?} in {:?}: {:?}",
                    self.path,
                    std::io::Error::last_os_error(),
                );
                return None;
            }
            let read = read as usize;
            if read < buf.capacity() {
                // SAFETY: `readlinkat` initialized exactly the first `read` bytes.
                unsafe { buf.set_len(read) };
                return Some(buf);
            }
            // The link may have been truncated; retry with a larger buffer.
            buf.reserve(buf.capacity() * 2);
        }
    }
}

struct Wrap<'a, T>(UnsafeCell<&'a mut T>);

impl<'a, T> Wrap<'a, T> {
    fn get(&self) -> &'a mut T {
        unsafe { *(self.0.get()) }
    }
}

#[allow(clippy::non_send_fields_in_send_ty)]
unsafe impl<T> Send for Wrap<'_, T> {}
unsafe impl<T> Sync for Wrap<'_, T> {}

#[cfg(feature = "gpu")]
mod gpu;
mod inner;
mod refresh;
mod status;

#[cfg(test)]
mod tests;

pub(crate) use self::inner::compute_cpu_usage;
pub(crate) use self::refresh::refresh_procs;

#[cfg(all(feature = "fuzzing", target_os = "linux"))]
pub(crate) fn fuzz_parse_stat(data: &[u8]) {
    let _ = self::refresh::parse_stat_file(data, None);
    let _ = self::refresh::split_content(data);
}