cosca 0.7.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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
//! Placing a task in a leaf's subtree by its cgroup id, and deciding before a spawn whether a front
//! can be placed. Unprivileged: the ids are forced, and the probe reads a child of this process.

use std::os::fd::{AsFd as _, OwnedFd};
use std::sync::Arc;

use super::ProbeEnd;
use super::{dying_in, front_placement, Subtree};
use crate::containment::cgroup::fault::{self, ProbeStep};
use crate::containment::cgroup::test_support::{alone, kill_record};
use crate::identity::{FakeKernel, HostKernel, UNREADABLE_STATUS_REASON};
use crate::log_capture::warns_since;
use crate::send_log::Via;
use crate::test_groups::{cgroup, Group};

/// A cgroup id with bits above the low 32, as kernfs gives once its 32-bit counter wraps.
const HIGH: u64 = 0x1_0000_0007;

fn own_pidfd() -> OwnedFd {
    rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty()).expect("pidfd_open")
}

fn subtree(leaf_id: u64, killed: bool) -> Subtree {
    Subtree::new(
        Some(leaf_id),
        None,
        None,
        crate::containment::cgroup::Swept::default(),
        super::PlacedAtRemoval::default(),
        kill_record(killed),
    )
}

/// A subtree whose leaf directory is a stand-in, an ordinary empty directory with `stat` as its
/// `cgroup.stat` (none: `None`), with a path, so a task it cannot place is placed through `/proc`.
/// The directory is returned to outlive the subtree.
fn stand_in_subtree(stat: Option<&str>) -> (Subtree, tempfile::TempDir) {
    let dir = tempfile::tempdir().expect("tempdir");
    // A live cgroup's file, which the walk reads to tell its root was not removed.
    std::fs::write(dir.path().join("cgroup.events"), "populated 0\n").expect("write the stand-in cgroup.events");
    if let Some(stat) = stat {
        std::fs::write(dir.path().join("cgroup.stat"), stat).expect("write the stand-in cgroup.stat");
    }
    let fd = rustix::fs::open(
        dir.path(),
        rustix::fs::OFlags::PATH | rustix::fs::OFlags::DIRECTORY | rustix::fs::OFlags::CLOEXEC,
        rustix::fs::Mode::empty(),
    )
    .expect("open the stand-in leaf");
    (subtree_of(fd, crate::containment::cgroup::Swept::default()), dir)
}

/// A subtree of the leaf `fd` holds, with a path, killed through.
fn subtree_of(fd: OwnedFd, swept: crate::containment::cgroup::Swept) -> Subtree {
    Subtree::new(
        Some(HIGH),
        Some(Arc::new(fd)),
        Some("/stand-in-leaf".to_owned()),
        swept,
        super::PlacedAtRemoval::default(),
        kill_record(true),
    )
}

/// Whether `leaf` holds this process, read as a task whose pidfd's cgroup id is `id`, with `/proc`
/// hidden: only the id, the sweep's record and the walk may place it.
fn holds_hidden(leaf: &Subtree, id: u64) -> std::io::Result<bool> {
    let _id = fault::force_pidfd_cgroup_id(id);
    let _hidden = fault::hide_proc();
    let pidfd = own_pidfd();
    leaf.holds(std::process::id(), Some(pidfd.as_fd()))
}

/// A task is in the leaf only when all 64 bits of its cgroup id are the leaf's: an id equal in
/// its low 32 bits names another cgroup.
#[skuld::test]
fn a_subtree_compares_all_64_bits_of_a_cgroup_id() {
    let pidfd = own_pidfd();
    let pid = std::process::id();
    let leaf = subtree(HIGH, false);
    {
        let _id = fault::force_pidfd_cgroup_id(HIGH);
        assert!(leaf.holds(pid, Some(pidfd.as_fd())).expect("a forced id"));
    }
    {
        let _id = fault::force_pidfd_cgroup_id(HIGH & u64::from(u32::MAX));
        assert!(
            !leaf.holds(pid, Some(pidfd.as_fd())).expect("a forced id"),
            "an id equal only in its low 32 bits is another cgroup"
        );
    }
    let low = subtree(HIGH & u64::from(u32::MAX), false);
    let _id = fault::force_pidfd_cgroup_id(HIGH);
    assert!(!low.holds(pid, Some(pidfd.as_fd())).expect("a forced id"));
}

/// A kill reached a task only if the leaf's own kill landed: a task in the leaf whose kill failed
/// was reached by nothing.
#[skuld::test]
fn a_subtree_reached_a_task_only_once_its_kill_landed() {
    let pidfd = own_pidfd();
    let pid = std::process::id();
    let _id = fault::force_pidfd_cgroup_id(HIGH);
    assert!(subtree(HIGH, false)
        .holds(pid, Some(pidfd.as_fd()))
        .expect("a forced id"));
    assert!(!subtree(HIGH, false)
        .reached_by(pid, Some(pidfd.as_fd()))
        .expect("a forced id"));
    assert!(subtree(HIGH, true)
        .reached_by(pid, Some(pidfd.as_fd()))
        .expect("a forced id"));
}

/// With `PIDFD_GET_INFO`, fronts are placeable whatever `/proc` hides.
#[skuld::test]
fn with_pidfd_info_a_front_is_placeable_whatever_proc_hides() {
    let _id = fault::force_pidfd_cgroup_id(HIGH);
    let _hidden = fault::hide_proc();
    front_placement(&HostKernel, || Ok(HIGH)).expect("placeable by a pidfd's cgroup id");
}

/// Without `PIDFD_GET_INFO`, a `/proc` that shows a process this one may not trace makes fronts
/// placeable. The probe is real: a non-dumpable child of this process, read and reaped.
///
/// A precondition, declared by the cgroup group: the lane runs as root, whose `CAP_SYS_PTRACE` reads
/// a non-dumpable child's cgroup through `/proc` whatever its mount options (`hidepid` hides it from
/// anyone else). The refusal where `/proc` hides it is tested by forcing it.
#[skuld::test]
fn cgroup_without_pidfd_info_a_proc_that_shows_untraceable_processes_places_fronts(#[fixture(cgroup)] _group: &Group) {
    let _missing = fault::miss_pidfd_info();
    front_placement(&HostKernel, || Ok(HIGH)).expect("the lane's /proc shows its root every process");
}

