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