cosca 0.10.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! What the tree paths send, for every mechanism that has a root, every way the root can be reaped
//! (or only waited on, which reaps nothing) or its handle fail to vouch for it, and every entry
//! point that decides on one look at the root: the tree calls, the armed drop and a failed spawn's
//! `finish_elevated`, and the async graceful shutdown, which is the one entry point the async
//! `Child` makes its own waits for. After a reap by another the root's number may name another
//! process, so nothing may go out by it: no `killpg`, no walk from the root's pid, no signal by a
//! bare pid. What names the tree exactly still runs: an fd marker's holders, a cgroup's kill. A
//! `TreeWalk` checks the root after its snapshot instead, and walks nothing once the root is gone.
//! After the handle's own wait the root is a zombie of ours that pins its number, so the number is
//! used as before the wait.
//!
//! The recorders replace `killpg` with a record and record every walk, holder signal, pidfd signal,
//! `cgroup.kill` write and cgroup member's `SIGTERM` with its route.
//! Each cell's tree is a root `cat` and a second `cat` in its group (in its leaf, holding its
//! marker) that ignores `SIGTERM` and outlives the root. Both end once stdin closes, so a root an
//! entry point leaves alone ends without a signal. Every cell is checked, and the whole matrix is
//! printed if any cell is wrong.

use std::time::Duration;

use crate::test_child::Console;

use crate::identity::{ProcessId, Resolved};
use crate::test_child::reaped_elsewhere::kill_own_child;
#[cfg(target_os = "linux")]
use crate::test_groups::cgroup;
use crate::test_groups::{stray_signal, Group};

/// What a tree is contained by.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mechanism {
    /// A process group: `ContainMode::Session`, with the fd marker suppressed on macOS.
    Group,
    #[cfg(target_os = "macos")]
    MarkerWithGroup,
    #[cfg(target_os = "macos")]
    MarkerWalk,
    /// A tree walk: `ContainMode::TreeWalk`, with the fd marker suppressed on macOS.
    TreeWalk,
    #[cfg(target_os = "linux")]
    Cgroup,
}

impl Mechanism {
    fn has_group(self) -> bool {
        match self {
            Mechanism::Group => true,
            #[cfg(target_os = "macos")]
            Mechanism::MarkerWithGroup => true,
            #[cfg(target_os = "macos")]
            Mechanism::MarkerWalk => false,
            Mechanism::TreeWalk => false,
            #[cfg(target_os = "linux")]
            Mechanism::Cgroup => false,
        }
    }

    /// Whether the tree is reached by a walk from the root's pid.
    fn walks(self) -> bool {
        self.is_marker() || self == Mechanism::TreeWalk
    }

    fn is_marker(self) -> bool {
        #[cfg(target_os = "macos")]
        if matches!(self, Mechanism::MarkerWithGroup | Mechanism::MarkerWalk) {
            return true;
        }
        false
    }

    fn is_cgroup(self) -> bool {
        #[cfg(target_os = "linux")]
        if self == Mechanism::Cgroup {
            return true;
        }
        false
    }

    fn mode(self) -> crate::ContainMode {
        match self {
            Mechanism::Group => crate::ContainMode::Session,
            #[cfg(target_os = "macos")]
            Mechanism::MarkerWithGroup => crate::ContainMode::Session,
            #[cfg(target_os = "macos")]
            Mechanism::MarkerWalk => crate::ContainMode::TreeWalk,
            Mechanism::TreeWalk => crate::ContainMode::TreeWalk,
            #[cfg(target_os = "linux")]
            Mechanism::Cgroup => crate::ContainMode::Strongest,
        }
    }

    fn containment(self) -> crate::Containment {
        match self {
            Mechanism::Group => crate::Containment::Session,
            #[cfg(target_os = "macos")]
            Mechanism::MarkerWithGroup | Mechanism::MarkerWalk => crate::Containment::FdMarker,
            Mechanism::TreeWalk => crate::Containment::TreeWalk,
            #[cfg(target_os = "linux")]
            Mechanism::Cgroup => crate::Containment::CgroupV2,
        }
    }

    /// The tree's command: [`TREE`] under this mechanism, with every stdio piped.
    fn configure(self, cmd: &mut crate::Command) {
        cmd.args(["sh", "-c", if self.is_cgroup() { TREE_SAYING_EOF } else { TREE }]);
        cmd.contain_with(self.mode());
        #[cfg(target_os = "macos")]
        if matches!(self, Mechanism::Group | Mechanism::TreeWalk) {
            cmd.suppress_fd_marker();
        }
        cmd.stdin(crate::Stdio::pipe_in()).expect("stdin pipe");
        cmd.stdout(crate::Stdio::pipe_out()).expect("stdout pipe");
        cmd.stderr(crate::Stdio::pipe_out()).expect("stderr pipe");
    }
}