/// Without `PIDFD_GET_INFO`, a `/proc` that hides a process this one may not trace refuses an
/// elevated, contained spawn, naming `hidepid`.
#[skuld::test]
fn without_pidfd_info_a_hidepid_proc_refuses_naming_hidepid() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    match front_placement(&HostKernel, || Ok(HIGH)) {
        Err(crate::error::Error::Unsupported { detail, .. }) => {
            assert!(detail.contains("hidepid"), "{detail}");
            assert!(detail.contains("before anything is spawned"), "{detail}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// Without `PIDFD_GET_INFO`, a `/proc` of an outer pid namespace refuses, naming that, not
/// `hidepid`.
#[skuld::test]
fn without_pidfd_info_a_diverged_proc_view_refuses_naming_the_view() {
    let _missing = fault::miss_pidfd_info();
    let kernel = FakeKernel::over(&HostKernel).diverged_view();
    match front_placement(&kernel, || Ok(HIGH)) {
        Err(crate::error::Error::Unsupported { detail, .. }) => {
            assert!(detail.contains("an outer pid namespace's"), "{detail}");
            assert!(!detail.contains("hidepid"), "{detail}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// Without `PIDFD_GET_INFO`, an unassessable `/proc` view refuses, naming that, not `hidepid`.
#[skuld::test]
fn without_pidfd_info_an_unassessable_proc_view_refuses_naming_the_view() {
    let _missing = fault::miss_pidfd_info();
    let kernel = FakeKernel::over(&HostKernel).unreadable_view();
    match front_placement(&kernel, || Ok(HIGH)) {
        Err(crate::error::Error::Unsupported { detail, .. }) => {
            assert!(
                detail.contains(&format!("could not be established ({UNREADABLE_STATUS_REASON})")),
                "{detail}"
            );
            assert!(!detail.contains("hidepid"), "{detail}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// The probe's socket lands on whatever descriptors are free, std's own included: with fds 0 and 1
/// closed it still reads, and still refuses where `/proc` hides. Runs in a process of its own:
/// closing 0 and 1 is process-wide. Its precondition is the cgroup group's root, as above.
#[skuld::test]
fn cgroup_the_placement_probe_answers_with_fds_0_and_1_closed(#[fixture(cgroup)] _group: &Group) {
    use crate::test_own_process::{own_process, test_path};
    use crate::test_spawn::spawn;
    use crate::test_stdio::RestoreStdio;

    let Some(done) = own_process(
        test_path!(cgroup_the_placement_probe_answers_with_fds_0_and_1_closed),
        spawn,
    ) else {
        return;
    };
    let _missing = fault::miss_pidfd_info();
    let restore = RestoreStdio::close(&done, &[0, 1]);
    let shown = front_placement(&HostKernel, || Ok(HIGH));
    let hidden = {
        let _hidden = fault::hide_proc();
        front_placement(&HostKernel, || Ok(HIGH))
    };
    drop(restore);
    shown.expect("this test's /proc hides nothing");
    assert!(
        matches!(hidden, Err(crate::error::Error::Unsupported { .. })),
        "{hidden:?}"
    );
}

/// `cgroup.stat`'s count of removed cgroups not yet freed.
#[skuld::test]
fn dying_cgroups_are_read_from_cgroup_stat() {
    assert_eq!(dying_in("nr_descendants 0\nnr_dying_descendants 0\n"), Some(0));
    assert_eq!(
        dying_in("nr_descendants 2\nnr_dying_descendants 1\nnr_subsys_cpu 3\n"),
        Some(1)
    );
    assert_eq!(dying_in("nr_descendants 0\n"), None);
    assert_eq!(dying_in("nr_dying_descendants_x 0\n"), None);
}

/// A task in a cgroup nested under the leaf is in the subtree, found by the walk with no `/proc`.
#[skuld::test]
fn cgroup_a_task_in_a_nested_cgroup_is_found_by_the_walk(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::dir_walk_tests::{id_at, Scratch};
    let scratch = Scratch::new("reach-nested");
    let nested = id_at(&scratch.make("a/b/c"));
    scratch.make("d");
    let leaf = subtree_of(scratch.fd(), crate::containment::cgroup::Swept::default());
    assert!(holds_hidden(&leaf, nested).expect("no /proc read"));
}

/// A task in a cgroup the walk finds nowhere, under a leaf with no cgroup removed but not freed,
/// is outside it, read with no `/proc`.
#[skuld::test]
fn a_task_the_walk_finds_nowhere_is_outside() {
    let (leaf, _dir) = stand_in_subtree(Some("nr_descendants 0\nnr_dying_descendants 0\n"));
    assert!(!holds_hidden(&leaf, HIGH + 1).expect("no /proc read"));
}

/// A walk that finds nothing, but cannot show the cgroup is not one removed and not yet freed (the
/// leaf's `cgroup.stat` counts some, holds no count, or cannot be read), says so at `debug`, with the
/// cause; one that proves it says nothing. Mutant: "the unproven absence is silent".
#[skuld::test]
fn a_walk_that_finds_nothing_but_cannot_prove_it_says_why() {
    crate::log_capture::install();
    let says = "so it is not shown to be outside";
    for (stat, cause) in [
        (Some("nr_dying_descendants 2\n"), Some("2 are removed")),
        (Some("nr_descendants 0\n"), Some("an unknown number")),
        (None, Some("cgroup.stat cannot be read")),
        (Some("nr_dying_descendants 0\n"), None),
    ] {
        let (leaf, _dir) = stand_in_subtree(stat);
        let mark = crate::log_capture::mark();
        let held = holds_hidden(&leaf, HIGH + 1);
        let logs = crate::log_capture::records_since_on_current_thread(mark, says);
        match cause {
            Some(cause) => {
                held.expect_err("not shown outside, so placed through the hidden /proc");
                assert_eq!(logs.len(), 1, "{stat:?}: {logs:?}");
                assert_eq!(logs[0].0, log::Level::Debug, "{stat:?}");
                assert!(logs[0].1.contains(cause), "{stat:?}: {logs:?}");
            }
            None => {
                assert!(!held.expect("proven outside"));
                assert_eq!(logs, [], "{stat:?}");
            }
        }
    }
}

/// A task in a cgroup the sweep removed is in the subtree, once the leaf is gone too.
#[skuld::test]
fn cgroup_a_task_in_a_cgroup_the_sweep_removed_is_in_the_subtree(#[fixture(cgroup)] _group: &Group) {
    use crate::containment::cgroup::dir_walk_tests::{id_at, Scratch};
    let scratch = Scratch::new("reach-swept");
    let sub = id_at(&scratch.make("sub"));
    let leaf = crate::containment::cgroup::LeafDir::open_for_test(scratch.path());
    assert_eq!(leaf.remove_children().expect("sweep"), 1);
    leaf.rmdir().expect("remove the scratch leaf");
    let subtree = Subtree::new(
        Some(HIGH),
        Some(leaf.shared()),
        Some("/stand-in-leaf".to_owned()),
        leaf.swept(),
        super::PlacedAtRemoval::default(),
        kill_record(true),
    );
    assert!(holds_hidden(&subtree, sub).expect("no /proc read"));
}

/// A task the walk cannot place, because a cgroup under the leaf is removed but not freed, the
/// leaf's `cgroup.stat` cannot be read, or the walk itself cannot list a cgroup (the stand-in's
/// own directories are no cgroups), is placed through `/proc`, and where that is hidden, not at all.
#[skuld::test]
fn a_task_the_walk_cannot_place_is_placed_through_proc() {
    for (stat, sub) in [
        (Some("nr_dying_descendants 1\n"), false),
        (None, false),
        (Some("nr_dying_descendants 0\n"), true),
    ] {
        let (leaf, dir) = stand_in_subtree(stat);
        if sub {
            std::fs::create_dir(dir.path().join("sub")).expect("mkdir");
        }
        let err = holds_hidden(&leaf, HIGH + 1).expect_err("placed through the hidden /proc");
        assert!(err.to_string().contains("maybe one under it"), "{stat:?} {sub}: {err}");
    }
}

/// `/proc`'s ` (deleted)` after the leaf's own path is the removed leaf or a live namesake beside
/// it: it is answered by the place recorded before the leaf's removal alone, undecidable without
/// one, and never the leaf when the task's pidfd gave another cgroup id. A path under the leaf is
/// under it either way.
#[skuld::test]
fn a_removed_leaf_is_answered_by_the_place_recorded_before_its_removal() {
    use super::names_leaf;
    let unasked = || -> Option<bool> { panic!("not asked") };
    let (leaf, deleted) = ("/a/leaf", "/a/leaf (deleted)");
    assert!(names_leaf(leaf, leaf, false, unasked).expect("decided"));
    assert!(names_leaf("/a/leaf/sub (deleted)", leaf, true, unasked).expect("decided"));
    assert!(
        names_leaf(deleted, leaf, false, || Some(true)).expect("decided"),
        "recorded in the leaf"
    );
    assert!(
        !names_leaf(deleted, leaf, false, || Some(false)).expect("decided"),
        "recorded outside"
    );
    names_leaf(deleted, leaf, false, || None).expect_err("no record: the leaf or its namesake");
    assert!(
        !names_leaf(deleted, leaf, true, unasked).expect("decided"),
        "another cgroup id"
    );
    assert!(!names_leaf("/a/leafx (deleted)", leaf, false, unasked).expect("decided"));
}

/// A record answers only for the task it was made for.
#[skuld::test]
fn a_recorded_place_answers_for_its_own_task_alone() {
    let placed = super::PlacedAtRemoval::default();
    assert_eq!(placed.of(7), None);
    placed.record(7, true);
    assert_eq!((placed.of(7), placed.of(8)), (Some(true), None));
    placed.clear();
    assert_eq!(placed.of(7), None);
}

/// A `/proc` that hides a process this one may not trace with `EPERM` (`hidepid=1`) refuses as one
/// that hides it with `ENOENT`.
#[skuld::test]
fn without_pidfd_info_a_hidepid_1_proc_refuses_naming_hidepid() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc_as(libc::EPERM);
    match front_placement(&HostKernel, || Ok(HIGH)) {
        Err(crate::error::Error::Unsupported { detail, .. }) => assert!(detail.contains("hidepid"), "{detail}"),
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// A probe child that stays dumpable proves nothing about a front: the probe fails, naming that.
#[skuld::test]
fn a_probe_child_that_stays_dumpable_fails_the_probe() {
    let _missing = fault::miss_pidfd_info();
    let _dumpable = fault::keep_probe_dumpable();
    match front_placement(&HostKernel, || Ok(HIGH)) {
        Err(crate::error::Error::Io(e)) => assert!(e.to_string().contains("non-dumpable"), "{e}"),
        other => panic!("expected Io, got {other:?}"),
    }
}

/// `PIDFD_GET_INFO` refused on this process's own pidfd will refuse a front's too: the spawn is
/// refused, naming it.
#[skuld::test]
fn a_refused_pidfd_info_refuses_naming_it() {
    let _failing = fault::fail_pidfd_info();
    match front_placement(&HostKernel, || Ok(HIGH)) {
        Err(crate::error::Error::Unsupported { detail, .. }) => {
            assert!(detail.contains("PIDFD_GET_INFO failed"), "{detail}");
        }
        other => panic!("expected Unsupported, got {other:?}"),
    }
}

/// A host that gives no cgroup's id by `name_to_handle_at` (`ENOSYS` without `CONFIG_FHANDLE`,
/// `EOPNOTSUPP` without export operations, `EPERM` from a seccomp filter) gives no place to
/// compare with: the spawn is refused as unsupported, naming the errno, before anything else.
#[skuld::test]
fn a_host_that_gives_no_cgroup_id_refuses_naming_the_errno() {
    for errno in [libc::ENOSYS, libc::EOPNOTSUPP, libc::EPERM] {
        match front_placement(&HostKernel, || Err(std::io::Error::from_raw_os_error(errno))) {
            Err(crate::error::Error::Unsupported { detail, .. }) => {
                let named = std::io::Error::from_raw_os_error(errno).to_string();
                assert!(detail.contains(&named), "{errno}: {detail}");
                assert!(detail.contains("before anything is spawned"), "{errno}: {detail}");
            }
            other => panic!("{errno}: expected Unsupported, got {other:?}"),
        }
    }
}

/// Any other failure to read the leaf's id is the spawn's I/O error, not a claim about the host.
#[skuld::test]
fn any_other_failure_to_read_the_leaf_id_is_an_io_error() {
    match front_placement(&HostKernel, || Err(std::io::Error::from_raw_os_error(libc::ENOMEM))) {
        Err(crate::error::Error::Io(e)) => assert!(e.to_string().contains("leaf"), "{e}"),
        other => panic!("expected Io, got {other:?}"),
    }
}

/// A forked probe, killed and reaped when dropped, so a probe a failing assertion would leave
/// running does not outlive the test.
struct ProbeGuard(OwnedFd);

impl Drop for ProbeGuard {
    fn drop(&mut self) {
        // Already reaped by the test: nothing to signal.
        if rustix::process::pidfd_send_signal(self.0.as_fd(), rustix::process::Signal::KILL).is_ok() {
            _ = rustix::process::waitid(
                rustix::process::WaitId::PidFd(self.0.as_fd()),
                rustix::process::WaitIdOptions::EXITED,
            );
        }
    }
}

impl ProbeGuard {
    fn of(pid: libc::pid_t) -> ProbeGuard {
        ProbeGuard(
            rustix::process::pidfd_open(
                rustix::process::Pid::from_raw(pid).expect("a positive pid"),
                rustix::process::PidfdFlags::empty(),
            )
            .expect("pidfd_open the probe"),
        )
    }
}

/// This test process's own `/proc`.
fn proc_dir() -> crate::identity::ProcDir {
    match crate::identity::proc_view_with(&crate::identity::HostKernel) {
        crate::identity::ProcView::Same(dir) => dir,
        _ => panic!("precondition: this test's /proc is its own pid namespace's"),
    }
}

/// The probe child reports that it is non-dumpable and asks to die with its parent, both before it
/// is read, and dies of `SIGKILL` once the thread that forked it has exited: a supervisor that dies
/// mid-probe leaves no process waiting for good. Mutant: "the probe sets no parent-death signal" (the
/// report names it, so the test fails by assertion before it waits for the death).
#[skuld::test]
fn the_probe_child_dies_with_the_thread_that_forked_it() {
    use std::io::Read as _;

    let (ready_tx, ready_rx) = std::sync::mpsc::channel();
    let (go_tx, go_rx) = std::sync::mpsc::channel::<()>();
    // `move`: a failing assertion unwinds out of this closure and drops `go_tx` before the scope
    // joins the forking thread, which waits for it.
    std::thread::scope(move |scope| {
        scope.spawn(move || {
            let parent = rustix::process::getpid().as_raw_nonzero().get();
            let probe = super::fork_probe(&proc_dir(), parent, false).expect("fork the probe");
            let mut report = [0u8; 2];
            probe.channel().read_exact(&mut report).expect("the probe reports");
            // Kept past this thread's end: the child must die of its parent-death signal, which the
            // probe's own end (a kill) would pre-empt.
            ready_tx.send((probe, report)).expect("report the probe");
            // The thread ends when the test lets it go, or when the test fails and drops `go_tx`.
            _ = go_rx.recv();
        });
        let (probe, report) = ready_rx.recv().expect("the probe");
        let pidfd = ProbeGuard::of(probe.pid);
        assert_eq!(
            report,
            [0, libc::SIGKILL as u8],
            "non-dumpable, and killed with its parent"
        );
        go_tx.send(()).expect("let the forking thread end");
        let status = rustix::process::waitid(
            rustix::process::WaitId::PidFd(pidfd.0.as_fd()),
            rustix::process::WaitIdOptions::EXITED,
        )
        .expect("the probe ends with its forking thread")
        .expect("a blocking waitid returns a status");
        assert_eq!(status.terminating_signal(), Some(libc::SIGKILL));
    });
}

/// A probe whose parent is already gone when it starts (so `getppid` is no longer the pid recorded
/// before the fork) exits without reporting. Mutant: "the probe does not compare its parent".
#[skuld::test]
fn a_probe_whose_parent_is_gone_exits_without_reporting() {
    use std::io::Read as _;

    // Not this process's pid, so the child's `getppid` differs from it, as after a reparenting.
    let not_the_parent = rustix::process::getpid().as_raw_nonzero().get() + 1;
    let probe = super::fork_probe(&proc_dir(), not_the_parent, false).expect("fork the probe");
    let pidfd = ProbeGuard::of(probe.pid);
    // The child's end of the socket closes with the child: end of file, with nothing reported. One
    // read, so a probe that reports instead fails the assertion, and does not leave the read
    // waiting for the end of a probe that waits to be killed.
    let mut reported = [0u8; 2];
    let read = probe.channel().read(&mut reported).expect("read the probe's report");
    assert_eq!(read, 0, "the probe reported {reported:?}");
    let status = rustix::process::waitid(
        rustix::process::WaitId::PidFd(pidfd.0.as_fd()),
        rustix::process::WaitIdOptions::EXITED,
    )
    .expect("reap the probe")
    .expect("a blocking waitid returns a status");
    assert_eq!(status.exit_status(), Some(super::ABANDONED));
}

/// The descriptors open in the process `pid`, each with what it names (`readlink`).
fn descriptors_of(pid: libc::pid_t) -> std::collections::BTreeMap<i32, String> {
    std::fs::read_dir(format!("/proc/{pid}/fd"))
        .expect("list the probe child's descriptors")
        .map(|entry| {
            let entry = entry.expect("a descriptor entry");
            let fd = entry
                .file_name()
                .to_str()
                .and_then(|n| n.parse().ok())
                .expect("a numbered entry");
            let target = std::fs::read_link(entry.path()).expect("read what the descriptor names");
            (fd, target.to_string_lossy().into_owned())
        })
        .collect()
}

/// What this process's descriptor `fd` names.
fn own_descriptor(fd: &impl std::os::fd::AsRawFd) -> String {
    let target = std::fs::read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).expect("read an own descriptor");
    target.to_string_lossy().into_owned()
}

/// Forks two probes, the second while the first's parent end is open here, and checks each child holds
/// only its own socket end. Dumpable, so `/proc/<pid>/fd` is readable without `CAP_SYS_PTRACE`.
fn assert_two_probes_hold_only_their_own() {
    use std::io::Read as _;

    let proc = proc_dir();
    let parent = rustix::process::getpid().as_raw_nonzero().get();
    let first = super::fork_probe(&proc, parent, true).expect("fork the first probe");
    let second = super::fork_probe(&proc, parent, true).expect("fork the second probe");
    // Each child closes what it inherited before it reports.
    let mut report = [0u8; 2];
    first
        .channel()
        .read_exact(&mut report)
        .expect("the first probe reports");
    second
        .channel()
        .read_exact(&mut report)
        .expect("the second probe reports");
    for (name, probe) in [("first", &first), ("second", &second)] {
        let held: Vec<_> = descriptors_of(probe.pid).into_values().collect();
        assert!(
            matches!(held.as_slice(), [one] if one.starts_with("socket:")),
            "the {name} probe's child holds only its end of the socket: {held:?}"
        );
        assert_ne!(
            held[0],
            own_descriptor(probe.channel()),
            "the {name} probe's child holds its parent's end"
        );
    }
    let first_parent_end = own_descriptor(first.channel());
    assert!(
        !descriptors_of(second.pid)
            .values()
            .any(|target| *target == first_parent_end),
        "the second probe's child holds the first's parent end"
    );
}

/// Two concurrent probes' children each hold only their own descriptors, so neither keeps the
/// other's parent end open. Mutant: "the child keeps the descriptors it inherited".
#[skuld::test]
fn concurrent_probes_children_each_hold_only_their_own_descriptors() {
    assert_two_probes_hold_only_their_own();
}

/// The same where `close_range` is refused (a kernel before 5.9, or a seccomp filter): the child
/// closes the rest by a walk of its `/proc/self/fd`. Mutant: "the walk closes nothing".
#[skuld::test]
fn probes_children_hold_only_their_own_descriptors_without_close_range() {
    let _refused = fault::refuse_probe_close_range();
    assert_two_probes_hold_only_their_own();
}

/// A `close_range` that closes the first range and is refused the next leaves the child to close the
/// rest by the walk: the walk's directory is opened before any range is closed. Mutant: "the walk
/// opens its directory only after the ranges ran" (the first range closes the `/proc` handle it opens
/// through, and the child dies `ABANDONED`).
#[skuld::test]
fn probes_children_hold_only_their_own_descriptors_when_a_later_close_range_is_refused() {
    let _refused = fault::refuse_probe_close_range_after(1);
    assert_two_probes_hold_only_their_own();
}

/// The probe's child is killed through a pidfd that names it, never by its number, and reaped
/// through it. Mutants: "kill the probe's child by pid" (the route is recorded by the helper that
/// makes the syscall), "the kill is recorded and not made" (the child then exits by itself, unkilled,
/// once released).
#[skuld::test]
fn the_probe_child_is_killed_through_its_pidfd() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    fault::take_probe_steps();
    front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
        ]
    );
}

/// Whether no child of this process holds `pid`: a probe's child that was reaped, by anyone.
fn no_child_holds(pid: libc::pid_t) -> Result<bool, rustix::io::Errno> {
    use rustix::process::{waitid, Pid, WaitId, WaitIdOptions};
    let pid = Pid::from_raw(pid).expect("a positive pid");
    match waitid(
        WaitId::Pid(pid),
        WaitIdOptions::EXITED | WaitIdOptions::NOHANG | WaitIdOptions::NOWAIT,
    ) {
        Err(rustix::io::Errno::CHILD) => Ok(true),
        Err(e) => Err(e),
        Ok(_) => Ok(false),
    }
}

/// A probe's child that no pidfd can pin (`pidfd_open` fails with `EMFILE`) is killed and reaped by
/// its number, as before pidfds, and no probe process is left. Mutants: "a failed `pidfd_open`
/// returns, leaving the probe's child unreaped", "the kill by number is not made".
#[skuld::test]
fn a_probe_child_no_pidfd_can_pin_is_killed_and_reaped_by_its_number() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let forked = std::rc::Rc::new(std::cell::Cell::new(None));
    let _unpinned = fault::set_before_probe_pin({
        let forked = forked.clone();
        move |pid| {
            forked.set(Some(pid));
            Some(libc::EMFILE)
        }
    });
    fault::take_probe_steps();
    front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    let pid = forked.get().expect("the probe forked");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pid, libc::SIGKILL),
            ProbeStep::Reap(Via::Pid, ProbeEnd::Signal(libc::SIGKILL))
        ]
    );
    assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}

/// A probe's child reaped elsewhere before its pidfd was opened is not this process's to kill: its
/// number is sent nothing, and the probe fails. Mutant: "a probe reaped elsewhere is killed by its
/// number".
#[skuld::test]
fn a_probe_child_reaped_elsewhere_before_its_pin_is_sent_nothing() {
    let _missing = fault::miss_pidfd_info();
    let _reaped = fault::set_before_probe_pin(|pid| {
        // SAFETY: `pid` is this test's own unreaped child.
        assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
        crate::test_child::reaped_elsewhere::reap_behind(pid as u32);
        None
    });
    fault::take_probe_steps();
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe has no child left");
    assert_eq!(fault::take_probe_steps(), [], "nothing was sent");
    assert!(matches!(err, crate::error::Error::Io(_)), "{err:?}");
}

/// A probe's child whose kill through its pidfd fails other than `ESRCH` is sent nothing by its
/// number: it is released, exits by itself, and is reaped through the pidfd that still names it.
/// The failed kill is a `warn` naming the child. Mutants: "a failed kill falls back to the number",
/// "the failed kill is logged below `warn`", "the child is released only by its socket's close" (it
/// then exits with another status), "the reap goes by number".
#[skuld::test]
fn a_probe_child_whose_pidfd_kill_fails_is_released_and_reaped_through_its_pidfd() {
    crate::log_capture::install();
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let forked = std::rc::Rc::new(std::cell::Cell::new(None));
    let _failed = fault::set_before_probe_kill({
        let forked = forked.clone();
        move |pid| {
            forked.set(Some(pid));
            Some(libc::EPERM)
        }
    });
    fault::take_probe_steps();
    let mark = crate::log_capture::mark();
    front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    let pid = forked.get().expect("the probe's child was to be killed");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Exit(super::RELEASED))
        ]
    );
    let warns = warns_since(mark, "");
    assert!(
        warns.iter().any(|w| w.contains(&format!("child {pid}"))),
        "a warn names the probe's child {pid}: {warns:?}"
    );
    assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}

/// A probe's child that no pidfd can pin, and whose kill by number fails, is released and reaped by
/// its number, and the failed kill is a `warn` naming it. Mutants: "the kill's answer is ignored",
/// "the child is released only by its socket's close".
#[skuld::test]
fn a_probe_child_whose_kill_by_number_fails_is_released_and_warned() {
    crate::log_capture::install();
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let forked = std::rc::Rc::new(std::cell::Cell::new(None));
    let _unpinned = fault::set_before_probe_pin({
        let forked = forked.clone();
        move |pid| {
            forked.set(Some(pid));
            Some(libc::EMFILE)
        }
    });
    let _failed = fault::set_before_probe_kill(|_| Some(libc::EPERM));
    fault::take_probe_steps();
    let mark = crate::log_capture::mark();
    front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    let pid = forked.get().expect("the probe forked");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pid, libc::SIGKILL),
            ProbeStep::Reap(Via::Pid, ProbeEnd::Exit(super::RELEASED))
        ]
    );
    let warns = warns_since(mark, "");
    assert!(
        warns.iter().any(|w| w.contains(&format!("child {pid}"))),
        "a warn names the probe's child {pid}: {warns:?}"
    );
    assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}

