cosca 0.5.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
// Unit tests for process-group membership listing and the identity it carries.

use super::{members, state, GroupState, Member};
use crate::identity::{Liveness, ProcessId};
use nix::sys::signal::Signal;

fn is_alive(m: &Member) -> bool {
    matches!(ProcessId::from_parts(m.pid, m.token).is_alive(), Liveness::Alive)
}

/// Block until `pid` has exited, leaving it UNREAPED so it is a zombie the
/// kernel still lists in its process group. `waitid(WEXITED | WNOWAIT)` is the
/// real primitive for this — nothing here is timed. `nix` does not expose
/// `waitid` on macOS (0.31 configures it out), so call `libc` directly,
/// following the same `waitid(WEXITED | WNOWAIT)` idiom `reap_now` uses in
/// `src/tokio/child.rs` — including its EINTR retry, so a stray signal to the
/// test process fails the wait, not the test.
fn await_zombie(pid: u32) {
    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
    loop {
        // SAFETY: a well-formed `waitid` call; `info` is a valid, owned, zeroed
        // `siginfo_t` the kernel fills in. WNOWAIT leaves the child reapable.
        let rc = unsafe { libc::waitid(libc::P_PID, pid as libc::id_t, &mut info, libc::WEXITED | libc::WNOWAIT) };
        if rc == 0 {
            return;
        }
        let err = std::io::Error::last_os_error();
        if err.raw_os_error() == Some(libc::EINTR) {
            continue;
        }
        panic!("waitid failed: {err}");
    }
}

use crate::test_child::{await_member_ready, member_command};

/// A group we lead lists the member we put in it, with a token that resolves to Alive.
#[skuld::test]
fn members_lists_a_live_owned_group() {
    // Held for the fork itself — see `fdmarker_tests.rs`'s module docs.
    let mut child = crate::test_spawn::spawn(&mut member_command(0)).expect("spawn leader");
    await_member_ready(&mut child);
    let pgid = child.id() as i32;

    let listed = members(pgid).expect("list the group");
    let leader = listed
        .iter()
        .find(|m| m.pid == child.id())
        .unwrap_or_else(|| panic!("leader {} missing from {listed:?}", child.id()));
    assert!(is_alive(leader), "a running leader's token must resolve to Alive");

    _ = child.kill();
    _ = child.wait();
}

/// Once the leader has exited unreaped, the kernel still lists it in the group,
/// and its token must resolve to Dead (zombie) — the state that makes an EPERM
/// answer meaningless.
#[skuld::test]
fn members_marks_an_unreaped_leader_as_dead() {
    use std::os::unix::process::CommandExt;
    // Held for the fork itself — see `fdmarker_tests.rs`'s module docs.
    let child = crate::test_spawn::spawn(std::process::Command::new("true").process_group(0)).expect("spawn true");
    let pid = child.id();
    await_zombie(pid);

    let listed = members(pid as i32).expect("list the group");
    let leader = listed
        .iter()
        .find(|m| m.pid == pid)
        .unwrap_or_else(|| panic!("unreaped leader {pid} missing from {listed:?}"));
    assert!(
        !is_alive(leader),
        "an exited, unreaped leader's token must resolve to Dead, not Alive"
    );

    let mut child = child;
    child.wait().expect("reap");
}

/// A pgid with no members at all lists nothing, and that is not an error. Uses `i32::MAX`
/// (2147483647), not a forward scan from the test's own pid: a forward scan would assert on
/// the exact predicate the scan itself already satisfied — a tautology proving nothing beyond
/// what the loop condition already established — AND a genuine (if narrow) check-then-act
/// gap, since the scanned range is exactly where the kernel's allocator is likely to hand out
/// a NEW pid next, including to this crate's own sibling tests, several of which spawn
/// `process_group(0)` children whose pgid == their pid. `i32::MAX` cannot collide: measured
/// directly on this host,
/// `sysctl(KERN_PROC_PGRP, i32::MAX)` returns `rc=0` with zero actual records (confirming no
/// real pid/pgid is ever allocated anywhere near it — `kern.maxproc`/`pid_max` stay far
/// below `2^31` on every real system), so this is a fixed value, not a scan, and the
/// assertion is a genuine independent check rather than a restatement of the fixture.
#[skuld::test]
fn members_of_an_absent_group_is_empty() {
    assert_eq!(members(i32::MAX).expect("list an absent group"), vec![]);
}

