Skip to main content

capsule_runtime/
cgroup.rs

1//! Linux cgroup v2 scoping for a capsule's whole native-subprocess tree.
2//!
3//! `resources::apply_hard_rlimits` bounds each spawned process individually. That is necessary
4//! and not sufficient: `RLIMIT_NPROC` is a **per-uid** ceiling, checked against every thread the
5//! uid owns on the host, so it cannot bound one tree, and no rlimit bounds *aggregate* memory or
6//! CPU across a tree at all. A cgroup v2 scope does exactly what rlimits structurally cannot:
7//! `pids.max`, `memory.max` and `cpu.max` apply to every task in the scope together, and the
8//! kernel enforces them at fork/allocate time rather than after the fact. `memory.swap.max` is
9//! written as [`SCOPE_SWAP_MAX`] beside `memory.max`, so the memory ceiling bounds the tree's
10//! whole footprint rather than only its resident pages. A spawn that joins a
11//! scope therefore gets no `RLIMIT_NPROC` at all, and `pids.max` is its only process bound — see
12//! `resources::NprocBound`.
13//!
14//! ## Install requirement: systemd user cgroup delegation
15//!
16//! Creating a cgroup requires write access to a cgroup directory, and this runtime has none by
17//! default. The usual alternative — start as root, create the cgroup, then drop privileges —
18//! is not available here: nothing in this codebase ever runs as root or drops privileges (there
19//! is no setuid or privilege-drop path anywhere in `capsule-runtime` or `murmur-cli`), so there
20//! is no privileged phase to create a cgroup from. The mechanism that fits how this runtime
21//! actually runs is **systemd user delegation**: the user unit or scope `mur` runs under carries
22//! `Delegate=yes` for `memory pids cpu io`, which hands the unprivileged user write access to
23//! its own cgroup subtree. This is the same mechanism rootless Docker and Podman use for the
24//! identical problem. The exact unit configuration is in
25//! `docs/content/reference/resource-limits-manual-verification.md`.
26//!
27//! ## Self-relocation before probing an inherited cgroup
28//!
29//! cgroup v2 refuses to enable controllers for a cgroup's children while that cgroup still holds
30//! tasks, so a bounded child can only be built under a base this process is the *sole* occupant
31//! of. An interactive shell's cgroup holds the shell, its pane scope, and everything else the
32//! user is running; under `cargo test`, `cargo` stays resident beside every test binary. Stepping
33//! aside into [`SUPERVISOR_LEAF`] moves only this process, so co-residency alone makes the base
34//! unusable regardless of delegation.
35//!
36//! [`move_self_into_own_systemd_scope`] asks the systemd *user* manager over the session bus for
37//! a freshly created transient scope carrying `Delegate=yes`, moving this process into a
38//! brand-new cgroup — a sibling of whatever it left, not a child — that it is the sole occupant
39//! of by construction. The step-aside logic below then always succeeds, since nothing else is
40//! ever in that scope to contend with.
41//!
42//! The request is best-effort and silent: with no systemd, no session bus, or a policy denial,
43//! the runtime probes whatever cgroup it inherited, exactly as it does when this step is skipped.
44//!
45//! ## Fail closed, but only where the threat exists
46//!
47//! On Linux, a capsule that can spawn *any* native subprocess and cannot be given a cgroup
48//! refuses to launch (`RuntimeError::CgroupDelegationUnavailable`) rather than running that
49//! subprocess tree unbounded. A capsule that declares no subprocess capability at all needs no
50//! scope and is never blocked — there is no process tree to bound. On macOS, cgroups cannot
51//! exist at all, so this module is inert and the runtime falls back to rlimits-only enforcement
52//! with a `W-SEC-010` warning; refusing every launch on the primary development platform for a
53//! kernel feature that platform will never have would be a policy, not a protection.
54//!
55//! ## A scope outlives no runtime
56//!
57//! Each scope [`CgroupScope::create`] makes on Linux has a watcher: a process forked from the
58//! runtime that blocks reading a pipe whose write end only the runtime holds. When the read
59//! returns end-of-file — the scope's `Drop` closed it, or the kernel closed it because the runtime
60//! died by any means, `SIGKILL` and the OOM killer included — the watcher kills the scope and
61//! exits. A parent-death signal would reach only a direct child, and a backgrounded server is a
62//! grandchild; the pipe reaches every death at once. The watcher stays in the runtime's own
63//! cgroup, never in the scope it kills, and holds none of the runtime's other descriptors, so it
64//! keeps no pipe from reaching end-of-file and no port bound.
65//!
66//! ## Cross-platform shape
67//!
68//! Following `sandbox.rs`: the types here are defined unconditionally and stay type-checked and
69//! unit-testable on macOS, with the *behavior* gated internally by `cfg(target_os = "linux")`
70//! and cross-platform-dead surface marked `#[cfg_attr(not(target_os = "linux"), allow(dead_code))]`.
71//! Nothing is hidden behind a module-level `cfg`.
72
73use std::path::{Path, PathBuf};
74use std::sync::{
75    atomic::{AtomicU64, Ordering},
76    Arc,
77};
78#[cfg(target_os = "linux")]
79use std::time::Duration;
80
81use crate::resources::HostResourceLimits;
82
83/// Where the unified cgroup v2 hierarchy is mounted on a conventional host. Only used as the
84/// fallback when `/proc/mounts` does not name a `cgroup2` mount explicitly.
85#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
86const DEFAULT_CGROUP2_MOUNT: &str = "/sys/fs/cgroup";
87
88/// The `cpu.max` period, in microseconds. The kernel's own default; the quota this module
89/// writes is expressed against it (`cgroup_cpu_percent * 1000` µs of every 100 000 µs).
90#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
91const CPU_MAX_PERIOD_US: u64 = 100_000;
92
93/// `memory.swap.max` for every scope: no swap at all.
94///
95/// `memory.max` alone bounds only resident pages; with `memory.swap.max` at the kernel default
96/// `max`, a tree over `cgroup_memory_bytes` is pushed out to swap instead of being OOM-killed and
97/// keeps growing there. Zero makes `cgroup_memory_bytes` the tree's whole memory footprint, which
98/// is what the manifest field promises.
99pub const SCOPE_SWAP_MAX: &str = "0";
100
101/// One cgroup interface file a scope's limits are written to, and the value written.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub(crate) struct ScopeLimit {
104    pub(crate) file: &'static str,
105    pub(crate) value: String,
106    /// Whether a kernel that exposes no such file still yields a bounded scope. Only
107    /// `memory.swap.max` is: it is absent when swap support is compiled out or swap accounting
108    /// is off at boot, and on such a kernel there is no per-cgroup swap control to write. A file
109    /// that exists and refuses the write is fatal either way.
110    pub(crate) absent_ok: bool,
111}
112
113/// The limit writes a scope is created with, in write order. `io.max` is not among them: it is
114/// best-effort and reported separately (see [`CgroupScope::apply_io_max`]).
115#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
116pub(crate) fn scope_limits(limits: &HostResourceLimits) -> Vec<ScopeLimit> {
117    let required = |file, value| ScopeLimit {
118        file,
119        value,
120        absent_ok: false,
121    };
122    vec![
123        required("memory.max", limits.cgroup_memory_bytes.to_string()),
124        ScopeLimit {
125            file: "memory.swap.max",
126            value: SCOPE_SWAP_MAX.to_string(),
127            absent_ok: true,
128        },
129        required("pids.max", limits.cgroup_pids_max.to_string()),
130        required(
131            "cpu.max",
132            format!(
133                "{} {CPU_MAX_PERIOD_US}",
134                u64::from(limits.cgroup_cpu_percent) * (CPU_MAX_PERIOD_US / 100)
135            ),
136        ),
137    ]
138}
139
140/// Whether this kernel gives a cgroup a `memory.swap.max` to write, as `mur doctor` reports it.
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub enum SwapControl {
143    /// A cgroup on this host carries `memory.swap.max`, so a scope's swap is bounded at
144    /// [`SCOPE_SWAP_MAX`].
145    Exposed,
146    /// A cgroup on this host carries `memory.max` and no `memory.swap.max`: the kernel has no
147    /// per-cgroup swap control, and a scope's swap is unbounded.
148    Absent,
149    /// No cgroup this process can see has the memory controller enabled, so the question cannot
150    /// be answered from here. Also the answer off Linux.
151    Unknown,
152}
153
154/// Probe whether this kernel exposes `memory.swap.max`, without creating or moving anything.
155///
156/// Walks from this process's own cgroup up to the hierarchy root and answers from the first
157/// cgroup that has the memory controller (a `memory.max` file): the file set a cgroup gets is the
158/// kernel's, so one cgroup with `memory.max` and no `memory.swap.max` speaks for every scope this
159/// host would create.
160#[must_use]
161pub fn probe_swap_control() -> SwapControl {
162    #[cfg(not(target_os = "linux"))]
163    {
164        SwapControl::Unknown
165    }
166
167    #[cfg(target_os = "linux")]
168    {
169        let mount = std::fs::read_to_string("/proc/mounts")
170            .map(|contents| parse_cgroup2_mount(&contents))
171            .unwrap_or_else(|_| DEFAULT_CGROUP2_MOUNT.to_string());
172        let Some(own) = std::fs::read_to_string("/proc/self/cgroup")
173            .ok()
174            .and_then(|contents| parse_unified_cgroup_path(&contents))
175        else {
176            return SwapControl::Unknown;
177        };
178        let root = PathBuf::from(mount);
179        let mut dir = root.join(own.trim_start_matches('/'));
180        loop {
181            if dir.join("memory.max").exists() {
182                return if dir.join("memory.swap.max").exists() {
183                    SwapControl::Exposed
184                } else {
185                    SwapControl::Absent
186                };
187            }
188            if dir == root || !dir.pop() || !dir.starts_with(&root) {
189                return SwapControl::Unknown;
190            }
191        }
192    }
193}
194
195/// How many swap areas `/proc/swaps` lists as active, or `None` where it cannot be read.
196#[must_use]
197pub fn active_swap_areas() -> Option<usize> {
198    let contents = std::fs::read_to_string("/proc/swaps").ok()?;
199    Some(count_swap_areas(&contents))
200}
201
202/// Count the device lines in `/proc/swaps` contents, below its one header line.
203fn count_swap_areas(contents: &str) -> usize {
204    contents
205        .lines()
206        .skip(1)
207        .filter(|line| !line.trim().is_empty())
208        .count()
209}
210
211/// Controllers that must be delegated and settable. `io` is deliberately absent: it is
212/// best-effort (see [`CgroupScope::apply_io_max`]).
213#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
214const REQUIRED_CONTROLLERS: &[&str] = &["memory", "pids", "cpu"];
215
216/// Name of the leaf cgroup the runtime moves *itself* into when its delegated base still holds
217/// processes. cgroup v2's "no internal processes" rule forbids enabling controllers in a
218/// cgroup's `subtree_control` while that cgroup directly contains tasks, so the manager has to
219/// step down into its own leaf first — the same move rootless Podman/Docker make.
220#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
221const SUPERVISOR_LEAF: &str = "murmur-supervisor";
222
223/// A cgroup v2 scope created for one capsule session, holding that session's whole native
224/// subprocess tree.
225///
226/// Constructed once per launch (never per subprocess) so that `pids.max` and `memory.max` bound
227/// the tree *in aggregate* — a per-call scope would let N sequential shell calls each spend the
228/// full budget, which is precisely the aggregate case rlimits already fail to cover.
229#[derive(Debug)]
230pub(crate) struct CgroupScope {
231    /// Absolute path of the scope directory, e.g.
232    /// `/sys/fs/cgroup/user.slice/user-1000.slice/user@1000.service/app.slice/mur.scope/murmur-ses_abc123`.
233    path: PathBuf,
234    /// `cgroup.procs`, opened write-only in the **parent** before any fork. The forked child's
235    /// `pre_exec` closure only ever writes its own pid to this already-open descriptor — it
236    /// never performs a path lookup, matching how `sandbox.rs` pre-opens its Landlock fds rather
237    /// than opening paths inside `pre_exec`.
238    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
239    procs_fd: Option<std::os::fd::OwnedFd>,
240    /// Who is inside the scope right now, which decides whether a counter delta can be pinned on
241    /// one call. Behind its own `Arc` so a [`ScopeOccupancy`] can outlive the borrow it was
242    /// taken from and move to a demoted command's thread.
243    occupancy: Arc<Occupancy>,
244    /// The process that kills the scope once the runtime is gone. `None` off Linux and for a
245    /// scope with no directory.
246    #[cfg(target_os = "linux")]
247    watcher: Option<ScopeWatcher>,
248}
249
250/// The scope's occupancy counters.
251///
252/// The scope's kill/denial counters are shared by every process in it, so a delta read across one
253/// call's window is evidence about that call only when nothing else ran in the scope during the
254/// window. These two counters are what answer that.
255#[derive(Debug, Default)]
256struct Occupancy {
257    /// Shell commands and native tools inside the scope now.
258    occupants: AtomicU64,
259    /// Entries since the scope was created. Never decremented: a later entry is visible as a
260    /// higher number even after it has left.
261    entries: AtomicU64,
262}
263
264impl Occupancy {
265    /// Mark one spawn as inside the scope until the returned guard drops.
266    fn enter(self: &Arc<Self>) -> ScopeOccupancy {
267        // Every access is `SeqCst`, and `entries` is read on both sides of the `occupants`
268        // increment. An entry that raced in between the two increments — counted in one, not yet
269        // in the other — moves `entries` past what was read first, so neither call can think it
270        // was alone while the other was already on its way in.
271        let entries_before = self.entries.load(Ordering::SeqCst);
272        let others_inside = self.occupants.fetch_add(1, Ordering::SeqCst) > 0;
273        let sequence = self.entries.fetch_add(1, Ordering::SeqCst);
274        ScopeOccupancy {
275            occupancy: Arc::clone(self),
276            alone_at_entry: !others_inside && sequence == entries_before,
277            sequence,
278        }
279    }
280}
281
282/// One spawn's stay inside a [`CgroupScope`]. Leaves the scope on drop.
283///
284/// Held for as long as the process it was taken for runs — a demoted command carries it to its
285/// own thread — so a sibling's window overlaps it exactly when the two processes did.
286#[derive(Debug)]
287pub(crate) struct ScopeOccupancy {
288    occupancy: Arc<Occupancy>,
289    alone_at_entry: bool,
290    sequence: u64,
291}
292
293impl ScopeOccupancy {
294    /// Whether this spawn had the scope to itself from entry until now: nobody was inside when it
295    /// entered, and nobody has entered since.
296    pub(crate) fn exclusive(&self) -> bool {
297        self.alone_at_entry && self.occupancy.entries.load(Ordering::SeqCst) == self.sequence + 1
298    }
299}
300
301impl Drop for ScopeOccupancy {
302    fn drop(&mut self) {
303        self.occupancy.occupants.fetch_sub(1, Ordering::SeqCst);
304    }
305}
306
307/// Snapshot of the kernel-maintained kill/denial counters on a scope.
308///
309/// Read before and after a subprocess runs, so attribution rests on the *delta* for that call
310/// rather than on a session-cumulative total that any earlier call could have moved.
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
312pub(crate) struct CgroupEventCounters {
313    /// `memory.events`' `oom_kill` — tasks the kernel killed for exceeding `memory.max`.
314    pub(crate) oom_kill: u64,
315    /// `pids.events`' `max` — forks refused for exceeding `pids.max`.
316    pub(crate) pids_max: u64,
317}
318
319impl CgroupEventCounters {
320    /// The named limit this delta unambiguously attributes to, or `None`.
321    ///
322    /// Both counters are maintained by the kernel and incremented only by the condition they
323    /// name, so a nonzero delta is evidence rather than inference — the property that makes
324    /// these two safe to report where a bare `SIGKILL` is not (see
325    /// [`crate::resources::limit_from_signal`]).
326    ///
327    /// The evidence is about the scope, not about any one process in it. A delta read across one
328    /// call's window is about that call only when the call was alone in the scope for the whole
329    /// window ([`ScopeOccupancy::exclusive`]); `shell::attribute_resource_limit` is where that
330    /// rule is applied.
331    pub(crate) fn attribution_since(&self, before: Self) -> Option<&'static str> {
332        if self.oom_kill > before.oom_kill {
333            return Some("cgroup_memory_bytes");
334        }
335        if self.pids_max > before.pids_max {
336            return Some("cgroup_pids_max");
337        }
338        None
339    }
340}
341
342/// Whether the declared `capabilities.resources.cgroup_io_bytes_per_sec` ceiling is actually on
343/// this session's cgroup scope.
344///
345/// Four states rather than a `bool` because "the write failed" and "there was never a scope to
346/// write to" are different findings with different remediations, and neither is the same as "this
347/// value was never established". [`Self::NotProbed`] is the `Default` so a report nobody filled in
348/// claims nothing.
349#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]
350#[serde(rename_all = "kebab-case")]
351pub enum IoMaxStatus {
352    /// The `io.max` write succeeded against the device backing the workdir. The ceiling is on the
353    /// scope.
354    Enforced,
355    /// A scope exists and the `io.max` write did not succeed. `memory.max`, `pids.max` and
356    /// `cpu.max` are still enforced on it; I/O bandwidth is not bounded. What `W-SEC-021` reports.
357    Unavailable,
358    /// No scope was asked for: either this capsule declares no way to reach a native subprocess,
359    /// or this is not Linux, where cgroups cannot exist. Not a shortfall — there is no process
360    /// tree for a ceiling to apply to.
361    NotRequired,
362    /// Nobody asked. The `Default`, so a [`IoMaxReport`] that was constructed rather than measured
363    /// asserts nothing about the host.
364    #[default]
365    NotProbed,
366}
367
368/// The declared I/O ceiling and what became of it, carried into `--explain-scope`, into
369/// `session_start.effective_grants` and into `W-SEC-021`.
370///
371/// `io.max` is non-fatal, so a ceiling that did not apply refuses nothing. This value is what
372/// carries that outcome alongside the claim, so the manifest's declared ceiling and what the
373/// kernel accepted cannot disagree in silence.
374#[derive(Debug, Clone, PartialEq, Eq, Default, serde::Serialize)]
375pub struct IoMaxReport {
376    /// The effective `capabilities.resources.cgroup_io_bytes_per_sec`, after
377    /// [`HostResourceLimits::resolve`] has applied its default. Reported whatever the status, so a
378    /// reader can see what was asked for as well as what happened to it.
379    pub declared_bytes_per_sec: u64,
380    /// What happened to it.
381    pub status: IoMaxStatus,
382    /// Why, for every status but [`IoMaxStatus::Enforced`]. Absent from the JSON when there is
383    /// nothing to say.
384    #[serde(skip_serializing_if = "Option::is_none")]
385    pub reason: Option<String>,
386}
387
388impl IoMaxReport {
389    /// The ceiling applied.
390    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
391    fn enforced(declared_bytes_per_sec: u64) -> Self {
392        Self {
393            declared_bytes_per_sec,
394            status: IoMaxStatus::Enforced,
395            reason: None,
396        }
397    }
398
399    /// A scope exists and the ceiling is not on it.
400    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
401    fn unavailable(declared_bytes_per_sec: u64, reason: impl Into<String>) -> Self {
402        Self {
403            declared_bytes_per_sec,
404            status: IoMaxStatus::Unavailable,
405            reason: Some(reason.into()),
406        }
407    }
408
409    /// No cgroup scope is required because this capsule can reach no native subprocess.
410    ///
411    /// Public, and takes no reason argument: `mur run --explain-scope` has to produce the
412    /// byte-for-byte report a launch produces — `trace.rs`'s `session_start_effective_grants_match_explain_scope_json`
413    /// asserts the two objects are equal — so the wording lives here rather than once per caller.
414    #[must_use]
415    pub fn no_scope_required(declared_bytes_per_sec: u64) -> Self {
416        Self::not_required(declared_bytes_per_sec, NO_SCOPE_REASON)
417    }
418
419    /// No scope was asked for. Always carries its reason: "not required" is the one status whose
420    /// two causes — a capsule that can spawn nothing, and a platform with no cgroups — a reader
421    /// cannot tell apart from the status alone.
422    fn not_required(declared_bytes_per_sec: u64, reason: impl Into<String>) -> Self {
423        Self {
424            declared_bytes_per_sec,
425            status: IoMaxStatus::NotRequired,
426            reason: Some(reason.into()),
427        }
428    }
429}
430
431/// Reason text for the two [`IoMaxStatus::NotRequired`] causes, in one place so `prepare_scope`
432/// and [`probe_io_max`] cannot word the same finding differently.
433const NO_SCOPE_REASON: &str = "this capsule declares no way to run a native subprocess, so it is \
434     given no cgroup scope and there is no process tree for an I/O ceiling to apply to";
435#[cfg_attr(target_os = "linux", allow(dead_code))]
436const NOT_LINUX_REASON: &str =
437    "cgroups are a Linux mechanism and this host has none, so no io.max ceiling can exist here";
438
439/// The message `W-SEC-021` carries, minus the reason the host gave.
440const IO_MAX_UNAVAILABLE_WARNING: &str = "the declared \
441capabilities.resources.cgroup_io_bytes_per_sec ceiling did not apply to this session's cgroup \
442scope, so this capsule's native subprocess tree has no I/O bandwidth bound; memory.max, pids.max \
443and cpu.max are still enforced on the scope";
444
445/// Pure decision for the unenforced-`io.max` warning, split out of
446/// [`warn_for_unenforced_io_max`] the same way `sandbox::aggregate_bounding_warning` is split out
447/// of its emitter, so a test can assert it without capturing stderr.
448///
449/// Fires on [`IoMaxStatus::Unavailable`] alone. `NotRequired` is not a shortfall and `NotProbed`
450/// is not a finding, so neither warns.
451pub(crate) fn io_max_warning(report: &IoMaxReport) -> Option<(&'static str, String)> {
452    if report.status != IoMaxStatus::Unavailable {
453        return None;
454    }
455    let declared = report.declared_bytes_per_sec;
456    let reason = report.reason.as_deref().unwrap_or("no reason reported");
457    Some((
458        murmur_artifact::W_SEC_021,
459        format!("{IO_MAX_UNAVAILABLE_WARNING} (declared {declared} bytes/s): {reason}"),
460    ))
461}
462
463/// Fires at every launch, not just once.
464pub(crate) fn warn_for_unenforced_io_max(
465    workdir: &crate::workdir_fs::WorkdirRoot,
466    report: &IoMaxReport,
467) {
468    if let Some((code, message)) = io_max_warning(report) {
469        let link = murmur_artifact::security_warning_link(code);
470        crate::runtime_err!("[capsule-runtime] warning[{code}]: {message} ({link})");
471        crate::agent::append_bootstrap_log(
472            workdir,
473            &format!("[capability-policy] warning[{code}]: {message} ({link})"),
474        );
475    }
476}
477
478/// What [`prepare_scope`] establishes: the scope, and what became of its I/O ceiling.
479///
480/// A struct rather than a tuple so the two values cannot be swapped at a call site, and so a
481/// caller cannot take the scope without also being handed the ceiling's outcome.
482#[derive(Debug)]
483pub(crate) struct PreparedScope {
484    /// The scope, or `None` where none was required or none can exist.
485    pub(crate) scope: Option<Arc<CgroupScope>>,
486    /// Whether the declared `io.max` ceiling applied, established by performing the write rather
487    /// than by inferring it.
488    pub(crate) io_max: IoMaxReport,
489}
490
491/// Decide-and-create entry point, called once per launch before any WASM is instantiated.
492///
493/// * `required == false` (the capsule declares no way to spawn a native subprocess) → `Ok(None)`
494///   on every platform. There is no process tree to bound, so demanding host configuration here
495///   would be a regression for WASM-only capsules with nothing to show for it.
496/// * non-Linux → `Ok(None)` always. Never an error: cgroups are structurally impossible there,
497///   not a host misconfiguration.
498/// * Linux and required → probe delegation and create the scope; `Err(reason)` if the host
499///   cannot delegate one, which the caller turns into
500///   [`crate::errors::RuntimeError::CgroupDelegationUnavailable`].
501///
502/// The returned [`PreparedScope`] always carries an [`IoMaxReport`], on every one of those paths:
503/// the declared I/O ceiling is reported as applying, as not applying, or as not required, and
504/// never left silent.
505pub(crate) fn prepare_scope(
506    required: bool,
507    limits: &HostResourceLimits,
508    session_id: &str,
509    workdir: &Path,
510) -> Result<PreparedScope, String> {
511    if !required {
512        return Ok(PreparedScope {
513            scope: None,
514            io_max: IoMaxReport::no_scope_required(limits.cgroup_io_bytes_per_sec),
515        });
516    }
517    #[cfg(target_os = "linux")]
518    {
519        let (scope, io_max) = CgroupScope::create(limits, session_id, workdir)?;
520        Ok(PreparedScope {
521            scope: Some(Arc::new(scope)),
522            io_max,
523        })
524    }
525    #[cfg(not(target_os = "linux"))]
526    {
527        let _ = (session_id, workdir);
528        Ok(PreparedScope {
529            scope: None,
530            io_max: IoMaxReport::not_required(limits.cgroup_io_bytes_per_sec, NOT_LINUX_REASON),
531        })
532    }
533}
534
535/// Answers "would the declared `io.max` ceiling apply on this host?" by performing the write,
536/// against a throwaway cgroup created and removed inside this call.
537///
538/// The diagnostic half of [`prepare_scope`], for `mur run --explain-scope`, which runs before any
539/// workdir exists and before any session is staged. Inferring the answer from "is the `io`
540/// controller delegated" is wrong: the write can fail for a device the block layer will not
541/// accept (tmpfs, overlayfs, a device-mapper stack) on a host whose `io` controller is delegated
542/// perfectly well. Only performing the write answers it.
543///
544/// `workdir` need not exist. The device is resolved from its nearest existing ancestor, so the
545/// probe names the device a launch would use without creating anything.
546///
547/// Off Linux it reports [`IoMaxStatus::NotRequired`]. Whatever the outcome, the throwaway
548/// directory does not survive the call.
549#[must_use]
550pub fn probe_io_max(limits: &HostResourceLimits, workdir: &Path) -> IoMaxReport {
551    let declared = limits.cgroup_io_bytes_per_sec;
552    #[cfg(target_os = "linux")]
553    {
554        let base = match delegated_base() {
555            Ok(base) => base,
556            Err(reason) => {
557                return IoMaxReport::unavailable(
558                    declared,
559                    format!("no delegated cgroup base to write io.max into: {reason}"),
560                )
561            }
562        };
563        let path = base.join(scope_dir_name("explain-scope"));
564        if let Err(error) = std::fs::create_dir(&path) {
565            return IoMaxReport::unavailable(
566                declared,
567                format!(
568                    "could not create a throwaway cgroup at {}: {error}",
569                    path.display()
570                ),
571            );
572        }
573        let report = write_io_max(&path, declared, workdir);
574        // Best-effort by necessity and not by preference: the scope holds no tasks, so the only
575        // way this fails is a host that took the directory away underneath us.
576        let _ = std::fs::remove_dir(&path);
577        report
578    }
579    #[cfg(not(target_os = "linux"))]
580    {
581        let _ = workdir;
582        IoMaxReport::not_required(declared, NOT_LINUX_REASON)
583    }
584}
585
586/// Does this policy give the capsule any way to run a native subprocess at all?
587///
588/// The exact condition the Linux fail-closed launch refusal keys on: `capabilities.shell.allow`,
589/// `capabilities.spawn.allow`, or a declared artifact whose implementation is native (passed in
590/// by the caller, which is the only place the installed-artifact list is in hand).
591pub fn requires_process_bounding(
592    policy: &crate::types::CapabilityPolicy,
593    has_native_artifact: bool,
594) -> bool {
595    !policy.shell_allow.is_empty() || !policy.spawn_allow.is_empty() || has_native_artifact
596}
597
598impl CgroupScope {
599    /// Absolute path of this scope's directory.
600    pub(crate) fn path(&self) -> &Path {
601        &self.path
602    }
603
604    /// Move the **calling** process into this scope.
605    ///
606    /// Called from inside the forked child's `pre_exec` closure: it writes the child's own pid
607    /// to the parent-opened `cgroup.procs` descriptor with a single `write(2)`, formatting the
608    /// pid into a stack buffer so the whole path stays allocation-free and async-signal-safe.
609    /// Every process the child subsequently forks inherits the scope, which is what makes the
610    /// bound apply to the *tree* rather than to one process.
611    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
612    #[allow(unsafe_code)]
613    pub(crate) fn join_current_process(&self) -> std::io::Result<()> {
614        use std::os::fd::AsRawFd;
615
616        let Some(fd) = self.procs_fd.as_ref() else {
617            return Ok(());
618        };
619
620        // SAFETY: `getpid` takes no arguments and cannot fail.
621        let pid = unsafe { libc::getpid() };
622        let mut buf = [0u8; 24];
623        let written = format_pid(pid, &mut buf);
624
625        let mut offset = 0;
626        while offset < written {
627            // SAFETY: `fd` is an open write-only descriptor owned by `self`, and the slice
628            // passed is a live sub-range of the stack buffer above.
629            let rc = unsafe {
630                libc::write(
631                    fd.as_raw_fd(),
632                    buf[offset..written].as_ptr().cast::<libc::c_void>(),
633                    written - offset,
634                )
635            };
636            if rc < 0 {
637                let error = std::io::Error::last_os_error();
638                if error.kind() == std::io::ErrorKind::Interrupted {
639                    continue;
640                }
641                return Err(error);
642            }
643            offset += rc as usize;
644        }
645        Ok(())
646    }
647
648    /// Mark one spawn as inside this scope until the returned guard drops. Taken before the
649    /// counter snapshot a call's attribution is read against.
650    pub(crate) fn enter(&self) -> ScopeOccupancy {
651        self.occupancy.enter()
652    }
653
654    /// Whether [`Self::join_current_process`] moves the caller into this scope, which it does
655    /// exactly when the `cgroup.procs` descriptor is open; without it a join returns `Ok(())` and
656    /// moves nothing. Every scope [`prepare_scope`] hands out has one. The `RLIMIT_NPROC` decision
657    /// keys on this, not on the scope's presence, so a join that places nothing never leaves a
658    /// spawn without its process bound.
659    pub(crate) fn places_subprocesses(&self) -> bool {
660        self.procs_fd.is_some()
661    }
662
663    /// Current `memory.events`/`pids.events` counters.
664    ///
665    /// Must be read while the scope directory still exists — the files vanish with it, which is
666    /// why cleanup happens in `Drop` at session end and never right after a child is reaped.
667    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
668    pub(crate) fn event_counters(&self) -> CgroupEventCounters {
669        CgroupEventCounters {
670            oom_kill: read_event_counter(&self.path.join("memory.events"), "oom_kill"),
671            pids_max: read_event_counter(&self.path.join("pids.events"), "max"),
672        }
673    }
674}
675
676impl CgroupScope {
677    /// Kill every process in this scope, whatever session or process group it put itself in.
678    ///
679    /// Writes `1` to `cgroup.kill` (Linux 5.14+), which `SIGKILL`s the whole scope in one kernel
680    /// operation that races no fork. Where that file does not exist, falls back to freezing the
681    /// scope, `SIGKILL`ing every pid `cgroup.procs` lists and thawing it, repeated until the scope
682    /// is empty or [`KILL_FALLBACK_DEADLINE`] has passed. Returns as soon as the signals are sent;
683    /// [`Self::wait_until_empty`] waits for the processes to be gone.
684    ///
685    /// The scope is a child of the delegated base, never the runtime's own cgroup, so the runtime
686    /// is never in what this kills.
687    pub(crate) fn kill_all(&self) -> std::io::Result<()> {
688        if self.path.as_os_str().is_empty() {
689            return Ok(());
690        }
691        #[cfg(target_os = "linux")]
692        {
693            #[cfg(test)]
694            let forced = FORCE_KILL_FALLBACK.with(std::cell::Cell::get);
695            #[cfg(not(test))]
696            let forced = false;
697            if !forced {
698                match write_existing(&self.path.join("cgroup.kill"), "1") {
699                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
700                    written => return written,
701                }
702            }
703            self.kill_by_freezing()
704        }
705        #[cfg(not(target_os = "linux"))]
706        Ok(())
707    }
708
709    /// Whether `cgroup.procs` lists no process, polled until it does or `timeout` passes.
710    ///
711    /// An exited process leaves `cgroup.procs` when it exits, not when its parent reaps it, so
712    /// a killed command the runtime has not yet waited for does not hold this up.
713    pub(crate) fn wait_until_empty(&self, timeout: std::time::Duration) -> bool {
714        let deadline = std::time::Instant::now() + timeout;
715        loop {
716            if self.member_pids().is_empty() {
717                return true;
718            }
719            if std::time::Instant::now() >= deadline {
720                return false;
721            }
722            std::thread::sleep(KILL_POLL_INTERVAL);
723        }
724    }
725
726    /// Every pid `cgroup.procs` lists now. Empty when the file cannot be read, which is a scope
727    /// whose directory is already gone.
728    pub(crate) fn member_pids(&self) -> Vec<i32> {
729        if self.path.as_os_str().is_empty() {
730            return Vec::new();
731        }
732        std::fs::read_to_string(self.path.join("cgroup.procs"))
733            .map(|procs| {
734                procs
735                    .lines()
736                    .filter_map(|line| line.trim().parse().ok())
737                    .collect()
738            })
739            .unwrap_or_default()
740    }
741
742    /// `cgroup.kill` for a kernel that has none: freeze, `SIGKILL` each listed pid, thaw.
743    ///
744    /// Freezing first stops a listed process from forking a child the loop has not seen, and
745    /// keeps a pid from being reused between reading it and signalling it. A frozen task still
746    /// takes `SIGKILL`; it dies once thawed.
747    #[cfg(target_os = "linux")]
748    #[allow(unsafe_code)]
749    fn kill_by_freezing(&self) -> std::io::Result<()> {
750        let freeze = self.path.join("cgroup.freeze");
751        let deadline = std::time::Instant::now() + KILL_FALLBACK_DEADLINE;
752        loop {
753            let pids = self.member_pids();
754            if pids.is_empty() {
755                return Ok(());
756            }
757            // Best-effort: a kernel without the freezer still gets every listed pid killed.
758            let _ = write_existing(&freeze, "1");
759            for pid in pids {
760                // SAFETY: `kill` takes two integers and dereferences nothing.
761                unsafe { libc::kill(pid, libc::SIGKILL) };
762            }
763            let _ = write_existing(&freeze, "0");
764            if std::time::Instant::now() >= deadline {
765                return Err(std::io::Error::other(format!(
766                    "processes were still in {} after {} ms of SIGKILL",
767                    self.path.display(),
768                    KILL_FALLBACK_DEADLINE.as_millis()
769                )));
770            }
771            std::thread::sleep(KILL_POLL_INTERVAL);
772        }
773    }
774}
775
776/// How long [`CgroupScope::kill_all`]'s fallback keeps signalling a scope that is not yet empty.
777const KILL_FALLBACK_DEADLINE: std::time::Duration = std::time::Duration::from_secs(2);
778
779/// How often a kill or an emptiness wait re-reads `cgroup.procs`.
780const KILL_POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
781
782/// Writes `value` to a control file that must already exist, so an absent file reads as
783/// `NotFound` rather than as a refused create.
784#[cfg(target_os = "linux")]
785fn write_existing(path: &Path, value: &str) -> std::io::Result<()> {
786    use std::io::Write as _;
787    let file = std::fs::OpenOptions::new().write(true).open(path)?;
788    (&file).write_all(value.as_bytes())
789}
790
791// Forces `CgroupScope::kill_all` onto its freeze-and-signal fallback, as on a kernel with no
792// `cgroup.kill`. Read on the calling thread, so it reaches a `kill_all` the test calls itself.
793#[cfg(all(test, target_os = "linux"))]
794thread_local! {
795    pub(crate) static FORCE_KILL_FALLBACK: std::cell::Cell<bool> =
796        const { std::cell::Cell::new(false) };
797}
798
799impl Drop for CgroupScope {
800    /// Kills whatever is still in the scope, then removes the scope directory, best-effort.
801    ///
802    /// The backstop for a session that never reached `ShellEnforcement::end_session`, which has
803    /// already killed the scope on every ordinary path. A cgroup directory can only be removed
804    /// once empty, so the removal waits, bounded, for the kill to land; a scope still occupied
805    /// after that is logged and moved past rather than retried, because blocking teardown on a
806    /// process that will not die would turn a leaked directory into a hung exit.
807    fn drop(&mut self) {
808        if self.path.as_os_str().is_empty() {
809            return;
810        }
811        if !self.member_pids().is_empty() {
812            let _ = self.kill_all();
813            self.wait_until_empty(KILL_FALLBACK_DEADLINE);
814        }
815        // Drop the descriptor before the rmdir so nothing holds the directory open, and reap the
816        // watcher, which holds its own descriptors on the scope's files until it exits.
817        self.procs_fd = None;
818        #[cfg(target_os = "linux")]
819        {
820            self.watcher = None;
821        }
822        if let Err(error) = std::fs::remove_dir(&self.path) {
823            crate::runtime_err!(
824                "[capsule-runtime] note: could not remove cgroup scope {} ({error}); \
825                 it will be reclaimed once its last task exits",
826                self.path.display()
827            );
828        }
829    }
830}
831
832/// The process that kills one scope once nothing holds its lifeline's write end open.
833///
834/// [`Self::spawn`] forks it from the runtime; dropping this closes the write end and reaps it.
835/// See the module documentation, "A scope outlives no runtime".
836#[cfg(target_os = "linux")]
837#[derive(Debug)]
838struct ScopeWatcher {
839    /// The lifeline's write end. Opened `O_CLOEXEC`, so no program the runtime execs holds a copy,
840    /// and the watcher closes the copy it inherited: its read sees end-of-file exactly when this
841    /// is closed or the runtime is gone.
842    lifeline: std::sync::Mutex<Option<std::os::fd::OwnedFd>>,
843    pid: libc::pid_t,
844}
845
846/// The descriptors a watcher kills its scope through, opened by the runtime before the fork:
847/// `cgroup.kill` where the kernel has it, else `cgroup.freeze` (when present) and `cgroup.procs`
848/// for the freeze-and-signal loop [`CgroupScope::kill_all`] falls back to.
849#[cfg(target_os = "linux")]
850#[derive(Clone, Copy)]
851struct WatcherKill {
852    kill: libc::c_int,
853    freeze: libc::c_int,
854    procs: libc::c_int,
855}
856
857#[cfg(target_os = "linux")]
858impl ScopeWatcher {
859    /// Fork the watcher of the scope at `scope`. Everything it needs is opened here, in the
860    /// runtime, so the forked child — one thread of a multithreaded process — runs only
861    /// async-signal-safe syscalls on descriptors and stack buffers that already exist.
862    #[allow(unsafe_code)]
863    fn spawn(scope: &Path) -> std::io::Result<Self> {
864        use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
865
866        #[cfg(test)]
867        let forced = FORCE_KILL_FALLBACK.with(std::cell::Cell::get);
868        #[cfg(not(test))]
869        let forced = false;
870        let kill = if forced {
871            None
872        } else {
873            open_if_present(&scope.join("cgroup.kill"), libc::O_WRONLY)?
874        };
875        let (freeze, procs) = match kill {
876            Some(_) => (None, None),
877            None => (
878                open_if_present(&scope.join("cgroup.freeze"), libc::O_WRONLY)?,
879                Some(open_with(&scope.join("cgroup.procs"), libc::O_RDONLY)?),
880            ),
881        };
882        let devnull = open_with(Path::new("/dev/null"), libc::O_RDWR)?;
883
884        let mut ends = [0 as libc::c_int; 2];
885        // SAFETY: `ends` is a two-element array, the size `pipe2` writes into.
886        if unsafe { libc::pipe2(ends.as_mut_ptr(), libc::O_CLOEXEC) } != 0 {
887            return Err(std::io::Error::last_os_error());
888        }
889        // SAFETY: both descriptors were just returned by the successful `pipe2` above and nothing
890        // else owns them.
891        let (read_end, write_end) =
892            unsafe { (OwnedFd::from_raw_fd(ends[0]), OwnedFd::from_raw_fd(ends[1])) };
893
894        let raw = |fd: &Option<OwnedFd>| fd.as_ref().map_or(-1, AsRawFd::as_raw_fd);
895        let plan = WatcherKill {
896            kill: raw(&kill),
897            freeze: raw(&freeze),
898            procs: raw(&procs),
899        };
900        // Sorted here, before the fork: the child keeps exactly these. The entries are distinct:
901        // Rust's startup opens 0-2 when they are closed, so every descriptor opened above is 3 or
902        // higher, and the child's `dup2` onto 0-2 replaces none of them.
903        let mut keep = [-1 as libc::c_int; 7];
904        let mut kept = 0;
905        for fd in [
906            0,
907            1,
908            2,
909            read_end.as_raw_fd(),
910            plan.kill,
911            plan.freeze,
912            plan.procs,
913        ] {
914            if fd >= 0 {
915                keep[kept] = fd;
916                kept += 1;
917            }
918        }
919        keep[..kept].sort_unstable();
920        let devnull_fd = devnull.as_raw_fd();
921        let read_fd = read_end.as_raw_fd();
922        let deadline_ns = KILL_FALLBACK_DEADLINE.as_nanos() as i64;
923
924        // SAFETY: `fork()` from a possibly-multithreaded process is sound as long as the child
925        // touches nothing but async-signal-safe primitives. The child runs only `dup2`,
926        // `close_range`/`close`, `setpgid`, `sigaction`, `read`, `lseek`, `write`, `kill`,
927        // `clock_gettime` and `nanosleep` on descriptors and stack values prepared above, then
928        // `_exit`: no allocation, no locks, no stdio, no destructor.
929        let pid = unsafe { libc::fork() };
930        if pid < 0 {
931            return Err(std::io::Error::last_os_error());
932        }
933        if pid == 0 {
934            // SAFETY: forked-child context; `watch` ends in `_exit` and never returns.
935            unsafe { watch(devnull_fd, &keep[..kept], read_fd, plan, deadline_ns) }
936        }
937        Ok(Self {
938            lifeline: std::sync::Mutex::new(Some(write_end)),
939            pid,
940        })
941    }
942
943    /// Close the lifeline's write end, as the runtime's death would, without reaping.
944    #[cfg(test)]
945    fn cut_lifeline(&self) {
946        self.lifeline
947            .lock()
948            .unwrap_or_else(std::sync::PoisonError::into_inner)
949            .take();
950    }
951}
952
953#[cfg(target_os = "linux")]
954impl Drop for ScopeWatcher {
955    /// Closes the lifeline, so the watcher kills the scope (by now empty, on every path through
956    /// [`CgroupScope`]'s `Drop`) and exits, then reaps it.
957    #[allow(unsafe_code)]
958    fn drop(&mut self) {
959        self.lifeline
960            .get_mut()
961            .unwrap_or_else(std::sync::PoisonError::into_inner)
962            .take();
963        let mut status = 0;
964        loop {
965            // SAFETY: `self.pid` is the watcher this value forked; `status` is a live local.
966            let waited = unsafe { libc::waitpid(self.pid, &mut status, 0) };
967            if waited >= 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::EINTR) {
968                return;
969            }
970        }
971    }
972}
973
974/// `path` opened with `flags | O_CLOEXEC`.
975#[cfg(target_os = "linux")]
976fn open_with(path: &Path, flags: libc::c_int) -> std::io::Result<std::os::fd::OwnedFd> {
977    use std::os::unix::fs::OpenOptionsExt;
978
979    std::fs::OpenOptions::new()
980        .read(flags & libc::O_ACCMODE != libc::O_WRONLY)
981        .write(flags & libc::O_ACCMODE != libc::O_RDONLY)
982        .custom_flags(libc::O_CLOEXEC)
983        .open(path)
984        .map(std::os::fd::OwnedFd::from)
985}
986
987/// [`open_with`], or `None` for a control file this kernel does not expose.
988#[cfg(target_os = "linux")]
989fn open_if_present(
990    path: &Path,
991    flags: libc::c_int,
992) -> std::io::Result<Option<std::os::fd::OwnedFd>> {
993    match open_with(path, flags) {
994        Ok(fd) => Ok(Some(fd)),
995        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
996        Err(error) => Err(error),
997    }
998}
999
1000/// The watcher's whole life, in the forked child: hold no descriptor but `keep`, leave the
1001/// runtime's process group, ignore the signals a terminal or launcher sends a group, block until
1002/// the lifeline reads end-of-file, kill the scope, exit.
1003///
1004/// # Safety
1005///
1006/// Called only in a child just forked by [`ScopeWatcher::spawn`], with `keep` sorted and holding
1007/// 0, 1, 2, `read_fd` and every descriptor `plan` names. Never returns.
1008#[cfg(target_os = "linux")]
1009#[allow(unsafe_code)]
1010unsafe fn watch(
1011    devnull: libc::c_int,
1012    keep: &[libc::c_int],
1013    read_fd: libc::c_int,
1014    plan: WatcherKill,
1015    deadline_ns: i64,
1016) -> ! {
1017    // SAFETY (whole body): every call is an async-signal-safe syscall on descriptors the parent
1018    // opened before the fork or on stack values; nothing allocates or takes a lock.
1019    unsafe {
1020        // Standard streams onto /dev/null, so no pipe of the runtime's stays open through them.
1021        for target in 0..3 {
1022            libc::dup2(devnull, target);
1023        }
1024        let mut low: libc::c_uint = 0;
1025        for &fd in keep {
1026            let fd = fd as libc::c_uint;
1027            if fd > low {
1028                close_range(low, fd - 1);
1029            }
1030            low = fd + 1;
1031        }
1032        close_range(low, libc::c_uint::MAX);
1033
1034        libc::setpgid(0, 0);
1035        let mut ignore: libc::sigaction = std::mem::zeroed();
1036        ignore.sa_sigaction = libc::SIG_IGN;
1037        for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP, libc::SIGPIPE] {
1038            libc::sigaction(signal, &ignore, std::ptr::null_mut());
1039        }
1040
1041        let mut byte = [0u8; 1];
1042        loop {
1043            let read = libc::read(read_fd, byte.as_mut_ptr().cast(), 1);
1044            if read == 0 {
1045                break;
1046            }
1047            if read < 0 && *libc::__errno_location() != libc::EINTR {
1048                break;
1049            }
1050        }
1051
1052        kill_scope(plan, deadline_ns);
1053        libc::_exit(0)
1054    }
1055}
1056
1057/// Close every descriptor in `low..=high`: `close_range(2)`, else one `close` per descriptor up to
1058/// the open-files limit, for a kernel older than 5.9.
1059///
1060/// # Safety
1061///
1062/// Async-signal-safe; called only from [`watch`].
1063#[cfg(target_os = "linux")]
1064#[allow(unsafe_code)]
1065unsafe fn close_range(low: libc::c_uint, high: libc::c_uint) {
1066    // SAFETY: integer arguments only.
1067    unsafe {
1068        if libc::syscall(libc::SYS_close_range, low, high, 0 as libc::c_uint) == 0 {
1069            return;
1070        }
1071        let mut limit: libc::rlimit = std::mem::zeroed();
1072        let ceiling = if libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) == 0 {
1073            limit.rlim_cur.min(libc::c_uint::MAX as libc::rlim_t) as libc::c_uint
1074        } else {
1075            1 << 20
1076        };
1077        let mut fd = low;
1078        while fd <= high && fd < ceiling {
1079            libc::close(fd as libc::c_int);
1080            fd += 1;
1081        }
1082    }
1083}
1084
1085/// [`CgroupScope::kill_all`] for the watcher: one write to `cgroup.kill`, else freeze, `SIGKILL`
1086/// every pid `cgroup.procs` lists, thaw, until none is listed or `deadline_ns` has passed.
1087///
1088/// # Safety
1089///
1090/// Async-signal-safe; called only from [`watch`].
1091#[cfg(target_os = "linux")]
1092#[allow(unsafe_code)]
1093unsafe fn kill_scope(plan: WatcherKill, deadline_ns: i64) {
1094    // SAFETY: syscalls on the descriptors `plan` names and on stack values.
1095    unsafe {
1096        if plan.kill >= 0 {
1097            write_control(plan.kill, b"1");
1098            return;
1099        }
1100        let start = monotonic_ns();
1101        loop {
1102            if plan.freeze >= 0 {
1103                write_control(plan.freeze, b"1");
1104            }
1105            let signalled = signal_listed(plan.procs);
1106            if plan.freeze >= 0 {
1107                write_control(plan.freeze, b"0");
1108            }
1109            if signalled == 0 || monotonic_ns() - start >= deadline_ns {
1110                return;
1111            }
1112            let pause = libc::timespec {
1113                tv_sec: 0,
1114                tv_nsec: KILL_POLL_INTERVAL.as_nanos() as libc::c_long,
1115            };
1116            libc::nanosleep(&pause, std::ptr::null_mut());
1117        }
1118    }
1119}
1120
1121/// Write `value` at the start of the control file `fd`.
1122///
1123/// # Safety
1124///
1125/// Async-signal-safe.
1126#[cfg(target_os = "linux")]
1127#[allow(unsafe_code)]
1128unsafe fn write_control(fd: libc::c_int, value: &[u8]) {
1129    // SAFETY: `value` is a live slice for the duration of the call.
1130    unsafe {
1131        libc::lseek(fd, 0, libc::SEEK_SET);
1132        libc::write(fd, value.as_ptr().cast(), value.len());
1133    }
1134}
1135
1136/// `SIGKILL` every pid the `cgroup.procs` descriptor `procs` lists now, read from its start into a
1137/// stack buffer and parsed as it arrives. Returns how many were signalled.
1138///
1139/// # Safety
1140///
1141/// Async-signal-safe.
1142#[cfg(target_os = "linux")]
1143#[allow(unsafe_code)]
1144unsafe fn signal_listed(procs: libc::c_int) -> usize {
1145    // SAFETY: reads into a stack buffer of the length passed; `kill` takes integers.
1146    unsafe {
1147        if procs < 0 || libc::lseek(procs, 0, libc::SEEK_SET) < 0 {
1148            return 0;
1149        }
1150        let mut buf = [0u8; 512];
1151        let mut pid: libc::pid_t = 0;
1152        let mut digits = false;
1153        let mut signalled = 0;
1154        loop {
1155            let read = libc::read(procs, buf.as_mut_ptr().cast(), buf.len());
1156            if read < 0 && *libc::__errno_location() == libc::EINTR {
1157                continue;
1158            }
1159            if read <= 0 {
1160                break;
1161            }
1162            for &byte in &buf[..read as usize] {
1163                if byte.is_ascii_digit() {
1164                    pid = pid
1165                        .saturating_mul(10)
1166                        .saturating_add(libc::pid_t::from(byte - b'0'));
1167                    digits = true;
1168                } else {
1169                    if digits && pid > 0 {
1170                        libc::kill(pid, libc::SIGKILL);
1171                        signalled += 1;
1172                    }
1173                    pid = 0;
1174                    digits = false;
1175                }
1176            }
1177        }
1178        if digits && pid > 0 {
1179            libc::kill(pid, libc::SIGKILL);
1180            signalled += 1;
1181        }
1182        signalled
1183    }
1184}
1185
1186/// `CLOCK_MONOTONIC` in nanoseconds.
1187///
1188/// # Safety
1189///
1190/// Async-signal-safe.
1191#[cfg(target_os = "linux")]
1192#[allow(unsafe_code)]
1193unsafe fn monotonic_ns() -> i64 {
1194    // SAFETY: `now` is a live local `clock_gettime` writes into.
1195    unsafe {
1196        let mut now: libc::timespec = std::mem::zeroed();
1197        libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut now);
1198        now.tv_sec as i64 * 1_000_000_000 + now.tv_nsec as i64
1199    }
1200}
1201
1202/// Format `pid` into `buf` as decimal ASCII followed by a newline, returning the byte count.
1203///
1204/// Hand-rolled because [`CgroupScope::join_current_process`] runs between `fork` and `execve`,
1205/// where `format!` (and the allocator lock behind it) is not async-signal-safe.
1206#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1207fn format_pid(pid: i32, buf: &mut [u8; 24]) -> usize {
1208    let mut digits = [0u8; 20];
1209    let mut count = 0;
1210    let mut value = pid.unsigned_abs() as u64;
1211    if value == 0 {
1212        digits[0] = b'0';
1213        count = 1;
1214    }
1215    while value > 0 {
1216        digits[count] = b'0' + (value % 10) as u8;
1217        value /= 10;
1218        count += 1;
1219    }
1220
1221    let mut written = 0;
1222    for index in (0..count).rev() {
1223        buf[written] = digits[index];
1224        written += 1;
1225    }
1226    buf[written] = b'\n';
1227    written + 1
1228}
1229
1230/// Read one `<key> <value>` counter out of a cgroup `*.events` file, or `0` if the file or key
1231/// is absent. Absence is not an error: `memory.events` only exists once the memory controller is
1232/// enabled, and treating a missing counter as zero means attribution simply declines to name a
1233/// limit rather than inventing one.
1234#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1235fn read_event_counter(path: &Path, key: &str) -> u64 {
1236    let Ok(contents) = std::fs::read_to_string(path) else {
1237        return 0;
1238    };
1239    parse_event_counter(&contents, key)
1240}
1241
1242/// Pure parse half of [`read_event_counter`] — no syscalls, so it is unit-testable on macOS.
1243#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1244fn parse_event_counter(contents: &str, key: &str) -> u64 {
1245    for line in contents.lines() {
1246        let mut parts = line.split_whitespace();
1247        if parts.next() == Some(key) {
1248            return parts
1249                .next()
1250                .and_then(|value| value.parse().ok())
1251                .unwrap_or(0);
1252        }
1253    }
1254    0
1255}
1256
1257/// Turn a session id into a directory name safe to create under the delegated base: everything
1258/// outside `[A-Za-z0-9._-]` becomes `_`.
1259///
1260/// The name is also made unique per scope, with the pid and a per-process serial. The id alone
1261/// cannot carry that: `plan::execute` passes the plan's *authored* id, so two plans running
1262/// concurrently in one process would otherwise land on the same directory — and because
1263/// [`CgroupScope`]'s `Drop` removes the scope by path, the first to finish would delete a cgroup
1264/// the other is still bounded by, leaving that subprocess tree unbounded. Sanitizing stays a
1265/// belt-and-braces guard against a hostile id rather than a live escape vector.
1266///
1267/// Operators still find scopes by the documented `murmur-*` glob.
1268#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1269fn scope_dir_name(session_id: &str) -> String {
1270    static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1271    let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1272
1273    let sanitized: String = session_id
1274        .chars()
1275        .map(|c| {
1276            if c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-' {
1277                c
1278            } else {
1279                '_'
1280            }
1281        })
1282        .collect();
1283    let pid = std::process::id();
1284    if sanitized.is_empty() {
1285        format!("murmur-{pid}-{serial}")
1286    } else {
1287        format!("murmur-{sanitized}-{pid}-{serial}")
1288    }
1289}
1290
1291/// Extract the unified-hierarchy path from `/proc/self/cgroup` contents.
1292///
1293/// A cgroup v2 host writes exactly one line whose hierarchy id is `0` and whose controller list
1294/// is empty: `0::/user.slice/...`. Returning `None` for anything else is what makes a v1-only
1295/// (or hybrid, v2-less) host a clean "cannot delegate" rather than a wrong path.
1296#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1297fn parse_unified_cgroup_path(contents: &str) -> Option<String> {
1298    for line in contents.lines() {
1299        let mut parts = line.splitn(3, ':');
1300        let (Some("0"), Some(""), Some(path)) = (parts.next(), parts.next(), parts.next()) else {
1301            continue;
1302        };
1303        if path.starts_with('/') {
1304            return Some(path.to_string());
1305        }
1306    }
1307    None
1308}
1309
1310/// Find the `cgroup2` mount point in `/proc/mounts` contents, falling back to the conventional
1311/// `/sys/fs/cgroup`.
1312#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1313fn parse_cgroup2_mount(contents: &str) -> String {
1314    for line in contents.lines() {
1315        let mut parts = line.split_whitespace();
1316        let (Some(_source), Some(target), Some(fstype)) =
1317            (parts.next(), parts.next(), parts.next())
1318        else {
1319            continue;
1320        };
1321        if fstype == "cgroup2" {
1322            return target.to_string();
1323        }
1324    }
1325    DEFAULT_CGROUP2_MOUNT.to_string()
1326}
1327
1328/// Which of `wanted` are missing from a `cgroup.subtree_control` file's contents.
1329#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1330fn missing_controllers(subtree_control: &str, wanted: &[&str]) -> Vec<String> {
1331    let enabled: Vec<&str> = subtree_control.split_whitespace().collect();
1332    wanted
1333        .iter()
1334        .filter(|controller| !enabled.contains(*controller))
1335        .map(|controller| (*controller).to_string())
1336        .collect()
1337}
1338
1339/// Encode a `st_dev` value as the `MAJ:MIN` string `io.max` expects, using glibc's device-number
1340/// layout (12+20 bit split, not the legacy 8+8).
1341#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1342fn device_major_minor(dev: u64) -> (u64, u64) {
1343    let major = ((dev >> 8) & 0xfff) | ((dev >> 32) & !0xfff);
1344    let minor = (dev & 0xff) | ((dev >> 12) & !0xff);
1345    (major, minor)
1346}
1347
1348#[cfg(target_os = "linux")]
1349impl CgroupScope {
1350    /// Probe delegation, enable the controllers, create the scope directory, and write its
1351    /// limits from [`scope_limits`]. Any failure to establish `memory.max`, `memory.swap.max`,
1352    /// `pids.max` or `cpu.max` is fatal — they are settable on any cgroup v2 host once the
1353    /// controllers are delegated, so a failure there means the bound genuinely does not exist and
1354    /// the launch must not proceed. The one exception is a kernel that exposes no
1355    /// `memory.swap.max` at all (see [`ScopeLimit::absent_ok`]).
1356    fn create(
1357        limits: &HostResourceLimits,
1358        session_id: &str,
1359        workdir: &Path,
1360    ) -> Result<(Self, IoMaxReport), String> {
1361        let base = delegated_base()?;
1362
1363        let path = base.join(scope_dir_name(session_id));
1364        if let Err(error) = std::fs::create_dir(&path) {
1365            if error.kind() != std::io::ErrorKind::AlreadyExists {
1366                return Err(format!(
1367                    "could not create cgroup scope at {}: {error}",
1368                    path.display()
1369                ));
1370            }
1371        }
1372
1373        let scope = Self {
1374            path,
1375            procs_fd: None,
1376            occupancy: Arc::default(),
1377            watcher: None,
1378        };
1379
1380        for limit in scope_limits(limits) {
1381            scope.write_limit(&limit)?;
1382        }
1383        let io_max = scope.apply_io_max(limits.cgroup_io_bytes_per_sec, workdir);
1384
1385        // Opened last, so a scope that failed any of the fatal writes above is never handed out
1386        // with a usable join descriptor.
1387        let procs_fd = open_write_only(&scope.path.join("cgroup.procs")).map_err(|error| {
1388            format!(
1389                "could not open {}/cgroup.procs for subprocess placement: {error}",
1390                scope.path.display()
1391            )
1392        })?;
1393
1394        let watcher = ScopeWatcher::spawn(&scope.path).map_err(|error| {
1395            format!(
1396                "could not start the watcher that kills {} if the runtime dies: {error}",
1397                scope.path.display()
1398            )
1399        })?;
1400
1401        Ok((
1402            Self {
1403                path: scope.take_path(),
1404                procs_fd: Some(procs_fd),
1405                occupancy: Arc::default(),
1406                watcher: Some(watcher),
1407            },
1408            io_max,
1409        ))
1410    }
1411
1412    /// Move the path out of a scope that must not run its `Drop` (which would `rmdir` the
1413    /// directory the returned value is about to take ownership of).
1414    fn take_path(mut self) -> PathBuf {
1415        let path = std::mem::take(&mut self.path);
1416        // `self.path` is now empty, which `Drop` treats as "nothing to remove".
1417        path
1418    }
1419
1420    /// Opened without `O_CREAT`, so a file this kernel does not expose reads as `NotFound`
1421    /// rather than as a refused create.
1422    fn write_limit(&self, limit: &ScopeLimit) -> Result<(), String> {
1423        let path = self.path.join(limit.file);
1424        let value = &limit.value;
1425        match write_existing(&path, &format!("{value}\n")) {
1426            Err(error) if limit.absent_ok && error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1427            written => written
1428                .map_err(|error| format!("could not write {value} to {}: {error}", path.display())),
1429        }
1430    }
1431
1432    /// Best-effort `io.max` on the workdir's backing block device, reported rather than printed.
1433    ///
1434    /// Non-fatal by design, and the only one of the four controllers treated that way: the
1435    /// backing device of a path cannot always be resolved to a real `MAJ:MIN` the block layer
1436    /// accepts (overlayfs, tmpfs, btrfs subvolumes and device-mapper stacks all break the
1437    /// assumption), and I/O throughput is the least safety-critical of the four — a capsule that
1438    /// saturates disk bandwidth is slow, where one that exhausts memory or pids is fatal.
1439    ///
1440    /// Non-fatal is not the same as unreported: the returned [`IoMaxReport`] travels into
1441    /// `--explain-scope`, into `session_start.effective_grants.io_max` and into `W-SEC-021`, so
1442    /// the manifest's declared ceiling and what the kernel accepted cannot disagree in silence.
1443    fn apply_io_max(&self, bytes_per_sec: u64, workdir: &Path) -> IoMaxReport {
1444        write_io_max(&self.path, bytes_per_sec, workdir)
1445    }
1446}
1447
1448/// Writes `io.max` into `scope_path` for the device behind `workdir`, and says what happened.
1449///
1450/// The one place the `io.max` line is composed, shared by [`CgroupScope::apply_io_max`] at launch
1451/// and by [`probe_io_max`] under `--explain-scope`, so the diagnostic exercises the identical
1452/// write the launch performs rather than a paraphrase of it.
1453///
1454/// The device comes from [`io_max_device`], which resolves it from the nearest *existing*
1455/// ancestor of `workdir`: `--explain-scope` runs before the workdir is created, and a launch's
1456/// workdir sits on the same filesystem as the project directory it is created under.
1457#[cfg(target_os = "linux")]
1458fn write_io_max(scope_path: &Path, bytes_per_sec: u64, workdir: &Path) -> IoMaxReport {
1459    let (major, minor) = match io_max_device(workdir) {
1460        Ok(device) => device,
1461        Err(reason) => return IoMaxReport::unavailable(bytes_per_sec, reason),
1462    };
1463    let value = format!("{major}:{minor} rbps={bytes_per_sec} wbps={bytes_per_sec}");
1464    match std::fs::write(scope_path.join("io.max"), format!("{value}\n")) {
1465        Ok(()) => IoMaxReport::enforced(bytes_per_sec),
1466        // The scope directory is deliberately not named: `--explain-scope` writes into a throwaway
1467        // cgroup and a launch writes into the session's, so including it would make the two
1468        // reports differ for no reason a reader could act on — and
1469        // `session_start.effective_grants` has to be the byte-for-byte object `--explain-scope`
1470        // prints. The `MAJ:MIN` and the errno are what identify the failure.
1471        Err(error) => IoMaxReport::unavailable(
1472            bytes_per_sec,
1473            format!("writing `{value}` to the scope's io.max: {error}"),
1474        ),
1475    }
1476}
1477
1478/// The `MAJ:MIN` an `io.max` line has to name for the filesystem behind `path`, or why that
1479/// filesystem has no device a ceiling can name.
1480///
1481/// `st_dev` is not the answer on its own. Two things stand between a path and a device the block
1482/// layer accepts:
1483///
1484/// * A filesystem the kernel gives an anonymous `dev_t` — btrfs, overlayfs, tmpfs, every FUSE
1485///   mount — has major `0`, which names no device. `/proc/self/mountinfo` records what the
1486///   covering mount was mounted from, and where that source is a block device node its `st_rdev`
1487///   is the device the filesystem's I/O actually reaches.
1488/// * `blkcg` binds a limit to a request queue and only a whole disk carries one, so the block
1489///   layer answers `ENODEV` for a partition — which is what `st_dev` reports for the common case
1490///   of a filesystem on `/dev/sda1` or `/dev/nvme0n1p7`. [`whole_disk_device`] takes the last hop.
1491///
1492/// A filesystem with no block device behind it at all carries no I/O ceiling, and the `Err` says
1493/// which mount and what it is backed by. That is a measurement of the resolution, not a guess
1494/// about the write: there is no device for a write to name.
1495#[cfg(target_os = "linux")]
1496fn io_max_device(path: &Path) -> Result<(u64, u64), String> {
1497    use std::os::linux::fs::MetadataExt;
1498
1499    let Some(existing) = nearest_existing_ancestor(path) else {
1500        return Err(format!(
1501            "could not stat {} or any ancestor of it to find its backing device",
1502            path.display()
1503        ));
1504    };
1505    let metadata = existing.metadata().map_err(|error| {
1506        format!(
1507            "could not stat {} to find its backing device: {error}",
1508            existing.display()
1509        )
1510    })?;
1511    let (major, minor) = device_major_minor(metadata.st_dev());
1512    let (major, minor) = if major == 0 {
1513        mount_source_device(existing)?
1514    } else {
1515        (major, minor)
1516    };
1517    Ok(whole_disk_device(major, minor))
1518}
1519
1520/// The block device the mount covering `path` was mounted from.
1521///
1522/// Reached only for a filesystem whose `st_dev` is anonymous. `path` must exist, so that
1523/// canonicalizing it yields the path the kernel's own mount lookup would take — a mount point
1524/// reached through a symlink matches nothing in `mountinfo`.
1525#[cfg(target_os = "linux")]
1526fn mount_source_device(path: &Path) -> Result<(u64, u64), String> {
1527    use std::os::unix::fs::{FileTypeExt, MetadataExt};
1528
1529    let resolved = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
1530    let mountinfo = std::fs::read_to_string("/proc/self/mountinfo").map_err(|error| {
1531        format!(
1532            "reading /proc/self/mountinfo to find the device behind {}: {error}",
1533            resolved.display()
1534        )
1535    })?;
1536    let Some(mount) = mount_covering(&mountinfo, &resolved) else {
1537        return Err(format!(
1538            "no mount in /proc/self/mountinfo covers {}, so its backing device is unknown",
1539            resolved.display()
1540        ));
1541    };
1542    match std::fs::metadata(&mount.source) {
1543        Ok(metadata) if metadata.file_type().is_block_device() => {
1544            Ok(device_major_minor(metadata.rdev()))
1545        }
1546        _ => Err(format!(
1547            "the filesystem mounted at {} is backed by `{}`, which is not a block device, so no \
1548             io.max ceiling can name one",
1549            mount.mount_point.display(),
1550            mount.source.display()
1551        )),
1552    }
1553}
1554
1555/// `major:minor` of the whole disk carrying `major:minor`, which is itself where it is not a
1556/// partition.
1557///
1558/// A partition has a `partition` attribute in sysfs and sits inside its disk's directory, so the
1559/// parent's `dev` is the disk. Every failure to read sysfs answers with the device as given: the
1560/// write that follows is what decides, and reporting a device the block layer then refuses is a
1561/// better outcome than reporting a device nothing was tried against.
1562#[cfg(target_os = "linux")]
1563fn whole_disk_device(major: u64, minor: u64) -> (u64, u64) {
1564    let device = PathBuf::from(format!("/sys/dev/block/{major}:{minor}"));
1565    if !device.join("partition").exists() {
1566        return (major, minor);
1567    }
1568    std::fs::read_to_string(device.join("../dev"))
1569        .ok()
1570        .and_then(|contents| parse_dev_line(&contents))
1571        .unwrap_or((major, minor))
1572}
1573
1574/// The `MAJ:MIN` on a sysfs `dev` attribute.
1575#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1576fn parse_dev_line(contents: &str) -> Option<(u64, u64)> {
1577    let (major, minor) = contents.trim().split_once(':')?;
1578    Some((major.parse().ok()?, minor.parse().ok()?))
1579}
1580
1581/// One `/proc/self/mountinfo` line, reduced to the two fields that identify a filesystem's
1582/// backing device.
1583#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1584#[derive(Debug, PartialEq, Eq)]
1585struct MountEntry {
1586    /// Where the filesystem is mounted, as the kernel spells it.
1587    mount_point: PathBuf,
1588    /// What it was mounted from: a block device node for an ordinary disk filesystem, and a bare
1589    /// name such as `tmpfs` for one with nothing behind it.
1590    source: PathBuf,
1591}
1592
1593/// The mount `path` lands in: the entry whose mount point is the longest prefix of it.
1594///
1595/// Later lines win a tie. `mountinfo` is in mount order, so a filesystem mounted over an earlier
1596/// one at the same point is the one a lookup reaches.
1597#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1598fn mount_covering(mountinfo: &str, path: &Path) -> Option<MountEntry> {
1599    let mut best: Option<(usize, MountEntry)> = None;
1600    for line in mountinfo.lines() {
1601        let Some(entry) = parse_mount_entry(line) else {
1602            continue;
1603        };
1604        if !path.starts_with(&entry.mount_point) {
1605            continue;
1606        }
1607        let depth = entry.mount_point.components().count();
1608        if best.as_ref().is_none_or(|(best, _)| depth >= *best) {
1609            best = Some((depth, entry));
1610        }
1611    }
1612    best.map(|(_, entry)| entry)
1613}
1614
1615/// Mount point and source out of one `mountinfo` line.
1616///
1617/// The optional-fields run is terminated by a lone `-`, which no field can contain: `mountinfo`
1618/// escapes space, tab, newline and backslash as octal, so splitting on `" - "` is unambiguous.
1619#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1620fn parse_mount_entry(line: &str) -> Option<MountEntry> {
1621    let (mounted, backing) = line.split_once(" - ")?;
1622    let mount_point = mounted.split_whitespace().nth(4)?;
1623    let source = backing.split_whitespace().nth(1)?;
1624    Some(MountEntry {
1625        mount_point: unescape_octal(mount_point),
1626        source: unescape_octal(source),
1627    })
1628}
1629
1630/// Decode `mountinfo`'s `\NNN` octal escapes, byte-wise, so a mount point containing a space or a
1631/// non-ASCII byte compares equal to the path the kernel reports for it.
1632#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1633fn unescape_octal(field: &str) -> PathBuf {
1634    use std::os::unix::ffi::OsStringExt;
1635
1636    let bytes = field.as_bytes();
1637    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
1638    let mut index = 0;
1639    while index < bytes.len() {
1640        let escape = bytes[index] == b'\\'
1641            && index + 3 < bytes.len()
1642            && bytes[index + 1..index + 4]
1643                .iter()
1644                .all(|byte| (b'0'..=b'7').contains(byte));
1645        if escape {
1646            let digits = &field[index + 1..index + 4];
1647            out.push(u8::from_str_radix(digits, 8).expect("three octal digits"));
1648            index += 4;
1649        } else {
1650            out.push(bytes[index]);
1651            index += 1;
1652        }
1653    }
1654    PathBuf::from(std::ffi::OsString::from_vec(out))
1655}
1656
1657/// The closest ancestor of `path` that exists, which is `path` itself where it does.
1658///
1659/// The backing device is a property of the filesystem, not of the leaf, so an ancestor's answer
1660/// is the answer for a path that has not been created yet — the state `--explain-scope` finds the
1661/// would-be workdir in.
1662#[cfg(target_os = "linux")]
1663fn nearest_existing_ancestor(path: &Path) -> Option<&Path> {
1664    let mut candidate = Some(path);
1665    while let Some(current) = candidate {
1666        if current.exists() {
1667            return Some(current);
1668        }
1669        candidate = current.parent();
1670    }
1671    None
1672}
1673
1674/// The delegated cgroup root this process creates its scopes under, resolved once.
1675///
1676/// [`probe_delegation`] derives the root from `/proc/self/cgroup`, but establishing the first
1677/// scope may move this process into `<root>/murmur-supervisor` to vacate the root — cgroup v2
1678/// forbids a cgroup from both holding processes and enabling controllers for its children. Once
1679/// that move has happened the process's own cgroup is no longer the delegated root, so
1680/// re-deriving it per call mistakes the leaf for the root and nests one level deeper every time,
1681/// until the nested leaf has no delegated controllers at all and every further session is
1682/// refused. Any process that opens a second session — concurrently or in sequence — hits this.
1683///
1684/// Resolving once, under a lock, keeps every scope a sibling directly under the real root, and
1685/// makes concurrent first-callers agree on that root instead of racing to relocate each other.
1686/// Only success is cached: a host that is not delegated must keep reporting so on every attempt.
1687#[cfg(target_os = "linux")]
1688fn delegated_base() -> Result<PathBuf, String> {
1689    static BASE: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
1690
1691    // A poisoned lock guards no invariant worth honouring here: the cache is either populated or
1692    // it is not, and a caller that panicked cannot have left it half-written.
1693    let mut cached = BASE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
1694    if let Some(base) = cached.as_ref() {
1695        return Ok(base.clone());
1696    }
1697
1698    // Best-effort: relocate into our own scope before probing. On failure, the probe below runs
1699    // against the inherited cgroup — the correct fallback on a host with no systemd to ask.
1700    move_self_into_own_systemd_scope();
1701
1702    let base = probe_delegation()?;
1703    enable_controllers(&base)?;
1704    *cached = Some(base.clone());
1705    Ok(base)
1706}
1707
1708/// Ask the systemd user manager for a freshly created, delegated transient scope holding this
1709/// process, so the cgroup this runtime builds under is one it is the only occupant of.
1710///
1711/// Best-effort and non-fatal: every failure here (no systemd, no session bus, policy denial, a
1712/// migration that never lands) leaves the process exactly where it was — the state
1713/// [`probe_delegation`] handles. Never let a failed optimisation become a launch refusal.
1714///
1715/// Runs at most once per process — a scope is a property of the process, not the session, and
1716/// [`delegated_base`] retries on failure but caches only success, so the guard has to live here.
1717#[cfg(target_os = "linux")]
1718fn move_self_into_own_systemd_scope() {
1719    static ATTEMPTED: std::sync::Once = std::sync::Once::new();
1720    ATTEMPTED.call_once(|| {
1721        let _ = request_transient_scope(&transient_scope_unit_name());
1722    });
1723}
1724
1725/// Name of the transient scope unit to ask systemd for.
1726///
1727/// `murmur-` keeps the operator-facing convention the scope *directories* already use
1728/// ([`scope_dir_name`]), so `systemctl --user list-units 'murmur-*.scope'` finds the runtime's
1729/// units the same way a `murmur-*` glob finds its cgroup directories. The pid and a per-process
1730/// serial keep it unique against a recycled pid whose earlier unit systemd has not yet collected.
1731#[cfg(target_os = "linux")]
1732fn transient_scope_unit_name() -> String {
1733    static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1734    let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1735    format!("murmur-{}-{serial}.scope", std::process::id())
1736}
1737
1738/// The D-Bus half of [`move_self_into_own_systemd_scope`], plus confirmation that the kernel
1739/// actually moved us.
1740#[cfg(target_os = "linux")]
1741fn request_transient_scope(unit: &str) -> Result<(), String> {
1742    // `zbus::block_on` drives the connection on the calling thread and panics or deadlocks inside
1743    // another runtime's task; run it on a thread of its own so a caller inside tokio is safe.
1744    let owned_unit = unit.to_string();
1745    std::thread::Builder::new()
1746        .name("murmur-cgroup-scope".to_string())
1747        .spawn(move || start_transient_scope(&owned_unit))
1748        .map_err(|error| format!("could not spawn the D-Bus thread: {error}"))?
1749        .join()
1750        .map_err(|_| "the D-Bus thread panicked".to_string())??;
1751
1752    await_scope_membership(unit)
1753}
1754
1755/// `StartTransientUnit` on the systemd user manager: create `unit` as a scope containing this
1756/// process, with its cgroup subtree delegated to us.
1757///
1758/// The call is
1759/// `org.freedesktop.systemd1.Manager.StartTransientUnit(in s name, in s mode, in a(sv) properties,
1760/// in a(sa(sv)) aux)` on `/org/freedesktop/systemd1` at the well-known name
1761/// `org.freedesktop.systemd1`, over the **session** bus (`$DBUS_SESSION_BUS_ADDRESS`, falling back
1762/// to `$XDG_RUNTIME_DIR/bus`) so the unit lands in this user's manager and needs no privilege.
1763/// The properties are the same set `systemd-run --user --scope -p Delegate=yes` sends:
1764///
1765/// * `PIDs` (`au`) — this process, which is what makes systemd *move* it rather than fork a new one.
1766/// * `Delegate` (`b`) — hand the scope's subtree to us, controllers and all, and stop managing it.
1767/// * `CollectMode` (`s`) — `inactive-or-failed`, so the unit is garbage-collected when this
1768///   process exits rather than lingering as a failed unit an operator has to reset.
1769/// * `Description` (`s`) — what `systemctl --user list-units` shows beside the unit.
1770#[cfg(target_os = "linux")]
1771fn start_transient_scope(unit: &str) -> Result<(), String> {
1772    use zbus::Variant;
1773
1774    let properties: Vec<(&str, Variant<'_>)> = vec![
1775        (
1776            "Description",
1777            Variant::from("Murmur capsule subprocess scope"),
1778        ),
1779        ("PIDs", Variant::from(vec![std::process::id()])),
1780        ("Delegate", Variant::from(true)),
1781        ("CollectMode", Variant::from("inactive-or-failed")),
1782    ];
1783    // No auxiliary units: a scope has none.
1784    let aux: Vec<(&str, Vec<(&str, Variant<'_>)>)> = Vec::new();
1785
1786    zbus::block_on(async {
1787        let connection = zbus::Connection::session()
1788            .await
1789            .map_err(|error| format!("no systemd session bus: {error}"))?;
1790        connection
1791            .call_method(
1792                Some("org.freedesktop.systemd1"),
1793                "/org/freedesktop/systemd1",
1794                Some("org.freedesktop.systemd1.Manager"),
1795                "StartTransientUnit",
1796                // "fail" rather than "replace": a name collision means something is wrong with
1797                // our assumption of uniqueness, and displacing an unrelated unit is never the fix.
1798                &(unit, "fail", properties, aux),
1799            )
1800            .await
1801            .map(|_| ())
1802            .map_err(|error| format!("systemd refused to start {unit}: {error}"))
1803    })
1804}
1805
1806/// Wait until `/proc/self/cgroup` actually reports us inside `unit`'s cgroup.
1807///
1808/// `StartTransientUnit` returns once the job is *enqueued*, not once the move has happened, and
1809/// every later step (the delegation probe, the controller enable, the scope directory) depends on
1810/// where this process actually lives — so migration is confirmed from `/proc/self/cgroup`, the
1811/// same source the rest of this module reads, rather than inferred from a job object path.
1812///
1813/// The 2s deadline mirrors [`enable_controllers`]: both wait on systemd/kernel bookkeeping that
1814/// normally completes in a millisecond or two, and a wait that long means something structural is
1815/// wrong. A timeout here is cheap — the caller ignores it and falls back to probing the inherited
1816/// cgroup. The step is 1ms because this wait sits on the launch path of every capsule that needs a
1817/// scope, and the move lands a millisecond or two after `StartTransientUnit` returns, so every
1818/// step the loop oversleeps is added to the launch.
1819#[cfg(target_os = "linux")]
1820fn await_scope_membership(unit: &str) -> Result<(), String> {
1821    let deadline = std::time::Instant::now() + Duration::from_secs(2);
1822    loop {
1823        let current = std::fs::read_to_string("/proc/self/cgroup").unwrap_or_default();
1824        if let Some(path) = parse_unified_cgroup_path(&current) {
1825            if path.rsplit('/').next() == Some(unit) {
1826                return Ok(());
1827            }
1828        }
1829        if std::time::Instant::now() >= deadline {
1830            return Err(format!(
1831                "systemd accepted the request for {unit} but this process is not in it"
1832            ));
1833        }
1834        std::thread::sleep(Duration::from_millis(1));
1835    }
1836}
1837
1838/// Locate the delegated cgroup v2 directory this process may create children under, confirming
1839/// the controllers this runtime needs are actually available there.
1840///
1841/// Returns the base directory on success, or a message naming what is missing — that message is
1842/// what reaches the operator inside
1843/// [`crate::errors::RuntimeError::CgroupDelegationUnavailable`], so it names the delegation
1844/// requirement rather than only the failed syscall.
1845#[cfg(target_os = "linux")]
1846fn probe_delegation() -> Result<PathBuf, String> {
1847    let self_cgroup = std::fs::read_to_string("/proc/self/cgroup")
1848        .map_err(|error| format!("could not read /proc/self/cgroup: {error}"))?;
1849    let relative = parse_unified_cgroup_path(&self_cgroup).ok_or_else(|| {
1850        "this host has no cgroup v2 unified hierarchy (no `0::` line in /proc/self/cgroup); \
1851         cgroup v1-only and hybrid hosts cannot be delegated a v2 scope"
1852            .to_string()
1853    })?;
1854
1855    let mount = std::fs::read_to_string("/proc/mounts")
1856        .map(|contents| parse_cgroup2_mount(&contents))
1857        .unwrap_or_else(|_| DEFAULT_CGROUP2_MOUNT.to_string());
1858
1859    let base = ascend_out_of_supervisor_leaves(
1860        PathBuf::from(mount).join(relative.trim_start_matches('/')),
1861    );
1862    if !base.is_dir() {
1863        return Err(format!(
1864            "delegated cgroup directory {} does not exist",
1865            base.display()
1866        ));
1867    }
1868
1869    let controllers =
1870        std::fs::read_to_string(base.join("cgroup.controllers")).map_err(|error| {
1871            format!(
1872                "could not read {}/cgroup.controllers: {error}",
1873                base.display()
1874            )
1875        })?;
1876    let unavailable = missing_controllers(&controllers, REQUIRED_CONTROLLERS);
1877    if !unavailable.is_empty() {
1878        return Err(format!(
1879            "cgroup controllers [{}] are not delegated to {}; the unit `mur` runs under needs \
1880             `Delegate=yes` (or `Delegate=memory pids cpu io`)",
1881            unavailable.join(", "),
1882            base.display()
1883        ));
1884    }
1885
1886    // The probe must confirm we can actually *create* a child here, not just read the directory:
1887    // a readable cgroup with no write permission is the exact shape of an undelegated host.
1888    // Named per-pid so two `mur` processes probing concurrently never race on the same path.
1889    let probe_dir = base.join(format!("murmur-delegation-probe-{}", std::process::id()));
1890    let _ = std::fs::remove_dir(&probe_dir);
1891    std::fs::create_dir(&probe_dir).map_err(|error| {
1892        format!(
1893            "cannot create a child cgroup under {} ({error}); the unit `mur` runs under needs \
1894             `Delegate=yes` for memory, pids, cpu and io",
1895            base.display()
1896        )
1897    })?;
1898    let _ = std::fs::remove_dir(&probe_dir);
1899
1900    Ok(base)
1901}
1902
1903/// Enable `memory`, `pids`, `cpu` (and `io`, best-effort) in the delegated base's
1904/// `cgroup.subtree_control` so a child cgroup can carry their limit files.
1905///
1906/// If the base still holds this process directly, the write is refused (`EBUSY`) by cgroup v2's
1907/// "no internal processes" rule; the recovery is to move this process into its own leaf and try
1908/// once more. That relocation stays entirely inside the delegated subtree.
1909#[cfg(target_os = "linux")]
1910fn enable_controllers(base: &Path) -> Result<(), String> {
1911    let subtree_control = base.join("cgroup.subtree_control");
1912    let current = std::fs::read_to_string(&subtree_control).unwrap_or_default();
1913
1914    // `io` is requested opportunistically: a host that delegates only the three required
1915    // controllers still gets a fully-enforced scope, just without `io.max`.
1916    let available = std::fs::read_to_string(base.join("cgroup.controllers")).unwrap_or_default();
1917    let mut wanted: Vec<&str> = REQUIRED_CONTROLLERS.to_vec();
1918    if available.split_whitespace().any(|c| c == "io") {
1919        wanted.push("io");
1920    }
1921
1922    let missing = missing_controllers(&current, &wanted);
1923    if missing.is_empty() {
1924        return Ok(());
1925    }
1926    let directive = missing
1927        .iter()
1928        .map(|controller| format!("+{controller}"))
1929        .collect::<Vec<_>>()
1930        .join(" ");
1931
1932    if std::fs::write(&subtree_control, format!("{directive}\n")).is_ok() {
1933        return Ok(());
1934    }
1935
1936    move_self_to_supervisor_leaf(base)?;
1937
1938    // Stepping aside vacates *this* process, and cgroup v2 refuses the write while the base holds
1939    // any task at all. When several murmur processes share a base — a test binary and the `mur`
1940    // children it spawns, or two capsules launched together — each is independently discovering
1941    // it must step aside, so the first write after our own move can still hit `EBUSY` on peers
1942    // that have not moved yet. Retrying briefly lets the group finish draining; a peer that wins
1943    // the race and enables the controllers first is just as good, which is why the loop re-reads
1944    // `subtree_control` rather than only retrying the write.
1945    //
1946    // Bounded, because a task that never leaves is a genuine misconfiguration and has to surface
1947    // as one rather than hang the launch.
1948    let deadline = std::time::Instant::now() + Duration::from_secs(2);
1949    // Left uninitialised: every path that reaches the deadline check has just gone through the
1950    // write's `Err` arm, so the fallback below only ever describes a real failure.
1951    let mut last_error;
1952    loop {
1953        let current = std::fs::read_to_string(&subtree_control).unwrap_or_default();
1954        if missing_controllers(&current, &wanted).is_empty() {
1955            return Ok(());
1956        }
1957        match std::fs::write(&subtree_control, format!("{directive}\n")) {
1958            Ok(()) => return Ok(()),
1959            Err(error) => last_error = Some(error),
1960        }
1961        if std::time::Instant::now() >= deadline {
1962            break;
1963        }
1964        std::thread::sleep(Duration::from_millis(20));
1965    }
1966
1967    Err(format!(
1968        "could not enable controllers [{}] in {} ({}); the unit `mur` runs under needs \
1969         `Delegate=yes` for memory, pids, cpu and io",
1970        missing.join(", "),
1971        subtree_control.display(),
1972        last_error.map_or_else(|| "still occupied".to_string(), |error| error.to_string()),
1973    ))
1974}
1975
1976/// Walk up out of any `murmur-supervisor` leaves the path ends in.
1977///
1978/// The leaf is where a murmur process steps aside so controllers can be enabled on the delegated
1979/// base. Every process it then spawns *inherits that leaf as its own cgroup* — so a `mur`
1980/// subprocess reading `/proc/self/cgroup` would take the leaf for its delegated base and step
1981/// aside again inside it, one level deeper per generation, until the innermost leaf has no
1982/// controllers delegated to it at all and every launch below that point is refused.
1983///
1984/// Ascending here makes every generation agree on the same real base, which is also what lets
1985/// them share one scope parent rather than fragmenting the delegation.
1986#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
1987fn ascend_out_of_supervisor_leaves(mut base: PathBuf) -> PathBuf {
1988    while base.file_name().and_then(|name| name.to_str()) == Some(SUPERVISOR_LEAF) {
1989        base.pop();
1990    }
1991    base
1992}
1993
1994/// Move this process into `<base>/murmur-supervisor`, creating it if needed.
1995#[cfg(target_os = "linux")]
1996fn move_self_to_supervisor_leaf(base: &Path) -> Result<(), String> {
1997    let leaf = base.join(SUPERVISOR_LEAF);
1998    if let Err(error) = std::fs::create_dir(&leaf) {
1999        if error.kind() != std::io::ErrorKind::AlreadyExists {
2000            return Err(format!(
2001                "could not create {} to vacate the delegated cgroup: {error}",
2002                leaf.display()
2003            ));
2004        }
2005    }
2006    std::fs::write(
2007        leaf.join("cgroup.procs"),
2008        format!("{}\n", std::process::id()),
2009    )
2010    .map_err(|error| {
2011        format!(
2012            "could not move this process into {} to vacate the delegated cgroup: {error}",
2013            leaf.display()
2014        )
2015    })
2016}
2017
2018/// `open(path, O_WRONLY | O_CLOEXEC)`.
2019///
2020/// `CLOEXEC` matters twice over: the descriptor is written from `pre_exec` (still open at that
2021/// point) and must not survive into the exec'd binary, where it would hand a capsule the ability
2022/// to move arbitrary pids into its own cgroup.
2023#[cfg(target_os = "linux")]
2024#[allow(unsafe_code)]
2025fn open_write_only(path: &Path) -> std::io::Result<std::os::fd::OwnedFd> {
2026    use std::os::unix::fs::OpenOptionsExt;
2027
2028    std::fs::OpenOptions::new()
2029        .write(true)
2030        .custom_flags(libc::O_CLOEXEC)
2031        .open(path)
2032        .map(std::os::fd::OwnedFd::from)
2033}
2034
2035/// Whether this host can hand the runtime a delegated cgroup v2 scope — the precondition
2036/// [`prepare_scope`] fails closed on.
2037///
2038/// Test support, not a runtime code path: `mur` never asks this question, it asks systemd for a
2039/// scope and reports [`crate::errors::RuntimeError::CgroupDelegationUnavailable`] when it cannot
2040/// get one. Tests that launch a capsule tripping [`requires_process_bounding`] call this to skip
2041/// visibly instead, because a containerised runner has no delegable subtree to give and the
2042/// refusal there says nothing about the code under test. What CI therefore cannot cover is
2043/// covered by hand: `docs/content/reference/resource-limits-manual-verification.md`.
2044///
2045/// Probed by actually creating a transient `--user` scope with `Delegate=yes`, since a
2046/// `systemd-run` binary on `PATH` says nothing about a reachable user manager — and the user
2047/// manager is the half a runner is missing. Off Linux there are no cgroups, this module is inert
2048/// and nothing is ever refused, so the answer is `true`.
2049pub fn cgroup_delegation_available() -> bool {
2050    #[cfg(not(target_os = "linux"))]
2051    {
2052        true
2053    }
2054
2055    #[cfg(target_os = "linux")]
2056    {
2057        // Answered through `delegated_base`, the same call `prepare_scope` makes, so the answer
2058        // cannot disagree with what a launch does on this host. A separate `systemd-run` probe
2059        // answers a different question and is wrong in both directions: a user manager hands out
2060        // a scope on a host whose controllers `enable_controllers` cannot delegate, and the
2061        // inherited cgroup carries delegated controllers on a host with no reachable session bus.
2062        delegated_base().is_ok()
2063    }
2064}
2065
2066/// Whether the filesystem behind `path` has a block device an `io.max` ceiling can name.
2067///
2068/// Test support beside [`cgroup_delegation_available`], for the half of the `io.max` scenario
2069/// that needs a ceiling to actually apply: a checkout on tmpfs, on overlayfs or on a FUSE mount
2070/// has no device for the block layer to bind a limit to, and `enforced` is unreachable there
2071/// however well the host delegates cgroups. Answered through [`io_max_device`], the same
2072/// resolution a launch performs, so a test cannot stand down on a host the launch would have
2073/// satisfied. Off Linux there is no `io.max` at all.
2074#[must_use]
2075pub fn io_max_device_available(path: &Path) -> bool {
2076    #[cfg(not(target_os = "linux"))]
2077    {
2078        let _ = path;
2079        false
2080    }
2081
2082    #[cfg(target_os = "linux")]
2083    {
2084        io_max_device(path).is_ok()
2085    }
2086}
2087
2088/// Whether a test that launches a subprocess-capable capsule must stand down on this host,
2089/// printing the blocker when it must.
2090///
2091/// Both blockers are asked through the same calls a launch makes -- `delegated_base` for the
2092/// cgroup scope, `detect_egress_namespace_blocker` for the network namespace -- so the gate and
2093/// the launch cannot reach different conclusions about the host. A containerised CI runner
2094/// typically clears the first and fails the second.
2095pub fn skip_without_host_support(test_name: &str) -> bool {
2096    if crate::network_namespace::skip_without_egress_namespace(test_name) {
2097        return true;
2098    }
2099    if !cgroup_delegation_available() {
2100        crate::runtime_err!(
2101            "[SKIP-HOST] {test_name}: this host cannot delegate a cgroup v2 scope, so a capsule \
2102             that can spawn native subprocesses refuses to launch with E-RUN-012 before anything \
2103             this test observes happens -- see {}",
2104            murmur_artifact::docs_reference_url!("resource-limits/#platform-behavior")
2105        );
2106        return true;
2107    }
2108    false
2109}
2110
2111#[cfg(test)]
2112mod tests {
2113    use super::*;
2114    use crate::types::CapabilityPolicy;
2115
2116    /// The wire spelling every consumer reads: `--explain-scope --json`, `mur doctor` and
2117    /// `session_start.effective_grants.io_max` in `trace.jsonl`. Kebab-case, not the `Debug`
2118    /// rendering, which is free to change.
2119    #[test]
2120    fn io_max_status_wire_names_are_kebab_case() {
2121        let spellings: Vec<String> = [
2122            IoMaxStatus::Enforced,
2123            IoMaxStatus::Unavailable,
2124            IoMaxStatus::NotRequired,
2125            IoMaxStatus::NotProbed,
2126        ]
2127        .into_iter()
2128        .map(|status| {
2129            serde_json::to_value(status)
2130                .unwrap()
2131                .as_str()
2132                .unwrap()
2133                .to_string()
2134        })
2135        .collect();
2136        assert_eq!(
2137            spellings,
2138            vec!["enforced", "unavailable", "not-required", "not-probed"]
2139        );
2140    }
2141
2142    /// A report nobody filled in must claim nothing, which is what makes it safe to construct one
2143    /// at stage time and overwrite it once the scope exists.
2144    #[test]
2145    fn an_unfilled_report_claims_nothing() {
2146        let report = IoMaxReport::default();
2147        assert_eq!(report.status, IoMaxStatus::NotProbed);
2148        assert_eq!(report.declared_bytes_per_sec, 0);
2149        assert_eq!(report.reason, None);
2150        assert_eq!(io_max_warning(&report), None);
2151    }
2152
2153    /// `reason` is the only optional key, and it is present for every status but `Enforced`.
2154    #[test]
2155    fn only_a_failed_write_omits_nothing_and_a_successful_one_explains_nothing() {
2156        let enforced = serde_json::to_value(IoMaxReport::enforced(1_000)).unwrap();
2157        assert_eq!(enforced["status"], "enforced");
2158        assert_eq!(enforced["declared_bytes_per_sec"], 1_000);
2159        assert!(
2160            enforced.get("reason").is_none(),
2161            "an applied ceiling has nothing to explain: {enforced}"
2162        );
2163
2164        let unavailable =
2165            serde_json::to_value(IoMaxReport::unavailable(1_000, "no io controller")).unwrap();
2166        assert_eq!(unavailable["status"], "unavailable");
2167        assert_eq!(unavailable["reason"], "no io controller");
2168    }
2169
2170    /// `W-SEC-021` fires on the one status that is a shortfall, and its message names the
2171    /// declared ceiling, the host's reason, and the three limits that *are* still enforced —
2172    /// without which "io.max did not apply" reads as "this session is unbounded".
2173    #[test]
2174    fn the_warning_fires_only_where_a_declared_ceiling_did_not_apply() {
2175        assert_eq!(io_max_warning(&IoMaxReport::enforced(4_096)), None);
2176        assert_eq!(
2177            io_max_warning(&IoMaxReport::not_required(4_096, NO_SCOPE_REASON)),
2178            None
2179        );
2180
2181        let (code, message) = io_max_warning(&IoMaxReport::unavailable(
2182            4_096,
2183            "device 0:24 is not a block device",
2184        ))
2185        .expect("an unapplied ceiling must be reported");
2186        assert_eq!(code, murmur_artifact::W_SEC_021);
2187        assert!(message.contains("4096 bytes/s"), "message was: {message}");
2188        assert!(
2189            message.contains("device 0:24 is not a block device"),
2190            "message was: {message}"
2191        );
2192        assert!(message.contains("memory.max"), "message was: {message}");
2193    }
2194
2195    /// `--explain-scope` runs before the workdir exists, so the probe has to name the device a
2196    /// launch would use without creating anything.
2197    #[cfg(target_os = "linux")]
2198    #[test]
2199    fn the_device_is_resolved_from_the_nearest_existing_ancestor() {
2200        let temp = tempfile::tempdir().unwrap();
2201        let missing = temp
2202            .path()
2203            .join("workdir")
2204            .join("does")
2205            .join("not")
2206            .join("exist");
2207        assert_eq!(
2208            nearest_existing_ancestor(&missing),
2209            Some(temp.path()),
2210            "an ancestor of a tempdir always exists"
2211        );
2212        assert_eq!(
2213            io_max_device(&missing).ok(),
2214            io_max_device(temp.path()).ok(),
2215            "a path that does not exist yet must resolve to its filesystem's device"
2216        );
2217        assert!(!missing.exists(), "resolving a device must create nothing");
2218    }
2219
2220    /// The mount a path lands in is the deepest one covering it, not the first line that matches
2221    /// — `/` covers every path, and a nested mount is what a lookup actually reaches.
2222    #[test]
2223    fn the_covering_mount_is_the_deepest_one() {
2224        let mountinfo = "\
222525 30 0:29 / / rw,relatime shared:1 - btrfs /dev/nvme0n1p5 rw,subvol=/
222626 25 0:31 / /dev/shm rw,nosuid shared:2 - tmpfs tmpfs rw,inode64
222727 25 0:41 / /space rw,relatime shared:3 - btrfs /dev/nvme0n1p7 rw,subvol=/
2228";
2229        let covering = |path: &str| mount_covering(mountinfo, Path::new(path)).unwrap();
2230
2231        assert_eq!(
2232            covering("/space/project/workdir").source,
2233            PathBuf::from("/dev/nvme0n1p7")
2234        );
2235        assert_eq!(covering("/dev/shm/project").source, PathBuf::from("tmpfs"));
2236        assert_eq!(
2237            covering("/home/someone").source,
2238            PathBuf::from("/dev/nvme0n1p5"),
2239            "a path under no nested mount belongs to the root filesystem"
2240        );
2241        assert_eq!(
2242            covering("/spaceship").source,
2243            PathBuf::from("/dev/nvme0n1p5"),
2244            "mount points match whole path components, not string prefixes"
2245        );
2246    }
2247
2248    /// A filesystem mounted over another at the same point is the one a lookup reaches, so the
2249    /// later line wins.
2250    #[test]
2251    fn a_mount_over_another_at_the_same_point_wins() {
2252        let mountinfo = "\
225325 30 0:29 / / rw shared:1 - ext4 /dev/sda1 rw
225426 25 0:31 / /mnt rw shared:2 - ext4 /dev/sdb1 rw
225527 25 0:32 / /mnt rw shared:3 - ext4 /dev/sdc1 rw
2256";
2257        assert_eq!(
2258            mount_covering(mountinfo, Path::new("/mnt/data"))
2259                .unwrap()
2260                .source,
2261            PathBuf::from("/dev/sdc1")
2262        );
2263    }
2264
2265    /// `mountinfo` escapes the four characters that would break its own field separation, and a
2266    /// mount point that does not decode compares equal to nothing.
2267    #[test]
2268    fn mount_point_escapes_are_decoded() {
2269        let mountinfo = "\
227025 30 0:29 / /media/a\\040disk rw shared:1 - ext4 /dev/sdb1 rw
2271";
2272        let entry = mount_covering(mountinfo, Path::new("/media/a disk/project")).unwrap();
2273        assert_eq!(entry.mount_point, PathBuf::from("/media/a disk"));
2274        assert_eq!(entry.source, PathBuf::from("/dev/sdb1"));
2275        assert_eq!(unescape_octal("no\\134escape"), PathBuf::from("no\\escape"));
2276        assert_eq!(
2277            unescape_octal("\\04"),
2278            PathBuf::from("\\04"),
2279            "a truncated escape is not an escape"
2280        );
2281    }
2282
2283    /// A sysfs `dev` attribute is the only place the parent disk's number comes from.
2284    #[test]
2285    fn sysfs_dev_attributes_are_read_as_major_minor() {
2286        assert_eq!(parse_dev_line("259:0\n"), Some((259, 0)));
2287        assert_eq!(parse_dev_line(""), None);
2288        assert_eq!(parse_dev_line("259"), None);
2289    }
2290
2291    /// The block layer binds an `io.max` entry to a request queue, and only a whole disk carries
2292    /// one — so whatever device this checkout sits on, the resolved one must not be a partition.
2293    /// Naming a partition is the failure that makes `enforced` unreachable on an ordinary host.
2294    #[cfg(target_os = "linux")]
2295    #[test]
2296    fn the_resolved_device_is_never_a_partition() {
2297        let Ok((major, minor)) = io_max_device(Path::new(".")) else {
2298            // A checkout on a filesystem with no block device behind it has no device to check,
2299            // and `write_io_max` reports that rather than naming one.
2300            return;
2301        };
2302        let sysfs = PathBuf::from(format!("/sys/dev/block/{major}:{minor}"));
2303        assert!(
2304            !sysfs.join("partition").exists(),
2305            "io.max was given the partition {major}:{minor}, which the block layer refuses"
2306        );
2307    }
2308
2309    /// The diagnostic answers the question by exercising it, and leaves nothing behind whichever
2310    /// way it answers.
2311    #[cfg(target_os = "linux")]
2312    #[test]
2313    fn probing_io_max_creates_nothing_that_survives_the_call() {
2314        if skip_without_host_support("probing_io_max_creates_nothing_that_survives_the_call") {
2315            return;
2316        }
2317        let temp = tempfile::tempdir().unwrap();
2318        let report = probe_io_max(&HostResourceLimits::default(), &temp.path().join("workdir"));
2319        assert!(
2320            matches!(
2321                report.status,
2322                IoMaxStatus::Enforced | IoMaxStatus::Unavailable
2323            ),
2324            "a performed probe must report what it performed, got {report:?}"
2325        );
2326
2327        // Counted by name rather than by directory count: this binary's other tests create and
2328        // remove scopes under the same base concurrently, and only `probe_io_max` names one
2329        // `explain-scope`.
2330        let leftovers: Vec<String> = std::fs::read_dir(delegated_base().expect("a delegated base"))
2331            .unwrap()
2332            .filter_map(|entry| Some(entry.ok()?.file_name().to_string_lossy().into_owned()))
2333            .filter(|name| name.contains("explain-scope"))
2334            .collect();
2335        assert!(
2336            leftovers.is_empty(),
2337            "the throwaway cgroup outlived the probe: {leftovers:?}"
2338        );
2339    }
2340
2341    #[test]
2342    fn scope_is_required_by_any_route_to_a_native_subprocess() {
2343        let shell = CapabilityPolicy {
2344            shell_allow: vec!["bash".to_string()],
2345            ..CapabilityPolicy::default()
2346        };
2347        let spawn = CapabilityPolicy {
2348            spawn_allow: vec!["child".to_string()],
2349            ..CapabilityPolicy::default()
2350        };
2351        let bare = CapabilityPolicy::default();
2352
2353        assert!(requires_process_bounding(&shell, false));
2354        assert!(requires_process_bounding(&spawn, false));
2355        assert!(
2356            requires_process_bounding(&bare, true),
2357            "a native artifact alone is enough"
2358        );
2359        assert!(
2360            !requires_process_bounding(&bare, false),
2361            "a WASM-only capsule has no process tree to bound and must not be blocked"
2362        );
2363    }
2364
2365    /// A capsule with no subprocess capability never needs delegation — on any platform, and
2366    /// notably including Linux, where a blanket requirement would be a disproportionate
2367    /// regression for WASM-only capsules.
2368    #[test]
2369    fn prepare_scope_returns_none_when_bounding_is_not_required() {
2370        let temp = tempfile::tempdir().unwrap();
2371        let scope = prepare_scope(
2372            false,
2373            &HostResourceLimits::default(),
2374            "ses_test",
2375            temp.path(),
2376        )
2377        .expect("a capsule with no subprocess capability must never be refused");
2378        assert!(scope.scope.is_none());
2379        // Not a shortfall and never a warning: there is no process tree for a ceiling to apply to.
2380        assert_eq!(scope.io_max.status, IoMaxStatus::NotRequired);
2381        assert!(
2382            scope.io_max.reason.is_some(),
2383            "not-required must say which cause"
2384        );
2385        assert_eq!(io_max_warning(&scope.io_max), None);
2386    }
2387
2388    /// macOS can never have a cgroup, so a required scope there must be a silent `None` rather
2389    /// than a launch-blocking error.
2390    #[cfg(not(target_os = "linux"))]
2391    #[test]
2392    fn prepare_scope_is_never_an_error_off_linux() {
2393        let temp = tempfile::tempdir().unwrap();
2394        let scope = prepare_scope(
2395            true,
2396            &HostResourceLimits::default(),
2397            "ses_test",
2398            temp.path(),
2399        )
2400        .expect("a non-Linux host must not refuse to launch for a missing cgroup");
2401        assert!(scope.scope.is_none());
2402        assert_eq!(scope.io_max.status, IoMaxStatus::NotRequired);
2403        assert!(scope
2404            .io_max
2405            .reason
2406            .as_deref()
2407            .expect("not-required off Linux must say cgroups cannot exist here")
2408            .contains("Linux"));
2409    }
2410
2411    /// The point of asking systemd for a scope: a Linux host with a working user session hands
2412    /// out a bounded scope no matter what this process's *inherited* cgroup looked like — an
2413    /// interactive shell's cgroup full of co-resident processes, or the one `cargo test` keeps
2414    /// itself resident in while running this very binary.
2415    #[cfg(target_os = "linux")]
2416    #[test]
2417    #[allow(clippy::print_stdout)]
2418    fn a_required_scope_is_created_whatever_cgroup_this_process_inherited() {
2419        if skip_without_host_support(
2420            "a_required_scope_is_created_whatever_cgroup_this_process_inherited",
2421        ) {
2422            return;
2423        }
2424        let temp = tempfile::tempdir().unwrap();
2425        let prepared = prepare_scope(
2426            true,
2427            &HostResourceLimits::default(),
2428            "ses_selftest",
2429            temp.path(),
2430        )
2431        .expect("a Linux host with a systemd user session must be able to bound a subprocess tree");
2432        let io_max = prepared.io_max.clone();
2433        let scope = prepared
2434            .scope
2435            .expect("a required scope on Linux is never `None`");
2436
2437        for file in ["memory.max", "pids.max", "cpu.max"] {
2438            let contents = std::fs::read_to_string(scope.path().join(file))
2439                .unwrap_or_else(|error| panic!("{file} unreadable in the scope: {error}"));
2440            assert!(!contents.trim().is_empty(), "{file} was left unset");
2441            assert_ne!(contents.trim(), "max", "{file} carries no ceiling");
2442        }
2443        match std::fs::read_to_string(scope.path().join("memory.swap.max")) {
2444            Ok(contents) => {
2445                assert_eq!(
2446                    contents.trim(),
2447                    SCOPE_SWAP_MAX,
2448                    "memory.swap.max was not bounded"
2449                );
2450                assert_eq!(contents.trim(), "0");
2451                println!(
2452                    "memory.swap.max in the created scope reads {}",
2453                    contents.trim()
2454                );
2455            }
2456            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
2457                assert_eq!(probe_swap_control(), SwapControl::Absent);
2458                println!("this kernel exposes no memory.swap.max; swap is not bounded here");
2459            }
2460            Err(error) => panic!("memory.swap.max unreadable in the scope: {error}"),
2461        }
2462
2463        // Whatever the host did with `io.max`, the scope says which of the two it was, and never
2464        // `NotProbed`: a scope that exists has had the write attempted against it.
2465        assert!(
2466            matches!(
2467                io_max.status,
2468                IoMaxStatus::Enforced | IoMaxStatus::Unavailable
2469            ),
2470            "a created scope must report a performed io.max write, got {io_max:?}"
2471        );
2472        assert_eq!(
2473            io_max.declared_bytes_per_sec,
2474            HostResourceLimits::default().cgroup_io_bytes_per_sec
2475        );
2476        if io_max.status == IoMaxStatus::Unavailable {
2477            assert!(io_max.reason.is_some(), "unavailable must carry a reason");
2478            assert!(io_max_warning(&io_max).is_some());
2479        } else {
2480            assert_eq!(io_max.reason, None);
2481            assert_eq!(io_max_warning(&io_max), None);
2482        }
2483    }
2484
2485    /// On a kernel with no `cgroup.kill`, killing a scope freezes it, signals every member and
2486    /// thaws it until it is empty — reaching a `setsid` process and a grandchild as surely as the
2487    /// one-write kill does.
2488    #[cfg(target_os = "linux")]
2489    #[test]
2490    #[allow(clippy::print_stdout)]
2491    fn killing_a_scope_without_cgroup_kill_empties_it() {
2492        if skip_without_host_support("killing_a_scope_without_cgroup_kill_empties_it") {
2493            return;
2494        }
2495        let temp = tempfile::tempdir().unwrap();
2496        let scope = prepare_scope(
2497            true,
2498            &HostResourceLimits::default(),
2499            "ses_kill_fallback",
2500            temp.path(),
2501        )
2502        .expect("a delegated scope")
2503        .scope
2504        .expect("a required scope on Linux is never None");
2505        let enforcement = crate::sandbox::ShellEnforcement {
2506            cgroup_scope: Some(Arc::clone(&scope)),
2507            ..crate::sandbox::ShellEnforcement::environment_only()
2508        };
2509        let mut command = std::process::Command::new("bash");
2510        command
2511            .args([
2512                "-c",
2513                "setsid sleep 300 >/dev/null 2>&1 & sleep 300 >/dev/null 2>&1 & wait",
2514            ])
2515            .stdout(std::process::Stdio::null())
2516            .stderr(std::process::Stdio::null());
2517        crate::sandbox::attach_process_limits(&mut command, &enforcement);
2518        let mut child = command.spawn().expect("bash spawns into the scope");
2519
2520        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2521        while scope.member_pids().len() < 3 {
2522            assert!(
2523                std::time::Instant::now() < deadline,
2524                "the scope never held bash and both sleepers: {:?}",
2525                scope.member_pids()
2526            );
2527            std::thread::sleep(std::time::Duration::from_millis(20));
2528        }
2529        let members = scope.member_pids();
2530
2531        FORCE_KILL_FALLBACK.with(|flag| flag.set(true));
2532        let killed = scope.kill_all();
2533        FORCE_KILL_FALLBACK.with(|flag| flag.set(false));
2534        let emptied = scope.wait_until_empty(std::time::Duration::from_secs(2));
2535        let status = child.wait().expect("bash is reaped");
2536        println!(
2537            "members before: {members:?}; fallback kill: {killed:?}; empty: {emptied}; \
2538             cgroup.procs after: {:?}; bash: {status}",
2539            scope.member_pids()
2540        );
2541        killed.expect("the fallback kill succeeds");
2542        assert!(emptied, "the scope still holds {:?}", scope.member_pids());
2543        assert_eq!(
2544            std::os::unix::process::ExitStatusExt::signal(&status),
2545            Some(libc::SIGKILL)
2546        );
2547    }
2548
2549    /// A required scope holding a `bash` that started a `setsid` sleeper and a plain one, once all
2550    /// three are in it. `fallback` makes the scope's watcher use the freeze-and-signal loop.
2551    #[cfg(target_os = "linux")]
2552    fn scope_with_sleepers(
2553        session: &str,
2554        fallback: bool,
2555    ) -> (Arc<CgroupScope>, std::process::Child) {
2556        let temp = tempfile::tempdir().unwrap();
2557        FORCE_KILL_FALLBACK.with(|flag| flag.set(fallback));
2558        let scope = prepare_scope(true, &HostResourceLimits::default(), session, temp.path());
2559        FORCE_KILL_FALLBACK.with(|flag| flag.set(false));
2560        let scope = scope
2561            .expect("a delegated scope")
2562            .scope
2563            .expect("a required scope on Linux is never None");
2564        let enforcement = crate::sandbox::ShellEnforcement {
2565            cgroup_scope: Some(Arc::clone(&scope)),
2566            ..crate::sandbox::ShellEnforcement::environment_only()
2567        };
2568        let mut command = std::process::Command::new("bash");
2569        command
2570            .args([
2571                "-c",
2572                "setsid sleep 300 >/dev/null 2>&1 & sleep 300 >/dev/null 2>&1 & wait",
2573            ])
2574            .stdout(std::process::Stdio::null())
2575            .stderr(std::process::Stdio::null());
2576        crate::sandbox::attach_process_limits(&mut command, &enforcement);
2577        let child = command.spawn().expect("bash spawns into the scope");
2578        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2579        while scope.member_pids().len() < 3 {
2580            assert!(
2581                std::time::Instant::now() < deadline,
2582                "the scope never held bash and both sleepers: {:?}",
2583                scope.member_pids()
2584            );
2585            std::thread::sleep(std::time::Duration::from_millis(20));
2586        }
2587        (scope, child)
2588    }
2589
2590    #[cfg(target_os = "linux")]
2591    fn watcher_of(scope: &CgroupScope) -> &ScopeWatcher {
2592        scope
2593            .watcher
2594            .as_ref()
2595            .expect("a scope on Linux has a watcher")
2596    }
2597
2598    /// Closing the lifeline is what the kernel does when the runtime dies: the watcher empties the
2599    /// scope with no `Drop`, no `kill_all` and no call from the runtime.
2600    #[cfg(target_os = "linux")]
2601    fn assert_a_cut_lifeline_empties_the_scope(test_name: &str, fallback: bool) {
2602        if skip_without_host_support(test_name) {
2603            return;
2604        }
2605        let (scope, mut child) = scope_with_sleepers(test_name, fallback);
2606        let members = scope.member_pids();
2607        watcher_of(&scope).cut_lifeline();
2608        assert!(
2609            scope.wait_until_empty(std::time::Duration::from_secs(5)),
2610            "the watcher left {:?} of {members:?} in the scope",
2611            scope.member_pids()
2612        );
2613        for pid in members {
2614            assert!(
2615                !Path::new(&format!("/proc/{pid}")).exists()
2616                    || std::fs::read_to_string(format!("/proc/{pid}/stat"))
2617                        .is_ok_and(|stat| stat.contains(") Z ")),
2618                "{pid} is still running"
2619            );
2620        }
2621        let status = child.wait().expect("bash is reaped");
2622        assert_eq!(
2623            std::os::unix::process::ExitStatusExt::signal(&status),
2624            Some(libc::SIGKILL)
2625        );
2626    }
2627
2628    #[cfg(target_os = "linux")]
2629    #[test]
2630    fn scope_watcher_kills_the_scope_through_cgroup_kill_when_the_lifeline_closes() {
2631        assert_a_cut_lifeline_empties_the_scope(
2632            "scope_watcher_kills_the_scope_through_cgroup_kill_when_the_lifeline_closes",
2633            false,
2634        );
2635    }
2636
2637    #[cfg(target_os = "linux")]
2638    #[test]
2639    fn scope_watcher_kills_the_scope_by_freezing_when_the_lifeline_closes() {
2640        assert_a_cut_lifeline_empties_the_scope(
2641            "scope_watcher_kills_the_scope_by_freezing_when_the_lifeline_closes",
2642            true,
2643        );
2644    }
2645
2646    /// The watcher sits outside the scope it kills, in a process group of its own, holding
2647    /// `/dev/null` on 0–2, its lifeline's read end and the scope's control files — none of this
2648    /// process's descriptors.
2649    #[cfg(target_os = "linux")]
2650    #[test]
2651    #[allow(unsafe_code)]
2652    fn scope_watcher_holds_only_its_own_descriptors_outside_the_scope() {
2653        if skip_without_host_support(
2654            "scope_watcher_holds_only_its_own_descriptors_outside_the_scope",
2655        ) {
2656            return;
2657        }
2658        // A descriptor of this process's own that the watcher must not hold.
2659        let own = tempfile::tempfile().unwrap();
2660        let own_target = std::fs::read_link(format!(
2661            "/proc/self/fd/{}",
2662            std::os::fd::AsRawFd::as_raw_fd(&own)
2663        ))
2664        .unwrap();
2665        let (scope, mut child) = scope_with_sleepers("ses_watcher_fds", false);
2666        let pid = watcher_of(&scope).pid;
2667
2668        let fd_dir = format!("/proc/{pid}/fd");
2669        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
2670        let targets = loop {
2671            let targets: Vec<(String, PathBuf)> = std::fs::read_dir(&fd_dir)
2672                .unwrap()
2673                .filter_map(Result::ok)
2674                .filter_map(|entry| {
2675                    let target = std::fs::read_link(entry.path()).ok()?;
2676                    Some((entry.file_name().to_string_lossy().into_owned(), target))
2677                })
2678                .collect();
2679            let settled = targets.iter().all(|(_, target)| {
2680                target == Path::new("/dev/null")
2681                    || target.to_string_lossy().starts_with("pipe:")
2682                    || target.starts_with(scope.path())
2683            });
2684            if settled || std::time::Instant::now() >= deadline {
2685                break targets;
2686            }
2687            std::thread::sleep(std::time::Duration::from_millis(20));
2688        };
2689        let mut numbers: Vec<u32> = targets
2690            .iter()
2691            .map(|(name, _)| name.parse().unwrap())
2692            .collect();
2693        numbers.sort_unstable();
2694        assert!(numbers.starts_with(&[0, 1, 2]), "{targets:?}");
2695        for (name, target) in &targets {
2696            assert_ne!(target, &own_target, "fd {name}");
2697            if ["0", "1", "2"].contains(&name.as_str()) {
2698                assert_eq!(target, Path::new("/dev/null"), "fd {name}");
2699            } else {
2700                assert!(
2701                    target.to_string_lossy().starts_with("pipe:")
2702                        || target.starts_with(scope.path()),
2703                    "fd {name} -> {}",
2704                    target.display()
2705                );
2706            }
2707        }
2708        let pipes = targets
2709            .iter()
2710            .filter(|(_, target)| target.to_string_lossy().starts_with("pipe:"))
2711            .count();
2712        assert_eq!(pipes, 1, "the lifeline is its only pipe: {targets:?}");
2713
2714        assert!(!scope.member_pids().contains(&pid));
2715        // SAFETY: `getpgid` takes an integer and dereferences nothing.
2716        assert_eq!(
2717            unsafe { libc::getpgid(pid) },
2718            pid,
2719            "a process group of its own"
2720        );
2721
2722        scope.kill_all().unwrap();
2723        child.wait().unwrap();
2724    }
2725
2726    /// Dropping the scope reaps its watcher: a second wait finds no such child.
2727    #[cfg(target_os = "linux")]
2728    #[test]
2729    #[allow(unsafe_code)]
2730    fn scope_watcher_is_reaped_when_the_scope_drops() {
2731        if skip_without_host_support("scope_watcher_is_reaped_when_the_scope_drops") {
2732            return;
2733        }
2734        let (scope, mut child) = scope_with_sleepers("ses_watcher_reaped", false);
2735        let pid = watcher_of(&scope).pid;
2736        let path = scope.path().to_path_buf();
2737        drop(Arc::try_unwrap(scope).expect("the test holds the only reference"));
2738        child.wait().unwrap();
2739        let mut status = 0;
2740        // SAFETY: `pid` is an integer and `status` a live local.
2741        let waited = unsafe { libc::waitpid(pid, &mut status, libc::WNOHANG) };
2742        assert_eq!(waited, -1);
2743        assert_eq!(
2744            std::io::Error::last_os_error().raw_os_error(),
2745            Some(libc::ECHILD)
2746        );
2747        assert!(!path.exists(), "the scope directory is removed");
2748    }
2749
2750    /// Swap is bounded at zero whatever the manifest declares, beside a `memory.max` that is the
2751    /// declared ceiling itself.
2752    #[test]
2753    fn the_scope_limits_bound_swap_at_zero() {
2754        let declared = HostResourceLimits {
2755            cgroup_memory_bytes: 268_435_456,
2756            ..HostResourceLimits::default()
2757        };
2758        for limits in [HostResourceLimits::default(), declared] {
2759            let writes: Vec<(&str, String)> = scope_limits(&limits)
2760                .into_iter()
2761                .map(|limit| (limit.file, limit.value))
2762                .collect();
2763            assert!(
2764                writes.contains(&("memory.swap.max", "0".to_string())),
2765                "writes were {writes:?}"
2766            );
2767            assert!(writes.contains(&("memory.max", limits.cgroup_memory_bytes.to_string())));
2768            assert_eq!(
2769                writes.iter().map(|(file, _)| *file).collect::<Vec<_>>(),
2770                ["memory.max", "memory.swap.max", "pids.max", "cpu.max"]
2771            );
2772        }
2773        let absent_ok: Vec<&str> = scope_limits(&HostResourceLimits::default())
2774            .into_iter()
2775            .filter(|limit| limit.absent_ok)
2776            .map(|limit| limit.file)
2777            .collect();
2778        assert_eq!(absent_ok, ["memory.swap.max"]);
2779    }
2780
2781    #[test]
2782    fn active_swap_areas_are_the_lines_below_the_header() {
2783        let header = "Filename\t\t\t\tType\t\tSize\t\tUsed\t\tPriority\n";
2784        assert_eq!(count_swap_areas(header), 0);
2785        assert_eq!(count_swap_areas(""), 0);
2786        assert_eq!(
2787            count_swap_areas(&format!(
2788                "{header}/swapfile                               file\t\t33554428\t\t0\t\t-2\n"
2789            )),
2790            1
2791        );
2792    }
2793
2794    /// The unit name systemd is asked for stays inside the `murmur-*` convention operators
2795    /// already use to find this runtime's cgroup directories, and stays unique per request.
2796    #[cfg(target_os = "linux")]
2797    #[test]
2798    fn transient_scope_unit_names_are_murmur_prefixed_and_unique() {
2799        let first = transient_scope_unit_name();
2800        let second = transient_scope_unit_name();
2801        assert!(first.starts_with(&format!("murmur-{}-", std::process::id())));
2802        assert!(first.ends_with(".scope"));
2803        assert_ne!(first, second);
2804    }
2805
2806    #[test]
2807    fn unified_cgroup_path_is_read_from_the_zero_hierarchy_line() {
2808        let v2_only = "0::/user.slice/user-1000.slice/user@1000.service/app.slice/mur.scope\n";
2809        assert_eq!(
2810            parse_unified_cgroup_path(v2_only).as_deref(),
2811            Some("/user.slice/user-1000.slice/user@1000.service/app.slice/mur.scope")
2812        );
2813
2814        let hybrid = "12:pids:/user.slice\n11:memory:/user.slice\n0::/user.slice/session.scope\n";
2815        assert_eq!(
2816            parse_unified_cgroup_path(hybrid).as_deref(),
2817            Some("/user.slice/session.scope")
2818        );
2819
2820        let v1_only = "12:pids:/user.slice\n11:memory:/user.slice\n";
2821        assert_eq!(parse_unified_cgroup_path(v1_only), None);
2822    }
2823
2824    #[test]
2825    fn cgroup2_mount_falls_back_to_the_conventional_path() {
2826        let mounts = "cgroup2 /custom/cgroup cgroup2 rw,nsdelegate 0 0\n";
2827        assert_eq!(parse_cgroup2_mount(mounts), "/custom/cgroup");
2828        assert_eq!(
2829            parse_cgroup2_mount("proc /proc proc rw 0 0\n"),
2830            "/sys/fs/cgroup"
2831        );
2832    }
2833
2834    #[test]
2835    fn missing_controllers_reports_only_what_is_absent() {
2836        assert_eq!(
2837            missing_controllers("cpu memory", REQUIRED_CONTROLLERS),
2838            vec!["pids".to_string()]
2839        );
2840        assert!(missing_controllers("cpu io memory pids", REQUIRED_CONTROLLERS).is_empty());
2841        assert_eq!(
2842            missing_controllers("", REQUIRED_CONTROLLERS),
2843            vec!["memory".to_string(), "pids".to_string(), "cpu".to_string()]
2844        );
2845    }
2846
2847    #[test]
2848    fn event_counters_parse_the_named_key_only() {
2849        let memory_events = "low 0\nhigh 0\nmax 12\noom 3\noom_kill 2\n";
2850        assert_eq!(parse_event_counter(memory_events, "oom_kill"), 2);
2851        assert_eq!(parse_event_counter(memory_events, "max"), 12);
2852        assert_eq!(parse_event_counter("max 7\n", "max"), 7);
2853        assert_eq!(parse_event_counter("", "oom_kill"), 0);
2854        assert_eq!(parse_event_counter("oom_kill\n", "oom_kill"), 0);
2855    }
2856
2857    /// Attribution keys on the delta, not the absolute counter: a session-cumulative total would
2858    /// mis-attribute every later call once any earlier one had been OOM-killed.
2859    #[test]
2860    fn attribution_uses_the_delta_across_one_call() {
2861        let before = CgroupEventCounters {
2862            oom_kill: 1,
2863            pids_max: 4,
2864        };
2865        assert_eq!(before.attribution_since(before), None);
2866        assert_eq!(
2867            CgroupEventCounters {
2868                oom_kill: 2,
2869                pids_max: 4
2870            }
2871            .attribution_since(before),
2872            Some("cgroup_memory_bytes")
2873        );
2874        assert_eq!(
2875            CgroupEventCounters {
2876                oom_kill: 1,
2877                pids_max: 5
2878            }
2879            .attribution_since(before),
2880            Some("cgroup_pids_max")
2881        );
2882    }
2883
2884    /// A scope with no directory behind it: occupancy needs no kernel, and `Drop` skips the
2885    /// `rmdir` for an empty path.
2886    fn scope_without_kernel() -> CgroupScope {
2887        CgroupScope {
2888            path: PathBuf::new(),
2889            procs_fd: None,
2890            occupancy: Arc::default(),
2891            #[cfg(target_os = "linux")]
2892            watcher: None,
2893        }
2894    }
2895
2896    #[test]
2897    fn occupancy_alone_is_exclusive() {
2898        let scope = scope_without_kernel();
2899        let call = scope.enter();
2900        assert!(call.exclusive());
2901    }
2902
2903    #[test]
2904    fn occupancy_entering_beside_another_is_not_exclusive() {
2905        let scope = scope_without_kernel();
2906        let first = scope.enter();
2907        let second = scope.enter();
2908        assert!(!second.exclusive(), "someone was already inside");
2909        drop(first);
2910        assert!(
2911            !second.exclusive(),
2912            "the sibling leaving does not clean the window it shared"
2913        );
2914    }
2915
2916    #[test]
2917    fn occupancy_someone_entering_during_the_window_makes_it_shared() {
2918        let scope = scope_without_kernel();
2919        let first = scope.enter();
2920        assert!(first.exclusive());
2921        drop(scope.enter());
2922        assert!(
2923            !first.exclusive(),
2924            "a call that entered and left inside this window could have moved the counters"
2925        );
2926    }
2927
2928    #[test]
2929    fn occupancy_drop_releases_the_scope() {
2930        let scope = scope_without_kernel();
2931        drop(scope.enter());
2932        let next = scope.enter();
2933        assert!(
2934            next.exclusive(),
2935            "an earlier call that has left does not share this window"
2936        );
2937    }
2938
2939    /// The guard is owned: it moves to a demoted command's thread and keeps the scope occupied
2940    /// there after the scope's borrow has ended.
2941    #[test]
2942    fn occupancy_guard_outlives_its_borrow_on_another_thread() {
2943        let scope = scope_without_kernel();
2944        let demoted = scope.enter();
2945        let held = std::thread::spawn(move || demoted);
2946        let demoted = held.join().unwrap();
2947        let foreground = scope.enter();
2948        assert!(!foreground.exclusive());
2949        assert!(!demoted.exclusive());
2950    }
2951
2952    #[test]
2953    fn scope_dir_name_is_sanitized_and_never_empty() {
2954        assert!(scope_dir_name("ses_abc123").starts_with("murmur-ses_abc123-"));
2955        assert!(scope_dir_name("../escape").starts_with("murmur-.._escape-"));
2956        assert!(!scope_dir_name("../escape").contains('/'));
2957        assert!(scope_dir_name("").starts_with("murmur-"));
2958    }
2959
2960    /// A subprocess inherits its parent's cgroup, so a `mur` spawned by a runtime that already
2961    /// stepped aside starts life *inside* the supervisor leaf. Reading that as its delegated base
2962    /// would nest another leaf inside it, one per generation, until nothing is delegated.
2963    #[test]
2964    fn delegated_base_ascends_out_of_inherited_supervisor_leaves() {
2965        let base = PathBuf::from("/sys/fs/cgroup/user.slice/app.slice/mur.scope");
2966
2967        assert_eq!(ascend_out_of_supervisor_leaves(base.clone()), base);
2968        assert_eq!(
2969            ascend_out_of_supervisor_leaves(base.join(SUPERVISOR_LEAF)),
2970            base
2971        );
2972        assert_eq!(
2973            ascend_out_of_supervisor_leaves(base.join(SUPERVISOR_LEAF).join(SUPERVISOR_LEAF)),
2974            base,
2975            "a base already nested by an earlier build must still resolve to the real root"
2976        );
2977    }
2978
2979    /// Two scopes must never share a directory even when handed the same id: `Drop` removes the
2980    /// scope by path, so a collision would have one session delete the cgroup still bounding
2981    /// another's subprocess tree.
2982    #[test]
2983    fn scope_dir_name_is_unique_per_call_for_one_id() {
2984        let first = scope_dir_name("p");
2985        let second = scope_dir_name("p");
2986        assert_ne!(
2987            first, second,
2988            "same plan id must not reuse a scope directory"
2989        );
2990    }
2991
2992    #[test]
2993    fn pid_is_formatted_without_allocating() {
2994        let mut buf = [0u8; 24];
2995        let len = format_pid(4321, &mut buf);
2996        assert_eq!(&buf[..len], b"4321\n");
2997
2998        let len = format_pid(7, &mut buf);
2999        assert_eq!(&buf[..len], b"7\n");
3000    }
3001
3002    #[test]
3003    fn device_numbers_use_the_wide_glibc_encoding() {
3004        // 8:0 (`/dev/sda`) encodes as 0x800 under the 12+20 bit layout.
3005        assert_eq!(device_major_minor(0x800), (8, 0));
3006        // 259:3 (`nvme0n1p3`) needs the wide major field, which the legacy 8+8 layout truncates.
3007        assert_eq!(device_major_minor((259 << 8) | 3), (259, 3));
3008    }
3009}