/// A failed kill of one probe's child is not held up by a second probe's child forked while the
/// first's parent end was open in this process: the first child is released and reaped, while the
/// second still runs. Mutant: "the child keeps the descriptors it inherited, and is released only by
/// its socket's close" (the first's reap would then wait on the second child).
#[skuld::test]
fn a_failed_kill_of_one_probe_is_not_stalled_by_another_probes_child() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let second = std::rc::Rc::new(std::cell::RefCell::new(None));
    let _failed = fault::set_before_probe_kill({
        let second = second.clone();
        move |_| {
            use std::io::Read as _;
            let parent = rustix::process::getpid().as_raw_nonzero().get();
            let probe = super::fork_probe(&proc_dir(), parent, false).expect("fork the second probe");
            let mut report = [0u8; 2];
            probe
                .channel()
                .read_exact(&mut report)
                .expect("the second probe reports");
            *second.borrow_mut() = Some(probe);
            Some(libc::EPERM)
        }
    });
    fault::take_probe_steps();
    front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Exit(super::RELEASED))
        ]
    );
    let second = second.borrow_mut().take().expect("the second probe forked");
    let pid = second.pid;
    assert_eq!(
        no_child_holds(pid),
        Ok(false),
        "the second probe's child {pid} still runs"
    );
    second.end().expect("end the second probe");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
        ]
    );
}