/// The token the listing carries is the SAME encoding a live read of the pid would produce —
/// not a different, incompatible one — so a later `ProcessId::from_parts` re-check is
/// comparing like with like. (macOS: pinned across `proc_pidinfo` and `sysctl` by the
/// existing `kinfo_tests` cross-source oracle; this test pins the listing itself against
/// `ProcessId::of`'s live read, on both platforms.)
#[skuld::test]
fn members_token_matches_a_live_read_of_the_same_pid() {
    // Held for the fork itself — see `fdmarker_tests.rs`'s module docs.
    let mut child = crate::test_spawn::spawn(&mut member_command(0)).expect("spawn leader");
    await_member_ready(&mut child);
    let pgid = child.id() as i32;

    let listed = members(pgid).expect("list the group");
    let leader = listed.iter().find(|m| m.pid == child.id()).expect("leader listed");
    let live = ProcessId::of(child.id()).found().expect("resolve the live leader");
    assert_eq!(
        leader.token,
        live.start_token_raw(),
        "listing token must match a fresh live read"
    );

    _ = child.kill();
    _ = child.wait();
}

/// A group we own holds no refusers once SIGKILLed — and `state` really did deliver the
/// signal, not just classify: the leader is dead afterward.
#[skuld::test]
fn state_of_an_owned_group_is_cleared_and_the_signal_was_real() {
    use std::os::unix::process::ExitStatusExt;

    // Held for the fork itself — see `fdmarker_tests.rs`'s module docs.
    let mut child = crate::test_spawn::spawn(&mut member_command(0)).expect("spawn leader");
    await_member_ready(&mut child);
    let pgid = child.id() as i32;
    assert!(
        matches!(state(pgid, Signal::SIGKILL), GroupState::Cleared),
        "a group we own must never report refusers"
    );
    let status = child.wait().expect("wait after state()'s own SIGKILL");
    // Not `!status.success()`: `Child::wait()` closes the piped stdin (see `member_command`), so
    // the leader exits non-zero on EOF even if `state()` never signalled it.
    assert_eq!(
        status.signal(),
        Some(libc::SIGKILL),
        "state() must have actually delivered SIGKILL, not just probed, got {status:?}"
    );
}

/// A group whose only member is our own unreaped zombie is cleared: there is nothing left
/// running. This is the benign case macOS reports as EPERM.
#[skuld::test]
fn state_of_an_all_zombie_group_is_cleared() {
    use std::os::unix::process::CommandExt;
    // Held for the fork itself — see `fdmarker_tests.rs`'s module docs.
    let child = crate::test_spawn::spawn(std::process::Command::new("true").process_group(0)).expect("spawn true");
    let pid = child.id();
    await_zombie(pid);
    assert!(
        matches!(state(pid as i32, Signal::SIGKILL), GroupState::Cleared),
        "a group holding only a zombie has nothing left to kill"
    );
    let mut child = child;
    child.wait().expect("reap");
}

/// `classify_member`'s pure decision. Only `Liveness::Dead` skips the attempt (a panicking
/// closure proves it); `Alive` AND `Unknown` both proceed to `reached()` and are classified
/// identically from its answer — the fix for a guard-then-do inversion review caught
/// (`classify_member`'s own doc comment has the full account). `Reached::Unknown` still needs
/// a real permission-denying host (`hidepid`) to construct for real; exercised here directly.
#[skuld::test]
fn classify_member_is_total_over_liveness_and_reached() {
    use super::{classify_member, MemberOutcome, Reached};
    use crate::identity::Liveness;

    assert!(matches!(
        classify_member(1, Liveness::Dead, || panic!("must not reach for Dead")),
        MemberOutcome::NotASurvivor
    ));
    for liveness in [Liveness::Alive, Liveness::Unknown] {
        assert!(matches!(
            classify_member(1, liveness, || Reached::Yes),
            MemberOutcome::NotASurvivor
        ));
        assert!(matches!(
            classify_member(1, liveness, || Reached::No),
            MemberOutcome::Survivor(1)
        ));
        assert!(matches!(
            classify_member(1, liveness, || Reached::Unknown),
            MemberOutcome::Unassessable(1)
        ));
    }
}

