From c8d81dcd991e81e6f7ae4ab4b972aade103e757e Mon Sep 17 00:00:00 2001
From: James Gober
Date: Sun, 29 Nov 2026 14:05:53 -0500
Subject: [PATCH 1/9] Hardening for 0.8.0
The guard creates and checks a private lock directory on Windows, and
names a pid only when that process can be the other copy. Memory
readings read only what they return. Error codes are taken straight
after the failing call. Windows disk busy time survives clock steps.
Every threat has a named attack test, docs/SECURITY.md lists the
defences and their costs, and CI gains an AddressSanitizer job, the
24-hour fuzz rounds, and a soak run.
---
.github/workflows/ci.yml | 32 ++++++
.github/workflows/fuzz-round.yml | 84 ++++++++++++++++
.github/workflows/fuzz.yml | 70 ++++++++++++-
CHANGELOG.md | 51 +++++++++-
Cargo.toml | 5 +-
README.md | 16 ++-
bench/src/bin/soak.rs | 90 +++++++++++++++++
dev/PLAN.md | 10 +-
dev/ROADMAP.md | 4 +-
docs/API.md | 10 +-
docs/PLATFORM-NOTES.md | 3 +
docs/README.md | 14 +++
docs/SECURITY.md | 43 ++++++++
src/error.rs | 8 +-
src/lib.rs | 7 +-
src/linux/mem.rs | 58 ++++++++++-
src/linux/process.rs | 29 +++++-
src/linux/virt.rs | 2 +-
src/mem.rs | 41 +++++++-
src/parse/smbios.rs | 2 +-
src/process/guard.rs | 165 +++++++++++++++++++++++++++----
src/summary.rs | 10 +-
src/sys/apple/cpu.rs | 20 ++--
src/sys/apple/disk.rs | 7 +-
src/sys/apple/host.rs | 40 +++++---
src/sys/apple/iokit.rs | 70 +++++++++----
src/sys/apple/mem.rs | 21 +++-
src/sys/apple/mod.rs | 13 ++-
src/sys/apple/net.rs | 10 +-
src/sys/apple/power.rs | 18 ++--
src/sys/apple/process.rs | 48 ++++++---
src/sys/freebsd/cpu.rs | 6 +-
src/sys/freebsd/ffi.rs | 2 +
src/sys/freebsd/host.rs | 7 +-
src/sys/freebsd/mem.rs | 22 ++++-
src/sys/freebsd/mod.rs | 7 +-
src/sys/freebsd/process.rs | 20 ++--
src/sys/linux/live.rs | 6 ++
src/sys/unsupported.rs | 5 +
src/sys/windows/disk.rs | 81 ++++++++++++---
src/sys/windows/ffi.rs | 65 ++++++++++++
src/sys/windows/firmware.rs | 12 ++-
src/sys/windows/mod.rs | 161 ++++++++++++++++++++++++++++++
src/sys/windows/report.rs | 33 ++++---
src/virt.rs | 9 +-
tests/descriptors.rs | 2 +-
46 files changed, 1265 insertions(+), 174 deletions(-)
create mode 100644 .github/workflows/fuzz-round.yml
create mode 100644 bench/src/bin/soak.rs
create mode 100644 docs/README.md
create mode 100644 docs/SECURITY.md
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 1cca18e..9b7da5c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -262,6 +262,38 @@ jobs:
MIRIFLAGS: "-Zmiri-disable-isolation"
PROPTEST_CASES: "16"
+ asan:
+ name: AddressSanitizer (${{ matrix.name }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - name: Linux
+ os: ubuntu-latest
+ target: x86_64-unknown-linux-gnu
+ leaks: "1"
+ # LeakSanitizer does not run on macOS.
+ - name: macOS
+ os: macos-latest
+ target: aarch64-apple-darwin
+ leaks: "0"
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dtolnay/rust-toolchain@nightly
+ - uses: Swatinem/rust-cache@v2
+ with:
+ key: asan
+ # Every test, the FFI backends included, with each allocation and
+ # access checked (threat T12). Naming the target keeps build scripts
+ # out of the instrumented build.
+ - name: Tests under AddressSanitizer
+ run: cargo test --target ${{ matrix.target }} --all-features --lib --tests
+ env:
+ RUSTFLAGS: "-Zsanitizer=address"
+ ASAN_OPTIONS: "detect_leaks=${{ matrix.leaks }}:detect_stack_use_after_return=1"
+ PROPTEST_CASES: "32"
+
# A DLL in the import table that a stripped-down Windows lacks stops the whole
# program before `main`, so a real binary runs where the fewest DLLs exist.
nanoserver:
diff --git a/.github/workflows/fuzz-round.yml b/.github/workflows/fuzz-round.yml
new file mode 100644
index 0000000..8a1443d
--- /dev/null
+++ b/.github/workflows/fuzz-round.yml
@@ -0,0 +1,84 @@
+name: Fuzz round
+
+# One round of the long fuzz run (fuzz.yml, `rounds` input): every target for
+# `seconds`, starting from the corpus the previous round left in the cache.
+on:
+ workflow_call:
+ inputs:
+ seconds:
+ type: string
+ required: true
+ round:
+ type: string
+ required: true
+
+env:
+ FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
+
+jobs:
+ fuzz:
+ name: Round ${{ inputs.round }} (${{ matrix.target }})
+ runs-on: ubuntu-latest
+ timeout-minutes: 345
+ strategy:
+ fail-fast: false
+ # Eight at a time, so the long run leaves runners for other work.
+ max-parallel: 8
+ matrix:
+ target:
+ - os_release
+ - release
+ - version
+ - cpu_list
+ - cpuinfo
+ - cpu_name
+ - proc_status
+ - mountinfo
+ - cgroup
+ - pid_file
+ - instance_id
+ - bytes_display
+ - procfs
+ - smbios
+ - uevent
+ - resolv
+ - utmp
+ - windows_zones
+ - fingerprint
+ - pci_ids
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dtolnay/rust-toolchain@nightly
+ - uses: Swatinem/rust-cache@v2
+ with:
+ workspaces: fuzz
+ key: ${{ matrix.target }}
+ - name: Install cargo-fuzz
+ uses: taiki-e/install-action@v2
+ with:
+ tool: cargo-fuzz
+ - name: Restore the corpus
+ uses: actions/cache/restore@v4
+ with:
+ path: fuzz/corpus/${{ matrix.target }}
+ key: corpus-${{ matrix.target }}-${{ github.run_id }}-${{ inputs.round }}
+ restore-keys: corpus-${{ matrix.target }}-
+ - name: Fuzz
+ run: |
+ mkdir -p "fuzz/corpus/${{ matrix.target }}"
+ echo "corpus: $(ls "fuzz/corpus/${{ matrix.target }}" | wc -l) inputs"
+ cargo fuzz run --target x86_64-unknown-linux-gnu ${{ matrix.target }} \
+ "fuzz/corpus/${{ matrix.target }}" tests/fixtures -- \
+ -max_total_time=${{ inputs.seconds }} -print_final_stats=1
+ - name: Save the corpus
+ if: always()
+ uses: actions/cache/save@v4
+ with:
+ path: fuzz/corpus/${{ matrix.target }}
+ key: corpus-${{ matrix.target }}-${{ github.run_id }}-${{ inputs.round }}
+ - uses: actions/upload-artifact@v5
+ if: failure()
+ with:
+ name: crash-round${{ inputs.round }}-${{ matrix.target }}
+ path: fuzz/artifacts/
+ retention-days: 30
diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml
index dc3429a..a9c4ce3 100644
--- a/.github/workflows/fuzz.yml
+++ b/.github/workflows/fuzz.yml
@@ -1,8 +1,10 @@
name: Fuzz
-# Ten minutes per parser every night (dev/PLAN.md section 19.1); 24 hours per
-# target is run by hand before 0.8. Crashes are uploaded as artifacts and fixed
-# test-first (fuzz/README.md).
+# Ten minutes per parser every night (dev/PLAN.md section 19.1). The long runs
+# before a release (`long`): 24 hours of fuzzing per target, as five chained
+# rounds of fuzz-round.yml, each starting from the corpus the last one saved,
+# and the soak run (bench/src/bin/soak.rs) for as long as a hosted job may run.
+# Crashes are uploaded as artifacts and fixed test-first (fuzz/README.md).
on:
schedule:
- cron: "17 3 * * *"
@@ -11,6 +13,10 @@ on:
seconds:
description: Seconds per target
default: "600"
+ long:
+ description: 24 hours per target in five rounds, and the soak runs
+ type: boolean
+ default: false
env:
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
@@ -18,6 +24,7 @@ env:
jobs:
fuzz:
name: Fuzz (${{ matrix.target }})
+ if: ${{ !inputs.long }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
@@ -42,6 +49,7 @@ jobs:
- utmp
- windows_zones
- fingerprint
+ - pci_ids
steps:
- uses: actions/checkout@v5
- uses: dtolnay/rust-toolchain@nightly
@@ -66,3 +74,59 @@ jobs:
name: crash-${{ matrix.target }}
path: fuzz/artifacts/
retention-days: 30
+
+ round1:
+ if: ${{ inputs.long }}
+ uses: ./.github/workflows/fuzz-round.yml
+ with:
+ seconds: "17400"
+ round: "1"
+
+ round2:
+ needs: round1
+ if: ${{ !cancelled() && inputs.long }}
+ uses: ./.github/workflows/fuzz-round.yml
+ with:
+ seconds: "17400"
+ round: "2"
+
+ round3:
+ needs: round2
+ if: ${{ !cancelled() && inputs.long }}
+ uses: ./.github/workflows/fuzz-round.yml
+ with:
+ seconds: "17400"
+ round: "3"
+
+ round4:
+ needs: round3
+ if: ${{ !cancelled() && inputs.long }}
+ uses: ./.github/workflows/fuzz-round.yml
+ with:
+ seconds: "17400"
+ round: "4"
+
+ round5:
+ needs: round4
+ if: ${{ !cancelled() && inputs.long }}
+ uses: ./.github/workflows/fuzz-round.yml
+ with:
+ seconds: "17400"
+ round: "5"
+
+ soak:
+ name: Soak (${{ matrix.os }})
+ if: ${{ inputs.long }}
+ runs-on: ${{ matrix.os }}
+ timeout-minutes: 355
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ steps:
+ - uses: actions/checkout@v5
+ - uses: dtolnay/rust-toolchain@stable
+ - name: Soak, 5 h 40 min (the hosted job limit is 6 h)
+ working-directory: bench
+ shell: bash
+ run: cargo run --release --bin soak -- 20400
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 81dd6ae..27d3aa3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,54 @@
---
+## [0.8.0] - 2026-11-29
+
+Hardening: every threat in the model has a named attack test, the process
+guard is as strict on Windows as on Unix, and the release went through a
+24-hour fuzz run per parser and a soak run.
+
+### Added
+
+- `docs/SECURITY.md`: what the crate guarantees, every threat with its
+ defence, its cost, and its test, and how to report a vulnerability.
+- An AddressSanitizer job on Linux and macOS that runs every test.
+- A soak run (`bench/src/bin/soak.rs`) that calls every reading in a loop and
+ fails if memory or open descriptors grow, and the long runs before a release
+ (`fuzz.yml` with `long`: 24 hours per fuzz target, and the soak run).
+
+### Changed
+
+- **Windows process guard:** a missing lock directory is created for this
+ account, `SYSTEM`, and `Administrators` alone, and a lock directory another
+ account can change is refused, as group- or world-writable directories are
+ on Unix. A program that used a directory under `C:\ProgramData` directly
+ must move its lock to a private directory. The default directory is created
+ the same way.
+- `Error::AlreadyRunning` names a pid only when that process is running and
+ started before its pid file was written; otherwise the pid is `None`. It
+ never names a process that cannot be the other copy.
+- `mem::total()`, `mem::host_total()`, and `mem::limit()` read only what they
+ return: no VM counters for a total, and on Linux no soft or swap limit files
+ for the total. macOS and FreeBSD read the installed memory once.
+- The minimum Windows is 10 version 1511, or Server 2016.
+- Requires path-lib 1.3 (with the `guard` feature).
+
+### Fixed
+
+- Windows disk busy time no longer reads 0% for a while after the clock is set
+ back, or one spike after it is set forward.
+- Error codes are read straight after the call that failed, and calls that set
+ none (`getloadavg`, `localtime_r`, a `proc_listallpids` or `proc_pidinfo`
+ answer of 0) report `Malformed` instead of a stale or zero code.
+- FreeBSD `disk::io_totals()` asks again when a disk comes or goes during the
+ read, instead of failing once.
+- A Windows drive whose product string has no terminator no longer carries the
+ next fields into the drive's name, and only a cloud's fixed asset tag is kept
+ from the firmware table.
+- The message for a user without a home directory had stray spaces.
+
+---
+
## [0.7.0] - 2026-11-11
Optimisation: every reading measured against the crates people use for it, the
@@ -406,7 +454,8 @@ The scaffold and the plan. No functional code yet.
`dev/ROADMAP.md`.
- `tests/fixtures/` and `fuzz/` skeletons.
-[Unreleased]: https://github.com/jamesgober/sys-lib/compare/v0.7.0...HEAD
+[Unreleased]: https://github.com/jamesgober/sys-lib/compare/v0.8.0...HEAD
+[0.8.0]: https://github.com/jamesgober/sys-lib/compare/v0.7.0...v0.8.0
[0.7.0]: https://github.com/jamesgober/sys-lib/compare/v0.6.0...v0.7.0
[0.6.0]: https://github.com/jamesgober/sys-lib/compare/v0.5.1...v0.6.0
[0.5.1]: https://github.com/jamesgober/sys-lib/compare/v0.5.0...v0.5.1
diff --git a/Cargo.toml b/Cargo.toml
index ec33ab3..f3f0ee7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,7 +3,7 @@
# =============================================================================
[package]
name = "sys-lib"
-version = "0.7.0"
+version = "0.8.0"
# Minimum Supported Rust Version (MSRV)
# 1.89: `std::fs::File::lock` and `File::try_lock` are stable from 1.89.0, so
@@ -103,7 +103,7 @@ device-id = ["dep:crypt-io"]
clock-lib = { version = "1.1", optional = true, default-features = false, features = ["std"] }
crypt-io = { version = "1.2.2", optional = true, default-features = false, features = ["std", "mac-blake3", "zeroize"] }
id-forge = { version = "1.0", optional = true, default-features = false, features = ["ulid"] }
-path-lib = { version = "1.0", optional = true }
+path-lib = { version = "1.3", optional = true }
# DEV DEPENDENCIES
@@ -129,6 +129,7 @@ windows-sys = { version = "0.61", features = [
"Win32_NetworkManagement_Ndis",
"Win32_Networking_WinSock",
"Win32_Security",
+ "Win32_Security_Authorization",
"Win32_System_Diagnostics_Debug",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_LibraryLoader",
diff --git a/README.md b/README.md
index 6469cef..0b00e0e 100644
--- a/README.md
+++ b/README.md
@@ -9,9 +9,10 @@
-
+
+
@@ -29,7 +30,7 @@
MSRV is 1.89+ (Rust 2024 edition). unsafe is denied at the crate root and allowed only in one OS module per platform.
- Status: 0.7.0, feature complete and measured. The boot kit, the live readings (memory, CPU, disks, network, pressure, this process), detection and identity (virtualization, form factor, topology, power, DNS, the time zone, firmware, launch context, summary(), an application-scoped device id), and now the server readiness, benchmark environment, and security posture reports, temperatures, graphics adapters, and explicit roots for monitoring agents. Linux (64-bit, and 32-bit glibc on x86 and Arm), macOS, Windows, and FreeBSD; Android and iOS best effort. 0.7 measured every reading against the crates people use for it (docs/PERFORMANCE.md); 0.8 to 1.0 harden; the API is in docs/API.md. Design: dev/PLAN.md; schedule: dev/ROADMAP.md.
+ Status: 0.8.0, feature complete, measured, and hardened. The boot kit, the live readings (memory, CPU, disks, network, pressure, this process), detection and identity (virtualization, form factor, topology, power, DNS, the time zone, firmware, launch context, summary(), an application-scoped device id), and now the server readiness, benchmark environment, and security posture reports, temperatures, graphics adapters, and explicit roots for monitoring agents. Linux (64-bit, and 32-bit glibc on x86 and Arm), macOS, Windows, and FreeBSD; Android and iOS best effort. 0.7 measured every reading against the crates people use for it (docs/PERFORMANCE.md); 0.8 hardened it, with every threat and its test in docs/SECURITY.md; the API is in docs/API.md. Design: dev/PLAN.md; schedule: dev/ROADMAP.md.
@@ -40,15 +41,22 @@
Static facts read once and cached (OS name and version, CPU model, core counts, CPU features, caches, topology, virtualization, form factor); live readings read fresh on every call with no allocation for single values (memory, swap, uptime, load, disk space, this process's memory and CPU time); caller-owned samplers for values that need two readings (CPU usage, network rates); the boot kit (build info, instance info, process guard); and an opt-in device id derived with a keyed hash, so raw hardware identifiers never leave the library. It does not read other processes' details, change system settings, or run in the background; the few readings that walk the process table (`host::processes()` on macOS and FreeBSD, `process::threads()` on Windows) say so and their cost.
-## Quick start
+## Installation
Cargo's rename makes the crate `sys` in your code:
```toml
[dependencies]
-sys = { package = "sys-lib", version = "0.7" }
+sys = { package = "sys-lib", version = "0.8" }
+
+# The application-scoped device id (brings crypt-io's BLAKE3 stack):
+sys = { package = "sys-lib", version = "0.8", features = ["device-id"] }
```
+The default features are `instance` (instance info) and `guard` (the process guard). `default-features = false` keeps every reading and report and brings no dependency at all.
+
+## Quick start
+
Tier 1 is one plain call per fact. Static facts are read once and cached, so
every later call costs about a nanosecond:
diff --git a/bench/src/bin/soak.rs b/bench/src/bin/soak.rs
new file mode 100644
index 0000000..cc682a0
--- /dev/null
+++ b/bench/src/bin/soak.rs
@@ -0,0 +1,90 @@
+//! The soak run (dev/PLAN.md section 19, threat T12): every reading in a loop
+//! for `seconds` (default 600), with this process's resident memory and open
+//! descriptors (handles on Windows) sampled every 30 s. After the first tenth of
+//! the run, neither may grow: descriptors not at all, memory by at most 10%
+//! plus 4 MiB (allocator noise). Exits 1 when either grows.
+//!
+//! `cargo run --release --bin soak -- 28800` for the 8 hours of the release
+//! checklist.
+
+use std::{
+ process::ExitCode,
+ time::{Duration, Instant},
+};
+
+use sys_lib as sys;
+
+fn every_reading(cpu: &mut sys::cpu::Sampler, disk: &mut sys::disk::IoSampler, net: &mut sys::net::Sampler) {
+ let _ = (sys::os::info(), sys::os::is_64bit(), sys::os::form_factor());
+ let _ = (sys::cpu::count(), sys::cpu::name(), sys::cpu::topology());
+ let _ = (sys::cpu::load(), sys::cpu::times(), sys::cpu::frequency());
+ let _ = (sys::cpu::current_frequency(), sys::cpu::quota(), sys::cpu::pressure());
+ let _ = (sys::mem::snapshot(), sys::mem::activity(), sys::mem::events());
+ let _ = (sys::mem::huge_pages(), sys::mem::modules(), sys::mem::pressure());
+ let _ = (sys::mem::total(), sys::mem::limit(), sys::mem::host_total());
+ let _ = (sys::disk::list(), sys::disk::of("."), sys::disk::space("."));
+ let _ = (sys::disk::io_totals(), sys::disk::io_counters(), sys::disk::pressure());
+ let _ = (sys::net::interfaces(), sys::net::totals(), sys::net::counters());
+ let _ = (sys::net::connections(), sys::net::primary(), sys::net::dns());
+ let _ = (sys::host::name(), sys::host::uptime(), sys::host::processes());
+ let _ = (sys::host::open_files(), sys::host::timezone(), sys::host::sessions());
+ let _ = (sys::host::clock_sync(), sys::host::model(), sys::host::firmware());
+ let _ = (sys::process::user(), sys::process::is_elevated(), sys::process::limits());
+ let _ = (sys::process::memory_detail(), sys::process::cpu_time(), sys::process::io());
+ let _ = (sys::process::threads(), sys::process::launch());
+ let _ = (sys::virt::detect(), sys::virt::cloud());
+ let _ = (sys::power::batteries(), sys::power::on_ac());
+ let _ = (sys::sensors::temperatures(), sys::gpu::list());
+ let _ = (sys::security::posture(), sys::bench::environment(), sys::summary());
+ let _ = sys::readiness::report_for(sys::readiness::Profile::Database, ".");
+ let _ = (sys::device::id("com.example.soak"), sys::device::report());
+ let _ = (cpu.sample(), disk.sample(), net.sample());
+}
+
+/// Resident bytes and open descriptors now.
+fn usage() -> (u64, usize) {
+ let resident = sys::process::memory().map_or(0, |b| b.raw());
+ let files = sys::process::open_files().unwrap_or(0);
+ (resident, files)
+}
+
+fn main() -> ExitCode {
+ let seconds: u64 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(600);
+ let run = Duration::from_secs(seconds);
+ let warm = run / 10;
+ let every = Duration::from_secs(30).min(run / 20).max(Duration::from_secs(1));
+ let (mut cpu, mut disk, mut net) = (
+ sys::cpu::Sampler::new().expect("a CPU sampler"),
+ sys::disk::IoSampler::new().expect("a disk sampler"),
+ sys::net::Sampler::new().expect("a network sampler"),
+ );
+ let start = Instant::now();
+ let mut next = start;
+ let (mut calls, mut base, mut worst) = (0u64, (0u64, 0usize), (0u64, 0usize));
+ println!("{:>8} {:>10} {:>12} {:>6}", "seconds", "calls", "resident", "files");
+ while start.elapsed() < run {
+ every_reading(&mut cpu, &mut disk, &mut net);
+ calls += 1;
+ if Instant::now() >= next {
+ next += every;
+ let (resident, files) = usage();
+ println!("{:>8} {calls:>10} {resident:>12} {files:>6}", start.elapsed().as_secs());
+ if start.elapsed() < warm {
+ base = (base.0.max(resident), base.1.max(files));
+ } else {
+ worst = (worst.0.max(resident), worst.1.max(files));
+ }
+ }
+ }
+ let limit = base.0 + base.0 / 10 + (4 << 20);
+ println!(
+ "warm-up peak: {} bytes, {} files; after: {} bytes, {} files; {calls} rounds of every reading",
+ base.0, base.1, worst.0, worst.1
+ );
+ if worst.1 > base.1 || worst.0 > limit {
+ println!("GROWTH: memory above {limit} bytes or descriptors above {}", base.1);
+ return ExitCode::FAILURE;
+ }
+ println!("no growth");
+ ExitCode::SUCCESS
+}
diff --git a/dev/PLAN.md b/dev/PLAN.md
index 3218a4f..57419c8 100644
--- a/dev/PLAN.md
+++ b/dev/PLAN.md
@@ -765,7 +765,7 @@ Attackers: a local unprivileged user; a hostile container image or orchestrator
| T2 | cross-application correlation of device ids | keyed hash with an application-derived key; optional secret | two app ids on one fixture: Hamming distance over many pairs averages about 61 of 122 bits; secret changes the id | one key derivation, under 0.5 µs [est.] |
| T3 | device id used as authentication, then spoofed | documentation; no API implying verification; `AdminReset` as a change event | doc test asserts the warning paragraph; API review checklist | none |
| T4 | path or value injection through the environment (`TZ=../../etc/shadow`, hostile `LANG`, a `HOST_PROC`-style redirect) | no root overrides from the environment; `TZ`, `LC_*`, `LANG` validated and never used to open files; guard and interface names validated | hostile values set: no file outside the fixed list is opened (the fixture root records every path), values rejected or ignored | under 50 ns per validation [est.] |
-| T5 | TOCTOU on `/proc` (pid reuse, files changing between reads) | only `/proc/self` and `/proc/1`; one open per file, read to EOF; combined values clamped to invariants | fixture backend changing values between reads; invariants hold for every interleaving | clamping under 5 ns |
+| T5 | TOCTOU on `/proc` (pid reuse, files changing between reads) | only `/proc/self` and `/proc/1`, and the guard's one read of a lock holder's start time, checked against its pid file (D-112); one open per file, read to EOF; combined values clamped to invariants | fixture backend changing values between reads; invariants hold for every interleaving | clamping under 5 ns |
| T6 | untrusted `/proc` and `/sys` in containers (huge or negative numbers, binary junk, enormous files) | safe, bounded, checked parsers, no recursion, fuzzed | fuzz target per parser; proptest "never panics, never exceeds budget"; fixtures with `u64::MAX`, negatives, NUL bytes, 10 MB files | none measurable |
| T7 | resource exhaustion through huge files or lists (100 000 mounts, 4 096 CPUs) | per-file budget 1 MiB; list budgets (mounts 4 096, interfaces 4 096, CPUs 16 384) checked before allocation; `TooLarge` | fixtures one over each budget: `TooLarge`, allocation within budget (counting allocator) | none in the normal case |
| T8 | hangs on dead network filesystems or removable drives | network filesystems skipped by default; `SEM_FAILCRITICALERRORS` around Windows volume calls | Linux CI with an unreachable NFS mount: `disk::list()` within 100 ms; Windows empty removable drive: no dialog | none |
@@ -1276,3 +1276,11 @@ Other ideas:
| D-109 | 2026-11-11 | `disk::of` (and the readiness and posture lookups) stream mountinfo, keeping only the best match, bounded by 16 MiB read; the entry budget stays on `disk::list` | the whole table counted against `max_mounts`, so past 4 096 mounts (a busy Kubernetes node) a lookup that needs one entry failed |
| D-110 | 2026-11-11 | The readiness report's data-directory filesystem check shows the filesystem only, and `Display` prints control characters in found values as `?` | the mount source can name a server, an account, or a volume GUID, in a report made to be logged; a source with a line break forged report rows |
| D-111 | 2026-11-11 | Windows reads the host name once per process | `GetComputerNameExW` reads the registry (about 100 µs on a busy host) and a new name takes effect only at restart |
+| D-112 | 2026-11-29 | `AlreadyRunning { pid }` names a pid only when that process is running and started no later than the pid file was written (2 s slack); otherwise the file is read again up to 5 times 10 ms apart, then `None` | the holder writes its pid after it locks, a pid file can be left by an earlier run, and pids are reused: a pid that cannot be the holder must never be offered to an operator who will stop it. Reading another process's start time (`/proc//stat`, `proc_pidinfo`, `kern.proc.pid`, `GetProcessTimes`) is the one read of another process, and only on this refusal path |
+| D-113 | 2026-11-29 | On Windows a missing lock directory is created with a protected access list for this account, `SYSTEM`, and `Administrators`, and every lock directory must pass path-lib's `check_owner` with `Others::MayRead`; the default directory comes from `ensure_private` (path-lib 1.3) | the Unix mode and owner checks had no Windows counterpart: under `ProgramData` any local user could create the lock file first, refuse every start, or write the pid an operator is told to stop |
+| D-114 | 2026-11-29 | `MemWant` gains `free` (the host's free and available counters) and `detail` (the soft and swap limits); `mem::total()`, `host_total()`, and `limit()` ask only for what they return, and macOS and FreeBSD read the installed memory once | each Tier 1 reading performs only the reads it needs: the total needed no VM counters (and failed in a sandbox that refuses them), and Linux read one more file per cgroup ancestor for limits it then dropped |
+| D-115 | 2026-11-29 | Windows disk busy time keeps its clock origin while `QueryTime` runs with the uptime, and re-anchors when the two part by more than 1 s | `QueryTime` is the wall clock: a step back of S read 0% busy until S of real busy time had passed, a step forward one spike; the origin keeps the exact driver timestamps in the normal case |
+| D-116 | 2026-11-29 | The minimum Windows is 10 version 1511 and Server 2016; `IsWow64Process2` and the Windows 8 calls stay linked, not looked up | Rust's own standard library needs Windows 10, the 1507 release (LTSB 2015) is out of support, and a run-time lookup per call adds code for no supported system |
+| D-117 | 2026-11-29 | `cpu::available()` on Windows counts every processor of each group a process spans | Windows has no call for a process's per-group affinity; a process restricted to part of several groups (a job object's group affinity) may be over-counted, documented in PLATFORM-NOTES |
+| D-118 | 2026-11-29 | The owners of CoreFoundation, IOKit, and Mach objects (`Cf::new`, `Cf::lent`, `Io::new`, `Io::matching`, `SendRight::from_raw`, `ProcessorInfo::from_raw`) are `unsafe fn` with a `# Safety` section | they release or read whatever they are given; a Get-rule reference passed to `Cf::new` would compile without `unsafe` and be released twice |
+| D-119 | 2026-11-29 | The 24-hour fuzz run is five chained rounds on GitHub's runners (`fuzz.yml`, `long`), eight targets at a time, each round starting from the corpus the last saved | a hosted job stops at 6 hours; eight at a time (about 60 hours for the whole run) leaves runners for every other repository's CI |
diff --git a/dev/ROADMAP.md b/dev/ROADMAP.md
index 10e4564..63d68a8 100644
--- a/dev/ROADMAP.md
+++ b/dev/ROADMAP.md
@@ -86,10 +86,10 @@ Exit: every target in `PLAN.md` section 18 measured and published; at least 20%
## v0.8.0 - Hardening
Exit: no open finding; every threat has a passing attack test.
-- [ ] The remaining items of the independent review of 0.6.0 (tracked with the review).
+- [x] The guard, memory, error-code, and Windows hardening items left from 0.7 (D-112 to D-118).
- [ ] The readings marked open in `docs/PERFORMANCE.md`, macOS `device::id` and `mem::snapshot` first.
- [ ] Fuzzing: 24 hours per target with no finding open (the new parsers included: diskstats, vmstat, PSI, resolv.conf, utmp, sysctl text, SMBIOS types 0, 2, 17).
-- [ ] Attack tests for T1 to T16 complete; `docs/SECURITY.md` with the cost of each defence.
+- [x] Attack tests for T1 to T16 complete; `docs/SECURITY.md` with the cost of each defence.
- [ ] Soak: 8 hours, no growth in memory, descriptors, handles, CF references.
- [ ] AddressSanitizer job on Linux and macOS clean; the `hostile` fixture passes every function without panic.
diff --git a/docs/API.md b/docs/API.md
index fa68676..1840d45 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -94,11 +94,11 @@ Costs are estimates (marked [est.]) until they are measured in `0.7.0`; measured
```toml
[dependencies]
-sys = { package = "sys-lib", version = "0.4" }
+sys = { package = "sys-lib", version = "0.8" }
# Without instance info and the process guard (no dependencies at all):
-# sys = { package = "sys-lib", version = "0.4", default-features = false }
+# sys = { package = "sys-lib", version = "0.8", default-features = false }
# With device identity (from 0.5):
-# sys = { package = "sys-lib", version = "0.7", features = ["device-id"] }
+# sys = { package = "sys-lib", version = "0.8", features = ["device-id"] }
```
The package is `sys-lib` on crates.io (`sys` and `system` were taken). Cargo's rename makes it `sys` in your code, so every file writes `sys::os::name()` with no import line. Without the rename (`sys-lib = "0.4"`), add `use sys_lib as sys;` at the top of a file and the code is the same.
@@ -918,7 +918,7 @@ What the guard does, in order:
| Step | Linux and macOS | Windows |
|---|---|---|
| 1. open-file limit, checked | `OpenFilesTooLow` if the hard `RLIMIT_NOFILE` is below the minimum, before anything else, so a refusal changes nothing (a second copy started under a low limit gets this error, not `AlreadyRunning`) | not applicable |
-| 2. lock directory | the default (above), or an explicit `lock_dir`, created with mode 0700 if missing; refused if it is a symlink, group- or world-writable, owned by another user, or on a network filesystem (`nfs`, `cifs`, `smb2`, `fuse.sshfs`, WSL's `drvfs` and `9p`) unless `allow_network_lock(true)` | refused if it is a reparse point or on a remote drive unless allowed; a missing directory inherits its parent's permissions, and ownership is not checked, so choose a parent other users cannot write to (not `C:\ProgramData` itself) |
+| 2. lock directory | the default (above), or an explicit `lock_dir`, created with mode 0700 if missing; refused if it is a symlink, group- or world-writable, owned by another user, or on a network filesystem (`nfs`, `cifs`, `smb2`, `fuse.sshfs`, WSL's `drvfs` and `9p`) unless `allow_network_lock(true)` | refused if it is a reparse point or on a remote drive unless allowed; a missing directory is created with an access list for this account, `SYSTEM`, and `Administrators` alone, and a directory another account can change (one under `C:\ProgramData`, say) is refused (D-113) |
| 3. single-instance lock | `/.lock` opened with `O_NOFOLLOW`, then checked (the opened file must be the one inspected, by device and inode, and owned by this user), locked with `File::try_lock`, then checked again, so a file deleted or replaced between the open and the lock is never the one held (three tries); the OS releases the lock when the process dies, even after `kill -9` | the same file, `File::try_lock`, reparse points refused, opened without delete sharing, so the held file cannot be deleted or renamed |
| 4. pid file | `/.pid` written after the lock is held, with `path_lib::write_atomic` | same (the locked file cannot be read by another process, so the pid lives beside it) |
| 5. open-file limit, raised | soft limit raised to the target, capped at the hard limit, on Linux at `/proc/sys/fs/nr_open`, and on macOS at `kern.maxfilesperproc` | not applicable (no per-process descriptor count for sockets); reported as unlimited |
@@ -930,7 +930,7 @@ Errors, each saying what to do:
| Error | When | The message tells the operator |
|---|---|---|
-| `AlreadyRunning { pid, lock_file }` | another copy holds the lock | the lock file, and the pid when the pid file is readable: a hint to check, not proof (just after a copy starts the file can still hold the previous run's pid, which may since belong to another program) |
+| `AlreadyRunning { pid, lock_file }` | another copy holds the lock | the lock file, and the pid when the pid file names a running process that started before the file was written; otherwise `None`. Still a hint to check, not proof: a program that forks after the guard leaves its parent's pid behind (D-112) |
| `RunDirUnavailable { path, source }` | the directory cannot be created or written, is a symlink, is writable by others, or is on a network filesystem | the path, the reason, and the fix (`chmod 700`, a local directory, `allow_network_lock`) |
| `OpenFilesTooLow { have, need }` | the hard limit is below the minimum | what to raise: `LimitNOFILE=` in the systemd unit, `ulimit -Hn`, or launchd's limits |
| `InvalidInput` | the name failed validation | the rule |
diff --git a/docs/PLATFORM-NOTES.md b/docs/PLATFORM-NOTES.md
index 1e139ff..fc21b25 100644
--- a/docs/PLATFORM-NOTES.md
+++ b/docs/PLATFORM-NOTES.md
@@ -74,6 +74,9 @@ Everything below is checked by compiling and on CI runners, which are virtual ma
- Nano Server: CI runs a real binary there, so the imports load. user32, tbs, and powrprof are loaded at run time from System32 (D-070): on Nano Server `gpu::list()` is `Unsupported` and the power plan, TPM, and turbo fields are unknown.
- **Reports.** `sensors::temperatures()` lists drives only; there is no unprivileged documented CPU temperature. The readiness report's ephemeral-port check is `Unknown` (no documented source), and the open-file check passes (handles have no per-process limit). `security::posture()` reads the registry for Secure Boot, VBS, HVCI, and the firewall (true or false only when every profile agrees); BitLocker is `None`.
- `process::threads()` takes a process snapshot: tens of milliseconds on a host with many processes.
+- **Minimum version:** Windows 10 version 1511, or Windows Server 2016 (D-116). Older builds do not load a binary that links sys-lib (`IsWow64Process2`).
+- `cpu::available()` counts every processor of each processor group the process spans: Windows has no call for a process's affinity within several groups (D-117). On machines with one group (64 processors or fewer) the count follows the affinity mask exactly.
+- **Process guard:** a missing lock directory is created private (this account, `SYSTEM`, and `Administrators`), and a lock directory other accounts can change is refused, as on Unix (D-113).
## Android
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000..2792df6
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,14 @@
+# sys-lib documentation
+
+| Document | What it covers |
+|---|---|
+| [API.md](./API.md) | Every public item, the version it arrived in, its cost, and examples |
+| [ARCHITECTURE.md](./ARCHITECTURE.md) | How the crate is built: the platform boundary, the parsers, caching |
+| [SOURCES.md](./SOURCES.md) | Where each value comes from on each operating system |
+| [PLATFORM-NOTES.md](./PLATFORM-NOTES.md) | What differs by platform, and the readings a platform cannot answer |
+| [PERFORMANCE.md](./PERFORMANCE.md) | Measured costs against the crates people use instead, and the method |
+| [SECURITY.md](./SECURITY.md) | What the crate guarantees, the threats and their tests, and how to report a vulnerability |
+| [DEVICE-ID.md](./DEVICE-ID.md) | How the application-scoped device id is derived, and what it is not for |
+| [release/](./release/) | The notes for each release |
+
+The design and the decision log are in [`dev/PLAN.md`](../dev/PLAN.md), the schedule in [`dev/ROADMAP.md`](../dev/ROADMAP.md), and every change in [`CHANGELOG.md`](../CHANGELOG.md).
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
new file mode 100644
index 0000000..50e4bfb
--- /dev/null
+++ b/docs/SECURITY.md
@@ -0,0 +1,43 @@
+# Security
+
+sys-lib reads facts about the machine for the program that links it. Most of what it reads comes from places the program does not control: `/proc` and `/sys` inside a container whose image or orchestrator may be hostile, firmware tables, the registry, the environment, and files such as `/etc/os-release`. A reading that panics, hangs, or allocates without bound on such input takes the calling service down with it, so for sys-lib that is a security bug, even when memory safety holds.
+
+## Reporting
+
+Report a vulnerability privately through GitHub's security advisories for `jamesgober/sys-lib`, or by email to me@jamesgober.com. Please include the platform, the version, the features in use, and the input (a file's content, a mount table) that triggers it.
+
+## What the crate guarantees
+
+- **No panic on any input.** Every reading returns a value that keeps its invariants or an error. Every parser is safe Rust, bounded, without recursion, fuzzed, and run under Miri.
+- **No hang.** Network filesystems are never touched by default; Windows volume calls run with critical-error dialogs off; a FIFO where a file is expected is opened without blocking and refused.
+- **Bounded memory.** Every file read has a budget (1 MiB), every list a count limit checked before allocating, and every size-then-fill system call at most three tries; past a budget the answer is `TooLarge`.
+- **No subprocess.** No reading starts a program, so a planted `PATH` cannot change an answer. Only the build helper runs `git` and `$RUSTC`, at build time.
+- **No identifier leaves `device`.** Raw hardware identifiers live in a fixed buffer, wiped after hashing; errors, `Debug`, `Display`, and reports carry none.
+- **`unsafe` only at the system-call boundary.** It is confined to the platform modules, one operation per block, each with a `SAFETY` comment (both enforced by clippy). Every C struct has a size, alignment, and field-offset check against the platform headers on every target.
+
+## Threats and defences
+
+The full model, with the attackers considered, is in `dev/PLAN.md` section 14.
+
+| Id | Threat | Defence | Cost | Test |
+|---|---|---|---|---|
+| T1 | Raw hardware identifiers disclosed through logs, errors, `Debug`, `Display`, or the API | raw values exist only inside `device`, in a fixed buffer wiped after hashing; `Error` carries no values; `summary()` has no identifiers | one wipe of a 256-byte buffer per identifier read | `test_attack_t1_no_output_contains_a_raw_identifier`, `test_attack_t1_fingerprint_debug_names_anchors_only` |
+| T2 | One device id correlated across applications | a keyed hash with a key derived from the application id; an optional secret | one key derivation per call, inside the `device::id` figures in `docs/PERFORMANCE.md` | `test_attack_t2_applications_see_unrelated_fingerprints` |
+| T3 | A device id used to authenticate a machine, then spoofed | documentation; nothing in the API implies verification | none | `test_attack_t3_the_warning_is_in_the_documentation` |
+| T4 | Paths or values injected through the environment (`TZ=../../etc/shadow`, a hostile `LANG`, a `HOST_PROC`-style redirect) | no root override from the environment; `TZ`, `LC_*`, and `LANG` validated and never used to open a file; guard and interface names validated | a validation of a few bytes | `test_attack_t4_hostile_environment_changes_no_answer` |
+| T5 | Files that change between reads, and pids reused | only `/proc/self` and `/proc/1` are read, plus, when the guard refuses to start, the start time of the process its pid file names; one open per file, read to the end; combined values clamped to their invariants | a few comparisons per reading | `test_attack_t5_values_read_at_different_instants_keep_invariants`, `test_attack_t9_pid_names_only_a_process_that_can_hold_the_lock` |
+| T6 | Hostile `/proc` and `/sys` in a container: huge or negative numbers, binary junk, enormous files | safe, bounded, checked parsers without recursion; a fuzz target for every parser | none measurable | `test_attack_t6_hostile_values_in_every_file_never_panic`, the fuzz targets |
+| T7 | Resource exhaustion through huge files or lists (100 000 mounts, 4 096 CPUs) | a 1 MiB budget per file; list budgets (4 096 mounts and interfaces, 16 384 CPUs) checked before allocating; the mount lookup streams the table with a 16 MiB budget | none in the normal case | `test_attack_t7_oversized_files_and_lists_are_too_large` |
+| T8 | Hangs on a dead network filesystem, a FIFO, or a removable drive | network filesystems skipped by default; files outside `/proc` and `/sys` opened non-blocking and required to be regular files; critical-error dialogs off around Windows volume calls | one `fstat` per file opened outside `/proc` and `/sys` | `test_attack_t8_network_mounts_are_never_listed_by_default`, `test_linux_root_fifo_does_not_block` |
+| T9 | Attacks on the guard's lock file: a symbolic link at the lock path, a lock file planted first, a directory other users can write to, a lock file deleted while held, a pid that names another program | the lock directory must belong to this user and be closed to others (mode and owner on Unix, the access list on Windows) and is created that way; no-follow open; the locked file checked against the path; on Windows the held file cannot be deleted; a reported pid must name a running process that started before its pid file was written | one `stat` and one `fstat` when the guard starts (about 2 µs); on Windows one access-list check | `test_attack_t9_symlinked_lock_file_is_refused`, `test_attack_t9_writable_lock_dir_is_refused`, `test_attack_t9_symlinked_lock_dir_is_refused`, `test_attack_t9_windows_lock_dir_is_private_and_checked`, `test_attack_t9_pid_names_only_a_process_that_can_hold_the_lock`, `test_guard_is_held_until_the_lock_file_is_replaced`, `tests/guard.rs` |
+| T10 | The guard's umask change racing other threads | the guard runs before threads; it warns when more are running; the umask is set once | one file read when the guard starts | `test_attack_t10_guard_after_threads_warns_and_sets_the_umask_once` |
+| T11 | Build and instance information disclosing the build host, user, or source path | `BuildInfo::public()`; no build host, user, or path recorded; values validated before `rustc-env` | none at run time | `test_attack_t11_nothing_records_host_user_or_path`, `test_attack_t11_public_shows_name_and_version_only`, `test_attack_t11_writers_escape_hostile_values` |
+| T12 | Memory-safety bugs at the system-call boundary: wrong layouts, overruns in size-then-fill loops, leaked handles or references | `unsafe` confined to the platform modules; layout checks on every target; at most three tries per size-then-fill loop; lengths checked before slicing; release on drop; the owners of CoreFoundation, IOKit, and Mach objects are `unsafe fn` | none | `test_attack_t12_no_reading_holds_a_descriptor`, the layout tests, Miri on the parsers, the AddressSanitizer job (Linux, macOS), the soak run |
+| T13 | Identifying values (host name, user, MAC address) leaving the machine in logs | documented as identifying; excluded from `summary()`; the readiness report shows no mount source | none | `test_attack_t13_summary_has_no_identifying_values`, `test_readiness_display_cannot_be_forged_and_names_no_source` |
+| T14 | A spoofed environment (`KUBERNETES_SERVICE_HOST`, a planted `/.dockerenv`, fake DMI strings) | detection is advisory, every piece of evidence carries its strength, and the docs forbid security decisions on it | none | `test_attack_t14_environment_is_weak_evidence` |
+| T15 | Malformed firmware tables: bad lengths, missing terminators, structure loops | a bounded SMBIOS parser: each structure checked against the table end, at most 4 096 structures, no recursion; a drive's product string ends at the next field | none | `test_attack_t15_hostile_smbios_tables_stop_cleanly`, the `smbios` fuzz target |
+| T16 | A planted program run in place of a system tool (`PATH` with a fake `lsb_release`) | no subprocess at run time | none | `tests/attack_t16_subprocess.rs`, the CI check that `src/` starts no program |
+
+## Long runs
+
+Before each release, every fuzz target runs for 24 hours (five chained rounds on GitHub's runners, `fuzz.yml` with `long`), and the soak run (`bench/src/bin/soak.rs`) calls every reading in a loop and fails if this process's memory or open descriptors grow.
diff --git a/src/error.rs b/src/error.rs
index e3be26a..79cf5f1 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -94,10 +94,10 @@ pub enum Error {
},
/// The process guard found another copy holding the lock.
AlreadyRunning {
- /// The other copy's process id from its pid file, when readable. A
- /// hint, not proof: the file can still hold an earlier run's pid
- /// for a moment after a copy starts, and that pid may since belong
- /// to another program. Check it before stopping it.
+ /// The other copy's process id from its pid file, when that names a
+ /// running process that started before the file was written. A hint,
+ /// not proof (a program that forks after the guard leaves its
+ /// parent's pid behind): check it before stopping it.
pid: Option,
/// The lock file.
lock_file: PathBuf,
diff --git a/src/lib.rs b/src/lib.rs
index 2b9d17a..2775d40 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -11,7 +11,7 @@
//!
//! ## Tier 1
//!
-//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.7" }`,
+//! Add it with Cargo's rename, `sys = { package = "sys-lib", version = "0.8" }`,
//! and every file writes `sys::`; without the rename, `use sys_lib as sys;`
//! does the same (the examples use that form so they compile either way).
//! One plain call per fact; static facts are read once and cached:
@@ -49,8 +49,9 @@
//!
//! ## Status
//!
-//! `0.7.0`, optimisation: every reading measured against the crates people
-//! use for it, with the numbers in `docs/PERFORMANCE.md`. Feature complete
+//! `0.8.0`, hardening: every threat in the model has an attack test, with the
+//! defences and their costs in `docs/SECURITY.md`; every reading is measured
+//! against the crates people use for it in `docs/PERFORMANCE.md`. Feature complete
//! since `0.6`: the boot kit ([`os`], [`cpu`], [`host`], [`process`],
//! [`build`], and instance info), the live readings ([`mem`], [`disk`],
//! [`net`]), [`virt`], [`power`], [`summary()`], the environment reports,
diff --git a/src/linux/mem.rs b/src/linux/mem.rs
index 1ac8359..2d95739 100644
--- a/src/linux/mem.rs
+++ b/src/linux/mem.rs
@@ -153,8 +153,16 @@ pub(crate) fn read(
.map(|c| c.saturating_sub(stat_value(root, &p.stat, b"inactive_file").unwrap_or(0)));
raw.limit = Some(MemoryLimit {
hard: Bytes::new(hard),
- soft: bytes_file(root, &p.soft).map(Bytes::new),
- swap: tightest(root, &p.swap_max).map(Bytes::new),
+ soft: want
+ .detail
+ .then(|| bytes_file(root, &p.soft))
+ .flatten()
+ .map(Bytes::new),
+ swap: want
+ .detail
+ .then(|| tightest(root, &p.swap_max))
+ .flatten()
+ .map(Bytes::new),
source: LimitSource::Cgroup2,
});
raw.limited_used = used;
@@ -169,9 +177,16 @@ pub(crate) fn read(
.map(|c| {
c.saturating_sub(stat_value(root, &p.stat, b"total_inactive_file").unwrap_or(0))
});
- let soft = bytes_file(root, &p.soft).filter(|&v| v < V1_UNLIMITED);
+ let soft = want
+ .detail
+ .then(|| bytes_file(root, &p.soft))
+ .flatten()
+ .filter(|&v| v < V1_UNLIMITED);
// memory.memsw is memory plus swap; the swap share is the difference.
- let swap = bytes_file(root, &p.memsw)
+ let swap = want
+ .detail
+ .then(|| bytes_file(root, &p.memsw))
+ .flatten()
.filter(|&v| v < V1_UNLIMITED)
.map(|memsw| memsw.saturating_sub(hard));
raw.limit = Some(MemoryLimit {
@@ -342,6 +357,41 @@ mod tests {
assert_eq!(m.limit.unwrap().soft, Some(Bytes::from_mib(200)));
}
+ #[test]
+ fn test_linux_mem_total_reads_only_what_it_needs() {
+ // The total and the limit agree; only the limit reads the soft and
+ // swap files (one more per ancestor), and only snapshots read usage.
+ let name = "wsl2-systemd-scope-limited";
+ let cg = fixtures::cgroups(name);
+ let paths = MemPaths::new(&cg);
+ let opened = |want: MemWant| {
+ let (root, log) = fixtures::root(name).recording();
+ let raw = read(&root, paths.as_ref(), cg.lxcfs.meminfo, want).unwrap();
+ let files = log.lock().unwrap().clone();
+ (from_raw(raw), files)
+ };
+ let reads =
+ |files: &[String], leaf: &str| files.iter().filter(|p| p.ends_with(leaf)).count();
+ let (total, files) = opened(MemWant::TOTAL);
+ assert_eq!(total.total, Bytes::from_mib(256));
+ for leaf in [
+ "memory.high",
+ "memory.swap.max",
+ "memory.current",
+ "memory.stat",
+ ] {
+ assert_eq!(
+ reads(&files, leaf),
+ 0,
+ "{leaf} read for the total: {files:?}"
+ );
+ }
+ let (limit, files) = opened(MemWant::LIMIT);
+ assert_eq!(limit.limit.unwrap().soft, Some(Bytes::from_mib(200)));
+ assert!(reads(&files, "memory.swap.max") > 0, "{files:?}");
+ assert_eq!(reads(&files, "memory.current"), 0, "{files:?}");
+ }
+
#[test]
fn test_linux_mem_cgroup_v1_hierarchical_limit() {
// E-4: the v1 memory controller.
diff --git a/src/linux/process.rs b/src/linux/process.rs
index ef2036b..cf4b888 100644
--- a/src/linux/process.rs
+++ b/src/linux/process.rs
@@ -78,19 +78,40 @@ pub(crate) fn status_number(root: &Root, key: &[u8]) -> Result