/// A root `cat` and a `cat` it forked, in its group, that ignores `SIGTERM` (an ignored signal stays
/// ignored across `exec`) and reads the root's stdin through fd 3, as `sh` points a background job's
/// stdin at `/dev/null` otherwise. The forked `cat` prints its pid once it ignores `SIGTERM`. Both
/// hold the stderr pipe's write end, so stderr reaches EOF once both are gone. Closing stdin ends
/// both.
const TREE: &str = r#"exec 3<&0
sh -c 'trap "" TERM; echo $$; exec cat >/dev/null' <&3 3<&- &
exec 3<&-
exec cat >/dev/null"#;

/// [`TREE`] with a `sh` that waits for the forked `cat`, which is the pid it prints, and says `eof` on
/// stderr once that `cat` ends by itself. A `cat` a kill ended exits by a signal, and the `&&` says
/// nothing, however the kernel orders the two deaths.
const TREE_SAYING_EOF: &str = r#"exec 3<&0
sh -c 'trap "" TERM; exec 4<&0; cat >/dev/null <&4 4<&- & echo $!; wait $! && echo eof >&2' <&3 3<&- &
exec 3<&-
exec cat >/dev/null"#;

/// Whether the forked `cat` said it ended by itself: stderr, read to its end, holds `eof`.
fn said_eof(stderr: &[u8]) -> bool {
    String::from_utf8_lossy(stderr).lines().any(|line| line == "eof")
}

/// How the root was reaped before the entry point ran, and what its pid reads as then.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reap {
    None,
    /// The handle's own wait saw the root exit: a zombie of ours, which pins its number.
    Waited,
    /// Not reaped, but the root's own handle cannot answer (`RootState::Unknown`), so its pid may
    /// name another process. On Linux its pidfd still names it exactly.
    Unanswered,
    /// macOS: not reaped, but launchd holds the root (`RootState::Unpinned`) and may reap it at any
    /// time.
    #[cfg(target_os = "macos")]
    Unpinned,
    ForeignFree,
    ForeignReused,
    /// [`ForeignFree`](Reap::ForeignFree), seen by a `try_wait` first: it answers `ECHILD`.
    ForeignSeen,
}

impl Reap {
    const ALL: &[Reap] = &[
        Reap::None,
        Reap::Waited,
        Reap::Unanswered,
        #[cfg(target_os = "macos")]
        Reap::Unpinned,
        Reap::ForeignFree,
        Reap::ForeignReused,
        Reap::ForeignSeen,
    ];

    /// Whether the root's number still names the root: nobody reaped it and its handle vouches for it.
    fn pins_its_number(self) -> bool {
        matches!(self, Reap::None | Reap::Waited)
    }

    /// Whether the root is reaped when the entry point runs.
    fn reaped(self) -> bool {
        match self {
            Reap::None | Reap::Waited | Reap::Unanswered => false,
            #[cfg(target_os = "macos")]
            Reap::Unpinned => false,
            _ => true,
        }
    }

    /// Whether the cell exists for `mechanism`. On Linux the handle's answer is read only by a
    /// mechanism that reaches its tree through the root's number and does not check the root itself;
    /// macOS reads it for every mechanism.
    fn applies_to(self, mechanism: Mechanism) -> bool {
        #[cfg(target_os = "linux")]
        if self == Reap::Unanswered {
            return !mechanism.is_cgroup() && mechanism != Mechanism::TreeWalk;
        }
        let _ = mechanism;
        true
    }

    /// What every read of the root's pid answers after the reap: nothing, another process, or no
    /// answer.
    fn read(self, root: ProcessId) -> Option<Resolved<ProcessId>> {
        match self {
            Reap::None | Reap::Waited | Reap::Unanswered => None,
            #[cfg(target_os = "macos")]
            Reap::Unpinned => None,
            Reap::ForeignFree | Reap::ForeignSeen => Some(Resolved::Gone),
            Reap::ForeignReused => Some(Resolved::Found(root.with_other_value())),
        }
    }
}