/// `reconfirm_survivor`'s pure re-check, isolated from any real signal delivery: a
/// `Survivor` is downgraded ONLY on a positive `Dead` disagreement — a denied reconfirmation
/// (`Liveness::Unknown`) does NOT overturn the already-observed, authoritative `EPERM` a
/// `Survivor` carries (see this function's own doc comment for why `Unknown` and `Dead` are
/// not equivalent here). `NotASurvivor`/`Unassessable` pass through untouched (the panicking
/// closure proves no second check runs for them at all — there is nothing to reconfirm).
#[skuld::test]
fn reconfirm_survivor_downgrades_only_on_dead() {
    use super::{reconfirm_survivor, MemberOutcome};
    use crate::identity::Liveness;

    assert!(matches!(
        reconfirm_survivor(MemberOutcome::Survivor(1), || Liveness::Alive),
        MemberOutcome::Survivor(1)
    ));
    assert!(matches!(
        reconfirm_survivor(MemberOutcome::Survivor(1), || Liveness::Dead),
        MemberOutcome::NotASurvivor
    ));
    // Unknown does NOT downgrade: a denied reconfirmation is weaker evidence than the
    // already-observed EPERM, not a disagreement with it.
    assert!(matches!(
        reconfirm_survivor(MemberOutcome::Survivor(1), || Liveness::Unknown),
        MemberOutcome::Survivor(1)
    ));
    assert!(matches!(
        reconfirm_survivor(MemberOutcome::NotASurvivor, || panic!("must not recheck NotASurvivor")),
        MemberOutcome::NotASurvivor
    ));
    assert!(matches!(
        reconfirm_survivor(MemberOutcome::Unassessable(1), || panic!(
            "must not recheck Unassessable"
        )),
        MemberOutcome::Unassessable(1)
    ));
}

/// `decide`'s pure priority ordering, isolated from any real listing: a known refusal beats
/// an unresolved member, which beats a clean group — and neither a refuser nor an
/// unassessable member is ever silently dropped when both are present at once.
#[skuld::test]
fn decide_prioritizes_refused_over_unassessable_over_cleared() {
    use super::{decide, GroupState};

    assert!(matches!(
        decide(1, Signal::SIGKILL, vec![], vec![]),
        GroupState::Cleared
    ));
    match decide(1, Signal::SIGKILL, vec![], vec![5]) {
        GroupState::Unlistable { detail, .. } => assert!(detail.contains('5'), "got {detail:?}"),
        other => panic!("expected Unlistable, got {other:?}"),
    }
    match decide(1, Signal::SIGKILL, vec![7], vec![5]) {
        GroupState::Refused { refused, unassessable } => {
            assert_eq!(
                refused,
                vec![7],
                "a known refuser must not be lost to an unassessable member"
            );
            assert_eq!(
                unassessable,
                vec![5],
                "the unassessable member must not be silently dropped either"
            );
        }
        other => panic!("expected Refused, got {other:?}"),
    }
}

/// `excluded_from_sigkill_resend`'s pure predicate, isolated from any real listing or signal:
/// pid 1 is excluded regardless of `system`, a `system`-flagged pid is excluded regardless of
/// its number, and an ordinary user pid is excluded by neither rule.
#[skuld::test]
fn excluded_from_sigkill_resend_covers_pid_1_and_system_independently() {
    use super::excluded_from_sigkill_resend;

    assert!(excluded_from_sigkill_resend(1, false), "pid 1 must be excluded");
    assert!(
        excluded_from_sigkill_resend(1, true),
        "pid 1 must be excluded even if also flagged system"
    );
    assert!(
        excluded_from_sigkill_resend(12345, true),
        "a system-flagged pid other than 1 must be excluded"
    );
    assert!(
        !excluded_from_sigkill_resend(12345, false),
        "an ordinary, non-system pid must not be excluded"
    );
}