/// `SIGCHLD` set to `SIG_IGN` while the guard lives: the kernel reaps every child of this process
/// as it exits, as on a host that ignores `SIGCHLD`.
struct SigchldIgnored(nix::sys::signal::SigAction);

fn ignore_sigchld() -> SigchldIgnored {
    use nix::sys::signal::{sigaction, SaFlags, SigAction, SigHandler, SigSet, Signal};
    let ignore = SigAction::new(SigHandler::SigIgn, SaFlags::empty(), SigSet::empty());
    // SAFETY: installs no handler; the callers run [`alone`], so no other test shares the process.
    SigchldIgnored(unsafe { sigaction(Signal::SIGCHLD, &ignore) }.expect("ignore SIGCHLD"))
}

impl Drop for SigchldIgnored {
    fn drop(&mut self) {
        // SAFETY: restores the disposition `ignore_sigchld` saved.
        _ = unsafe { nix::sys::signal::sigaction(nix::sys::signal::Signal::SIGCHLD, &self.0) };
    }
}

/// A probe's child the kernel reaps itself (`SIGCHLD` ignored) is gone, not a failure: the reap's
/// `ECHILD` keeps the verdict already read, here that `/proc` hides the child. Mutant: "`ECHILD` at
/// the reap fails the probe" (the spawn's error is then `Io`, not the refusal). Run [`alone`]: the
/// disposition is process-wide.
#[skuld::test]
fn a_probe_child_reaped_by_an_ignored_sigchld_keeps_the_verdict() {
    if !alone("containment::cgroup::reach::reach_tests::a_probe_child_reaped_by_an_ignored_sigchld_keeps_the_verdict") {
        return;
    }
    let _ignored = ignore_sigchld();
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    fault::take_probe_steps();
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Elsewhere)
        ]
    );
}