impl Reap {
    /// What makes the sync `child`'s own handle fail to vouch for the root in this reap, if anything
    /// does: Linux, one failed peek; macOS, every look at the root answers the same, so a graceful
    /// shutdown's sweep reads what its signal read, and so does its wait.
    fn script(self, child: &mut crate::Child) -> Option<crate::os_process::fake::FakeProcess> {
        #[cfg(target_os = "linux")]
        if self == Reap::Unanswered {
            return Some(
                child
                    .proc
                    .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))])),
            );
        }
        #[cfg(target_os = "macos")]
        {
            use crate::os_process::child::{Foreign, PeekOutcome};
            use crate::os_process::fake::ReapAnswer;
            match self {
                Reap::Unanswered => {
                    return Some(child.proc.script_over(|f| {
                        f.peeks_always(|| Err(std::io::Error::other("forced peek failure")))
                            .reaps_always(ReapAnswer::Err(std::io::ErrorKind::Other))
                    }));
                }
                Reap::Unpinned => {
                    return Some(child.proc.script_over(|f| {
                        f.peeks_always(|| Ok(PeekOutcome::Foreign(Foreign::Orphaned)))
                            .reaps_always(ReapAnswer::Foreign(Foreign::Orphaned))
                    }));
                }
                _ => {}
            }
        }
        let _ = child;
        None
    }

    /// Checks that [`script`](Self::script)'s answers were used: on Linux the failed peek was the one
    /// look at the root the entry point took, and on macOS some look took the repeated answer.
    fn assert_script_used(self, script: Option<&crate::os_process::fake::FakeProcess>) {
        #[cfg(target_os = "linux")]
        if let Some(fake) = script {
            fake.assert_peeks_exhausted();
        }
        #[cfg(target_os = "macos")]
        if let Some(fake) = script {
            assert!(fake.repeats() > 0, "{self:?}: no look took the repeated answer");
        }
        let _ = (self, script);
    }

    /// States what makes the root's number read as this reap, through the kernel the child owns.
    fn state_reads(self, child: &mut crate::Child) {
        let id = child.id().expect(crate::test_child::IDENTITY_READ);
        if let Some(read) = self.read(id) {
            child.proc.number_reads_always(read);
        }
    }

    /// Puts the real root's answers back in place of [`script`](Self::script)'s, for the cell's
    /// cleanup, which kills and reaps the root for real.
    fn lift(scripted: Option<&crate::os_process::fake::FakeProcess>) {
        if let Some(fake) = scripted {
            let lifted = fake.clone().peeks([]).reaps([]);
            #[cfg(target_os = "macos")]
            let lifted = lifted.no_repeats();
            drop(lifted);
        }
    }

    /// Whether the root is unreaped, but its handle cannot vouch for it.
    fn untrusted(self) -> bool {
        !self.reaped() && !self.pins_its_number()
    }

    fn unpinned(self) -> bool {
        #[cfg(target_os = "macos")]
        if self == Reap::Unpinned {
            return true;
        }
        false
    }

    /// Whether the scripted answers must be lifted before the cell's cleanup kills and reaps the
    /// root: a macOS root scripted untrusted would refuse both.
    fn lift_before_cleanup(self) -> bool {
        cfg!(target_os = "macos") && self.untrusted()
    }
}

/// The entry point.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
    /// `kill_tree`.
    Kill,
    /// `terminate_tree`.
    Terminate,
    /// `graceful_shutdown_tree`, with no grace.
    GracefulShutdown,
    /// The handle's armed drop.
    Drop,
    /// A failed spawn's cleanup after a failed password write.
    FinishElevated,
}

impl Op {
    const ALL: [Op; 5] = [
        Op::Kill,
        Op::Terminate,
        Op::GracefulShutdown,
        Op::Drop,
        Op::FinishElevated,
    ];

    /// Whether the entry point consumes the handle: it kills the tree and the root, as `kill_tree`
    /// and `kill` together do.
    fn tears_down(self) -> bool {
        matches!(self, Op::Drop | Op::FinishElevated)
    }