/// `term_group`'s probe path against pid 1 — the one live, unsignalable-by-an-unprivileged-
/// caller process every Unix host has. Safe to run for real: `state(pgid, SIGTERM)` on this
/// pgid only ever *probes* (`kill(pid, 0)`) because `SIGTERM` never triggers this task's
/// resend path — no signal is delivered to `launchd`/`init` or its group siblings, on any
/// host, root or not. This exercises the ACTUAL production `state` function, not a parallel
/// test-only probe. The expectation comes from POSIX (an unprivileged process may not signal
/// one owned by another user) plus the host's own answer to "who owns pid 1", and it is
/// total: a root caller, or a host where pid 1 is ours, gets the complementary assertion.
///
/// **`reachable` is asked directly of the kernel, not derived from a hand-reconstructed
/// permission rule.**
#[skuld::test]
fn term_group_probe_reports_pid_1_as_a_refuser_unless_reachable() {
    let pgid = nix::unistd::getpgid(Some(nix::unistd::Pid::from_raw(1)))
        .expect("pid 1 has a process group")
        .as_raw();
    // SAFETY: pid 1 always exists; signal 0 sends no signal, only performs the kernel's own
    // permission check — this is the independent oracle, a syscall issued directly by the
    // test, not a call into any function this plan adds or modifies.
    let reachable = unsafe { libc::kill(1, 0) } == 0;
    match (state(pgid, Signal::SIGTERM), reachable) {
        (GroupState::Refused { refused, .. }, false) => {
            assert!(
                refused.contains(&1),
                "pid 1 must be reported as a refuser, got {refused:?}"
            );
        }
        (GroupState::Cleared, true) => {}
        (got, reachable) => panic!("pid 1 owned by uid {}, reachable={reachable}: got {got:?}", pid1_uid()),
    }
}

/// The real uid of pid 1, read from an oracle independent of this module.
#[cfg(target_os = "linux")]
fn pid1_uid() -> u32 {
    let status = std::fs::read_to_string("/proc/1/status").expect("read /proc/1/status");
    status
        .lines()
        .find_map(|l| l.strip_prefix("Uid:"))
        .and_then(|v| v.split_whitespace().next())
        .and_then(|v| v.parse().ok())
        .expect("Uid: line in /proc/1/status")
}

/// macOS pid 1 is always `launchd`, started by the kernel as root.
#[cfg(target_os = "macos")]
fn pid1_uid() -> u32 {
    0
}

/// Mutants: the op is another `PidfdOp`; the forced errno is not consumed (no fallback, so no
/// line).
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_refused_pidfd_open_falls_back_to_kill_naming_group_teardown() {
    use crate::containment::cgroup::test_support::{block_on, fork_running};

    crate::log_capture::install();
    let (gate_r, gate_w) = std::io::pipe().expect("pipe");
    let gate_r_fd = std::os::fd::AsRawFd::as_raw_fd(&gate_r);
    let child = fork_running(|| block_on(gate_r_fd));
    let id = ProcessId::of(child.pid()).found().expect("the live child resolves");
    let mark = crate::log_capture::mark();

    let forced = crate::wait::backend::fault::force_pidfd_open_errno_once(rustix::io::Errno::PERM);
    let reached = super::check_or_signal_linux_sigkill(child.pid(), id);
    drop(forced);

    assert!(matches!(reached, super::Reached::Yes), "got {reached:?}");
    let lines = crate::log_capture::records_since_on_current_thread(mark, "pidfd unavailable");
    assert_eq!(lines.len(), 1, "{lines:?}");
    assert_eq!(lines[0].0, log::Level::Debug);
    assert!(
        lines[0].1.contains(
            "process-group teardown is not supported on linux: cosca requires pidfd_open (Linux \u{2265} 5.3), \
             refused here: pidfd_open answered EPERM"
        ),
        "{lines:?}"
    );
    drop(gate_w);
}

/// A transient `pidfd_open` failure (`EMFILE`) also falls back to `kill(2)`: the debug line names
/// the syscall, not a refusal.
///
/// Mutants: the `Io` arm of the fallback is `Reached::Unknown`; the `Io` context drops
/// `pidfd_open:`.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_transient_pidfd_open_failure_falls_back_to_kill_naming_the_syscall() {
    use crate::containment::cgroup::test_support::{block_on, fork_running};

    crate::log_capture::install();
    let (gate_r, gate_w) = std::io::pipe().expect("pipe");
    let gate_r_fd = std::os::fd::AsRawFd::as_raw_fd(&gate_r);
    let child = fork_running(|| block_on(gate_r_fd));
    let id = ProcessId::of(child.pid()).found().expect("the live child resolves");
    let mark = crate::log_capture::mark();

    let forced = crate::wait::backend::fault::force_pidfd_open_errno_once(rustix::io::Errno::MFILE);
    let reached = super::check_or_signal_linux_sigkill(child.pid(), id);
    drop(forced);

    assert!(matches!(reached, super::Reached::Yes), "got {reached:?}");
    let lines = crate::log_capture::records_since_on_current_thread(mark, "pidfd unavailable");
    assert_eq!(lines.len(), 1, "{lines:?}");
    assert_eq!(lines[0].0, log::Level::Debug);
    assert!(lines[0].1.contains("pidfd_open: Too many open files"), "{lines:?}");
    drop(gate_w);
}