/// The same for a child no pidfd pins, killed and reaped by its number. Mutant: "`ECHILD` at the
/// reap by number fails the probe". Run [`alone`].
#[skuld::test]
fn a_probe_child_no_pidfd_pins_reaped_by_an_ignored_sigchld_keeps_the_verdict() {
    if !alone(
        "containment::cgroup::reach::reach_tests::a_probe_child_no_pidfd_pins_reaped_by_an_ignored_sigchld_keeps_the_verdict",
    ) {
        return;
    }
    let _ignored = ignore_sigchld();
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let _unpinned = fault::set_before_probe_pin(|_| Some(libc::EMFILE));
    fault::take_probe_steps();
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pid, libc::SIGKILL),
            ProbeStep::Reap(Via::Pid, ProbeEnd::Elsewhere)
        ]
    );
}

/// A probe's child that another waiter in the process reaps after the verdict is read, before its
/// kill, is gone: the kill answers `ESRCH`, the reap `ECHILD`, and the verdict stands. Mutant:
/// "`ECHILD` at the reap fails the probe".
#[skuld::test]
fn a_probe_child_reaped_by_another_waiter_keeps_the_verdict() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let _reaped = fault::set_before_probe_kill(|pid| {
        // SAFETY: `pid` is this test's own unreaped child.
        assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
        crate::test_child::reaped_elsewhere::reap_behind(pid as u32);
        None
    });
    fault::take_probe_steps();
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    assert!(matches!(err, crate::error::Error::Unsupported { .. }), "{err:?}");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Elsewhere)
        ]
    );
}