    /// Whether the tree's signal is `SIGKILL` alone.
    fn kills(self) -> bool {
        self == Op::Kill || self.tears_down()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Api {
    Sync,
    #[cfg(feature = "tokio")]
    Tokio,
}

impl Api {
    #[cfg(not(feature = "tokio"))]
    const ALL: &[Api] = &[Api::Sync];
    #[cfg(feature = "tokio")]
    const ALL: &[Api] = &[Api::Sync, Api::Tokio];

    /// Whether the cell exists for `op`: the async `Child` has its own cell only where it awaits the stop
    /// action.
    fn runs(self, op: Op) -> bool {
        #[cfg(feature = "tokio")]
        if self == Api::Tokio {
            return matches!(op, Op::Terminate | Op::GracefulShutdown);
        }
        let _ = op;
        true
    }
}

/// What one cell sent, through the recording seams.
#[derive(Debug, Default)]
struct Sent {
    // By number.
    killpg: bool,
    walk: bool,
    /// A signal to a bare pid: macOS's identity-checked kill of the root, or a cgroup member's
    /// `SIGTERM` by its number.
    by_pid: bool,
    // Exact.
    /// The signals the `cat`, a marker holder, got through the holders channel.
    holder: Vec<nix::sys::signal::Signal>,
    /// The signals the root, also a marker holder, got through the holders channel.
    root_holder: Vec<nix::sys::signal::Signal>,
    pidfd: bool,
    /// `kill_tree`'s handle backstop was sent the root's kill, after its sweep: the root was killed
    /// through its pidfd twice, once by the walk and once by the backstop.
    backstop: bool,
    /// A cgroup member's `SIGTERM` through its pidfd.
    member_term: bool,
    cgroup_kill: bool,
    /// A cgroup's forked `cat` ended by itself, once stdin closed, and not of a signal.
    survivor_ended_alone: bool,
}

/// What a cell must send through one channel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Want {
    Yes,
    No,
    Any,
}

impl Want {
    fn holds(self, sent: bool) -> bool {
        match self {
            Want::Yes => sent,
            Want::No => !sent,
            Want::Any => true,
        }
    }
}

struct Expected {
    killpg: Want,
    walk: Want,
    by_pid: Want,
    /// `None`: not checked.
    holder: Option<&'static [nix::sys::signal::Signal]>,
    /// `None`: not checked.
    root_holder: Option<&'static [nix::sys::signal::Signal]>,
    pidfd: Want,
    backstop: Want,
    /// A cgroup member's `SIGTERM` through its pidfd.
    member_term: Want,
    cgroup_kill: Want,
    /// A cgroup's kill ends the forked `cat` before stdin closes.
    survivor_ended_alone: Want,
}

fn expected(mechanism: Mechanism, reap: Reap, op: Op) -> Expected {
    use nix::sys::signal::Signal::{SIGKILL, SIGTERM};
    let reaped = reap.reaped();
    // After a foreign reap with the pid naming nothing, the group may still have members, but once
    // none survives another process may take the number first: nothing is sent by it.
    let killpg = if mechanism.has_group() && reap.pins_its_number() {
        Want::Yes
    } else if cfg!(target_os = "linux") && mechanism.has_group() && reap == Reap::Unanswered && op == Op::FinishElevated
    {
        // The one failed peek is the cleanup's first look; its root wait then leaves a zombie that
        // pins the number, so the early tree kill after that wait reads the root as unreaped.
        Want::Yes
    } else {
        Want::No
    };
    // A walk from a waited root finds nothing (its children went to init), so whether one is made is
    // not the number's use: `Any`. A mechanism that does not walk never makes one.
    let walk = match (mechanism.walks(), reap) {
        (true, Reap::None) => Want::Yes,
        (true, Reap::Waited) => Want::Any,
        _ => Want::No,
    };
    let by_pid = if mechanism.is_cgroup() && !op.kills() {
        Want::No
    } else if reap == Reap::Waited {
        // The handle has recorded the exit, so a signal to the root is `Sent::Gone` before any send,
        // and nothing else is sent by a bare pid.
        Want::No
    } else if cfg!(target_os = "macos") && op.tears_down() && reap == Reap::Unanswered {
        // A teardown kills the root through its handle, as `kill` does: on macOS by pid, after a
        // check of its unique id.
        Want::Yes
    } else if reaped || !reap.pins_its_number() {
        Want::No
    } else {
        Want::Any
    };
    let sweep: &'static [nix::sys::signal::Signal] = match op {
        Op::Kill | Op::Drop | Op::FinishElevated => &[SIGKILL],
        Op::Terminate => &[SIGTERM],
        Op::GracefulShutdown => &[SIGTERM, SIGKILL],
    };
    let holder: Option<&'static [nix::sys::signal::Signal]> = match (mechanism.is_marker(), reap.pins_its_number()) {
        (true, false) => Some(sweep),
        // A waited root's children went to init, so its walk finds no `cat` and the sweep signals it by
        // its marker, unless the group's `killpg` reached it first.
        (true, true) if reap == Reap::Waited && !mechanism.has_group() => Some(sweep),
        // The walk reaches the `cat` first.
        (true, true) => None,
        (false, _) => Some(&[]),
    };
    // A macOS root the handle cannot vouch for: launchd's zombie is left alone, and an unanswered
    // root is signalled with the other holders. A graceful shutdown's `SIGTERM` may end it before
    // the sweep looks for holders.
    let root_holder: Option<&'static [nix::sys::signal::Signal]> = if !(cfg!(target_os = "macos") && reap.untrusted()) {
        None
    } else if !mechanism.is_marker() || reap.unpinned() {
        Some(&[])
    } else {
        match op {
            Op::Kill | Op::Drop | Op::FinishElevated => Some(&[SIGKILL]),
            Op::Terminate => Some(&[SIGTERM]),
            Op::GracefulShutdown => None,
        }
    };
    // The handle backstop, through the pidfd; after a reap it has nothing to reach. A root whose
    // handle cannot answer is signalled through it by every entry point: it names the root exactly.
    // A walk sends its root's `SIGTERM` and its kill through the root's handle too.
    let pidfd = match (cfg!(target_os = "linux"), reaped, op) {
        (false, _, _) => Want::No,
        (true, true, _) => Want::Any,
        // The handle has recorded the exit: its signals to the root are `Sent::Gone`, none through the pidfd.
        (true, false, _) if reap == Reap::Waited => Want::No,
        (true, false, _) if reap != Reap::None => Want::Yes,
        (true, false, Op::Terminate) if mechanism.walks() => Want::Yes,
        (true, false, Op::Terminate) => Want::No,
        (true, false, _) => Want::Yes,
    };
    // The walk has already killed the root through the handle when `kill_tree` reaches the backstop,
    // so the backstop shows as a second kill through it: a `kill_tree` that skips it leaves the root
    // to a walk that may have found nothing.
    let backstop =
        if cfg!(target_os = "linux") && mechanism == Mechanism::TreeWalk && reap == Reap::None && op == Op::Kill {
            Want::Yes
        } else if reap == Reap::Waited {
            // No kill goes through the root's handle at all, let alone a second.
            Want::No
        } else {
            Want::Any
        };
    // The tree's second `cat` stays a running member, so the graceful half reaches it, reaped root
    // or not.
    let member_term = if mechanism.is_cgroup() && !op.kills() {
        Want::Yes
    } else {
        Want::No
    };
    let cgroup_kill = if mechanism.is_cgroup() && op != Op::Terminate {
        Want::Yes
    } else {
        Want::No
    };
    Expected {
        killpg,
        walk,
        by_pid,
        holder,
        root_holder,
        pidfd,
        backstop,
        member_term,
        cgroup_kill,
        survivor_ended_alone: if cgroup_kill == Want::Yes { Want::No } else { Want::Any },
    }
}