/// A member that is a live non-leader thread is `Unknown`, with a warn naming that cause, and is
/// never sent to the `kill(2)` fallback (a `kill` on a tid signals its whole thread group). The
/// `pid` argument is a disposable child, so a regression that fell back would land on it, never on
/// this test process.
#[cfg(target_os = "linux")]
#[skuld::test]
fn a_live_non_leader_thread_member_is_unknown_and_never_falls_back_to_kill() {
    use crate::containment::cgroup::test_support::{block_on, fork_running};

    crate::log_capture::install();
    let (gate_r, gate_w) = std::io::pipe().expect("pipe");
    let gate_r_fd = std::os::fd::AsRawFd::as_raw_fd(&gate_r);
    let child = fork_running(|| block_on(gate_r_fd));

    let (tid_tx, tid_rx) = std::sync::mpsc::channel();
    let (stop_tx, stop_rx) = std::sync::mpsc::channel::<()>();
    let worker = std::thread::spawn(move || {
        // SAFETY: SYS_gettid takes no arguments and always succeeds.
        tid_tx.send(unsafe { libc::syscall(libc::SYS_gettid) } as u32).unwrap();
        _ = stop_rx.recv();
    });
    let tid = tid_rx.recv().unwrap();
    let id = ProcessId::of(tid).found().expect("the live worker's tid resolves");
    let mark = crate::log_capture::mark();

    let forced = crate::wait::backend::fault::force_pidfd_open_errno_once(rustix::io::Errno::NOENT);
    let reached = super::check_or_signal_linux_sigkill(child.pid(), id);
    drop(forced);

    assert!(matches!(reached, super::Reached::Unknown), "got {reached:?}");
    assert_eq!(
        crate::log_capture::levels_since(mark, &format!("pid {tid} is a live thread, not a thread-group leader")),
        vec![log::Level::Warn]
    );
    _ = stop_tx.send(());
    worker.join().unwrap();
    drop(gate_w);
}

// Checked /proc view (Linux) =====

/// An outer namespace's `/proc` lists another namespace's processes: their pgids mean nothing
/// here, so the listing is an error naming the view, never an answer about `pgid`. Mutant:
/// "scan `/proc` by path whatever the view".
#[cfg(target_os = "linux")]
#[skuld::test]
fn members_is_an_error_when_the_proc_view_is_diverged() {
    use crate::identity::proc_view_fault::{force_proc_view_once, ForcedView};
    let _forced = force_proc_view_once(ForcedView::Diverged);
    let err = members(i32::MAX).expect_err("a diverged view lists nothing");
    assert!(err.to_string().contains("outer pid namespace"), "{err}");
}

#[cfg(target_os = "linux")]
#[skuld::test]
fn members_is_an_error_naming_the_cause_when_the_proc_view_is_unassessable() {
    use crate::identity::proc_view_fault::{force_proc_view_once, ForcedView};
    let _forced = force_proc_view_once(ForcedView::Unassessable);
    let err = members(i32::MAX).expect_err("an unassessable view lists nothing");
    assert!(err.to_string().contains("forced by a test"), "{err}");
}

/// Without `openat2` no `/proc` view can be established, and the listing says that is why:
/// `Unsupported`, naming the requirement, as a spawn does. Mutant: "surface every unreadable view
/// as `io::Error::other`".
#[cfg(target_os = "linux")]
#[skuld::test]
fn members_without_openat2_is_unsupported_naming_the_requirement() {
    use crate::identity::proc_view_fault::force_openat2_errno;
    for (errno, name) in [(rustix::io::Errno::NOSYS, "ENOSYS"), (rustix::io::Errno::PERM, "EPERM")] {
        let forced = force_openat2_errno(errno);
        let err = members(i32::MAX).expect_err("no openat2, no listing");
        drop(forced);
        assert_eq!(err.kind(), std::io::ErrorKind::Unsupported, "{errno}: {err}");
        assert_eq!(
            err.to_string(),
            format!(
                "containment::unix::group::members: {}, so pgid {} cannot be listed",
                crate::identity::openat2_refused_message(name),
                i32::MAX
            ),
            "{errno}"
        );
    }
}