/// A probe's child that is already dead when its kill through the pidfd answers `ESRCH` is reaped
/// through that pidfd, and nothing is sent by its number. Mutants: "`ESRCH` returns, leaving the
/// zombie", "`ESRCH` falls back to the number".
#[skuld::test]
fn a_probe_child_already_dead_at_its_pidfd_send_is_reaped_through_the_pidfd() {
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let forked = std::rc::Rc::new(std::cell::Cell::new(None));
    let _dead = fault::set_before_probe_kill({
        let forked = forked.clone();
        move |pid| {
            forked.set(Some(pid));
            // SAFETY: `pid` is this test's own unreaped child; it dies, and stays a zombie for its
            // pidfd to reap.
            assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
            Some(libc::ESRCH)
        }
    });
    fault::take_probe_steps();
    front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    let pid = forked.get().expect("the probe's child was to be killed");
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
        ]
    );
    assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}

/// The soft `RLIMIT_NOFILE` lowered to leave exactly `spare` (at least 1) descriptor numbers free
/// below it, counting the holes among the descriptors open now; the limit it replaced is put back
/// when the guard drops.
struct NofileLimit(libc::rlimit);

fn limit_nofile(spare: usize) -> NofileLimit {
    let open: std::collections::BTreeSet<i32> = descriptors_of(std::process::id() as libc::pid_t)
        .into_iter()
        // The listing's own directory descriptor is open only while it is read.
        .filter(|(_, target)| !target.ends_with("/fd"))
        .map(|(fd, _)| fd)
        .collect();
    let last_free = (0..)
        .filter(|fd| !open.contains(fd))
        .nth(spare - 1)
        .expect("a free descriptor number");
    let mut before = libc::rlimit {
        rlim_cur: 0,
        rlim_max: 0,
    };
    // SAFETY: `before` is a valid out-pointer.
    assert_eq!(
        unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut before) },
        0,
        "getrlimit"
    );
    let lowered = libc::rlimit {
        rlim_cur: last_free as libc::rlim_t + 1,
        rlim_max: before.rlim_max,
    };
    // SAFETY: `lowered` is a valid rlimit; the callers run [`alone`], so no other test shares the limit.
    assert_eq!(
        unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &lowered) },
        0,
        "setrlimit"
    );
    NofileLimit(before)
}