/// The checks `sent` fails against `want`, by channel.
fn mismatches(want: &Expected, sent: &Sent) -> Vec<String> {
    let mut wrong = Vec::new();
    let mut check = |name: &str, want: Want, sent: bool| {
        if !want.holds(sent) {
            wrong.push(format!("{name}: want {want:?}, sent {sent}"));
        }
    };
    check("killpg", want.killpg, sent.killpg);
    check("walk", want.walk, sent.walk);
    check("by-pid", want.by_pid, sent.by_pid);
    check("pidfd", want.pidfd, sent.pidfd);
    check("backstop", want.backstop, sent.backstop);
    check("member SIGTERM", want.member_term, sent.member_term);
    check("cgroup.kill", want.cgroup_kill, sent.cgroup_kill);
    check(
        "survivor ended alone",
        want.survivor_ended_alone,
        sent.survivor_ended_alone,
    );
    if let Some(holder) = want.holder {
        if sent.holder != holder {
            wrong.push(format!("holder: want {holder:?}, sent {:?}", sent.holder));
        }
    }
    if let Some(root) = want.root_holder {
        if sent.root_holder != root {
            wrong.push(format!("root holder: want {root:?}, sent {:?}", sent.root_holder));
        }
    }
    wrong
}

/// The recorders for one cell, on this thread.
struct Recorders {
    groups: crate::containment::unix::fault::KillGroupRecorder,
    terms: crate::containment::unix::fault::TermGroupRecorder,
    walks: crate::containment::treewalk::fault::WalkRecorder,
    sends: crate::send_log::Capture,
    #[cfg(target_os = "macos")]
    holders: crate::containment::fdmarker::fault::HolderKillRecorder,
}

impl Recorders {
    fn start() -> Recorders {
        #[cfg(target_os = "linux")]
        {
            crate::containment::cgroup::fault::record_leaf_steps();
            crate::containment::cgroup::fault::take_member_terms();
        }
        Recorders {
            groups: crate::containment::unix::fault::record_kill_group(),
            terms: crate::containment::unix::fault::record_term_group(),
            walks: crate::containment::treewalk::fault::record_walks(),
            sends: crate::send_log::Capture::start(),
            #[cfg(target_os = "macos")]
            holders: crate::containment::fdmarker::fault::record_holder_kills(),
        }
    }

