Skip to main content

sysinfo/unix/linux/
process.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::cell::UnsafeCell;
4use std::collections::{HashMap, HashSet};
5use std::ffi::{CStr, CString, OsStr, OsString};
6use std::fmt;
7use std::fs::{self, DirEntry, File, read_dir};
8use std::io::Read;
9use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
10use std::os::unix::ffi::{OsStrExt, OsStringExt};
11use std::path::{Path, PathBuf};
12use std::process::ExitStatus;
13use std::sync::atomic::{AtomicUsize, Ordering};
14#[cfg(feature = "gpu")]
15use std::time::Instant;
16
17use libc::{c_ulong, gid_t, pid_t, uid_t};
18
19use crate::sys::system::SystemInfo;
20use crate::sys::utils::{get_all_data_from_file, read_file_into, read_path_into};
21use crate::{
22    DiskUsage, Gid, Pid, Process, ProcessRefreshKind, ProcessStatus, ProcessesToUpdate, Signal,
23    ThreadKind, Uid, UpdateKind,
24};
25
26#[doc(hidden)]
27impl From<u8> for ProcessStatus {
28    fn from(status: u8) -> ProcessStatus {
29        match status {
30            b'R' => ProcessStatus::Run,
31            b'S' => ProcessStatus::Sleep,
32            b'I' => ProcessStatus::Idle,
33            b'D' => ProcessStatus::UninterruptibleDiskSleep,
34            b'Z' => ProcessStatus::Zombie,
35            b'T' => ProcessStatus::Stop,
36            b't' => ProcessStatus::Tracing,
37            b'X' | b'x' => ProcessStatus::Dead,
38            b'K' => ProcessStatus::Wakekill,
39            b'W' => ProcessStatus::Waking,
40            b'P' => ProcessStatus::Parked,
41            x => ProcessStatus::Unknown(x as u32),
42        }
43    }
44}
45
46impl fmt::Display for ProcessStatus {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        f.write_str(match *self {
49            ProcessStatus::Idle => "Idle",
50            ProcessStatus::Run => "Runnable",
51            ProcessStatus::Sleep => "Sleeping",
52            ProcessStatus::Stop => "Stopped",
53            ProcessStatus::Zombie => "Zombie",
54            ProcessStatus::Tracing => "Tracing",
55            ProcessStatus::Dead => "Dead",
56            ProcessStatus::Wakekill => "Wakekill",
57            ProcessStatus::Waking => "Waking",
58            ProcessStatus::Parked => "Parked",
59            ProcessStatus::UninterruptibleDiskSleep => "UninterruptibleDiskSleep",
60            _ => "Unknown",
61        })
62    }
63}
64
65#[allow(dead_code)]
66#[repr(usize)]
67enum ProcIndex {
68    Pid = 0,
69    State,
70    ParentPid,
71    GroupId,
72    SessionId,
73    Tty,
74    ForegroundProcessGroupId,
75    Flags,
76    MinorFaults,
77    ChildrenMinorFaults,
78    MajorFaults,
79    ChildrenMajorFaults,
80    UserTime,
81    SystemTime,
82    ChildrenUserTime,
83    ChildrenKernelTime,
84    Priority,
85    Nice,
86    NumberOfThreads,
87    IntervalTimerSigalarm,
88    StartTime,
89    VirtualSize,
90    ResidentSetSize,
91    // More exist but we only use the listed ones. For more, take a look at `man proc`.
92}
93
94#[cfg(feature = "gpu")]
95#[derive(Default)]
96struct GpuInfo {
97    last_update: Option<Instant>,
98    gpu_time: u64,
99    gpu_usage: Option<f32>,
100    memory: Option<u64>,
101    /// `true` if this is a thread sharing the fd table of its parent process. In such cases, to
102    /// prevent reading the `fd`/`fdinfo` folders to retrieve the same information, we instead skip
103    /// threads with this field to `true` and copy the information from the parent process after
104    /// we're done updating all processes.
105    share_parent_fd_table: bool,
106}
107
108pub(crate) struct ProcessInner {
109    pub(crate) name: OsString,
110    pub(crate) cmd: Vec<OsString>,
111    pub(crate) exe: Option<PathBuf>,
112    pub(crate) pid: Pid,
113    parent: Option<Pid>,
114    pub(crate) environ: Vec<OsString>,
115    pub(crate) cwd: Option<PathBuf>,
116    pub(crate) root: Option<PathBuf>,
117    pub(crate) memory: u64,
118    pub(crate) virtual_memory: u64,
119    utime: u64,
120    stime: u64,
121    old_utime: u64,
122    old_stime: u64,
123    start_time_without_boot_time: u64,
124    start_time: u64,
125    start_time_raw: u64,
126    run_time: u64,
127    pub(crate) updated: bool,
128    cpu_usage: f32,
129    user_id: Option<Uid>,
130    effective_user_id: Option<Uid>,
131    group_id: Option<Gid>,
132    effective_group_id: Option<Gid>,
133    pub(crate) status: ProcessStatus,
134    pub(crate) tasks: Option<HashSet<Pid>>,
135    old_read_bytes: u64,
136    old_written_bytes: u64,
137    read_bytes: u64,
138    written_bytes: u64,
139    thread_kind: Option<ThreadKind>,
140    proc_path: PathBuf,
141    accumulated_cpu_time: u64,
142    exists: bool,
143    #[cfg(feature = "gpu")]
144    gpu_info: GpuInfo,
145}
146
147impl ProcessInner {
148    pub(crate) fn new(pid: Pid, proc_path: PathBuf) -> Self {
149        Self {
150            name: OsString::new(),
151            pid,
152            parent: None,
153            cmd: Vec::new(),
154            environ: Vec::new(),
155            exe: None,
156            cwd: None,
157            root: None,
158            memory: 0,
159            virtual_memory: 0,
160            cpu_usage: 0.,
161            utime: 0,
162            stime: 0,
163            old_utime: 0,
164            old_stime: 0,
165            updated: true,
166            start_time_without_boot_time: 0,
167            start_time: 0,
168            start_time_raw: 0,
169            run_time: 0,
170            user_id: None,
171            effective_user_id: None,
172            group_id: None,
173            effective_group_id: None,
174            status: ProcessStatus::Unknown(0),
175            tasks: None,
176            old_read_bytes: 0,
177            old_written_bytes: 0,
178            read_bytes: 0,
179            written_bytes: 0,
180            thread_kind: None,
181            proc_path,
182            accumulated_cpu_time: 0,
183            exists: true,
184            #[cfg(feature = "gpu")]
185            gpu_info: GpuInfo::default(),
186        }
187    }
188
189    pub(crate) fn kill_with(&self, signal: Signal) -> Option<bool> {
190        let c_signal = crate::sys::system::convert_signal(signal)?;
191        unsafe { Some(libc::kill(self.pid.0, c_signal) == 0) }
192    }
193
194    pub(crate) fn name(&self) -> &OsStr {
195        &self.name
196    }
197
198    pub(crate) fn cmd(&self) -> &[OsString] {
199        &self.cmd
200    }
201
202    pub(crate) fn exe(&self) -> Option<&Path> {
203        self.exe.as_deref()
204    }
205
206    pub(crate) fn pid(&self) -> Pid {
207        self.pid
208    }
209
210    pub(crate) fn cgroup_limits(&self) -> Option<crate::CGroupLimits> {
211        crate::sys::cgroup::limits_for_process(&self.proc_path)
212    }
213
214    pub(crate) fn environ(&self) -> &[OsString] {
215        &self.environ
216    }
217
218    pub(crate) fn cwd(&self) -> Option<&Path> {
219        self.cwd.as_deref()
220    }
221
222    pub(crate) fn root(&self) -> Option<&Path> {
223        self.root.as_deref()
224    }
225
226    pub(crate) fn memory(&self) -> u64 {
227        self.memory
228    }
229
230    pub(crate) fn virtual_memory(&self) -> u64 {
231        self.virtual_memory
232    }
233
234    pub(crate) fn parent(&self) -> Option<Pid> {
235        self.parent
236    }
237
238    pub(crate) fn status(&self) -> ProcessStatus {
239        self.status
240    }
241
242    pub(crate) fn start_time(&self) -> u64 {
243        self.start_time
244    }
245
246    pub(crate) fn run_time(&self) -> u64 {
247        self.run_time
248    }
249
250    pub(crate) fn cpu_usage(&self) -> f32 {
251        self.cpu_usage
252    }
253
254    pub(crate) fn accumulated_cpu_time(&self) -> u64 {
255        self.accumulated_cpu_time
256    }
257
258    pub(crate) fn disk_usage(&self) -> DiskUsage {
259        DiskUsage {
260            written_bytes: self.written_bytes.saturating_sub(self.old_written_bytes),
261            total_written_bytes: self.written_bytes,
262            read_bytes: self.read_bytes.saturating_sub(self.old_read_bytes),
263            total_read_bytes: self.read_bytes,
264        }
265    }
266
267    pub(crate) fn user_id(&self) -> Option<&Uid> {
268        self.user_id.as_ref()
269    }
270
271    pub(crate) fn effective_user_id(&self) -> Option<&Uid> {
272        self.effective_user_id.as_ref()
273    }
274
275    pub(crate) fn group_id(&self) -> Option<Gid> {
276        self.group_id
277    }
278
279    pub(crate) fn effective_group_id(&self) -> Option<Gid> {
280        self.effective_group_id
281    }
282
283    pub(crate) fn wait(&self) -> Option<ExitStatus> {
284        // If anything fails when trying to retrieve the start time, better to return `None`.
285        let mut file = File::open(self.proc_path.join("stat")).ok()?;
286        let data = get_all_data_from_file(&mut file, 1024).ok()?;
287
288        let parts = parse_stat_file(&data, Some(self.start_time_raw))?;
289
290        if parts.start_time != self.start_time_raw {
291            sysinfo_debug!("Seems to not be the same process anymore");
292            return None;
293        }
294
295        crate::unix::utils::wait_process(self.pid)
296    }
297
298    pub(crate) fn session_id(&self) -> Option<Pid> {
299        unsafe {
300            let session_id = libc::getsid(self.pid.0);
301            if session_id < 0 {
302                None
303            } else {
304                Some(Pid(session_id))
305            }
306        }
307    }
308
309    pub(crate) fn thread_kind(&self) -> Option<ThreadKind> {
310        self.thread_kind
311    }
312
313    pub(crate) fn switch_updated(&mut self) -> bool {
314        std::mem::replace(&mut self.updated, false)
315    }
316
317    pub(crate) fn set_nonexistent(&mut self) {
318        self.exists = false;
319    }
320
321    pub(crate) fn exists(&self) -> bool {
322        self.exists
323    }
324
325    pub(crate) fn open_files(&self) -> Option<usize> {
326        let open_files_dir = self.proc_path.as_path().join("fd");
327        match fs::read_dir(&open_files_dir) {
328            Ok(entries) => Some(entries.count() as _),
329            Err(_error) => {
330                sysinfo_debug!(
331                    "Failed to get open files in `{}`: {_error:?}",
332                    open_files_dir.display(),
333                );
334                None
335            }
336        }
337    }
338
339    pub(crate) fn open_files_limit(&self) -> Option<usize> {
340        let limits_files = self.proc_path.as_path().join("limits");
341        match fs::read(&limits_files) {
342            Ok(content) => {
343                for line in content.split(|c| *c == b'\n') {
344                    if let Some(line) = line.strip_prefix(b"Max open files ")
345                        && let Some(nb) = line.split(|c| *c == b' ').find(|p| !p.is_empty())
346                    {
347                        return parse_ascii_checked_usize(nb);
348                    }
349                }
350                None
351            }
352            Err(_error) => {
353                sysinfo_debug!(
354                    "Failed to get limits in `{}`: {_error:?}",
355                    limits_files.display()
356                );
357                None
358            }
359        }
360    }
361
362    #[cfg(feature = "gpu")]
363    pub(crate) fn gpu_usage(&self) -> Option<f32> {
364        self.gpu_info.gpu_usage
365    }
366
367    #[cfg(feature = "gpu")]
368    pub fn gpu_memory(&self) -> Option<u64> {
369        self.gpu_info.memory
370    }
371}
372
373macro_rules! parse_integers {
374    ($($ty:ident: $name:ident),+) => {
375        $(
376            fn $name(bytes: &[u8]) -> Option<$ty> {
377                let mut num: $ty = 0;
378                for &b in bytes {
379                    if !b.is_ascii_digit() {
380                        return None;
381                    }
382                    num = num.checked_mul(10)?.checked_add((b - b'0') as $ty)?;
383                }
384                Some(num)
385            }
386        )+
387    }
388}
389
390parse_integers!(
391    u64: parse_ascii_checked_u64,
392    c_ulong: parse_ascii_checked_culong,
393    usize: parse_ascii_checked_usize,
394    pid_t: parse_ascii_checked_pid_t,
395    uid_t: parse_ascii_checked_uid_t
396);
397
398#[cfg(feature = "gpu")]
399mod gpu {
400    use super::*;
401    use std::mem::MaybeUninit;
402
403    const DRM_MAJOR: u32 = 226; // `/dev/dri/*`
404    const ACCEL_MAJOR: u32 = 261; // `/dev/accel/*`
405
406    // It's possible, using the `unshare` function, to make a thread not use the same `fd` table
407    // as its parent process. So returns `true` if both `pid` share the same fd table.
408    pub(super) fn same_fd_table(pid1: Pid, pid2: Pid) -> bool {
409        // FIXME: Remove it once `libc` defines this constant.
410        const KCMP_FILES: libc::c_int = 2;
411
412        unsafe { libc::syscall(libc::SYS_kcmp, pid1.0, pid2.0, KCMP_FILES, 0, 0) == 0 }
413    }
414
415    // Threads which share the fd table of their parent process aren't refreshed as it would be a
416    // duplicate. Instead, we go through all updated processes and for thread ones, we copy the
417    // GPU information from their parent. If the parent wasn't updated, the thread's own `fd` folder
418    // is read instead.
419    pub(super) fn update_threads_gpu_info(
420        proc_list: &mut HashMap<Pid, Process>,
421        refresh_kind: ProcessRefreshKind,
422        now: Instant,
423        buffers: &mut ProcessBuffers,
424    ) {
425        // Same issue as `refresh_procs`: `proc_list` needs to be accessed from two places at once.
426        // It's fine since the map itself isn't modified (and the thread and its parent are
427        // different entries).
428        let proc_list = Wrap(UnsafeCell::new(proc_list));
429        for p in proc_list.get().values_mut() {
430            let p = &mut p.inner;
431            if !p.updated || !p.gpu_info.share_parent_fd_table {
432                continue;
433            }
434            let parent_info = p
435                .parent
436                .filter(|parent| *parent != p.pid)
437                .and_then(|parent| proc_list.get().get(&parent))
438                .filter(|parent| parent.inner.updated)
439                .map(|parent| {
440                    (
441                        parent.inner.gpu_info.gpu_usage,
442                        parent.inner.gpu_info.memory,
443                    )
444                });
445            let gpu_info = &mut p.gpu_info;
446            if let Some((gpu_usage, memory)) = parent_info {
447                if refresh_kind.gpu_usage() {
448                    gpu_info.gpu_usage = gpu_usage;
449                }
450                if refresh_kind.gpu_memory() {
451                    gpu_info.memory = memory;
452                }
453            } else {
454                let path = super::to_c_string(p.proc_path.clone());
455                compute_gpu_usage(
456                    &mut ProcDir::new(&path),
457                    gpu_info,
458                    now,
459                    refresh_kind,
460                    buffers,
461                );
462            }
463        }
464    }
465
466    #[inline(always)]
467    #[allow(clippy::unnecessary_cast)]
468    fn is_gpu_device(
469        dir: &Dir,
470        file_name: &[libc::c_char],
471        stat: &mut MaybeUninit<libc::statx>,
472    ) -> bool {
473        unsafe {
474            if libc::statx(
475                dir.dir_fd,
476                file_name.as_ptr(),
477                libc::AT_STATX_DONT_SYNC | libc::AT_NO_AUTOMOUNT,
478                libc::STATX_TYPE,
479                stat.as_mut_ptr(),
480            ) != 0
481            {
482                return false;
483            }
484
485            let stat = stat.assume_init_ref();
486            (stat.stx_mode & libc::S_IFMT as libc::__u16) == libc::S_IFCHR as libc::__u16
487                && matches!(stat.stx_rdev_major, DRM_MAJOR | ACCEL_MAJOR)
488        }
489    }
490
491    struct Dir {
492        dir_fd: libc::c_int,
493    }
494
495    impl Dir {
496        fn open(proc_dir: &mut ProcDir<'_>, name: &CStr) -> Option<Self> {
497            let proc_dir_fd = proc_dir.dir_fd()?;
498            unsafe {
499                let dir_fd = retry_eintr!(libc::openat(
500                    proc_dir_fd.as_raw_fd(),
501                    name.as_ptr(),
502                    libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_DIRECTORY | libc::O_CLOEXEC,
503                ));
504                if dir_fd < 0 {
505                    None
506                } else {
507                    Some(Self { dir_fd })
508                }
509            }
510        }
511
512        fn update_dents_buf(&self, buf: &mut [u8]) -> Result<Option<usize>, ()> {
513            unsafe {
514                let read = libc::syscall(
515                    libc::SYS_getdents64,
516                    self.dir_fd,
517                    buf.as_mut_ptr() as *mut _,
518                    buf.len() as libc::c_int,
519                );
520                if read < 0 {
521                    sysinfo_debug!("getdents64 failed");
522                    Err(())
523                } else if read == 0 {
524                    Ok(None)
525                } else {
526                    Ok(Some(read as usize))
527                }
528            }
529        }
530
531        fn iter<'a>(&'a self, buf: &'a mut Vec<u8>) -> Result<Option<DirIter<'a>>, ()> {
532            if let Some(read) = self.update_dents_buf(buf)? {
533                Ok(Some(DirIter {
534                    read,
535                    pos: 0,
536                    dir: self,
537                    buf,
538                }))
539            } else {
540                Ok(None)
541            }
542        }
543    }
544
545    impl Drop for Dir {
546        fn drop(&mut self) {
547            unsafe {
548                libc::close(self.dir_fd);
549            }
550        }
551    }
552
553    struct DirIter<'a> {
554        pos: usize,
555        read: usize,
556        dir: &'a Dir,
557        // If we use an array instead of a Vec here, we get unaligned memory errors when we go
558        // through the `dirent64` entries. The `Vec` is reused across processes.
559        buf: &'a mut Vec<u8>,
560    }
561
562    impl<'a> Iterator for DirIter<'a> {
563        type Item = &'a [libc::c_char];
564
565        fn next(&mut self) -> Option<Self::Item> {
566            loop {
567                unsafe {
568                    if self.pos >= self.read {
569                        if let Ok(Some(read)) = self.dir.update_dents_buf(self.buf) {
570                            self.read = read;
571                            self.pos = 0;
572                        } else {
573                            // Reached the end!
574                            return None;
575                        }
576                    }
577                    let dir_entry = self.buf.as_ptr().add(self.pos) as *const libc::dirent64;
578                    let dir_entry = &*dir_entry;
579                    self.pos += dir_entry.d_reclen as usize;
580
581                    // It's only supposed to contain digits in any case, but that filters very well too.
582                    if dir_entry.d_name[0] != b'.' as libc::c_char {
583                        return Some(&dir_entry.d_name);
584                    }
585                }
586            }
587        }
588    }
589
590    // Maybe something to do in the future: if it's not an AMD or NVIDIA GPU, we can still compute the
591    // total % usage by adding all processes GPU time. However: we need to have access to `Gpus` all the
592    // time, so likely needs to be part of `System`, just like `Cpu`. Not really worth it since it comes
593    // with limitations (such as: only gives information for current user, unless it's an admin), so for
594    // now ignoring it.
595    pub(super) fn compute_gpu_usage(
596        proc_dir: &mut ProcDir<'_>,
597        gpu_info: &mut GpuInfo,
598        now: Instant,
599        refresh_kind: ProcessRefreshKind,
600        buffers: &mut ProcessBuffers,
601    ) {
602        use std::fs::File;
603
604        let Some(fd_dir) = Dir::open(proc_dir, c"fd") else {
605            return;
606        };
607        // Most processes don't have any GPU file descriptor, so we only open `fdinfo` once we
608        // found one.
609        let mut fdinfo_dir: Option<Dir> = None;
610
611        let mut total_time: u64 = 0;
612        let mut total_memory: u64 = 0;
613        let mut found_memory = false;
614        if let Ok(Some(dir_iter)) = fd_dir.iter(&mut buffers.dents) {
615            let mut stat = MaybeUninit::<libc::statx>::uninit();
616            // `drm-pdev` is only there for PCI GPUs. If this field is absent, `drm-client-id` is
617            // globally unique, so it's enough on its own to tell clients apart.
618            let mut gpus: Vec<(Vec<u8>, Option<Vec<u8>>)> = Vec::new();
619
620            for file_name in dir_iter {
621                if !is_gpu_device(&fd_dir, file_name, &mut stat) {
622                    continue;
623                }
624                let fdinfo_dir_fd = match fdinfo_dir {
625                    Some(ref dir) => dir.dir_fd,
626                    None => {
627                        let Some(dir) = Dir::open(proc_dir, c"fdinfo") else {
628                            return;
629                        };
630                        fdinfo_dir.insert(dir).dir_fd
631                    }
632                };
633                let buf = unsafe {
634                    let fd = retry_eintr!(libc::openat(
635                        fdinfo_dir_fd,
636                        file_name.as_ptr(),
637                        libc::O_RDONLY,
638                    ));
639                    if fd < 0 {
640                        continue;
641                    }
642                    // 4096 is the limit used in htop so why not.
643                    const BUF_SIZE: usize = 4096;
644                    let buf = &mut buffers.buf;
645                    if buf.len() < BUF_SIZE {
646                        assert!(buf.capacity() > BUF_SIZE);
647                        // SAFETY: we create `ProcessBuffers::buf` with a capacity of `16_384`, so
648                        // it's fine.
649                        buf.set_len(BUF_SIZE);
650                    }
651                    if let mut file = File::from_raw_fd(fd)
652                        // We pass a slice of maximum `BUF_SIZE` to never read more than
653                        // "necessary".
654                        && let Ok(read) = file.read(&mut buf[..BUF_SIZE])
655                    {
656                        &buf[..read]
657                    } else {
658                        continue;
659                    }
660                };
661                let mut gpu_id = None;
662                let mut pci = None;
663                let mut gpu_time: Option<u64> = None;
664                let mut gpu_memory: Option<u64> = None;
665                // All the keys are listed in
666                // <https://www.kernel.org/doc/html/latest/gpu/drm-usage-stats.html>.
667                for line in buf
668                    .split(|c| *c == b'\n')
669                    .filter_map(|line| line.strip_prefix(b"drm-"))
670                {
671                    if line.starts_with(b"client-id:") {
672                        if let Some(id) = line.splitn(2, |c| *c == b':').nth(1) {
673                            gpu_id = Some(id.trim_ascii().to_vec());
674                        }
675                    } else if line.starts_with(b"pdev:") {
676                        if let Some(dev) = line.splitn(2, |c| *c == b':').nth(1) {
677                            pci = Some(dev.trim_ascii().to_vec());
678                        }
679                    } else if let Some(line) = line.strip_prefix(b"engine-") {
680                        if refresh_kind.gpu_usage()
681                            && !line.starts_with(b"capacity-")
682                            && let Some(line) = line.strip_suffix(b" ns")
683                            && let Some(nb) = line.split(|c| *c == b':').nth(1)
684                            && let Some(nb) = parse_ascii_checked_u64(nb.trim_ascii())
685                        {
686                            *gpu_time.get_or_insert(0) += nb;
687                        }
688                    } else if let Some(line) = line.strip_prefix(b"total-") {
689                        #[allow(clippy::collapsible_if)]
690                        if refresh_kind.gpu_memory()
691                            && let Some(nb) = line.splitn(2, |c| *c == b':').nth(1)
692                            && let mut nb = nb
693                                .split(|c| *c == b' ' || *c == b'\t')
694                                .filter(|s| !s.is_empty())
695                            && let Some(value) = nb.next()
696                            && let Some(unit) = nb.next()
697                            && !unit.is_empty()
698                            && let Some(value) = parse_ascii_checked_u64(value.trim_ascii())
699                        {
700                            gpu_memory = match unit[0] {
701                                b'K' | b'k' => Some(value * 1024),
702                                b'M' | b'm' => Some(value * 1024 * 1024),
703                                b'G' | b'g' => Some(value * 1024 * 1024 * 1024),
704                                _ => {
705                                    eprintln!(
706                                        "Unknown GPU memory unit {unit:?} in {:?}",
707                                        proc_dir.path
708                                    );
709                                    None
710                                }
711                            };
712                        }
713                    }
714                }
715                // This is the fallback in case the gpu memory or time wasn't retrieved.
716                if let Some(gpu_id) = gpu_id
717                    && !gpus
718                        .iter()
719                        .any(|(s_id, s_pci)| *s_id == gpu_id && *s_pci == pci)
720                {
721                    gpus.push((gpu_id, pci));
722                    if let Some(gpu_time) = gpu_time {
723                        total_time = total_time.saturating_add(gpu_time);
724                    }
725                    if let Some(gpu_memory) = gpu_memory {
726                        total_memory = total_memory.saturating_add(gpu_memory);
727                        found_memory = true;
728                    }
729                }
730            }
731        }
732        if found_memory {
733            gpu_info.memory = Some(total_memory);
734        } else {
735            gpu_info.memory = None;
736        }
737        if total_time != 0 {
738            let elapsed_time = if let Some(last_update) = gpu_info.last_update {
739                now.duration_since(last_update).as_millis()
740            } else {
741                0
742            };
743            let gpu_time_delta = total_time.saturating_sub(gpu_info.gpu_time);
744
745            if gpu_time_delta == 0 || elapsed_time == 0 {
746                gpu_info.gpu_usage = None;
747            } else {
748                // We need to convert from nanos to millis, hence the `/ 1_000_000.`.
749                gpu_info.gpu_usage =
750                    Some(100. * (gpu_time_delta as f32) / 1_000_000. / (elapsed_time as f32));
751            }
752            gpu_info.last_update = Some(now);
753            gpu_info.gpu_time = total_time;
754        } else {
755            gpu_info.gpu_usage = Some(0.);
756        }
757    }
758}
759
760pub(crate) fn compute_cpu_usage(p: &mut ProcessInner, total_time: f32, max_value: f32) {
761    // First time updating the values without reference, wait for a second cycle to update cpu_usage
762    if p.old_utime == 0 && p.old_stime == 0 {
763        return;
764    }
765
766    // We use `max_value` to ensure that the process CPU usage will never get bigger than:
767    // `"number of CPUs" * 100.`
768    p.cpu_usage = (p
769        .utime
770        .saturating_sub(p.old_utime)
771        .saturating_add(p.stime.saturating_sub(p.old_stime)) as f32
772        / total_time
773        * 100.)
774        .min(max_value);
775}
776
777pub(crate) fn set_time(p: &mut ProcessInner, utime: u64, stime: u64) {
778    p.old_utime = p.utime;
779    p.old_stime = p.stime;
780    p.utime = utime;
781    p.stime = stime;
782}
783
784fn update_process_disk_activity(
785    p: &mut ProcessInner,
786    proc_dir: &mut ProcDir<'_>,
787    buf: &mut Vec<u8>,
788) {
789    if !proc_dir.read_into(c"io", buf) {
790        return;
791    }
792    let Ok(data) = std::str::from_utf8(buf) else {
793        return;
794    };
795    let mut done = 0;
796    for line in data.split('\n') {
797        let mut parts = line.split(": ");
798        match parts.next() {
799            Some("read_bytes") => {
800                p.old_read_bytes = p.read_bytes;
801                p.read_bytes = parts
802                    .next()
803                    .and_then(|x| x.parse::<u64>().ok())
804                    .unwrap_or(p.old_read_bytes);
805            }
806            Some("write_bytes") => {
807                p.old_written_bytes = p.written_bytes;
808                p.written_bytes = parts
809                    .next()
810                    .and_then(|x| x.parse::<u64>().ok())
811                    .unwrap_or(p.old_written_bytes);
812            }
813            _ => continue,
814        }
815        done += 1;
816        if done > 1 {
817            // No need to continue the reading.
818            break;
819        }
820    }
821}
822
823/// Buffers reused across processes during a refresh, to avoid allocating for each of them.
824struct ProcessBuffers {
825    buf: Vec<u8>,
826    /// Used to build the paths of the files to read.
827    path: PathBuf,
828    #[cfg(feature = "gpu")]
829    dents: Vec<u8>,
830}
831
832impl ProcessBuffers {
833    #[allow(clippy::uninit_vec)]
834    fn new(
835        #[cfg_attr(not(feature = "gpu"), allow(unused_variables))] refresh_kind: ProcessRefreshKind,
836    ) -> Self {
837        Self {
838            buf: Vec::with_capacity(16_384),
839            path: PathBuf::new(),
840            #[cfg(feature = "gpu")]
841            dents: {
842                if refresh_kind.gpu_usage() || refresh_kind.gpu_memory() {
843                    let mut data = Vec::with_capacity(std::mem::size_of::<libc::dirent64>() * 20);
844                    // SAFETY: `data` is set by syscalls, so no need to initialize it ourselves.
845                    unsafe {
846                        data.set_len(data.capacity());
847                    }
848                    data
849                } else {
850                    Vec::new()
851                }
852            },
853        }
854    }
855}
856
857/// Gives access to the files of a `/proc/<pid>` folder. The folder is opened (lazily) once and
858/// its files are then accessed relative to it, which avoids the kernel resolving the whole path
859/// every time.
860struct ProcDir<'a> {
861    path: &'a CStr,
862    dir_fd: Option<OwnedFd>,
863}
864
865impl<'a> ProcDir<'a> {
866    fn new(path: &'a CStr) -> Self {
867        Self { path, dir_fd: None }
868    }
869
870    fn dir_fd(&mut self) -> Option<&OwnedFd> {
871        if let Some(ref dir_fd) = self.dir_fd {
872            return Some(dir_fd);
873        }
874        let fd = retry_eintr!(unsafe {
875            libc::open(
876                self.path.as_ptr(),
877                libc::O_RDONLY | libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
878            )
879        });
880        if fd < 0 {
881            sysinfo_debug!(
882                "failed to open {:?}: {:?}",
883                self.path,
884                std::io::Error::last_os_error()
885            );
886            return None;
887        }
888        // SAFETY: `fd` was just opened and isn't owned by anything else.
889        self.dir_fd = unsafe { Some(OwnedFd::from_raw_fd(fd)) };
890        self.dir_fd.as_ref()
891    }
892
893    fn open(&mut self, name: &CStr) -> Option<File> {
894        let dir_fd = self.dir_fd()?;
895        let fd = retry_eintr!(unsafe {
896            libc::openat(
897                dir_fd.as_raw_fd(),
898                name.as_ptr(),
899                libc::O_RDONLY | libc::O_CLOEXEC,
900            )
901        });
902        if fd < 0 {
903            sysinfo_debug!(
904                "Failed to open file {name:?}: {:?}",
905                std::io::Error::last_os_error()
906            );
907            None
908        } else {
909            // SAFETY: `fd` was just opened and isn't owned by anything else.
910            Some(unsafe { File::from_raw_fd(fd) })
911        }
912    }
913
914    /// Reads the whole content of `name` into `buf`, replacing its previous content. Returns
915    /// `false` if an error occurred.
916    fn read_into(&mut self, name: &CStr, buf: &mut Vec<u8>) -> bool {
917        let Some(mut file) = self.open(name) else {
918            return false;
919        };
920        buf.clear();
921        if let Err(_err) = file.read_to_end(buf) {
922            sysinfo_debug!("Failed to read file: {_err:?}");
923            false
924        } else {
925            true
926        }
927    }
928
929    /// Reads the target of the `name` link into `buf`, replacing its previous content.
930    fn read_link<'b>(&mut self, name: &CStr, buf: &'b mut Vec<u8>) -> Option<&'b [u8]> {
931        let dir_fd = self.dir_fd()?;
932        buf.clear();
933        if buf.len() < 256 {
934            buf.reserve(256);
935        }
936        loop {
937            let read = unsafe {
938                libc::readlinkat(
939                    dir_fd.as_raw_fd(),
940                    name.as_ptr(),
941                    buf.as_mut_ptr() as *mut _,
942                    buf.capacity(),
943                )
944            };
945            if read < 0 {
946                sysinfo_debug!(
947                    "failed to read link {name:?} in {:?}: {:?}",
948                    self.path,
949                    std::io::Error::last_os_error(),
950                );
951                return None;
952            }
953            let read = read as usize;
954            if read < buf.capacity() {
955                // SAFETY: `readlinkat` initialized the first `read` bytes.
956                unsafe { buf.set_len(read) };
957                return Some(buf);
958            }
959            // The link might have been truncated, so we try again with a bigger buffer.
960            buf.reserve(buf.capacity() * 2);
961        }
962    }
963}
964
965struct Wrap<'a, T>(UnsafeCell<&'a mut T>);
966
967impl<'a, T> Wrap<'a, T> {
968    fn get(&self) -> &'a mut T {
969        unsafe { *(self.0.get()) }
970    }
971}
972
973#[allow(clippy::non_send_fields_in_send_ty)]
974unsafe impl<T> Send for Wrap<'_, T> {}
975unsafe impl<T> Sync for Wrap<'_, T> {}
976
977/// Reads the `stat` file into `buffers.buf`.
978fn _get_stat_data(proc_dir: &mut ProcDir<'_>, buffers: &mut ProcessBuffers) -> Result<(), ()> {
979    let Some(mut file) = proc_dir.open(c"stat") else {
980        return Err(());
981    };
982    read_file_into(&mut file, &mut buffers.buf).map_err(|_| ())?;
983    Ok(())
984}
985
986fn refresh_user_group_ids(
987    p: &mut ProcessInner,
988    ids: Option<Ids>,
989    refresh_kind: ProcessRefreshKind,
990) {
991    if !refresh_kind.user().needs_update(|| p.user_id.is_none()) {
992        return;
993    }
994
995    if let Some(Ids {
996        user_id,
997        effective_user_id,
998        group_id,
999        effective_group_id,
1000    }) = ids
1001    {
1002        p.user_id = Some(Uid(user_id));
1003        p.effective_user_id = Some(Uid(effective_user_id));
1004        p.group_id = Some(Gid(group_id));
1005        p.effective_group_id = Some(Gid(effective_group_id));
1006    }
1007}
1008
1009fn split_content(data: &[u8]) -> Vec<OsString> {
1010    let mut out = Vec::with_capacity(10);
1011    for part in data.split(|c| *c == 0) {
1012        if !part.is_empty() {
1013            out.push(OsStr::from_bytes(part).to_os_string());
1014        }
1015    }
1016    out
1017}
1018
1019#[allow(clippy::too_many_arguments)]
1020fn update_proc_info(
1021    p: &mut ProcessInner,
1022    parent_pid: Option<Pid>,
1023    refresh_kind: ProcessRefreshKind,
1024    proc_dir: &mut ProcDir<'_>,
1025    parts: &Parts,
1026    uptime: u64,
1027    info: &SystemInfo,
1028    ids: Option<Ids>,
1029    buffers: &mut ProcessBuffers,
1030    #[cfg(feature = "gpu")] now: Instant,
1031) {
1032    fn copy_from_file(proc_dir: &mut ProcDir<'_>, name: &CStr, buf: &mut Vec<u8>) -> Vec<OsString> {
1033        if proc_dir.read_into(name, buf) {
1034            split_content(buf)
1035        } else {
1036            Vec::new()
1037        }
1038    }
1039
1040    fn update_optional_path(target: &mut Option<PathBuf>, new_val: Option<&[u8]>) {
1041        if let Some(new_val) = new_val
1042            && target
1043                .as_ref()
1044                .is_none_or(|target| target.as_os_str().as_bytes() != new_val)
1045        {
1046            *target = Some(PathBuf::from(OsStr::from_bytes(new_val)));
1047        }
1048    }
1049
1050    update_parent_pid(p, parent_pid, parts);
1051
1052    p.status = parts.status;
1053    refresh_user_group_ids(p, ids, refresh_kind);
1054
1055    if refresh_kind.exe().needs_update(|| p.exe.is_none()) {
1056        // Do not use cmd[0] because it is not the same thing.
1057        // See https://github.com/GuillaumeGomez/sysinfo/issues/697.
1058        let new_exe = proc_dir.read_link(c"exe", &mut buffers.buf).map(|exe| {
1059            // If the target executable file was modified or removed, linux appends ` (deleted)`
1060            // at the end. We need to remove it.
1061            // See https://github.com/GuillaumeGomez/sysinfo/issues/1585.
1062            exe.strip_suffix(b" (deleted)").unwrap_or(exe)
1063        });
1064        update_optional_path(&mut p.exe, new_exe);
1065    }
1066
1067    if refresh_kind.cmd().needs_update(|| p.cmd.is_empty()) {
1068        let new_cmd = copy_from_file(proc_dir, c"cmdline", &mut buffers.buf);
1069        if !new_cmd.is_empty() || p.cmd.is_empty() {
1070            p.cmd = new_cmd;
1071        }
1072    }
1073    if refresh_kind.environ().needs_update(|| p.environ.is_empty()) {
1074        let new_environ = copy_from_file(proc_dir, c"environ", &mut buffers.buf);
1075        if !new_environ.is_empty() || p.environ.is_empty() {
1076            p.environ = new_environ;
1077        }
1078    }
1079    if refresh_kind.cwd().needs_update(|| p.cwd.is_none()) {
1080        update_optional_path(&mut p.cwd, proc_dir.read_link(c"cwd", &mut buffers.buf));
1081    }
1082    if refresh_kind.root().needs_update(|| p.root.is_none()) {
1083        update_optional_path(&mut p.root, proc_dir.read_link(c"root", &mut buffers.buf));
1084    }
1085
1086    update_time_and_memory(
1087        proc_dir,
1088        p,
1089        parts,
1090        uptime,
1091        info,
1092        refresh_kind,
1093        &mut buffers.buf,
1094    );
1095    if refresh_kind.disk_usage() {
1096        update_process_disk_activity(p, proc_dir, &mut buffers.buf);
1097    }
1098    // Needs to be after `update_time_and_memory`.
1099    if refresh_kind.cpu() {
1100        // The external values for CPU times are in "ticks", which are
1101        // scaled by "HZ", which is pegged externally at 100 ticks/second.
1102        p.accumulated_cpu_time =
1103            p.utime.saturating_add(p.stime).saturating_mul(1_000) / info.clock_cycle;
1104    }
1105    #[cfg(feature = "gpu")]
1106    if (refresh_kind.gpu_usage() || refresh_kind.gpu_memory())
1107        // Kernel threads don't have file descriptors, so no need to look for GPU ones.
1108        && p.thread_kind != Some(ThreadKind::Kernel)
1109    {
1110        p.gpu_info.share_parent_fd_table = p.thread_kind == Some(ThreadKind::Userland)
1111            && p.parent
1112                .is_some_and(|parent| self::gpu::same_fd_table(parent, p.pid));
1113        // If it's a thread sharing its parent process's file descriptor table, its GPU information
1114        // will be copied from it once all processes have been updated.
1115        if !p.gpu_info.share_parent_fd_table {
1116            self::gpu::compute_gpu_usage(proc_dir, &mut p.gpu_info, now, refresh_kind, buffers);
1117        }
1118    }
1119    p.updated = true;
1120    // A process can be marked as nonexistent (e.g. while hidden by `hidepid=invisible`) and
1121    // become readable again later.
1122    p.exists = true;
1123}
1124
1125fn update_parent_pid(p: &mut ProcessInner, parent_pid: Option<Pid>, parts: &Parts) {
1126    p.parent = match parent_pid {
1127        Some(parent_pid) if parent_pid.0 != 0 => Some(parent_pid),
1128        _ => match parts.parent_pid {
1129            Some(p) if p != 0 => Some(Pid(p)),
1130            _ => None,
1131        },
1132    };
1133}
1134
1135#[allow(clippy::too_many_arguments)]
1136fn retrieve_all_new_process_info(
1137    is_thread: bool,
1138    pid: Pid,
1139    parent_pid: Option<Pid>,
1140    parts: &mut Parts,
1141    proc_dir: &mut ProcDir<'_>,
1142    info: &SystemInfo,
1143    refresh_kind: ProcessRefreshKind,
1144    uptime: u64,
1145    ids: Option<Ids>,
1146    buffers: &mut ProcessBuffers,
1147    #[cfg(feature = "gpu")] now: Instant,
1148) -> Process {
1149    let mut p = ProcessInner::new(
1150        pid,
1151        PathBuf::from(OsStr::from_bytes(proc_dir.path.to_bytes())),
1152    );
1153
1154    // To be noted that the start time is invalid here, it still needs to be converted into
1155    // "real" time.
1156    let start_time_without_boot_time = parts.start_time / info.clock_cycle;
1157    p.start_time_raw = parts.start_time;
1158    p.start_time_without_boot_time = start_time_without_boot_time;
1159    p.start_time = p
1160        .start_time_without_boot_time
1161        .saturating_add(info.boot_time);
1162
1163    p.name = std::mem::take(&mut parts.short_exe);
1164    if parts
1165        .flags
1166        .is_some_and(|flags| flags & libc::PF_KTHREAD as c_ulong != 0)
1167    {
1168        p.thread_kind = Some(ThreadKind::Kernel);
1169    } else if is_thread {
1170        p.thread_kind = Some(ThreadKind::Userland);
1171    }
1172
1173    update_proc_info(
1174        &mut p,
1175        parent_pid,
1176        refresh_kind,
1177        proc_dir,
1178        parts,
1179        uptime,
1180        info,
1181        ids,
1182        buffers,
1183        #[cfg(feature = "gpu")]
1184        now,
1185    );
1186
1187    Process { inner: p }
1188}
1189
1190#[allow(clippy::too_many_arguments)]
1191fn update_existing_process(
1192    is_thread: bool,
1193    proc: &mut Process,
1194    proc_dir: &mut ProcDir<'_>,
1195    parent_pid: Option<Pid>,
1196    uptime: u64,
1197    info: &SystemInfo,
1198    refresh_kind: ProcessRefreshKind,
1199    tasks: Option<HashSet<Pid>>,
1200    ids: Option<Ids>,
1201    buffers: &mut ProcessBuffers,
1202    #[cfg(feature = "gpu")] now: Instant,
1203) -> Result<Option<Process>, ()> {
1204    let entry = &mut proc.inner;
1205    // It's possible that the file descriptor is no longer valid in case the
1206    // original process was terminated and another one took its place.
1207    _get_stat_data(proc_dir, buffers)?;
1208    entry.tasks = tasks;
1209
1210    // `parts` borrows the `stat` buffer while `buffers` is still needed, so we take it out and put
1211    // it back once done.
1212    let Some(mut parts) = parse_stat_file(&buffers.buf, Some(entry.start_time_raw)) else {
1213        return Err(());
1214    };
1215
1216    // It's possible that a new process took this same PID when the "original one" terminated.
1217    // If the start time differs, then it means it's not the same process anymore and that we
1218    // need to get all its information, hence why we check it here.
1219    if parts.start_time == entry.start_time_raw {
1220        // If the entry was first discovered without thread info
1221        // (e.g. in ProcessesToUpdate::All mode), fix its thread_kind now.
1222        if is_thread && entry.thread_kind.is_none() {
1223            entry.thread_kind = Some(ThreadKind::Userland);
1224        }
1225
1226        update_proc_info(
1227            entry,
1228            parent_pid,
1229            refresh_kind,
1230            proc_dir,
1231            &parts,
1232            uptime,
1233            info,
1234            ids,
1235            buffers,
1236            #[cfg(feature = "gpu")]
1237            now,
1238        );
1239        return Ok(None);
1240    }
1241    // If we're here, it means that the PID still exists but it's a different process.
1242    let p = retrieve_all_new_process_info(
1243        is_thread,
1244        entry.pid,
1245        parent_pid,
1246        &mut parts,
1247        proc_dir,
1248        info,
1249        refresh_kind,
1250        uptime,
1251        ids,
1252        buffers,
1253        #[cfg(feature = "gpu")]
1254        now,
1255    );
1256    *proc = p;
1257    // Since this PID is already in the HashMap, no need to add it again.
1258    Ok(None)
1259}
1260
1261#[allow(clippy::too_many_arguments)]
1262fn _get_process_data(
1263    path: &CStr,
1264    proc_list: &mut HashMap<Pid, Process>,
1265    pid: Pid,
1266    is_thread: bool,
1267    parent_pid: Option<Pid>,
1268    uptime: u64,
1269    info: &SystemInfo,
1270    refresh_kind: ProcessRefreshKind,
1271    tasks: Option<HashSet<Pid>>,
1272    ids: Option<Ids>,
1273    buffers: &mut ProcessBuffers,
1274    #[cfg(feature = "gpu")] now: Instant,
1275) -> Result<Option<Process>, ()> {
1276    let mut proc_dir = ProcDir::new(path);
1277    if let Some(ref mut entry) = proc_list.get_mut(&pid) {
1278        return update_existing_process(
1279            is_thread,
1280            entry,
1281            &mut proc_dir,
1282            parent_pid,
1283            uptime,
1284            info,
1285            refresh_kind,
1286            tasks,
1287            ids,
1288            buffers,
1289            #[cfg(feature = "gpu")]
1290            now,
1291        );
1292    }
1293    _get_stat_data(&mut proc_dir, buffers)?;
1294    // `parts` borrows the `stat` buffer while `buffers` is still needed, so we take it out and put
1295    // it back once done.
1296    let Some(mut parts) = parse_stat_file(&buffers.buf, None) else {
1297        return Err(());
1298    };
1299
1300    let mut new_process = retrieve_all_new_process_info(
1301        is_thread,
1302        pid,
1303        parent_pid,
1304        &mut parts,
1305        &mut proc_dir,
1306        info,
1307        refresh_kind,
1308        uptime,
1309        ids,
1310        buffers,
1311        #[cfg(feature = "gpu")]
1312        now,
1313    );
1314    new_process.inner.tasks = tasks;
1315    Ok(Some(new_process))
1316}
1317
1318fn old_get_memory(entry: &mut ProcessInner, parts: &Parts, info: &SystemInfo) {
1319    // rss
1320    entry.memory = parts.resident_set_size.saturating_mul(info.page_size_b);
1321    // vsz correspond to the Virtual memory size in bytes.
1322    // see: https://man7.org/linux/man-pages/man5/proc.5.html
1323    entry.virtual_memory = parts.virtual_size
1324}
1325
1326fn slice_to_nb(s: &[u8]) -> u64 {
1327    let mut nb: u64 = 0;
1328
1329    for c in s {
1330        nb = nb * 10 + (c - b'0') as u64;
1331    }
1332    nb
1333}
1334
1335fn get_memory(
1336    proc_dir: &mut ProcDir<'_>,
1337    entry: &mut ProcessInner,
1338    info: &SystemInfo,
1339    buf: &mut Vec<u8>,
1340) -> bool {
1341    if !proc_dir.read_into(c"statm", buf) {
1342        return false;
1343    }
1344    let mut parts = buf.split(|c| *c == b' ');
1345    entry.virtual_memory = parts
1346        .next()
1347        .map(slice_to_nb)
1348        .unwrap_or(0)
1349        .saturating_mul(info.page_size_b);
1350    entry.memory = parts
1351        .next()
1352        .map(slice_to_nb)
1353        .unwrap_or(0)
1354        .saturating_mul(info.page_size_b);
1355    true
1356}
1357
1358#[allow(clippy::too_many_arguments)]
1359fn update_time_and_memory(
1360    proc_dir: &mut ProcDir<'_>,
1361    entry: &mut ProcessInner,
1362    parts: &Parts,
1363    uptime: u64,
1364    info: &SystemInfo,
1365    refresh_kind: ProcessRefreshKind,
1366    buf: &mut Vec<u8>,
1367) {
1368    {
1369        #[allow(clippy::collapsible_if)]
1370        if refresh_kind.memory() {
1371            // Keeping this nested level for readability reasons.
1372            if !get_memory(proc_dir, entry, info, buf) {
1373                old_get_memory(entry, parts, info);
1374            }
1375        }
1376        set_time(entry, parts.user_time, parts.system_time);
1377        entry.run_time = uptime.saturating_sub(entry.start_time_without_boot_time);
1378    }
1379}
1380
1381struct ProcAndTasks {
1382    pid: Pid,
1383    parent_pid: Option<Pid>,
1384    path: CString,
1385    tasks: Option<HashSet<Pid>>,
1386    is_thread: bool,
1387    ids: Option<Ids>,
1388}
1389
1390#[cfg(feature = "multithread")]
1391#[inline]
1392pub(crate) fn iter<T>(val: T) -> rayon::iter::IterBridge<T>
1393where
1394    T: rayon::iter::ParallelBridge,
1395{
1396    val.par_bridge()
1397}
1398
1399#[cfg(not(feature = "multithread"))]
1400#[inline]
1401pub(crate) fn iter<T>(val: T) -> T
1402where
1403    T: Iterator,
1404{
1405    val
1406}
1407
1408/// We're forced to read the whole `/proc` folder because if a process died and another took its
1409/// place, we need to get the task parent (if it's a task).
1410pub(crate) fn refresh_procs(
1411    proc_list: &mut HashMap<Pid, Process>,
1412    proc_path: &Path,
1413    uptime: u64,
1414    info: &SystemInfo,
1415    processes_to_update: ProcessesToUpdate<'_>,
1416    refresh_kind: ProcessRefreshKind,
1417) -> usize {
1418    #[cfg(feature = "multithread")]
1419    use rayon::iter::ParallelIterator;
1420
1421    let nb_updated = AtomicUsize::new(0);
1422    #[cfg(feature = "gpu")]
1423    let now = Instant::now();
1424    let mut buffers = ProcessBuffers::new(refresh_kind);
1425
1426    // This code goes through processes (listed in `/proc`) and through tasks (listed in
1427    // `/proc/[PID]/task`). However, the stored tasks information is supposed to be already present
1428    // in the PIDs listed from `/proc` so there will be no duplicates between PIDs and tasks PID.
1429    //
1430    // If a task is not listed in `/proc`, then we don't retrieve its information.
1431    //
1432    // So in short: since we update the `HashMap` itself by adding/removing entries outside of the
1433    // parallel iterator, we can safely use it inside the parallel iterator and update its entries
1434    // concurrently.
1435    let procs = {
1436        let pid_iter: Box<dyn Iterator<Item = (PathBuf, Pid)> + Send> = match processes_to_update {
1437            ProcessesToUpdate::All => match read_dir(proc_path) {
1438                Ok(proc_entries) => Box::new(proc_entries.filter_map(filter_pid_entries)),
1439                Err(_err) => {
1440                    sysinfo_debug!("Failed to read folder {proc_path:?}: {_err:?}");
1441                    return 0;
1442                }
1443            },
1444            ProcessesToUpdate::Some(pids) => Box::new(
1445                pids.iter()
1446                    .map(|pid| (proc_path.join(pid.to_string()), *pid)),
1447            ),
1448        };
1449
1450        let proc_list = Wrap(UnsafeCell::new(proc_list));
1451
1452        let get_process_data = |buffers: &mut ProcessBuffers, e: ProcAndTasks| {
1453            let proc_list = proc_list.get();
1454            let new_process = _get_process_data(
1455                &e.path,
1456                proc_list,
1457                e.pid,
1458                e.is_thread,
1459                e.parent_pid,
1460                uptime,
1461                info,
1462                refresh_kind,
1463                e.tasks,
1464                e.ids,
1465                buffers,
1466                #[cfg(feature = "gpu")]
1467                now,
1468            )
1469            .ok()?;
1470            nb_updated.fetch_add(1, Ordering::Relaxed);
1471            new_process
1472        };
1473        let get_procs = |buffers: &mut ProcessBuffers, (path, pid): (PathBuf, Pid)| {
1474            get_proc_and_tasks(path, pid, refresh_kind, processes_to_update, buffers)
1475        };
1476
1477        // Each rayon job gets its own buffers.
1478        #[cfg(feature = "multithread")]
1479        let procs = iter(pid_iter)
1480            .map_init(|| ProcessBuffers::new(refresh_kind), get_procs)
1481            .flatten()
1482            .map_init(|| ProcessBuffers::new(refresh_kind), get_process_data)
1483            .flatten();
1484        #[cfg(not(feature = "multithread"))]
1485        let procs = {
1486            let mut procs_buffers = ProcessBuffers::new(refresh_kind);
1487            let buffers = &mut buffers;
1488            iter(pid_iter)
1489                .flat_map(move |e| get_procs(&mut procs_buffers, e))
1490                .filter_map(move |e| get_process_data(buffers, e))
1491        };
1492        procs.collect::<Vec<_>>()
1493    };
1494    for proc_ in procs {
1495        proc_list.insert(proc_.pid(), proc_);
1496    }
1497    #[cfg(feature = "gpu")]
1498    if refresh_kind.gpu_usage() || refresh_kind.gpu_memory() {
1499        gpu::update_threads_gpu_info(proc_list, refresh_kind, now, &mut buffers);
1500    }
1501    nb_updated.into_inner()
1502}
1503
1504fn filter_pid_entries(entry: Result<DirEntry, std::io::Error>) -> Option<(PathBuf, Pid)> {
1505    if let Ok(entry) = entry
1506        && entry.file_type().is_ok_and(|file_type| file_type.is_dir())
1507        && let Some(pid) = parse_ascii_checked_usize(entry.file_name().as_bytes())
1508    {
1509        Some((entry.path(), Pid::from(pid)))
1510    } else {
1511        None
1512    }
1513}
1514
1515fn get_proc_and_tasks(
1516    path: PathBuf,
1517    pid: Pid,
1518    refresh_kind: ProcessRefreshKind,
1519    processes_to_update: ProcessesToUpdate<'_>,
1520    buffers: &mut ProcessBuffers,
1521) -> Vec<ProcAndTasks> {
1522    let mut parent_pid = None;
1523    let mut is_thread = false;
1524
1525    let (ids, tgid) = match get_uid_and_gid_and_tgid(&path, buffers) {
1526        Some((ids, tgid)) => (Some(ids), Some(tgid)),
1527        None => (None, None),
1528    };
1529    let is_a_task = tgid.is_some_and(|tgid| tgid != pid);
1530    // Threads don't have meaningful tasks, so no need to fetch `procs` and `tasks`.
1531    let (mut procs, tasks) = if refresh_kind.tasks() && !is_a_task {
1532        let update_processes_list = processes_to_update == ProcessesToUpdate::All;
1533        // The `status` file allows to retrieve user info and tgid. If we're not interested in any,
1534        // then we don't read it.
1535        let retrieve_ids = update_processes_list && refresh_kind.user() != UpdateKind::Never;
1536        let mut procs = get_proc_tasks(&path, pid, retrieve_ids, buffers);
1537        let tasks = procs.iter().map(|ProcAndTasks { pid, .. }| *pid).collect();
1538
1539        if !update_processes_list {
1540            // Don't add the tasks to the list of processes to update.
1541            procs.clear();
1542        }
1543        (procs, Some(tasks))
1544    } else {
1545        (Vec::new(), None)
1546    };
1547
1548    // If the process' tgid doesn't match its pid, it is a task (thread).
1549    // This check must apply in ALL modes, not just `Some`.
1550    if is_a_task {
1551        parent_pid = tgid;
1552        is_thread = true;
1553    }
1554
1555    procs.push(ProcAndTasks {
1556        is_thread,
1557        pid,
1558        parent_pid,
1559        path: to_c_string(path),
1560        tasks,
1561        ids,
1562    });
1563
1564    procs
1565}
1566
1567fn to_c_string(path: PathBuf) -> CString {
1568    let mut path = path.into_os_string().into_vec();
1569    path.push(0);
1570    // SAFETY: Paths cannot contain NUL bytes and we added one at the end.
1571    unsafe { CString::from_vec_with_nul_unchecked(path) }
1572}
1573
1574fn get_proc_tasks(
1575    path: &Path,
1576    parent_pid: Pid,
1577    retrieve_ids: bool,
1578    buffers: &mut ProcessBuffers,
1579) -> Vec<ProcAndTasks> {
1580    let task_path = path.join("task");
1581
1582    read_dir(&task_path)
1583        .ok()
1584        .map(|task_entries| {
1585            task_entries
1586                .filter_map(filter_pid_entries)
1587                // Needed because tasks have their own PID listed in the "task" folder.
1588                .filter(|(_, pid)| *pid != parent_pid)
1589                .map(|(path, pid)| {
1590                    let ids = if retrieve_ids {
1591                        get_uid_and_gid_and_tgid(&path, buffers).map(|(ids, _)| ids)
1592                    } else {
1593                        None
1594                    };
1595                    ProcAndTasks {
1596                        pid,
1597                        is_thread: true,
1598                        path: to_c_string(path),
1599                        parent_pid: Some(parent_pid),
1600                        tasks: None,
1601                        ids,
1602                    }
1603                })
1604                .collect()
1605        })
1606        .unwrap_or_default()
1607}
1608
1609pub(crate) struct Ids {
1610    user_id: uid_t,
1611    effective_user_id: uid_t,
1612    group_id: gid_t,
1613    effective_group_id: gid_t,
1614}
1615
1616// Fetch real and effective UID and GID and store them into `Pids`. Returns the "thread group id"
1617// (tgid) as second value of the tuple.
1618fn get_uid_and_gid_and_tgid(proc_path: &Path, buffers: &mut ProcessBuffers) -> Option<(Ids, Pid)> {
1619    /// Writes `{base}/{file_name}` into `buf` and returns a reference to it.
1620    fn build_path<'a>(buf: &'a mut PathBuf, base: &Path, file_name: &str) -> &'a Path {
1621        buf.as_mut_os_string().clear();
1622        buf.push(base);
1623        buf.push(file_name);
1624        buf
1625    }
1626
1627    let status_path = build_path(&mut buffers.path, proc_path, "status");
1628    read_path_into(status_path, &mut buffers.buf).ok()?;
1629    let status_data = &buffers.buf;
1630
1631    // We're only interested in the lines starting with Uid: and Gid:
1632    // here. From these lines, we're looking at the first and second entries to get
1633    // the real u/gid.
1634
1635    let f = |h: &[u8], n: &[u8]| -> (Option<uid_t>, Option<uid_t>) {
1636        if let Some(h) = h.strip_prefix(n) {
1637            let mut ids = h
1638                .split(|c| *c == b'\t' || *c == b' ')
1639                .filter(|s| !s.is_empty());
1640            let real = ids.next().and_then(parse_ascii_checked_uid_t);
1641            let effective = ids.next().and_then(parse_ascii_checked_uid_t);
1642
1643            (real, effective)
1644        } else {
1645            (None, None)
1646        }
1647    };
1648    let mut uid = None;
1649    let mut effective_uid = None;
1650    let mut gid = None;
1651    let mut effective_gid = None;
1652    let mut tgid = None;
1653    for line in status_data.split(|c| *c == b'\n') {
1654        if let (Some(real), Some(effective)) = f(line, b"Uid:") {
1655            debug_assert!(uid.is_none() && effective_uid.is_none());
1656            uid = Some(real);
1657            effective_uid = Some(effective);
1658        } else if let (Some(real), Some(effective)) = f(line, b"Gid:") {
1659            debug_assert!(gid.is_none() && effective_gid.is_none());
1660            gid = Some(real);
1661            effective_gid = Some(effective);
1662        } else if let Some(line) = line.strip_prefix(b"Tgid:")
1663            && let Some(real) = parse_ascii_checked_pid_t(line.trim_ascii())
1664        {
1665            debug_assert!(tgid.is_none());
1666            tgid = Some(real);
1667        } else {
1668            continue;
1669        }
1670        if uid.is_some() && gid.is_some() && tgid.is_some() {
1671            break;
1672        }
1673    }
1674    match (uid, effective_uid, gid, effective_gid, tgid) {
1675        (
1676            Some(user_id),
1677            Some(effective_user_id),
1678            Some(group_id),
1679            Some(effective_group_id),
1680            Some(thread_group_id),
1681        ) => Some((
1682            Ids {
1683                user_id,
1684                effective_user_id,
1685                group_id,
1686                effective_group_id,
1687            },
1688            Pid(thread_group_id),
1689        )),
1690        _ => None,
1691    }
1692}
1693
1694#[cfg_attr(test, derive(PartialEq, Debug))]
1695struct Parts {
1696    short_exe: OsString,
1697    status: ProcessStatus,
1698    parent_pid: Option<pid_t>,
1699    flags: Option<c_ulong>,
1700    user_time: u64,
1701    system_time: u64,
1702    start_time: u64,
1703    virtual_size: u64,
1704    resident_set_size: u64,
1705}
1706
1707fn parse_stat_file(data: &[u8], start_time_raw: Option<u64>) -> Option<Parts> {
1708    // The stat file is "interesting" to parse, because spaces cannot
1709    // be used as delimiters. The second field stores the command name
1710    // surrounded by parentheses. Unfortunately, whitespace and
1711    // parentheses are legal parts of the command, so parsing has to
1712    // proceed like this: The first field is delimited by the first
1713    // whitespace, the second field is everything until the last ')'
1714    // in the entire string. All other fields are delimited by
1715    // whitespace.
1716
1717    // We ignore the first field (`pid`).
1718    let data = data.splitn(2, |&b| b == b' ').nth(1)?;
1719    let pos = data
1720        .iter()
1721        .rposition(|&b| b == b')')
1722        .or_else(|| data.iter().rposition(|&b| b == b')'))?;
1723    let short_exe = &data[1..pos];
1724
1725    let mut data = data[pos + 1..]
1726        .split(|c| *c == b' ')
1727        .filter(|p| !p.is_empty());
1728
1729    // This code is awful, but couldn't find a better way. We ensure that the parsing is done
1730    // correctly with the `test_parse_stat_file` test below.
1731    let status = data
1732        .next()
1733        .and_then(|part| part.first().copied().map(ProcessStatus::from))
1734        .unwrap_or(ProcessStatus::Unknown(0));
1735    let parent_pid = data.next().and_then(parse_ascii_checked_pid_t);
1736
1737    let flags = data
1738        .nth(ProcIndex::Flags as usize - ProcIndex::ParentPid as usize - 1)
1739        .and_then(parse_ascii_checked_culong);
1740    let user_time = data
1741        .nth(ProcIndex::UserTime as usize - ProcIndex::Flags as usize - 1)
1742        .and_then(parse_ascii_checked_u64)
1743        .unwrap_or(0);
1744    let system_time = data.next().and_then(parse_ascii_checked_u64).unwrap_or(0);
1745
1746    let start_time = data
1747        .nth(ProcIndex::StartTime as usize - ProcIndex::SystemTime as usize - 1)
1748        .and_then(parse_ascii_checked_u64)
1749        .unwrap_or(0);
1750    let virtual_size = data.next().and_then(parse_ascii_checked_u64).unwrap_or(0);
1751    let resident_set_size = data.next().and_then(parse_ascii_checked_u64).unwrap_or(0);
1752
1753    Some(Parts {
1754        status,
1755        parent_pid,
1756        flags,
1757        user_time,
1758        system_time,
1759        start_time,
1760        virtual_size,
1761        resident_set_size,
1762        short_exe: if start_time_raw.is_some_and(|raw| start_time == raw) {
1763            OsString::new()
1764        } else {
1765            OsStr::from_bytes(short_exe).to_os_string()
1766        },
1767    })
1768}
1769
1770#[cfg(test)]
1771mod tests {
1772    use super::{Parts, parse_stat_file, split_content};
1773    use std::ffi::OsString;
1774
1775    // A process marked as nonexistent (e.g. hidden by `hidepid=invisible` for one refresh) must
1776    // be reported as existing again once it can be read.
1777    #[test]
1778    fn test_exists_after_being_nonexistent() {
1779        use crate::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
1780
1781        let pid = Pid::from_u32(std::process::id());
1782        let mut s = System::new().unwrap();
1783        s.refresh_processes(ProcessesToUpdate::Some(&[pid]), false);
1784        s.process(pid).unwrap();
1785        s.inner
1786            .processes_mut()
1787            .get_mut(&pid)
1788            .unwrap()
1789            .inner
1790            .set_nonexistent();
1791        assert!(!s.process(pid).unwrap().exists());
1792        s.refresh_processes_specifics(
1793            ProcessesToUpdate::Some(&[pid]),
1794            false,
1795            ProcessRefreshKind::nothing(),
1796        );
1797        assert!(s.process(pid).unwrap().exists());
1798    }
1799
1800    // This test ensures that all the parts of the data are split.
1801    #[test]
1802    fn test_copy_file() {
1803        assert_eq!(split_content(b"hello\0"), vec![OsString::from("hello")]);
1804        assert_eq!(split_content(b"hello"), vec![OsString::from("hello")]);
1805        assert_eq!(
1806            split_content(b"hello\0b"),
1807            vec![OsString::from("hello"), "b".into()]
1808        );
1809        assert_eq!(
1810            split_content(b"hello\0\0\0\0b"),
1811            vec![OsString::from("hello"), "b".into()]
1812        );
1813    }
1814
1815    #[test]
1816    fn test_parse_stat_file() {
1817        // The (trimmed) content of a stat file.
1818        let content = b"1 (blob) S 2 0 0 0 -1 2129984 0 0 0 0 14 28 0 0 20 0 1 0 21 66 77";
1819        let data = parse_stat_file(content, None).unwrap();
1820        assert_eq!(
1821            data,
1822            Parts {
1823                short_exe: "blob".into(),
1824                status: crate::ProcessStatus::Sleep,
1825                parent_pid: Some(2),
1826                flags: Some(2129984),
1827                user_time: 14,
1828                start_time: 21,
1829                system_time: 28,
1830                virtual_size: 66,
1831                resident_set_size: 77,
1832            }
1833        );
1834    }
1835
1836    // This test ensures that even if we have a `(`/`)` char in the short exe name, we still make
1837    // it works.
1838    #[test]
1839    fn test_parse_stat_file_short_exe() {
1840        // The (trimmed) content of a stat file.
1841        let content = b"1 (bl()ob) S 2 0 0 0 -1 2129984 0 0 0 0 14 28 0 0 20 0 1 0 21 66 77";
1842        let data = parse_stat_file(content, None).unwrap();
1843        assert_eq!(
1844            data,
1845            Parts {
1846                short_exe: "bl()ob".into(),
1847                status: crate::ProcessStatus::Sleep,
1848                parent_pid: Some(2),
1849                flags: Some(2129984),
1850                user_time: 14,
1851                start_time: 21,
1852                system_time: 28,
1853                virtual_size: 66,
1854                resident_set_size: 77,
1855            }
1856        );
1857    }
1858
1859    #[test]
1860    fn test_parse_stat_file_long_exe() {
1861        // In case you wonder: yes, it's a real "short" exe name.
1862        let content = b"1 (nvidia-modeset/deferred_close_kthread_q) S 2 0 0 0 -1 2129984 0 0 0 0 14 28 0 0 20 0 1 0 21 66 77";
1863        let data = parse_stat_file(content, None).unwrap();
1864        assert_eq!(
1865            data,
1866            Parts {
1867                short_exe: "nvidia-modeset/deferred_close_kthread_q".into(),
1868                status: crate::ProcessStatus::Sleep,
1869                parent_pid: Some(2),
1870                flags: Some(2129984),
1871                user_time: 14,
1872                start_time: 21,
1873                system_time: 28,
1874                virtual_size: 66,
1875                resident_set_size: 77,
1876            }
1877        );
1878    }
1879}