impl Drop for NofileLimit {
    fn drop(&mut self) {
        // SAFETY: puts back the limit `limit_nofile` read.
        unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &self.0) };
    }
}

/// The placement probe answers its verdict (here that `/proc` hides the child) with only `spare`
/// descriptor numbers free below the soft limit, and its child is still pinned by a pidfd: killed and
/// reaped through it, with no `warn`.
fn assert_probe_answers_with_spare_descriptors(spare: usize) {
    crate::log_capture::install();
    let _missing = fault::miss_pidfd_info();
    let _hidden = fault::hide_proc();
    let _limit = limit_nofile(spare);
    fault::take_probe_steps();
    let mark = crate::log_capture::mark();
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("a hidden /proc refuses");
    assert!(
        matches!(&err, crate::error::Error::Unsupported { detail, .. } if detail.contains("hides the cgroup")),
        "the refusal is the hidden /proc's: {err:?}"
    );
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
        ]
    );
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
}

/// A low `RLIMIT_NOFILE` does not turn the probe's verdict into an `Io` failure, nor cost the child its
/// pidfd: with 3 descriptor numbers free (the `/proc` handle and the socket's two ends; the child's
/// end is closed here before the child's pidfd takes its number), the child still reports: it opens
/// nothing. Mutants: "the child copies its descriptors to the lowest free numbers above its own" (it
/// then needs three more than its parent holds, and dies `ABANDONED`), "this process's own pidfd
/// stays open during the probe" (the socket then fails with `EMFILE`). Run [`alone`]: the limit is
/// process-wide.
#[skuld::test]
fn the_probe_answers_with_the_fewest_descriptors_its_parent_needs() {
    if !alone("containment::cgroup::reach::reach_tests::the_probe_answers_with_the_fewest_descriptors_its_parent_needs")
    {
        return;
    }
    assert_probe_answers_with_spare_descriptors(3);
}

/// A probe's child that exits before its pin, with `SIGCHLD` ignored, is reaped by the kernel as it
/// exits; the spawn's error says so, and does not blame another reaper alone. Mutant: "the error
/// names only another reaper". Run [`alone`]: the disposition is process-wide.
#[skuld::test]
fn a_probe_child_that_exits_early_with_sigchld_ignored_says_so() {
    if !alone("containment::cgroup::reach::reach_tests::a_probe_child_that_exits_early_with_sigchld_ignored_says_so") {
        return;
    }
    let _ignored = ignore_sigchld();
    let _missing = fault::miss_pidfd_info();
    let _exits = fault::set_before_probe_pin(|pid| {
        // SAFETY: `pid` is this test's own unreaped child.
        assert_eq!(unsafe { libc::kill(pid, libc::SIGKILL) }, 0, "kill the probe's child");
        // With `SIGCHLD` ignored the wait ends once the child has died and the kernel reaped it: `ECHILD`.
        let waited = rustix::process::waitid(
            rustix::process::WaitId::Pid(rustix::process::Pid::from_raw(pid).expect("a positive pid")),
            rustix::process::WaitIdOptions::EXITED,
        );
        assert_eq!(
            waited.expect_err("the kernel reaps the child"),
            rustix::io::Errno::CHILD
        );
        None
    });
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe has no child left");
    assert!(
        err.to_string().contains("SIGCHLD"),
        "the error names the ignored SIGCHLD: {err}"
    );
}

/// A probe dropped before it was ended, as by an unwind between its fork and its end, kills and reaps
/// its child. Mutant: "`Probe` has no `Drop`" (the child, exiting by itself on its socket's close, is
/// left a zombie).
#[skuld::test]
fn a_probe_dropped_unended_is_killed_and_reaped() {
    fault::take_probe_steps();
    let parent = rustix::process::getpid().as_raw_nonzero().get();
    let pid = {
        let probe = super::fork_probe(&proc_dir(), parent, false).expect("fork the probe");
        probe.pid
    };
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Signal(libc::SIGKILL))
        ]
    );
    assert_eq!(no_child_holds(pid), Ok(true), "the probe's child {pid} is left");
}

/// A probe's child that cannot open its `/proc/self/fd` exits `ABANDONED` without reporting, whether or
/// not `close_range` works: the probe's error names that status, and a `warn` names the child and the
/// status. Mutant: "the child's exit status is dropped" (the error is the generic one).
#[skuld::test]
fn a_probe_child_that_cannot_close_its_descriptors_is_reported_abandoned() {
    crate::log_capture::install();
    let _missing = fault::miss_pidfd_info();
    let _no_dir = fault::fail_probe_fd_dir();
    let forked = std::rc::Rc::new(std::cell::Cell::new(None));
    let _seen = fault::set_before_probe_kill({
        let forked = forked.clone();
        move |pid| {
            forked.set(Some(pid));
            None
        }
    });
    fault::take_probe_steps();
    let mark = crate::log_capture::mark();
    let err = front_placement(&HostKernel, || Ok(HIGH)).expect_err("the probe fails");
    let pid = forked.get().expect("the probe's child was to be killed");
    assert!(
        matches!(&err, crate::error::Error::Io(e) if e.to_string().contains("ABANDONED")),
        "the error names the child's status: {err:?}"
    );
    assert_eq!(
        fault::take_probe_steps(),
        [
            ProbeStep::Kill(Via::Pidfd, libc::SIGKILL),
            ProbeStep::Reap(Via::Pidfd, ProbeEnd::Exit(super::ABANDONED))
        ]
    );
    let warns = warns_since(mark, "");
    assert!(
        warns
            .iter()
            .any(|w| w.contains(&format!("child {pid}")) && w.contains("ABANDONED")),
        "a warn names the probe's child {pid} and its status: {warns:?}"
    );
}