    /// What was sent so far. `root` and `cat` are the tree's pids.
    #[cfg_attr(
        not(target_os = "macos"),
        allow(unused_variables, reason = "only macOS has marker holders")
    )]
    fn sent(&self, root: u32, cat: u32) -> Sent {
        use crate::send_log::Via;
        let entries = self.sends.entries();
        #[cfg(target_os = "linux")]
        let (cgroup_kill, member_terms) = (
            crate::containment::cgroup::fault::take_leaf_steps()
                .iter()
                .any(|step| step == "kill"),
            crate::containment::cgroup::fault::take_member_terms(),
        );
        #[cfg(not(target_os = "linux"))]
        let (cgroup_kill, member_terms): (bool, Vec<(Option<u32>, Via, i32)>) = (false, Vec::new());
        Sent {
            killpg: !self.groups.killed().is_empty() || !self.terms.termed().is_empty(),
            walk: !self.walks.walked().is_empty(),
            by_pid: member_terms.iter().any(|(_, via, _)| *via == Via::Pid)
                || entries.iter().any(|(_, _, via)| *via == Via::Identity),
            member_term: member_terms.iter().any(|(_, via, _)| *via == Via::Pidfd),
            #[cfg(target_os = "macos")]
            holder: self.holders.signals_to(cat),
            #[cfg(not(target_os = "macos"))]
            holder: Vec::new(),
            #[cfg(target_os = "macos")]
            root_holder: self.holders.signals_to(root),
            #[cfg(not(target_os = "macos"))]
            root_holder: Vec::new(),
            pidfd: entries.iter().any(|(pid, _, via)| *pid == root && *via == Via::Pidfd),
            // The walk's own kill of the root and the backstop's go through the same handle: a second
            // kill through it is the backstop's.
            backstop: entries
                .iter()
                .filter(|(pid, sig, via)| *pid == root && *sig == crate::signal::Sig::Kill && *via == Via::Pidfd)
                .count()
                >= 2,
            cgroup_kill,
            survivor_ended_alone: false,
        }
    }
}

/// Checks a `try_wait` after a foreign reap answered `ECHILD`.
#[track_caller]
fn assert_echild<T: std::fmt::Debug>(waited: Result<T, crate::error::Error>) {
    assert!(
        matches!(&waited, Err(crate::error::Error::Io(e)) if e.raw_os_error() == Some(libc::ECHILD)),
        "a try_wait after a foreign reap: {waited:?}"
    );
}

/// Reads the `cat`'s pid, the line it prints once it ignores `SIGTERM`.
fn cat_pid(line: &str) -> u32 {
    line.trim().parse().expect("the cat's pid")
}

/// Runs one sync cell and returns what it sent.
fn run_sync(mechanism: Mechanism, reap: Reap, op: Op) -> Sent {
    use std::io::{BufRead as _, Read as _};
    let mut cmd = crate::test_child::command(Console::Hidden);
    mechanism.configure(&mut cmd);
    let mut child = cmd.spawn().expect("spawn");
    assert_eq!(child.containment(), mechanism.containment(), "{mechanism:?}");
    let mut line = String::new();
    std::io::BufReader::new(child.stdout().expect("stdout pipe"))
        .read_line(&mut line)
        .expect("read the cat's pid");
    let cat = cat_pid(&line);
    let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(child.stdin().expect("stdin pipe"))));
    let mut stderr = child.stderr().expect("stderr pipe");
    let root = child.pid();
    if reap == Reap::Waited {
        kill_own_child(root);
        child.wait().expect("the wait sees the root exit");
    }
    if reap.reaped() {
        kill_own_child(root);
        crate::test_child::reaped_elsewhere::reap_behind(root);
        if reap == Reap::ForeignSeen {
            assert_echild(child.try_wait());
        }
    }
    let scripted = reap.script(&mut child);
    reap.state_reads(&mut child);

    let _released = release_when_the_drain_blocks(mechanism, &stdin);
    #[cfg(target_os = "linux")]
    let _released_at_the_root_wait = crate::child::spawn::fault::release_when_a_teardown_waits(&stdin);
    let recorders = Recorders::start();
    // The cell checks what was sent, not what the call answered.
    _ = match op {
        Op::Kill => child.kill_tree(),
        Op::Terminate => child.terminate_tree(),
        Op::GracefulShutdown => child.graceful_shutdown_tree(Duration::ZERO).map(drop),
        Op::Drop => {
            drop(child);
            return finish_teardown(reap, scripted, recorders, root, cat, stdin, stderr);
        }
        Op::FinishElevated => {
            _ = crate::child::spawn::finish_elevated(child, failed_write());
            return finish_teardown(reap, scripted, recorders, root, cat, stdin, stderr);
        }
    };
    reap.assert_script_used(scripted.as_ref());
    let mut sent = recorders.sent(root, cat);
    if reap.lift_before_cleanup() {
        // The root's kill and reap below are the real ones.
        Reap::lift(scripted.as_ref());
    }

    // The tree is gone before the drop, which runs under the recorders: it sends no killpg.
    if !reap.reaped() {
        // Released, not killed: the op may have reaped the root, so its number may name another process.
        drop(stdin.take());
        child.wait().expect("reap the root");
    }
    drop(stdin.take());
    let mut rest = Vec::new();
    stderr
        .read_to_end(&mut rest)
        .expect("the root and the cat are gone, closing stderr");
    sent.survivor_ended_alone = said_eof(&rest);
    if mechanism.is_cgroup() {
        child.wait_tree().expect("the leaf drains");
    }
    drop(child);
    drop(recorders);
    sent
}

