Skip to main content

subc_os/
process_tree.rs

1//! Read-only process-table snapshots. No process is stopped or signalled.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::io;
5
6use crate::{MemoryKind, ResourceUsage};
7
8#[cfg(feature = "test-support")]
9std::thread_local! {
10    static TEST_WALL_CLOCK: std::cell::Cell<Option<std::time::SystemTime>> = const {
11        std::cell::Cell::new(None)
12    };
13}
14
15fn wall_clock_now() -> std::time::SystemTime {
16    #[cfg(feature = "test-support")]
17    if let Some(now) = TEST_WALL_CLOCK.get() {
18        return now;
19    }
20    std::time::SystemTime::now()
21}
22
23/// A process identity and its observed parent, session, program and resources.
24#[derive(Debug, Clone)]
25pub struct ProcessMember {
26    pub pid: u32,
27    pub parent_pid: u32,
28    pub session_id: Option<u32>,
29    /// Native kernel units, suitable for exact PID-reuse checks.
30    pub start_time: u64,
31    pub start_time_ms: u64,
32    pub name: String,
33    /// Unix CPU includes reaped children; Windows CPU is the process's own.
34    pub resources: Option<ResourceUsage>,
35    /// Separate own and reaped-child counters from the same native observation.
36    pub own_cpu_ms: Option<u64>,
37    pub reaped_cpu_ms: Option<u64>,
38    /// Query handle pinned to this Windows identity, usable after its exit.
39    #[cfg(windows)]
40    pub process: std::sync::Arc<crate::Process>,
41}
42
43/// A live program group. CPU includes its members' reaped children on Unix.
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct ProcessGroup {
46    pub name: String,
47    pub count: u64,
48    pub cpu_ms: u64,
49    pub memory_bytes: u64,
50}
51
52/// Cumulative CPU and current memory of the observed members of a tree.
53#[derive(Debug, Clone)]
54pub struct TreeUsage {
55    pub cpu_ms: u64,
56    pub memory_bytes: u64,
57    pub memory_kind: MemoryKind,
58    pub process_count: u64,
59    pub groups: Vec<ProcessGroup>,
60    pub members: Vec<ProcessMember>,
61}
62
63/// One process-table walk, reusable for any number of roots.
64///
65/// A table read with [`ProcessTable::read_for`] is narrowed: only the
66/// processes its interest set can reach were examined, and [`Self::covers`]
67/// says which pids it answers for exactly as a full walk would.
68#[derive(Debug, Clone, Default)]
69pub struct ProcessTable {
70    members: BTreeMap<u32, ProcessMember>,
71    unreadable: BTreeMap<u32, (Option<u32>, Option<u32>)>,
72    revision: u64,
73    observed_at_ms: u64,
74    #[cfg(target_os = "linux")]
75    started_at_ticks: Option<u64>,
76    started_at: Option<std::time::Instant>,
77    focus: Option<std::sync::Arc<Focus>>,
78}
79
80/// The birth-time cutoff captured at the start of a process-table walk.
81#[derive(Clone, Copy, Debug, Default)]
82pub struct BirthBaseline {
83    epoch_ms: u64,
84    #[cfg(target_os = "linux")]
85    ticks: Option<u64>,
86}
87
88impl BirthBaseline {
89    /// Whether a member was born after this cutoff, allowing for timestamp
90    /// resolution. On Linux, both sides use `CLOCK_BOOTTIME` start ticks;
91    /// other platforms compare the member's fixed epoch birth to the cutoff.
92    pub fn precedes(
93        self,
94        #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] native: u64,
95        epoch_ms: u64,
96    ) -> bool {
97        #[cfg(target_os = "linux")]
98        if let Some(ticks) = self.ticks {
99            return native > ticks.saturating_add(1);
100        }
101        epoch_ms
102            > self
103                .epoch_ms
104                .saturating_add(crate::process_start_time_precision_ms())
105    }
106}
107
108#[cfg(target_os = "linux")]
109fn boot_ticks() -> u64 {
110    let elapsed = rustix::time::clock_gettime(rustix::time::ClockId::Boottime);
111    let hz = rustix::param::clock_ticks_per_second().max(1);
112    (elapsed.tv_sec as u64).saturating_mul(hz).saturating_add(
113        (u128::from(elapsed.tv_nsec as u64) * u128::from(hz) / 1_000_000_000) as u64,
114    )
115}
116
117/// The pids a narrowed walk examined, and every pid its listing contained.
118/// A pid the listing did not contain is absent from a full walk too.
119#[derive(Debug, Default)]
120struct Focus {
121    selected: BTreeSet<u32>,
122    listed: BTreeSet<u32>,
123}
124
125impl ProcessTable {
126    /// Override only this thread's snapshot wall clock, restoring it on unwind.
127    /// Native process creation times and the monotonic clock are not changed.
128    #[cfg(feature = "test-support")]
129    #[doc(hidden)]
130    pub fn with_test_wall_clock<T>(now: std::time::SystemTime, operation: impl FnOnce() -> T) -> T {
131        struct Restore(Option<std::time::SystemTime>);
132        impl Drop for Restore {
133            fn drop(&mut self) {
134                TEST_WALL_CLOCK.set(self.0);
135            }
136        }
137        let _restore = Restore(TEST_WALL_CLOCK.replace(Some(now)));
138        operation()
139    }
140
141    /// Inject a complete or explicitly unreadable snapshot for downstream
142    /// accounting tests. This constructor is absent from normal library builds.
143    #[cfg(feature = "test-support")]
144    #[doc(hidden)]
145    pub fn from_test_members(
146        revision: u64,
147        observed_at_ms: u64,
148        members: Vec<ProcessMember>,
149        unreadable: Vec<(u32, Option<u32>, Option<u32>)>,
150    ) -> Self {
151        Self {
152            members: members
153                .into_iter()
154                .map(|member| (member.pid, member))
155                .collect(),
156            unreadable: unreadable
157                .into_iter()
158                .map(|(pid, parent, session)| (pid, (parent, session)))
159                .collect(),
160            revision,
161            observed_at_ms,
162            #[cfg(target_os = "linux")]
163            started_at_ticks: None,
164            started_at: Some(std::time::Instant::now()),
165            focus: None,
166        }
167    }
168    /// Read all visible processes once. Unreadable identities are retained as
169    /// uncertainty, so a related tree cannot silently become a partial sum.
170    pub fn read() -> io::Result<Self> {
171        Self::read_entries(entries)
172    }
173
174    /// Read only what `interest` can reach, answering exactly as [`Self::read`]
175    /// would for every pid [`Self::covers`] accepts.
176    ///
177    /// One listing supplies every process's parent and start. The per-process
178    /// reads (identity, session, resources and the exit fence) then cover only:
179    /// the interest pids; every listed process whose session is led by an
180    /// interest pid, or whose session or parent is unknown; all their
181    /// descendants; and every ancestor of all of those. That is every process
182    /// a tree rooted at an interest pid can select or be made uncertain by,
183    /// with or without its session, and every parent an ancestry walk from a
184    /// covered process can visit. Windows reads the full table.
185    pub fn read_for(interest: &BTreeSet<u32>) -> io::Result<Self> {
186        #[cfg(unix)]
187        {
188            Self::read_probed(entries, &Native, Some(interest))
189        }
190        #[cfg(not(unix))]
191        {
192            let _ = interest;
193            Self::read()
194        }
195    }
196
197    /// Whether queries about `pid` match a full walk. Always true for a full
198    /// table; for a narrowed one, true for examined pids and for pids the
199    /// walk's listing did not contain at all.
200    pub fn covers(&self, pid: u32) -> bool {
201        self.focus
202            .as_ref()
203            .is_none_or(|focus| focus.selected.contains(&pid) || !focus.listed.contains(&pid))
204    }
205
206    /// Whether this table examined only part of the host's processes.
207    pub fn is_narrowed(&self) -> bool {
208        self.focus.is_some()
209    }
210
211    fn begin() -> (u64, u64, std::time::Instant) {
212        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
213        let revision = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
214        let observed_at_ms = wall_clock_now()
215            .duration_since(std::time::UNIX_EPOCH)
216            .ok()
217            .and_then(|elapsed| u64::try_from(elapsed.as_millis()).ok())
218            .unwrap_or(0);
219        (revision, observed_at_ms, std::time::Instant::now())
220    }
221
222    fn read_entries(enumerate: impl FnOnce() -> io::Result<Vec<Entry>>) -> io::Result<Self> {
223        #[cfg(unix)]
224        {
225            Self::read_probed(enumerate, &Native, None)
226        }
227        #[cfg(windows)]
228        {
229            Self::read_windows(enumerate)
230        }
231        #[cfg(not(any(unix, windows)))]
232        {
233            let _ = enumerate;
234            Err(io::Error::new(
235                io::ErrorKind::Unsupported,
236                "process tables unavailable",
237            ))
238        }
239    }
240
241    /// The walk itself. With `interest`, only the processes [`focus`] selects
242    /// get the per-process reads; each of those gets exactly the reads, in the
243    /// order, that a full walk gives it.
244    #[cfg(unix)]
245    fn read_probed(
246        enumerate: impl FnOnce() -> io::Result<Vec<Entry>>,
247        probe: &impl Probe,
248        interest: Option<&BTreeSet<u32>>,
249    ) -> io::Result<Self> {
250        let (revision, observed_at_ms, started_at) = Self::begin();
251        #[cfg(target_os = "linux")]
252        let started_at_ticks = Some(boot_ticks());
253        let entries = enumerate()?;
254        let mut known = Known::default();
255        let focus = interest.map(|interest| focus(&entries, interest, probe, &mut known));
256        let mut members = BTreeMap::new();
257        let mut unreadable = BTreeMap::new();
258        for (pid, parent, name, expected_start) in entries {
259            if focus
260                .as_ref()
261                .is_some_and(|focus| !focus.selected.contains(&pid))
262            {
263                continue;
264            }
265            let parent = parent.or_else(|| {
266                known
267                    .parents
268                    .remove(&pid)
269                    .unwrap_or_else(|| probe.parent(pid))
270            });
271            let session_id = known
272                .sessions
273                .remove(&pid)
274                .unwrap_or_else(|| probe.session(pid));
275            let start = match probe.identity(pid) {
276                crate::IdentityRead::Alive(start) => Some(start),
277                crate::IdentityRead::Gone => continue,
278                crate::IdentityRead::Unknown => None,
279            };
280            let Some(start_time) =
281                start.filter(|start| expected_start.is_none_or(|expected| expected == *start))
282            else {
283                if probe.possibly_live(pid) {
284                    unreadable.insert(pid, (parent, session_id));
285                }
286                continue;
287            };
288            let Some(start_time_ms) = crate::start_time_ms_from_native(start_time) else {
289                unreadable.insert(pid, (parent, session_id));
290                continue;
291            };
292            let Some(parent_pid) = parent else {
293                unreadable.insert(pid, (None, session_id));
294                continue;
295            };
296            let name = name.unwrap_or_else(|| probe.name(pid));
297            let (resources, own_cpu_ms, reaped_cpu_ms) = probe.usage(pid).map_or(
298                (None, None, None),
299                |(mut usage, child_user, child_system)| {
300                    let millis = |duration: std::time::Duration| {
301                        u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
302                    };
303                    let own = millis(usage.cpu_user + usage.cpu_system);
304                    let reaped = millis(child_user + child_system);
305                    usage.cpu_user += child_user;
306                    usage.cpu_system += child_system;
307                    (Some(usage), Some(own), Some(reaped))
308                },
309            );
310            if !Self::same_identity(
311                pid,
312                start_time,
313                (Some(parent_pid), session_id),
314                probe.identity(pid),
315                &mut unreadable,
316            ) {
317                continue;
318            }
319            members.insert(
320                pid,
321                ProcessMember {
322                    pid,
323                    parent_pid,
324                    session_id,
325                    start_time,
326                    start_time_ms,
327                    name,
328                    resources,
329                    own_cpu_ms,
330                    reaped_cpu_ms,
331                },
332            );
333        }
334        // A reaped child's earlier sample can overlap a later parent's reaped
335        // counter. Drop confirmed exits, leaving recovery to that counter, but
336        // reject unknown identities rather than publishing a partial live sum.
337        Self::fence(&mut members, &mut unreadable, |member| {
338            probe.identity(member.pid)
339        });
340        Ok(Self {
341            members,
342            unreadable,
343            revision,
344            observed_at_ms,
345            #[cfg(target_os = "linux")]
346            started_at_ticks,
347            started_at: Some(started_at),
348            focus: focus.map(std::sync::Arc::new),
349        })
350    }
351
352    #[cfg(windows)]
353    fn read_windows(enumerate: impl FnOnce() -> io::Result<Vec<Entry>>) -> io::Result<Self> {
354        let (revision, observed_at_ms, started_at) = Self::begin();
355        let mut members = BTreeMap::new();
356        let mut unreadable = BTreeMap::new();
357        let entries = enumerate()?;
358        let listed_at: BTreeMap<u32, usize> = entries
359            .iter()
360            .enumerate()
361            .map(|(index, (pid, ..))| (*pid, index))
362            .collect();
363        for (index, (pid, parent, name, expected_start)) in entries.into_iter().enumerate() {
364            let parent = parent.or_else(|| crate::parent_pid(pid));
365            let parent = live_parent(parent, index, &listed_at);
366            let session_id = None;
367            let Some(process) = crate::Process::open(pid).ok().flatten() else {
368                unreadable.insert(pid, (parent, session_id));
369                continue;
370            };
371            let start = process.observe().map(|observation| observation.start_time);
372            let Some(start_time) =
373                start.filter(|start| expected_start.is_none_or(|expected| expected == *start))
374            else {
375                if possibly_live(pid) {
376                    unreadable.insert(pid, (parent, session_id));
377                }
378                continue;
379            };
380            let Some(start_time_ms) = crate::start_time_ms_from_native(start_time) else {
381                unreadable.insert(pid, (parent, session_id));
382                continue;
383            };
384            let parent_pid = match parent {
385                Some(parent) => parent,
386                None => {
387                    unreadable.insert(pid, (None, session_id));
388                    continue;
389                }
390            };
391            let resources = process.resource_usage();
392            let own_cpu_ms = resources.map(|usage| {
393                u64::try_from((usage.cpu_user + usage.cpu_system).as_millis()).unwrap_or(u64::MAX)
394            });
395            let reaped_cpu_ms = resources.map(|_| 0);
396            let current_start = process
397                .observe()
398                .map_or(crate::IdentityRead::Unknown, |observation| {
399                    crate::IdentityRead::Alive(observation.start_time)
400                });
401            if !Self::same_identity(
402                pid,
403                start_time,
404                (Some(parent_pid), session_id),
405                current_start,
406                &mut unreadable,
407            ) {
408                continue;
409            }
410            members.insert(
411                pid,
412                ProcessMember {
413                    pid,
414                    parent_pid,
415                    session_id,
416                    start_time,
417                    start_time_ms,
418                    name: name.unwrap_or_default(),
419                    resources,
420                    own_cpu_ms,
421                    reaped_cpu_ms,
422                    process: std::sync::Arc::new(process),
423                },
424            );
425        }
426        // A reaped child's earlier sample can overlap a later parent's reaped
427        // counter. Drop confirmed exits, leaving recovery to that counter, but
428        // reject unknown identities rather than publishing a partial live sum.
429        Self::fence(&mut members, &mut unreadable, |member| {
430            member
431                .process
432                .observe()
433                .map_or(crate::IdentityRead::Unknown, |observation| {
434                    crate::IdentityRead::Alive(observation.start_time)
435                })
436        });
437        Ok(Self {
438            members,
439            unreadable,
440            revision,
441            observed_at_ms,
442            started_at: Some(started_at),
443            focus: None,
444        })
445    }
446
447    fn fence(
448        members: &mut BTreeMap<u32, ProcessMember>,
449        unreadable: &mut BTreeMap<u32, (Option<u32>, Option<u32>)>,
450        mut identity: impl FnMut(&ProcessMember) -> crate::IdentityRead,
451    ) {
452        members.retain(|pid, member| {
453            Self::same_identity(
454                *pid,
455                member.start_time,
456                (Some(member.parent_pid), member.session_id),
457                identity(member),
458                unreadable,
459            )
460        });
461    }
462
463    fn same_identity(
464        pid: u32,
465        start: u64,
466        ownership: (Option<u32>, Option<u32>),
467        current: crate::IdentityRead,
468        unreadable: &mut BTreeMap<u32, (Option<u32>, Option<u32>)>,
469    ) -> bool {
470        match current {
471            crate::IdentityRead::Alive(now) if now == start => true,
472            crate::IdentityRead::Gone => false,
473            _ => {
474                unreadable.insert(pid, ownership);
475                false
476            }
477        }
478    }
479
480    /// Start of the walk, so exit confirmations can distinguish a
481    /// genuinely newer snapshot from a slow, earlier walk completing late.
482    pub fn started_at(&self) -> Option<std::time::Instant> {
483        self.started_at
484    }
485
486    pub fn process(&self, pid: u32) -> Option<&ProcessMember> {
487        self.members.get(&pid)
488    }
489
490    /// A process-local walk sequence, allocated before the walk starts. A slow
491    /// old walk cannot overwrite a newer accounting observation that finished first.
492    pub fn revision(&self) -> u64 {
493        self.revision
494    }
495
496    /// Wall-clock boundary before enumeration, for conservative birth checks.
497    pub fn observed_at_ms(&self) -> u64 {
498        self.observed_at_ms
499    }
500
501    /// Capture a reusable birth cutoff in this walk's clock domain (Linux
502    /// boot-relative start ticks, otherwise wall-clock epoch milliseconds).
503    pub fn birth_baseline(&self) -> BirthBaseline {
504        BirthBaseline {
505            epoch_ms: self.observed_at_ms,
506            #[cfg(target_os = "linux")]
507            ticks: self.started_at_ticks,
508        }
509    }
510
511    /// `None` means the PID was visible but its identity was unreadable, not that
512    /// the tracked process has exited. A different readable start identity is gone.
513    pub fn identity_alive(&self, pid: u32, start: u64) -> Option<bool> {
514        if self.unreadable.contains_key(&pid) {
515            return None;
516        }
517        Some(
518            self.process(pid)
519                .is_some_and(|member| member.start_time == start),
520        )
521    }
522
523    /// All identities successfully read in this walk, including resources that
524    /// could not be read. Consumers must not interpret those resources as zero.
525    pub fn members(&self) -> impl Iterator<Item = &ProcessMember> {
526        self.members.values()
527    }
528
529    /// Resolve descendants, optionally including a command leader's session.
530    /// The root must still have the expected native kernel start identity.
531    pub fn tree(&self, pid: u32, start_time: u64, include_session: bool) -> Option<TreeUsage> {
532        Self::sum(self.tree_members(pid, start_time, include_session)?)
533    }
534
535    /// Structural ownership does not depend on readable resource counters.
536    /// Unknown identities still refuse the result, rather than hiding overlap.
537    pub fn tree_identities(
538        &self,
539        pid: u32,
540        start_time: u64,
541        include_session: bool,
542    ) -> Option<BTreeSet<(u32, u64)>> {
543        Some(
544            self.tree_members(pid, start_time, include_session)?
545                .into_iter()
546                .map(|member| (member.pid, member.start_time))
547                .collect(),
548        )
549    }
550
551    fn tree_members(
552        &self,
553        pid: u32,
554        start_time: u64,
555        include_session: bool,
556    ) -> Option<Vec<ProcessMember>> {
557        let root = self.members.get(&pid)?;
558        if root.start_time != start_time {
559            return None;
560        }
561        let session = include_session
562            .then_some(root.session_id)
563            .flatten()
564            .filter(|id| *id == pid);
565        let mut selected = BTreeSet::from([pid]);
566        loop {
567            let before = selected.len();
568            for member in self.members.values() {
569                if selected.contains(&member.parent_pid)
570                    || session.is_some_and(|id| member.session_id == Some(id))
571                {
572                    // A reused parent PID must not acquire older processes.
573                    if self
574                        .members
575                        .get(&member.parent_pid)
576                        .is_none_or(|parent| parent.start_time <= member.start_time)
577                    {
578                        selected.insert(member.pid);
579                    }
580                }
581            }
582            if selected.len() == before {
583                break;
584            }
585        }
586        if self
587            .unreadable
588            .iter()
589            .any(|(pid, (parent, unreadable_session))| {
590                selected.contains(pid)
591                    || parent.is_none_or(|parent| selected.contains(&parent))
592                    || session.is_some_and(|session| {
593                        unreadable_session.is_none_or(|unknown| unknown == session)
594                    })
595            })
596        {
597            return None;
598        }
599        let members: Vec<_> = selected
600            .into_iter()
601            .filter_map(|pid| self.members.get(&pid).cloned())
602            .collect();
603        Some(members)
604    }
605
606    /// Sum distinct members, returning at most eight groups by descending memory.
607    pub fn sum(members: Vec<ProcessMember>) -> Option<TreeUsage> {
608        let memory_kind = members
609            .iter()
610            .find_map(|m| m.resources.map(|r| r.memory_kind))?;
611        let mut result = TreeUsage {
612            cpu_ms: 0,
613            memory_bytes: 0,
614            memory_kind,
615            process_count: 0,
616            groups: Vec::new(),
617            members,
618        };
619        let mut groups = BTreeMap::<String, ProcessGroup>::new();
620        let mut seen = BTreeSet::new();
621        for member in &result.members {
622            if !seen.insert((member.pid, member.start_time)) {
623                continue;
624            }
625            let resources = member.resources?;
626            let cpu_ms = u64::try_from((resources.cpu_user + resources.cpu_system).as_millis())
627                .unwrap_or(u64::MAX);
628            result.cpu_ms = result.cpu_ms.saturating_add(cpu_ms);
629            result.memory_bytes = result.memory_bytes.saturating_add(resources.memory_bytes);
630            result.process_count += 1;
631            let group = groups
632                .entry(member.name.clone())
633                .or_insert_with(|| ProcessGroup {
634                    name: member.name.clone(),
635                    count: 0,
636                    cpu_ms: 0,
637                    memory_bytes: 0,
638                });
639            group.count += 1;
640            group.cpu_ms = group.cpu_ms.saturating_add(cpu_ms);
641            group.memory_bytes = group.memory_bytes.saturating_add(resources.memory_bytes);
642        }
643        result.groups = groups.into_values().collect();
644        result.groups.sort_by(|a, b| {
645            b.memory_bytes
646                .cmp(&a.memory_bytes)
647                .then_with(|| a.name.cmp(&b.name))
648        });
649        result.groups.truncate(8);
650        Some(result)
651    }
652}
653
654#[cfg(unix)]
655fn possibly_live(pid: u32) -> bool {
656    // SAFETY: getsid is a read-only query and does not send a signal.
657    #[allow(unsafe_code)]
658    let session = unsafe { libc::getsid(pid as libc::pid_t) };
659    session >= 0 || io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
660}
661
662#[cfg(windows)]
663fn possibly_live(_pid: u32) -> bool {
664    true
665}
666
667/// Windows never reparents: a process keeps the pid of the parent that
668/// created it, even after that parent exits and the pid is given to a new
669/// process. Otherwise a new process that reuses such a pid inherits unrelated
670/// children: an unopenable one (csrss.exe and wininit.exe name an exited
671/// smss.exe) makes every tree rooted at the new process unknown, and a
672/// readable one makes the new process look like an ancestor.
673///
674/// Creation order, not start time, tells a real parent from a reused pid.
675/// Start times are wall-clock times, and a clock stepped back after boot
676/// makes boot processes look younger than processes started since. The
677/// native listing walks the kernel's active process list
678/// (`PsActiveProcessHead`), which appends each process when it is created, so
679/// a real parent is always listed before its child. A listed parent that
680/// appears after the child is a later process holding a reused pid, and the
681/// child is recorded with no live parent (0, as for System). This ordering is
682/// not documented; `the_native_listing_is_in_creation_order` fails if Windows
683/// stops providing it.
684#[cfg(windows)]
685fn live_parent(
686    parent: Option<u32>,
687    child_at: usize,
688    listed_at: &BTreeMap<u32, usize>,
689) -> Option<u32> {
690    let parent = parent?;
691    let reused = listed_at
692        .get(&parent)
693        .is_some_and(|parent_at| *parent_at > child_at);
694    Some(if reused { 0 } else { parent })
695}
696
697/// One listed process: pid, parent, program name and native start, each
698/// `None` when the listing did not supply it. A missing parent or name is
699/// read per process; a missing start is not compared against.
700type Entry = (u32, Option<u32>, Option<String>, Option<u64>);
701
702/// Own CPU and memory, then reaped-child user and system CPU.
703#[cfg(unix)]
704type Usage = (ResourceUsage, std::time::Duration, std::time::Duration);
705
706/// The per-process reads of a Unix walk. Tests substitute scripted answers
707/// to compare a narrowed walk with a full one over the same process table.
708#[cfg(unix)]
709trait Probe {
710    fn parent(&self, pid: u32) -> Option<u32>;
711    fn session(&self, pid: u32) -> Option<u32>;
712    fn name(&self, pid: u32) -> String;
713    fn identity(&self, pid: u32) -> crate::IdentityRead;
714    fn possibly_live(&self, pid: u32) -> bool;
715    fn usage(&self, pid: u32) -> Option<Usage>;
716}
717
718#[cfg(unix)]
719struct Native;
720
721#[cfg(unix)]
722impl Probe for Native {
723    fn parent(&self, pid: u32) -> Option<u32> {
724        crate::parent_pid(pid)
725    }
726
727    fn session(&self, pid: u32) -> Option<u32> {
728        // SAFETY: getsid is a read-only query of a numeric process.
729        #[allow(unsafe_code)]
730        let session = unsafe { libc::getsid(pid as libc::pid_t) };
731        u32::try_from(session).ok()
732    }
733
734    fn name(&self, pid: u32) -> String {
735        #[cfg(target_os = "macos")]
736        {
737            program_name(pid)
738        }
739        #[cfg(not(target_os = "macos"))]
740        {
741            let _ = pid;
742            String::new()
743        }
744    }
745
746    fn identity(&self, pid: u32) -> crate::IdentityRead {
747        crate::read_identity(pid)
748    }
749
750    fn possibly_live(&self, pid: u32) -> bool {
751        possibly_live(pid)
752    }
753
754    fn usage(&self, pid: u32) -> Option<Usage> {
755        #[cfg(target_os = "linux")]
756        {
757            crate::linux::resource_usage_parts(pid)
758        }
759        #[cfg(target_os = "macos")]
760        {
761            crate::macos::resource_usage_parts(pid)
762        }
763        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
764        {
765            // Without separate reaped-child counters, all CPU is the process's own.
766            crate::resource_usage(pid)
767                .map(|usage| (usage, std::time::Duration::ZERO, std::time::Duration::ZERO))
768        }
769    }
770}
771
772/// Parents and sessions a narrowed walk read while choosing its focus. The
773/// walk itself uses these answers instead of asking again, so each examined
774/// process gets one parent and one session read, as in a full walk.
775#[cfg(unix)]
776#[derive(Default)]
777struct Known {
778    parents: BTreeMap<u32, Option<u32>>,
779    sessions: BTreeMap<u32, Option<u32>>,
780}
781
782/// Choose the processes a narrowed walk examines; see [`ProcessTable::read_for`].
783///
784/// A tree query rooted at `root` selects `root`, then repeatedly every member
785/// whose parent is selected or, with its session, whose session id is
786/// `root` when `root` leads its own session. It is made uncertain by an
787/// unreadable process that is selected, whose parent is selected or unknown,
788/// or, with the session, whose session is `root` or unknown. Every such
789/// process is an interest pid, a session member of an interest pid that
790/// leads its session, a process with an unknown session or parent, or a
791/// descendant of one of those, so that set is examined. Adding all of their
792/// ancestors keeps every parent lookup and ancestry walk from an examined
793/// process exact too.
794#[cfg(unix)]
795fn focus(
796    entries: &[Entry],
797    interest: &BTreeSet<u32>,
798    probe: &impl Probe,
799    known: &mut Known,
800) -> Focus {
801    let mut parents = BTreeMap::new();
802    for (pid, parent, ..) in entries {
803        let parent = match parent {
804            Some(parent) => Some(*parent),
805            None => *known
806                .parents
807                .entry(*pid)
808                .or_insert_with(|| probe.parent(*pid)),
809        };
810        parents.insert(*pid, parent);
811    }
812    let mut children = BTreeMap::<u32, Vec<u32>>::new();
813    for (pid, parent) in &parents {
814        if let Some(parent) = parent {
815            children.entry(*parent).or_default().push(*pid);
816        }
817    }
818    let mut seeds: Vec<u32> = interest.iter().copied().collect();
819    seeds.extend(
820        parents
821            .iter()
822            .filter(|(_, parent)| parent.is_none())
823            .map(|(pid, _)| *pid),
824    );
825    let mut session = |pid: u32| {
826        *known
827            .sessions
828            .entry(pid)
829            .or_insert_with(|| probe.session(pid))
830    };
831    let leaders: BTreeSet<u32> = interest
832        .iter()
833        .copied()
834        .filter(|pid| parents.contains_key(pid))
835        .filter(|pid| session(*pid) == Some(*pid))
836        .collect();
837    if !leaders.is_empty() {
838        for pid in parents.keys() {
839            if session(*pid).is_none_or(|session| leaders.contains(&session)) {
840                seeds.push(*pid);
841            }
842        }
843    }
844    let mut selected = BTreeSet::new();
845    while let Some(pid) = seeds.pop() {
846        if selected.insert(pid) {
847            seeds.extend(children.get(&pid).into_iter().flatten().copied());
848        }
849    }
850    let reached: Vec<u32> = selected.iter().copied().collect();
851    for pid in reached {
852        let mut current = parents.get(&pid).copied().flatten();
853        while let Some(parent) = current.filter(|parent| parents.contains_key(parent)) {
854            if !selected.insert(parent) {
855                break;
856            }
857            current = parents.get(&parent).copied().flatten();
858        }
859    }
860    Focus {
861        selected,
862        listed: parents.into_keys().collect(),
863    }
864}
865
866#[cfg(target_os = "linux")]
867fn entries() -> io::Result<Vec<Entry>> {
868    let mut entries = Vec::new();
869    for entry in std::fs::read_dir("/proc")? {
870        let entry = entry?;
871        let Some(pid) = entry
872            .file_name()
873            .to_str()
874            .and_then(|s| s.parse::<u32>().ok())
875        else {
876            continue;
877        };
878        let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) else {
879            entries.push((pid, None, Some(String::new()), None));
880            continue;
881        };
882        let Some((name, rest)) = stat
883            .split_once('(')
884            .and_then(|(_, tail)| tail.rsplit_once(')'))
885        else {
886            entries.push((pid, None, Some(String::new()), None));
887            continue;
888        };
889        let parent = rest.split_whitespace().nth(1).and_then(|s| s.parse().ok());
890        let start = rest
891            .split_whitespace()
892            .nth(19)
893            .and_then(|value| value.parse().ok());
894        entries.push((pid, parent, Some(name.to_owned()), start));
895    }
896    Ok(entries)
897}
898
899/// One `sysctl(KERN_PROC_ALL)` lists every process with its parent and
900/// start. Names come from `proc_name` later, and only for processes a walk
901/// keeps, because the listing's 16-byte command name is shorter.
902#[cfg(target_os = "macos")]
903fn entries() -> io::Result<Vec<Entry>> {
904    Ok(crate::macos::process_list()?
905        .into_iter()
906        .map(|(pid, parent, start)| (pid, parent, None, start))
907        .collect())
908}
909
910#[cfg(target_os = "macos")]
911pub(crate) fn program_name(pid: u32) -> String {
912    #[allow(unsafe_code)]
913    unsafe extern "C" {
914        fn proc_name(pid: libc::c_int, buffer: *mut std::ffi::c_void, size: u32) -> libc::c_int;
915    }
916    let mut name = [0_u8; 1024];
917    // SAFETY: name is initialized, writable and its length is correct.
918    #[allow(unsafe_code)]
919    let length = unsafe {
920        proc_name(
921            pid as libc::c_int,
922            name.as_mut_ptr().cast(),
923            name.len() as u32,
924        )
925    };
926    let length = usize::try_from(length).unwrap_or(0).min(name.len());
927    String::from_utf8_lossy(&name[..length])
928        .trim_end_matches('\0')
929        .to_owned()
930}
931
932/// The listing a walk used before `KERN_PROC_ALL`: every pid from
933/// `proc_listallpids` with its `proc_name`, and the parent and start left to
934/// the per-process reads. Kept to measure the old walk's cost.
935#[cfg(all(test, target_os = "macos"))]
936fn legacy_entries() -> io::Result<Vec<Entry>> {
937    #[allow(unsafe_code)]
938    unsafe extern "C" {
939        fn proc_listallpids(buffer: *mut std::ffi::c_void, size: libc::c_int) -> libc::c_int;
940    }
941    // SAFETY: a null buffer asks only for the number of PIDs.
942    #[allow(unsafe_code)]
943    let count = unsafe { proc_listallpids(std::ptr::null_mut(), 0) };
944    if count <= 0 {
945        return Err(io::Error::last_os_error());
946    }
947    let mut pids = vec![0_i32; count as usize + 256];
948    // SAFETY: pids is an initialized writable buffer of the advertised size.
949    #[allow(unsafe_code)]
950    let count = unsafe {
951        proc_listallpids(
952            pids.as_mut_ptr().cast(),
953            (pids.len() * size_of::<i32>()) as i32,
954        )
955    };
956    if count <= 0 || count as usize >= pids.len() {
957        return Err(io::Error::last_os_error());
958    }
959    Ok(pids
960        .into_iter()
961        .take(count as usize)
962        .filter(|pid| *pid > 0)
963        .map(|pid| (pid as u32, None, Some(program_name(pid as u32)), None))
964        .collect())
965}
966
967#[cfg(windows)]
968fn entries() -> io::Result<Vec<Entry>> {
969    crate::windows::process_entries().map(|entries| {
970        entries
971            .into_iter()
972            .map(|(pid, parent, name, start)| (pid, parent, Some(name), Some(start)))
973            .collect()
974    })
975}
976
977#[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
978fn entries() -> io::Result<Vec<Entry>> {
979    Err(io::Error::new(
980        io::ErrorKind::Unsupported,
981        "process tables unavailable",
982    ))
983}
984
985#[cfg(all(test, unix))]
986mod narrowing_tests;
987
988#[cfg(test)]
989mod tests {
990    use super::*;
991    use std::time::Duration;
992
993    #[cfg(windows)]
994    #[test]
995    fn wall_clock_rollback_keeps_the_live_process_in_the_table() {
996        let pid = std::process::id();
997        let process = crate::Process::open(pid).unwrap().unwrap();
998        let start = process.observe().unwrap().start_time;
999        let table = ProcessTable::with_test_wall_clock(std::time::UNIX_EPOCH, || {
1000            ProcessTable::read().unwrap()
1001        });
1002        assert_eq!(process.observe().unwrap().start_time, start);
1003        assert!(
1004            !table.unreadable.contains_key(&pid),
1005            "the readable live process must not be classified as unreadable"
1006        );
1007        assert_eq!(
1008            table.process(pid).map(|member| member.start_time),
1009            Some(start),
1010            "a wall clock earlier than process creation must not hide a live identity"
1011        );
1012    }
1013
1014    #[cfg(windows)]
1015    #[test]
1016    fn reused_enumerated_pid_is_retained_as_uncertainty() {
1017        let pid = std::process::id();
1018        let process = crate::Process::open(pid).unwrap().unwrap();
1019        let start = process.observe().unwrap().start_time;
1020        let mut rows = entries().unwrap();
1021        let row = rows.iter_mut().find(|row| row.0 == pid).unwrap();
1022        assert_eq!(row.3, Some(start));
1023        row.3 = Some(start - 1);
1024        let table = ProcessTable::read_entries(|| Ok(rows)).unwrap();
1025        assert_eq!(process.observe().unwrap().start_time, start);
1026        assert!(table.process(pid).is_none());
1027        assert!(table.unreadable.contains_key(&pid));
1028        assert_eq!(table.identity_alive(pid, start), None);
1029    }
1030
1031    #[cfg(windows)]
1032    struct Kill(std::process::Child);
1033
1034    #[cfg(windows)]
1035    impl Drop for Kill {
1036        fn drop(&mut self) {
1037            let _ = self.0.kill();
1038            let _ = self.0.wait();
1039        }
1040    }
1041
1042    /// A process that waits on its open stdin until killed.
1043    #[cfg(windows)]
1044    fn waiting_process() -> Kill {
1045        Kill(
1046            std::process::Command::new("cmd.exe")
1047                .stdin(std::process::Stdio::piped())
1048                .stdout(std::process::Stdio::null())
1049                .stderr(std::process::Stdio::null())
1050                .spawn()
1051                .unwrap(),
1052        )
1053    }
1054
1055    /// Stale-parent detection relies on the native listing being in creation
1056    /// order, which Windows does not document. This fails if that changes.
1057    #[cfg(windows)]
1058    #[test]
1059    fn the_native_listing_is_in_creation_order() {
1060        let first = waiting_process();
1061        let second = waiting_process();
1062        let (first, second) = (first.0.id(), second.0.id());
1063        let mut rows = entries().unwrap();
1064        let at = |pid| rows.iter().position(|row| row.0 == pid).unwrap();
1065        assert!(at(std::process::id()) < at(first));
1066        assert!(
1067            at(first) < at(second),
1068            "a process started later is listed later"
1069        );
1070        // Cross the two links in the same real listing: only the one naming
1071        // the earlier process stays.
1072        for row in &mut rows {
1073            if row.0 == first {
1074                row.1 = Some(second);
1075            } else if row.0 == second {
1076                row.1 = Some(first);
1077            }
1078        }
1079        let table = ProcessTable::read_entries(|| Ok(rows)).unwrap();
1080        assert_eq!(table.process(second).unwrap().parent_pid, first);
1081        assert_eq!(table.process(first).unwrap().parent_pid, 0);
1082    }
1083
1084    #[cfg(windows)]
1085    #[test]
1086    fn a_listed_parent_that_appears_after_its_child_is_not_its_parent() {
1087        // The new process plays one that reuses a pid older processes still
1088        // name as their parent, as csrss.exe and wininit.exe name an exited
1089        // smss.exe.
1090        let root = waiting_process();
1091        let root_pid = root.0.id();
1092        let root_start = crate::start_time(root_pid).unwrap();
1093        let own = std::process::id();
1094        let own_start = crate::start_time(own).unwrap();
1095        // No process holds this pid, so opening it fails and the walk keeps
1096        // it as unreadable, like a protected system process.
1097        let unopenable = u32::MAX - 3;
1098        let unopenable_row = |start| {
1099            (
1100                unopenable,
1101                Some(root_pid),
1102                Some("csrss.exe".into()),
1103                Some(start),
1104            )
1105        };
1106        let root_row = (
1107            root_pid,
1108            Some(own),
1109            Some("cmd.exe".into()),
1110            Some(root_start),
1111        );
1112        // Listed before the root, yet with a later start time, as boot
1113        // processes look after the clock steps back: order decides.
1114        let stale = ProcessTable::read_entries(|| {
1115            Ok(vec![
1116                (
1117                    own,
1118                    Some(root_pid),
1119                    Some("older.exe".into()),
1120                    Some(own_start),
1121                ),
1122                unopenable_row(root_start + 1),
1123                root_row.clone(),
1124            ])
1125        })
1126        .unwrap();
1127        assert_eq!(
1128            stale.process(own).map(|member| member.parent_pid),
1129            Some(0),
1130            "a readable process listed before its parent has no live parent"
1131        );
1132        assert_eq!(stale.unreadable.get(&unopenable), Some(&(Some(0), None)));
1133        assert_eq!(
1134            stale.process(root_pid).map(|member| member.parent_pid),
1135            Some(own),
1136            "a parent listed first stays linked"
1137        );
1138        assert_eq!(
1139            stale.tree_identities(root_pid, root_start, true),
1140            Some(BTreeSet::from([(root_pid, root_start)])),
1141            "an older unreadable process cannot make the new root's tree unknown"
1142        );
1143        // An unreadable process listed after the root, which the root may
1144        // have created, still does, even with an earlier start time.
1145        let child = ProcessTable::read_entries(|| {
1146            Ok(vec![
1147                (own, None, Some("older.exe".into()), Some(own_start)),
1148                root_row.clone(),
1149                unopenable_row(root_start - 1),
1150            ])
1151        })
1152        .unwrap();
1153        assert_eq!(
1154            child.unreadable.get(&unopenable),
1155            Some(&(Some(root_pid), None))
1156        );
1157        assert_eq!(child.tree_identities(root_pid, root_start, true), None);
1158    }
1159
1160    fn member(
1161        pid: u32,
1162        parent_pid: u32,
1163        start_time: u64,
1164        session_id: u32,
1165        memory_bytes: u64,
1166    ) -> ProcessMember {
1167        ProcessMember {
1168            pid,
1169            parent_pid,
1170            start_time,
1171            start_time_ms: start_time,
1172            session_id: Some(session_id),
1173            name: format!("program-{pid}"),
1174            resources: Some(ResourceUsage {
1175                memory_bytes,
1176                memory_kind: MemoryKind::ResidentSet,
1177                swap_bytes: None,
1178                cpu_user: Duration::from_millis(memory_bytes * 10),
1179                cpu_system: Duration::ZERO,
1180            }),
1181            own_cpu_ms: Some(memory_bytes * 10),
1182            reaped_cpu_ms: Some(0),
1183            // These synthetic arithmetic fixtures never query the handle.
1184            #[cfg(windows)]
1185            process: std::sync::Arc::new(
1186                crate::Process::open(std::process::id()).unwrap().unwrap(),
1187            ),
1188        }
1189    }
1190
1191    #[test]
1192    fn tree_membership_checks_identity_includes_sessions_and_bounds_program_groups() {
1193        let members = vec![
1194            member(1, 0, 10, 1, 1),
1195            member(2, 1, 20, 1, 2),
1196            member(3, 99, 30, 1, 3),
1197            member(4, 99, 40, 4, 4),
1198            member(5, 1, 5, 5, 5),
1199        ];
1200        let table = ProcessTable {
1201            members: members
1202                .into_iter()
1203                .map(|member| (member.pid, member))
1204                .collect(),
1205            unreadable: BTreeMap::new(),
1206            revision: 1,
1207            observed_at_ms: 0,
1208            #[cfg(target_os = "linux")]
1209            started_at_ticks: None,
1210            started_at: None,
1211            focus: None,
1212        };
1213        assert!(table.tree(1, 11, true).is_none());
1214        let tree = table.tree(1, 10, false).unwrap();
1215        assert_eq!(
1216            (tree.cpu_ms, tree.memory_bytes, tree.process_count),
1217            (30, 3, 2)
1218        );
1219        let session = table.tree(1, 10, true).unwrap();
1220        assert_eq!(
1221            (session.cpu_ms, session.memory_bytes, session.process_count),
1222            (60, 6, 3)
1223        );
1224        assert_eq!(session.groups[0].name, "program-3");
1225        let mut members: Vec<_> = (1..=12)
1226            .map(|pid| member(pid, 0, 100, 0, u64::from(pid)))
1227            .collect();
1228        members.push(members[0].clone());
1229        let groups = ProcessTable::sum(members).unwrap();
1230        assert_eq!(
1231            groups.process_count, 12,
1232            "duplicate identities are counted only once"
1233        );
1234        assert_eq!(groups.groups.len(), 8);
1235        assert_eq!(groups.groups[0].memory_bytes, 12);
1236        assert_eq!(groups.groups[7].memory_bytes, 5);
1237    }
1238
1239    #[test]
1240    fn a_child_reaped_during_the_walk_keeps_parent_cpu_without_double_counting() {
1241        let mut table = ProcessTable::default();
1242        let mut parent = member(1, 0, 10, 1, 1);
1243        parent.resources.as_mut().unwrap().cpu_user = Duration::from_millis(110);
1244        parent.reaped_cpu_ms = Some(100);
1245        table.members.insert(1, parent);
1246        table.members.insert(2, member(2, 1, 20, 1, 10));
1247        ProcessTable::fence(&mut table.members, &mut table.unreadable, |member| {
1248            if member.pid == 2 {
1249                crate::IdentityRead::Gone
1250            } else {
1251                crate::IdentityRead::Alive(member.start_time)
1252            }
1253        });
1254        let tree = table
1255            .tree(1, 10, false)
1256            .expect("a confirmed exit must not void the parent");
1257        assert_eq!(
1258            tree.cpu_ms, 110,
1259            "the child's 100 ms is already in the parent's reaped counter"
1260        );
1261        assert_eq!(tree.process_count, 1);
1262        assert_eq!(
1263            table.identity_alive(2, 20),
1264            Some(false),
1265            "a confirmed exit is not an unreadable live identity"
1266        );
1267    }
1268
1269    #[test]
1270    fn identity_checks_drop_only_confirmed_exits_at_either_fence() {
1271        use crate::IdentityRead::{Alive, Gone, Unknown};
1272        for current in [Gone, Unknown, Alive(21)] {
1273            let mut unreadable = BTreeMap::new();
1274            assert!(!ProcessTable::same_identity(
1275                2,
1276                20,
1277                (Some(1), Some(1)),
1278                current,
1279                &mut unreadable
1280            ));
1281            assert_eq!(unreadable.contains_key(&2), current != Gone);
1282            let mut members = BTreeMap::from([(2, member(2, 1, 20, 1, 10))]);
1283            unreadable.clear();
1284            ProcessTable::fence(&mut members, &mut unreadable, |_| current);
1285            assert!(members.is_empty());
1286            assert_eq!(
1287                unreadable.contains_key(&2),
1288                current != Gone,
1289                "unknown identity and PID reuse must still reject the related tree"
1290            );
1291        }
1292    }
1293
1294    #[test]
1295    fn a_child_exiting_after_parent_read_defers_cpu_until_reaped() {
1296        let mut table = ProcessTable::default();
1297        table.members.insert(1, member(1, 0, 10, 1, 1));
1298        table.members.insert(2, member(2, 1, 20, 1, 10));
1299        ProcessTable::fence(&mut table.members, &mut table.unreadable, |member| {
1300            if member.pid == 2 {
1301                crate::IdentityRead::Gone
1302            } else {
1303                crate::IdentityRead::Alive(member.start_time)
1304            }
1305        });
1306        assert_eq!(table.tree(1, 10, false).unwrap().cpu_ms, 10);
1307        let parent = table.members.get_mut(&1).unwrap();
1308        parent.reaped_cpu_ms = Some(100);
1309        parent.resources.as_mut().unwrap().cpu_user = Duration::from_millis(110);
1310        assert_eq!(table.tree(1, 10, false).unwrap().cpu_ms, 110);
1311        assert_eq!(
1312            table.tree(1, 10, false).unwrap().cpu_ms,
1313            110,
1314            "re-reading the same cumulative counter cannot credit another child sample"
1315        );
1316    }
1317
1318    #[test]
1319    fn unreadable_member_never_becomes_a_confident_partial_tree() {
1320        let root = member(1, 0, 10, 1, 1);
1321        let mut child = member(2, 1, 20, 1, 2);
1322        child.resources = None;
1323        child.own_cpu_ms = None;
1324        child.reaped_cpu_ms = None;
1325        assert!(ProcessTable::sum(vec![root.clone(), child.clone()]).is_none());
1326        let mut table = ProcessTable::default();
1327        table.members.insert(1, root);
1328        table.members.insert(2, child);
1329        assert_eq!(
1330            table.tree_identities(1, 10, false).unwrap().len(),
1331            2,
1332            "resource uncertainty does not hide structural overlap"
1333        );
1334        assert!(table.tree(1, 10, false).is_none());
1335        table.members.remove(&2);
1336        table.unreadable.insert(2, (Some(1), Some(1)));
1337        assert!(table.tree(1, 10, false).is_none());
1338        table.unreadable.insert(2, (Some(99), Some(99)));
1339        assert!(table.tree(1, 10, false).is_some());
1340        table.unreadable.insert(2, (None, None));
1341        assert!(table.tree(1, 10, false).is_none());
1342    }
1343}