/// With fds 0 and 1 closed and `close_range` refused, the lowest numbers hold the `/proc` handle, the
/// socket's parent end and the walk's directory, and the walk still closes all but the child's end.
/// Mutant: "the walk skips the entry for descriptor 0". Runs in a process of its own: closing 0 and 1
/// is process-wide.
#[skuld::test]
fn the_walk_closes_the_lowest_descriptors_with_fds_0_and_1_closed() {
    use crate::test_own_process::{own_process, test_path};
    use crate::test_spawn::spawn;
    use crate::test_stdio::RestoreStdio;
    use std::io::Read as _;

    let Some(done) = own_process(
        test_path!(the_walk_closes_the_lowest_descriptors_with_fds_0_and_1_closed),
        spawn,
    ) else {
        return;
    };
    let _refused = fault::refuse_probe_close_range();
    // Declared before `proc`, which takes descriptor 0: it is closed before the restore puts back
    // the standard descriptor there.
    let restore = RestoreStdio::close(&done, &[0, 1]);
    let proc = proc_dir();
    let parent = rustix::process::getpid().as_raw_nonzero().get();
    let probe = super::fork_probe(&proc, parent, true).expect("fork the probe");
    let mut report = [0u8; 2];
    probe.channel().read_exact(&mut report).expect("the probe reports");
    let held: Vec<_> = descriptors_of(probe.pid).into_values().collect();
    drop(probe);
    drop(proc);
    drop(restore);
    assert!(
        matches!(held.as_slice(), [one] if one.starts_with("socket:")),
        "the probe's child holds only its end of the socket: {held:?}"
    );
}

/// The walk closes a long listing: with about 100 descriptors open, two of the low ones freed so the
/// socket lands below the rest, and `close_range` refused, the child still holds only its socket. The
/// listing outgrows one `getdents64` buffer, and each pass closes entries it is reading. Mutant: "the
/// walk stops after its first batch". Run [`alone`]: the descriptor numbers are process-wide.
#[skuld::test]
fn the_walk_closes_a_listing_longer_than_one_batch() {
    use std::io::Read as _;

    if !alone("containment::cgroup::reach::reach_tests::the_walk_closes_a_listing_longer_than_one_batch") {
        return;
    }
    let mut files: Vec<_> = (0..100)
        .map(|_| std::fs::File::open("/dev/null").expect("open /dev/null"))
        .collect();
    drop(files.drain(10..12));
    let _refused = fault::refuse_probe_close_range();
    let parent = rustix::process::getpid().as_raw_nonzero().get();
    let probe = super::fork_probe(&proc_dir(), parent, true).expect("fork the probe");
    let mut report = [0u8; 2];
    probe.channel().read_exact(&mut report).expect("the probe reports");
    let held: Vec<_> = descriptors_of(probe.pid).into_values().collect();
    assert!(
        matches!(held.as_slice(), [one] if one.starts_with("socket:")),
        "the probe's child holds only its end of the socket: {held:?}"
    );
}

/// A release byte that cannot be sent is a `warn` naming the probe's child. Mutant: "the failed send is
/// ignored".
#[skuld::test]
fn a_release_that_cannot_be_sent_is_a_warn_naming_the_child() {
    crate::log_capture::install();
    // Not a socket: the send fails with `ENOTSOCK`, not the `EPIPE` of a child already gone.
    let not_a_socket =
        std::os::unix::net::UnixStream::from(OwnedFd::from(std::fs::File::open("/dev/null").expect("open /dev/null")));
    let mark = crate::log_capture::mark();
    super::release_probe(4242, not_a_socket);
    let warns = warns_since(mark, "");
    assert!(
        warns.iter().any(|w| w.contains("child 4242")),
        "a warn names the probe's child: {warns:?}"
    );
}

/// The ranges `keep_only_own` closes leave exactly the kept descriptor and the walk's directory open,
/// and none is empty, which `close_range` refuses. Mutant: "the first range ends at the lower kept
/// descriptor, not below it".
#[skuld::test]
fn the_ranges_around_two_descriptors_cover_every_other_number() {
    use super::ranges_around;
    const MAX: u32 = u32::MAX;
    assert_eq!(ranges_around(0, 1), [None, None, Some((2, MAX))]);
    assert_eq!(ranges_around(1, 0), [None, None, Some((2, MAX))]);
    assert_eq!(ranges_around(5, 2), [Some((0, 1)), Some((3, 4)), Some((6, MAX))]);
    assert_eq!(ranges_around(2, 5), [Some((0, 1)), Some((3, 4)), Some((6, MAX))]);
    assert_eq!(ranges_around(0, 3), [None, Some((1, 2)), Some((4, MAX))]);
    assert_eq!(ranges_around(MAX, 0), [None, Some((1, MAX - 1)), None]);
}

/// A pidfd that names a process that is no child of this one (`ECHILD` at its `waitid`) does not pin
/// the probe's child: it is gone, not killed. Mutant: "`ECHILD` at the pin's `waitid` is a failed pin"
/// (the child would then be killed by its number).
#[skuld::test]
fn a_pidfd_naming_no_child_of_this_process_leaves_the_probe_child_gone() {
    let own = std::process::id() as libc::pid_t;
    match super::own_child_pidfd(own) {
        Err(super::Unpinned::Gone(e)) => assert!(e.to_string().contains(&format!("child {own}")), "{e}"),
        Err(super::Unpinned::Failed(e)) => panic!("expected Gone, got Failed({e})"),
        Ok(_) => panic!("expected Gone, got a pidfd"),
    }
}

/// A descriptor that cannot be waited on as a pidfd (`EBADF`) is a failed pin, not a gone child: the
/// number still names the probe's child, which is then held by it. Mutant: "any `waitid` failure at
/// the pin is a gone child".
#[skuld::test]
fn a_descriptor_that_is_no_pidfd_fails_the_pin() {
    let not_a_pidfd = OwnedFd::from(std::fs::File::open("/dev/null").expect("open /dev/null"));
    match super::confirm_child(4242, not_a_pidfd) {
        Err(super::Unpinned::Failed(e)) => assert_eq!(e.raw_os_error(), Some(libc::EBADF), "{e}"),
        Err(super::Unpinned::Gone(e)) => panic!("expected Failed, got Gone({e})"),
        Ok(_) => panic!("expected Failed, got a pidfd"),
    }
}

/// A subtree asked about a child with no pid cannot place it, though its kill landed: it has no
/// number to ask `/proc` with, so whether the kill reached it is unknown, not "no".
///
/// Mutant: the pid-less child is taken for not reached, or asked as pid 0.
#[skuld::test]
fn a_subtree_asked_about_a_pidless_child_cannot_place_it() {
    use crate::child::owned::teardown::Reach;

    let child = crate::child::owned::OwnedChild::new(Box::new(crate::os_process::fake::FakeProcess::new([])));
    assert!(subtree(HIGH, true).reached(&child).is_err());
}