fn failed_write() -> Result<(), crate::error::Error> {
    Err(crate::error::Error::Io(std::io::Error::other(
        "forced password-write failure",
    )))
}

/// A cgroup's teardown, and its graceful shutdown, wait for the leaf to drain, which only its kill
/// brings about: when that wait is about to block, stdin is closed, so a kill that sent nothing
/// lets the tree end by itself instead of the wait hanging.
#[cfg(target_os = "linux")]
fn release_when_the_drain_blocks<T: 'static>(
    mechanism: Mechanism,
    stdin: &std::rc::Rc<std::cell::Cell<Option<T>>>,
) -> Option<crate::wait::block_probe::Armed> {
    mechanism.is_cgroup().then(|| {
        let stdin = std::rc::Rc::clone(stdin);
        crate::wait::block_probe::on_drain_block(move || drop(stdin.take()))
    })
}

#[cfg(not(target_os = "linux"))]
fn release_when_the_drain_blocks<T>(_: Mechanism, _: &std::rc::Rc<std::cell::Cell<Option<T>>>) -> Option<()> {
    None
}

/// What a sync teardown sent, then the end of what it left: closing stdin ends a root it left
/// alone and a `cat` it did not kill. A root left unreaped stays a zombie until the test process
/// ends, as nothing may reap it by its number.
#[allow(clippy::too_many_arguments, reason = "one cell's state, passed through")]
fn finish_teardown(
    reap: Reap,
    scripted: Option<crate::os_process::fake::FakeProcess>,
    recorders: Recorders,
    root: u32,
    cat: u32,
    stdin: std::rc::Rc<std::cell::Cell<Option<crate::PipeWriter>>>,
    mut stderr: crate::PipeReader,
) -> Sent {
    use std::io::Read as _;
    reap.assert_script_used(scripted.as_ref());
    let mut sent = recorders.sent(root, cat);
    drop(stdin.take());
    let mut rest = Vec::new();
    stderr
        .read_to_end(&mut rest)
        .expect("the root and the cat are gone, closing stderr");
    sent.survivor_ended_alone = said_eof(&rest);
    drop(recorders);
    sent
}

