sinf 0.1.0

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

impl SystemInner {
    #[allow(clippy::cast_ptr_alignment)]
    pub(crate) fn refresh_processes_specifics(
        &mut self,
        processes_to_update: ProcessesToUpdate<'_>,
        refresh_kind: ProcessRefreshKind,
    ) -> usize {
        #[inline(always)]
        fn real_filter(e: Pid, filter: &[Pid]) -> bool {
            filter.contains(&e)
        }

        #[inline(always)]
        fn empty_filter(_e: Pid, _filter: &[Pid]) -> bool {
            true
        }

        #[allow(clippy::type_complexity)]
        let (filter_array, filter_callback): (
            &[Pid],
            &(dyn Fn(Pid, &[Pid]) -> bool + Sync + Send),
        ) = match processes_to_update {
            ProcessesToUpdate::All => (&[], &empty_filter),
            ProcessesToUpdate::Some(pids) => {
                if pids.is_empty() {
                    return 0;
                }
                (pids, &real_filter)
            }
        };

        let now = get_now();

        let nb_cpus = if refresh_kind.cpu() {
            self.cpus.len() as u64
        } else {
            0
        };

        // Use CreateToolhelp32Snapshot to take a snapshot of all running processes, and convert a failure into an error.
        let snapshot = match unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) } {
            Ok(handle) => handle,
            Err(_err) => {
                sinf_debug!(
                    "Error capturing process snapshot: CreateToolhelp32Snapshot returned {}",
                    _err
                );
                return 0;
            }
        };

        // This owns the handle and ensures that it is closed when dropped.
        let snapshot = unsafe { Owned::new(snapshot) };

        // https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/ns-tlhelp32-processentry32w The Microsoft documentation requires the 'dwSize' field of PROCESSENTRY32W to be
        let mut process_entry = PROCESSENTRY32W {
            dwSize: size_of::<PROCESSENTRY32W>() as u32,
            ..Default::default()
        };

        let mut num_procs = 0; // Tracks the number of updated processes.
        let process_list = &mut self.process_list;

        // Process the first entry.
        unsafe {
            if let Err(_error) = Process32FirstW(*snapshot, &mut process_entry) {
                sinf_debug!("Process32FirstW has failed: {_error:?}");
                return 0;
            }
        }

        #[cfg(feature = "gpu")]
        if (refresh_kind.gpu_usage() || refresh_kind.gpu_memory())
            && let Some(gpu_query) = self.gpu_query.as_mut()
        {
            gpu_query.refresh();
        }

        // Iterate over the processes in the snapshot, using Process32NextW to read each subsequent PROCESSENTRY32W.
        loop {
            let proc_id = Pid::from_u32(process_entry.th32ProcessID);

            if filter_callback(proc_id, filter_array) {
                // The process is already listed.
                if let Some(p) = process_list.get_mut(&proc_id) {
                    // Update it with the most recent information.
                    let p = &mut p.inner;
                    p.update(
                        refresh_kind,
                        nb_cpus,
                        now,
                        false,
                        process_entry.cntThreads,
                        #[cfg(feature = "gpu")]
                        &mut self.gpu_query,
                    );

                    // Update the parent process.
                    let parent = if process_entry.th32ParentProcessID == 0 {
                        None
                    } else {
                        Some(Pid::from_u32(process_entry.th32ParentProcessID))
                    };

                    p.parent = parent;
                } else {
                    // Build a new 'ProcessInner' from the Windows PROCESSENTRY32W struct.
                    let mut p = ProcessInner::from_process_entry(&process_entry, now);
                    p.update(
                        refresh_kind,
                        nb_cpus,
                        now,
                        false,
                        process_entry.cntThreads,
                        #[cfg(feature = "gpu")]
                        &mut self.gpu_query,
                    );
                    process_list.insert(proc_id, Process { inner: p });
                }

                num_procs += 1;
            }

            // Nothing left to process.
            if unsafe { Process32NextW(*snapshot, &mut process_entry).is_err() } {
                break;
            }
        }

        num_procs
    }

    pub(crate) fn processes(&self) -> &HashMap<Pid, Process> {
        &self.process_list
    }

    pub(crate) fn processes_mut(&mut self) -> &mut HashMap<Pid, Process> {
        &mut self.process_list
    }

    pub(crate) fn process(&self, pid: Pid) -> Option<&Process> {
        self.process_list.get(&pid)
    }
}