/// Any other `openat2` failure is not the requirement: it keeps its kind and does not claim
/// `openat2` is missing. Mutant: "flag every `/proc` open failure as missing `openat2`".
#[cfg(target_os = "linux")]
#[skuld::test]
fn members_with_another_openat2_failure_is_not_unsupported() {
    use crate::identity::proc_view_fault::force_openat2_errno;
    let forced = force_openat2_errno(rustix::io::Errno::NOENT);
    let err = members(i32::MAX).expect_err("an unopenable /proc lists nothing");
    drop(forced);
    assert_ne!(err.kind(), std::io::ErrorKind::Unsupported, "{err}");
    assert!(!err.to_string().contains("cosca requires openat2"), "{err}");
}

// Per-pid stat read failures (Linux) =====

/// The failures that mean "this pid says nothing about the group": it exited mid-scan (ENOENT,
/// ESRCH) or `hidepid` hides it (EACCES, and EPERM while the checked directory still answers).
/// The pgid matches nothing, so the honest answer is an empty listing. Mutant: "propagate every
/// read error".
#[cfg(target_os = "linux")]
#[skuld::test]
fn members_excludes_a_pid_whose_stat_read_says_it_is_gone_or_hidden() {
    for errno in [libc::ENOENT, libc::ESRCH, libc::EACCES, libc::EPERM] {
        let _forced = super::fault::force_stat_read(errno, None);
        let listed = members(i32::MAX).unwrap_or_else(|e| panic!("errno {errno} is an exclusion: {e}"));
        assert!(listed.is_empty(), "errno {errno}: {listed:?}");
    }
}

/// Every other failure says nothing about the pid, so it cannot clear the group: the listing is an
/// error naming the pid and the errno. Mutant: "exclude every read error" (the group reads as
/// `Cleared` while alive; EMFILE from a full fd table hits every pid at once).
#[cfg(target_os = "linux")]
#[skuld::test]
fn members_is_an_error_naming_pid_and_errno_for_any_other_stat_read_failure() {
    for errno in [
        libc::EXDEV,
        libc::ELOOP,
        libc::EMFILE,
        libc::ENFILE,
        libc::ENOMEM,
        libc::EIO,
        libc::ENOSYS,
    ] {
        let _forced = super::fault::force_stat_read(errno, None);
        let err = members(i32::MAX).expect_err("an unexplained read failure lists nothing");
        let text = err.to_string();
        assert!(
            text.contains(&std::io::Error::from_raw_os_error(errno).to_string()),
            "{errno}: {text}"
        );
        if matches!(errno, libc::EXDEV | libc::ELOOP) {
            assert!(text.contains("beyond a mount"), "{errno}: {text}");
        }
        let pid = text.split("/stat").next().unwrap().rsplit(' ').next().unwrap();
        assert!(
            pid.parse::<u32>().is_ok(),
            "{errno}: the error must name the pid before `/stat`: {text}"
        );
    }
}

/// EPERM is `hidepid`'s answer, and also a seccomp filter's for `openat2` installed mid-scan. Only
/// the checked directory answering afterwards tells them apart: if it refuses too, this is a
/// refusal, not a hidden pid. Mutant: "exclude EPERM without the re-check".
#[cfg(target_os = "linux")]
#[skuld::test]
fn members_is_an_error_for_eperm_when_the_checked_directory_also_refuses() {
    for recheck in [libc::EPERM, libc::ENOSYS, libc::EMFILE] {
        let _forced = super::fault::force_stat_read(libc::EPERM, Some(recheck));
        let err = members(i32::MAX).expect_err("a refusing directory lists nothing");
        let text = err.to_string();
        assert!(text.contains("self/stat"), "{recheck}: {text}");
        assert!(
            text.contains(&std::io::Error::from_raw_os_error(recheck).to_string()),
            "{recheck}: {text}"
        );
    }
}