/// Runs one tokio cell, the async `terminate_tree` or graceful shutdown (the entry points that await
/// the stop action and the async driver's waits), and returns what it sent. The other entry points are
/// the sync `Child`'s, which the async one calls through.
#[cfg(feature = "tokio")]
async fn run_tokio(mechanism: Mechanism, reap: Reap, op: Op) -> Sent {
    use ::tokio::io::{AsyncBufReadExt as _, AsyncReadExt as _};
    let mut cmd = crate::test_child::tokio_command(Console::Hidden);
    mechanism.configure(cmd.as_sync_mut());
    let mut child = cmd.spawn().await.expect("spawn");
    assert_eq!(child.containment(), mechanism.containment(), "{mechanism:?}");
    let mut line = String::new();
    ::tokio::io::BufReader::new(child.stdout().expect("stdout pipe"))
        .read_line(&mut line)
        .await
        .expect("read the cat's pid");
    let cat = cat_pid(&line);
    let stdin = std::rc::Rc::new(std::cell::Cell::new(Some(child.stdin().expect("stdin pipe"))));
    let mut stderr = child.stderr().expect("stderr pipe");
    let root = child.pid();
    if reap == Reap::Waited {
        kill_own_child(root);
        child.wait().await.expect("the wait sees the root exit");
    }
    if reap.reaped() {
        kill_own_child(root);
        crate::test_child::reaped_elsewhere::reap_behind(root);
        if reap == Reap::ForeignSeen {
            assert_echild(child.try_wait());
        }
    }
    let scripted = reap.script(&mut child.inner);
    reap.state_reads(&mut child.inner);

    let _released = release_when_the_drain_blocks(mechanism, &stdin);
    #[cfg(target_os = "linux")]
    let _released_at_the_root_wait = crate::child::spawn::fault::release_when_a_teardown_waits(&stdin);
    let recorders = Recorders::start();
    // The cell checks what was sent, not what the call answered.
    _ = match op {
        Op::Terminate => child.terminate_tree().await,
        Op::GracefulShutdown => child.graceful_shutdown_tree(Duration::ZERO).await.map(drop),
        Op::Kill | Op::Drop | Op::FinishElevated => unreachable!("{op:?} has no async cell"),
    };
    reap.assert_script_used(scripted.as_ref());
    let mut sent = recorders.sent(root, cat);
    if reap.lift_before_cleanup() {
        // The root's kill and reap below are the real ones.
        Reap::lift(scripted.as_ref());
    }

    if !reap.reaped() {
        // Released, not killed: the op may have reaped the root, so its number may name another process.
        drop(stdin.take());
        child.wait().await.expect("reap the root");
    }
    drop(stdin.take());
    let mut rest = Vec::new();
    stderr
        .read_to_end(&mut rest)
        .await
        .expect("the root and the cat are gone, closing stderr");
    sent.survivor_ended_alone = said_eof(&rest);
    if mechanism.is_cgroup() {
        child.wait_tree().await.expect("the leaf drains");
    }
    drop(child);
    drop(recorders);
    sent
}

/// Runs every cell of `mechanisms` and fails, printing the whole matrix, if any cell is wrong.
fn check_matrix(mechanisms: &[Mechanism]) {
    #[cfg(feature = "tokio")]
    let runtime = ::tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("build a current-thread runtime: the recorders are thread-local");
    let mut rows = Vec::new();
    let mut failed = 0;
    for &mechanism in mechanisms {
        for &reap in Reap::ALL.iter().filter(|reap| reap.applies_to(mechanism)) {
            for op in Op::ALL {
                for &api in Api::ALL.iter().filter(|api| api.runs(op)) {
                    let sent = match api {
                        Api::Sync => run_sync(mechanism, reap, op),
                        #[cfg(feature = "tokio")]
                        Api::Tokio => runtime.block_on(run_tokio(mechanism, reap, op)),
                    };
                    let want = expected(mechanism, reap, op);
                    let wrong = mismatches(&want, &sent);
                    let verdict = if wrong.is_empty() {
                        "ok".to_owned()
                    } else {
                        failed += 1;
                        format!("WRONG: {}", wrong.join("; "))
                    };
                    rows.push(format!(
                        "{mechanism:?} | {reap:?} | {op:?} | {api:?} | {sent:?} | {verdict}"
                    ));
                }
            }
        }
    }
    assert_eq!(
        failed,
        0,
        "{failed} of {} cells are wrong:\n{}",
        rows.len(),
        rows.join("\n")
    );
}

/// The process group, the tree walk, and on macOS both fd markers.
///
/// Mutants: a root the handle's own wait saw exit is read as reaped (no `killpg` after the wait);
/// `root_number` answers `Trusted` for any of a foreign reap, an own reap whose pid is
/// reused or names nothing (a group), or (macOS) a root that is
/// `Unpinned` or `Unknown`; the holders sweep skipped after a reap or for an untrusted root; an
/// `Unpinned` root signalled as a holder; `treewalk::hard_kill` or `treewalk::terminate` walks
/// without `anchor`. The recorders stop a `killpg`, not a walk from the reaped root's pid, so a
/// mutant that walks may signal an unrelated process's children.
#[skuld::test]
fn tree_paths_send_nothing_by_the_root_number_after_a_reap(#[fixture(stray_signal)] _stray: &Group) {
    #[cfg(target_os = "linux")]
    let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
    check_matrix(&[
        Mechanism::Group,
        Mechanism::TreeWalk,
        #[cfg(target_os = "macos")]
        Mechanism::MarkerWithGroup,
        #[cfg(target_os = "macos")]
        Mechanism::MarkerWalk,
    ]);
}

/// A cgroup names no pid, so its kill still runs after any reap, and ends the forked `cat` before stdin
/// closes: the cell fails if that `cat` says it ended by itself.
#[cfg(target_os = "linux")]
#[skuld::test]
fn cgroup_tree_paths_still_kill_through_the_cgroup_after_a_reap(#[fixture(cgroup)] _group: &Group) {
    check_matrix(&[Mechanism::Cgroup]);
}