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
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
use std::cell::Cell;

use super::dir::WalkStep;

type Hook = Box<dyn FnOnce()>;

thread_local! {
    static ON_TAKE_PLACEMENT: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static AFTER_PROCS_READ: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static AFTER_TERMINATE_PIN: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static MEMBER_TERMS: std::cell::RefCell<Vec<MemberTerm>> = const { std::cell::RefCell::new(Vec::new()) };
    static BEFORE_STATE_READ: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static FORCE_KILL_SUPPORTED: Cell<bool> = const { Cell::new(false) };
    static FORCE_PLACEMENT_WRITE_RESULT: Cell<Option<ForcedWrite>> = const { Cell::new(None) };
    static FORCE_OCCUPY_BEFORE_UNWIND: Cell<bool> = const { Cell::new(false) };
    static DRAIN_ZERO_REMAINING: std::cell::RefCell<Option<std::sync::mpsc::Sender<()>>> = const { std::cell::RefCell::new(None) };
    static WAIT_SITE_PARK: std::cell::RefCell<Option<std::sync::mpsc::Sender<WaitSitePark>>> = const { std::cell::RefCell::new(None) };
    static WAIT_DEADLINE_ARG: std::cell::RefCell<Option<std::sync::mpsc::Sender<std::time::Instant>>> = const { std::cell::RefCell::new(None) };
    static LEAF_STEPS: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
    static FORCE_INOTIFY_FAILURE: Cell<bool> = const { Cell::new(false) };
    static FORCE_KILL_CHECK_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
    static FORCE_OWN_CGROUP: std::cell::RefCell<Option<(String, std::path::PathBuf)>> = const { std::cell::RefCell::new(None) };
    static FORCE_LEAF_OPEN_FAILURE: Cell<bool> = const { Cell::new(false) };
    static FAIL_KILL_WRITES: Cell<bool> = const { Cell::new(false) };
    static REFUSED_KILL_WRITES: Cell<u32> = const { Cell::new(0) };
    static FAIL_NEXT_KILL_WRITE: Cell<bool> = const { Cell::new(false) };
    static PIDFD_INFO_MISSING: Cell<bool> = const { Cell::new(false) };
    static BEFORE_KILL_WRITE: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static AFTER_KILL_WRITE: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static FORCED_PIDFD_CGROUP_ID: Cell<Option<u64>> = const { Cell::new(None) };
    static BEFORE_WALK_OPEN: std::cell::RefCell<Option<WalkHook>> = const { std::cell::RefCell::new(None) };
    static BEFORE_SWEEP_REMOVE: std::cell::RefCell<Option<WalkHook>> = const { std::cell::RefCell::new(None) };
    static AFTER_DRAIN_WARN: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static WALK_FAILURE: std::cell::RefCell<Option<WalkFailure>> = const { std::cell::RefCell::new(None) };
    static PIDFD_INFO_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
    static PROBE_DUMPABLE: Cell<bool> = const { Cell::new(false) };
    static PROBE_CLOSE_RANGE_ALLOWED: Cell<Option<u32>> = const { Cell::new(None) };
    static PROBE_FD_DIR_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
    static PROBE_ENDS: std::cell::RefCell<Vec<super::reach::ProbeEnd>> = const { std::cell::RefCell::new(Vec::new()) };
    static CGROUP_ID_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
    static LIVENESS_READ_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
    static SUBTREE_FAILS: Cell<Option<i32>> = const { Cell::new(None) };
    static TERMINATE_FAILS: Cell<Option<(TerminateStep, i32, bool)>> = const { Cell::new(None) };
    static RMDIR_HOOK: std::cell::RefCell<Option<RmdirHook>> = std::cell::RefCell::new(None);
    static FORCE_KILL_ON_DROP_WAITID_EINTR: Cell<bool> = const { Cell::new(false) };
    static FORCE_KILL_ON_DROP_KILL_FAILURE: Cell<bool> = const { Cell::new(false) };
    static AFTER_FORK_STILL_LOCKED: std::cell::RefCell<Option<Hook>> = std::cell::RefCell::new(None);
    static ON_FORK_RUNNING_LOCK_CONTENDED: std::cell::RefCell<Option<Hook>> = std::cell::RefCell::new(None);
    static FORK_RUNNING_LOCK_HELD_REPORT_FD: Cell<Option<std::os::fd::RawFd>> = const { Cell::new(None) };
}

/// Given the leaf's path, answers a leaf's `rmdir` in the production removal's place, or `None`
/// to let the production removal run.
type RmdirHook = Box<dyn FnMut(&std::path::Path) -> Option<std::io::Result<()>>>;

/// While the guard lives, every `cgroup.kill` write on this thread fails with `EIO`, and kills
/// nothing: a failed kill whose members may all still run. A teardown after a failed kill must not
/// wait for the leaf's drain, nor block on its child (`set_between_kill_and_wait`) after taking as
/// delivered a kill that wrote nothing; either fails by assertion. A look after a refused kill
/// reaches the child-wait seam and is allowed.
pub(crate) fn fail_kill_writes() -> FailKillWrites {
    arm_fail_kill_writes(None)
}

/// [`fail_kill_writes`] that also runs `release` before it fails for a kill route that wrote
/// nothing: what the unwind from that failure would otherwise wait for forever, as a drop does for
/// a front only a kill ends.
pub(crate) fn fail_kill_writes_releasing_on_unwritten_kill(release: impl FnOnce() + 'static) -> FailKillWrites {
    arm_fail_kill_writes(Some((Box::new(release), ReleaseAt::UnwrittenKill)))
}

/// [`fail_kill_writes`] that runs `release` whenever the teardown is about to block on its child,
/// for a teardown that must not wait there: a wait ends what only a kill would, and the test sees
/// it, instead of hanging. A look after a refused kill is a reach of this seam too, so this is not
/// for a teardown that makes one.
pub(crate) fn fail_kill_writes_releasing_at_wait(release: impl FnOnce() + 'static) -> FailKillWrites {
    arm_fail_kill_writes(Some((Box::new(release), ReleaseAt::EveryWait)))
}

/// When [`arm_fail_kill_writes`] runs its release at the child-wait seam.
enum ReleaseAt {
    /// Only when no `cgroup.kill` was attempted.
    UnwrittenKill,
    /// At every reach of the seam.
    EveryWait,
}

fn arm_fail_kill_writes(release: Option<(Box<dyn FnOnce()>, ReleaseAt)>) -> FailKillWrites {
    FAIL_KILL_WRITES.with(|f| f.set(true));
    REFUSED_KILL_WRITES.with(|n| n.set(0));
    FailKillWrites {
        _no_drain_wait: crate::wait::block_probe::on_drain_block(|| {
            fail_once_unwinding(
                "a teardown whose cgroup.kill failed waited for the leaf's drain, which its members may never end",
            );
        }),
        _no_unwritten_kill: crate::child::spawn::fault::set_between_kill_and_wait(move || {
            let unwritten = REFUSED_KILL_WRITES.with(Cell::get) == 0;
            if let Some((release, at)) = release {
                if unwritten || matches!(at, ReleaseAt::EveryWait) {
                    release();
                }
            }
            if unwritten {
                fail_once_unwinding(
                    "a teardown took a kill as delivered and waited for its child, though no cgroup.kill was written",
                );
            }
        }),
    }
}

/// Fails the test with `message`, unless it is already unwinding: a second panic from a drop
/// aborts the process.
fn fail_once_unwinding(message: &str) {
    if !std::thread::panicking() {
        panic!("{message}");
    }
}

#[must_use = "the writes succeed again as soon as the guard is dropped"]
pub(crate) struct FailKillWrites {
    _no_drain_wait: crate::wait::block_probe::Armed,
    _no_unwritten_kill: crate::oneshot_hook::Armed,
}

impl Drop for FailKillWrites {
    fn drop(&mut self) {
        FAIL_KILL_WRITES.with(|f| f.set(false));
    }
}

/// Whether this write fails (see [`fail_kill_writes`]); a failure is counted.
pub(crate) fn kill_writes_fail() -> bool {
    let fails = FAIL_KILL_WRITES.with(Cell::get);
    if fails {
        REFUSED_KILL_WRITES.with(|n| n.set(n.get() + 1));
    }
    fails
}

/// The next `cgroup.kill` write on this thread fails with `EIO` and writes nothing; every write
/// after it goes through. A test that a failed write is final sees a later write as a `kill` in
/// the file.
pub(crate) fn fail_next_kill_write() -> FailNextKillWrite {
    FAIL_NEXT_KILL_WRITE.with(|f| f.set(true));
    FailNextKillWrite(())
}

#[must_use = "the failure is cleared as soon as the guard is dropped"]
pub(crate) struct FailNextKillWrite(());

impl Drop for FailNextKillWrite {
    fn drop(&mut self) {
        FAIL_NEXT_KILL_WRITE.with(|f| f.set(false));
    }
}

pub(crate) fn take_next_kill_write_failure() -> bool {
    FAIL_NEXT_KILL_WRITE.with(|f| f.replace(false))
}

/// While the guard lives, this thread reads `PIDFD_GET_INFO` as missing, as on a kernel before
/// 6.13: a task's cgroup is read through `/proc` instead.
pub(crate) fn miss_pidfd_info() -> MissPidfdInfo {
    PIDFD_INFO_MISSING.with(|f| f.set(true));
    MissPidfdInfo(())
}

#[must_use = "PIDFD_GET_INFO is back as soon as the guard is dropped"]
pub(crate) struct MissPidfdInfo(());

impl Drop for MissPidfdInfo {
    fn drop(&mut self) {
        PIDFD_INFO_MISSING.with(|f| f.set(false));
    }
}

pub(crate) fn pidfd_info_missing() -> bool {
    PIDFD_INFO_MISSING.with(Cell::get)
}

/// While the guard lives, `PIDFD_GET_INFO` fails on this thread with `EIO`, as a kernel that has
/// it refusing it.
pub(crate) fn fail_pidfd_info() -> FailPidfdInfo {
    fail_pidfd_info_with(libc::EIO)
}

/// [`fail_pidfd_info`] with `errno` in place of `EIO`.
pub(crate) fn fail_pidfd_info_with(errno: i32) -> FailPidfdInfo {
    PIDFD_INFO_FAILS.with(|f| f.set(Some(errno)));
    FailPidfdInfo(())
}

#[must_use = "PIDFD_GET_INFO answers again as soon as the guard is dropped"]
pub(crate) struct FailPidfdInfo(());

impl Drop for FailPidfdInfo {
    fn drop(&mut self) {
        PIDFD_INFO_FAILS.with(|f| f.set(None));
    }
}

/// The errno `PIDFD_GET_INFO` is made to fail with, if it is.
pub(crate) fn pidfd_info_fails() -> Option<i32> {
    PIDFD_INFO_FAILS.with(Cell::get)
}

/// While the guard lives, the placement probe's child forked from this thread stays dumpable, as
/// one whose `PR_SET_DUMPABLE` failed.
pub(crate) fn keep_probe_dumpable() -> KeepProbeDumpable {
    PROBE_DUMPABLE.with(|f| f.set(true));
    KeepProbeDumpable(())
}

#[must_use = "the probe's child is made non-dumpable again as soon as the guard is dropped"]
pub(crate) struct KeepProbeDumpable(());

impl Drop for KeepProbeDumpable {
    fn drop(&mut self) {
        PROBE_DUMPABLE.with(|f| f.set(false));
    }
}

pub(crate) fn probe_kept_dumpable() -> bool {
    PROBE_DUMPABLE.with(Cell::get)
}

/// While the guard lives, the placement probe's child forked from this thread finds `close_range`
/// refused, as on a kernel before 5.9, and closes its other descriptors by a walk of `/proc`.
pub(crate) fn refuse_probe_close_range() -> RefuseProbeCloseRange {
    refuse_probe_close_range_after(0)
}

/// [`refuse_probe_close_range`], once the child's first `allowed` calls have succeeded.
pub(crate) fn refuse_probe_close_range_after(allowed: u32) -> RefuseProbeCloseRange {
    PROBE_CLOSE_RANGE_ALLOWED.with(|f| f.set(Some(allowed)));
    RefuseProbeCloseRange(())
}

#[must_use = "close_range is allowed again as soon as the guard is dropped"]
pub(crate) struct RefuseProbeCloseRange(());

impl Drop for RefuseProbeCloseRange {
    fn drop(&mut self) {
        PROBE_CLOSE_RANGE_ALLOWED.with(|f| f.set(None));
    }
}

/// Whether the forked probe child's next `close_range` is refused, counting it. Read in the child: a
/// `const` thread-local with no destructor, so async-signal-safe.
pub(crate) fn probe_close_range_refused() -> bool {
    PROBE_CLOSE_RANGE_ALLOWED.with(|f| match f.get() {
        None => false,
        Some(0) => true,
        Some(allowed) => {
            f.set(Some(allowed - 1));
            false
        }
    })
}

/// While the guard lives, the placement probe's child forked from this thread cannot open its
/// `/proc/self/fd`: its `openat2` answers `errno`, as under a seccomp filter that refuses it.
pub(crate) fn fail_probe_fd_dir(errno: i32) -> FailProbeFdDir {
    PROBE_FD_DIR_FAILS.with(|f| f.set(Some(errno)));
    FailProbeFdDir(())
}

#[must_use = "the directory opens again as soon as the guard is dropped"]
pub(crate) struct FailProbeFdDir(());

impl Drop for FailProbeFdDir {
    fn drop(&mut self) {
        PROBE_FD_DIR_FAILS.with(|f| f.set(None));
    }
}

/// The errno the probe child's open of its `/proc/self/fd` answers, if a test makes it fail. Read in
/// the forked child: a `const` thread-local with no destructor, so async-signal-safe.
pub(crate) fn probe_fd_dir_fails() -> Option<i32> {
    PROBE_FD_DIR_FAILS.with(Cell::get)
}

/// Notes how a placement probe's child ended, once it was reaped, on this thread.
pub(crate) fn record_probe_end(end: super::reach::ProbeEnd) {
    PROBE_ENDS.with(|s| s.borrow_mut().push(end));
}

/// How the placement probes' children ended on this thread since the last call.
pub(crate) fn take_probe_ends() -> Vec<super::reach::ProbeEnd> {
    PROBE_ENDS.with(|s| std::mem::take(&mut *s.borrow_mut()))
}

/// Run `hook` once, right before the next `cgroup.kill` write on this thread; the guard clears it.
pub(crate) fn set_before_kill_write(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&BEFORE_KILL_WRITE, hook)
}

pub(crate) fn run_before_kill_write() {
    crate::oneshot_hook::fire(&BEFORE_KILL_WRITE);
}

/// Run `hook` once, right after the next `cgroup.kill` write on this thread that succeeded, before
/// anything waits on its effect. A fixture that only the kill would end is released here, so a kill
/// that sent nothing fails an assertion on how the fixture ended instead of hanging the wait for
/// its drain; a write that fails (or is made to) runs nothing.
pub(crate) fn set_after_kill_write(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&AFTER_KILL_WRITE, hook)
}

pub(crate) fn run_after_kill_write() {
    crate::oneshot_hook::fire(&AFTER_KILL_WRITE);
}

/// Make the NEXT leaf directory made on this thread fail to be held after its `mkdir`, with
/// `EMFILE`, as at `RLIMIT_NOFILE`. Take semantics.
pub(crate) fn set_force_leaf_open_failure(on: bool) {
    FORCE_LEAF_OPEN_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_leaf_open_failure() -> bool {
    FORCE_LEAF_OPEN_FAILURE.with(|f| f.replace(false))
}

/// Make the NEXT leaf creation's `cgroup.kill` lookup on this thread fail with `errno`: a lookup
/// through the held leaf directory fails only on a real error, which a temp directory cannot
/// produce. Take semantics.
pub(crate) fn set_force_kill_check_errno(errno: i32) {
    FORCE_KILL_CHECK_ERRNO.with(|f| f.set(Some(errno)));
}
pub(crate) fn take_force_kill_check_errno() -> Option<i32> {
    FORCE_KILL_CHECK_ERRNO.with(|f| f.take())
}

/// Make the NEXT drain watch on this thread fail to create its inotify instance, as
/// `fs.inotify.max_user_instances` would. Take semantics: assert [`take_force_inotify_failure`]
/// returns `false` afterwards to prove it was consumed.
pub(crate) fn set_force_inotify_failure(on: bool) {
    FORCE_INOTIFY_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_inotify_failure() -> bool {
    FORCE_INOTIFY_FAILURE.with(|f| f.replace(false))
}

/// Replace every leaf `rmdir` on this thread with `hook`, until [`take_rmdir_hook`]. A temp
/// directory gives none of cgroupfs's `rmdir` answers, so a test supplies them.
pub(crate) fn set_rmdir_hook(mut hook: impl FnMut(&std::path::Path) -> std::io::Result<()> + 'static) {
    RMDIR_HOOK.with(|h| *h.borrow_mut() = Some(Box::new(move |path| Some(hook(path)))));
}
/// While the guard lives, run `observe` with the leaf's path at every leaf `rmdir` on this
/// thread, then the production removal: for a test on a real cgroupfs.
pub(crate) fn observe_rmdirs(mut observe: impl FnMut(&std::path::Path) + 'static) -> ObserveRmdirs {
    RMDIR_HOOK.with(|h| {
        *h.borrow_mut() = Some(Box::new(move |path| {
            observe(path);
            None
        }))
    });
    ObserveRmdirs(())
}

#[must_use = "the observer is removed as soon as the guard is dropped"]
pub(crate) struct ObserveRmdirs(());

impl Drop for ObserveRmdirs {
    fn drop(&mut self) {
        take_rmdir_hook();
    }
}
pub(crate) fn take_rmdir_hook() {
    RMDIR_HOOK.with(|h| h.borrow_mut().take());
}
pub(crate) fn run_rmdir_hook(path: &std::path::Path) -> Option<std::io::Result<()>> {
    let mut hook = RMDIR_HOOK.with(|h| h.borrow_mut().take())?;
    let result = hook(path);
    RMDIR_HOOK.with(|h| *h.borrow_mut() = Some(hook));
    result
}

/// Run `hook` once right after the next slow-drain warn on this thread, before the wait goes on:
/// a fixture only the drain's end would release is let go here, so a mutant that never warned
/// fails an assertion instead of hanging.
#[cfg(feature = "tokio")]
pub(crate) fn set_after_drain_warn(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&AFTER_DRAIN_WARN, hook)
}

pub(crate) fn run_after_drain_warn() {
    crate::oneshot_hook::fire(&AFTER_DRAIN_WARN);
}

/// Send on `notify` each time a leaf's drain step on this thread takes its zero-remaining
/// shortcut — answers `MembersRemain` from a step that arms no listener. Kept until
/// [`take_drain_zero_remaining_notifier`].
pub(crate) fn set_drain_zero_remaining_notifier(notify: std::sync::mpsc::Sender<()>) {
    DRAIN_ZERO_REMAINING.with(|d| *d.borrow_mut() = Some(notify));
}
pub(crate) fn take_drain_zero_remaining_notifier() {
    DRAIN_ZERO_REMAINING.with(|d| d.borrow_mut().take());
}
pub(crate) fn notify_drain_zero_remaining() {
    DRAIN_ZERO_REMAINING.with(|d| {
        if let Some(notify) = d.borrow().as_ref() {
            // The send runs in release too; only its check is debug-only.
            let sent = notify.send(());
            debug_assert!(sent.is_ok(), "zero-remaining notifier's receiver was dropped");
        }
    });
}

/// What `wait_drained`'s own `Block` arm saw when its wait call returned — including a listener
/// already notified at registration, before any real park. `deadline` is the caller's own
/// requested instant for a bounded park, not necessarily the one actually armed (`wait_deadline`
/// consumes the listener, with no way to read that back) — `None` for an unbounded park, whose
/// `woken` is always `true`: it has no timeout to elapse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct WaitSitePark {
    pub(crate) deadline: Option<std::time::Instant>,
    pub(crate) woken: bool,
}

/// Send on `notify` each time `wait_drained`'s own `Block` arm's wait call returns — proof the
/// call was reached, not that a real park happened: it also fires for a listener already
/// notified at registration, before `wait_deadline`/`wait` ever parks. Kept until
/// [`take_wait_site_park_notifier`].
pub(crate) fn set_wait_site_park_notifier(notify: std::sync::mpsc::Sender<WaitSitePark>) {
    WAIT_SITE_PARK.with(|p| *p.borrow_mut() = Some(notify));
}
pub(crate) fn take_wait_site_park_notifier() {
    WAIT_SITE_PARK.with(|p| p.borrow_mut().take());
}
pub(crate) fn notify_wait_site_park(park: WaitSitePark) {
    WAIT_SITE_PARK.with(|p| {
        if let Some(notify) = p.borrow().as_ref() {
            let sent = notify.send(park);
            debug_assert!(sent.is_ok(), "wait-site-park notifier's receiver was dropped");
        }
    });
}

/// Send on `notify` the exact instant about to be passed to `listener.wait_deadline(at)`, from
/// `CgroupLeaf::wait_deadline_seamed` — the ONLY place this seam fires, one line above the real
/// call, from the same `at` binding the call itself receives. Closes the sync side's own gap
/// (`wait_deadline` consumes the listener and exposes no way to read back what it actually
/// armed): `wait_deadline_seamed` exists so there is exactly one call site for the real
/// `wait_deadline`, with this notify built in, rather than two separately-maintained lines a
/// mutant could edit one of without the other. Kept until [`take_wait_deadline_arg_notifier`].
pub(crate) fn set_wait_deadline_arg_notifier(notify: std::sync::mpsc::Sender<std::time::Instant>) {
    WAIT_DEADLINE_ARG.with(|p| *p.borrow_mut() = Some(notify));
}
pub(crate) fn take_wait_deadline_arg_notifier() {
    WAIT_DEADLINE_ARG.with(|p| p.borrow_mut().take());
}
pub(crate) fn notify_wait_deadline_arg(at: std::time::Instant) {
    WAIT_DEADLINE_ARG.with(|p| {
        if let Some(notify) = p.borrow().as_ref() {
            let sent = notify.send(at);
            debug_assert!(sent.is_ok(), "wait-deadline-arg notifier's receiver was dropped");
        }
    });
}

/// Record, on this thread, each `cgroup.kill` write (`"kill"`) and each `rmdir` of a leaf, the
/// latter with its `cgroup.events` as read at that moment, until [`take_leaf_steps`].
pub(crate) fn record_leaf_steps() {
    LEAF_STEPS.with(|s| *s.borrow_mut() = Some(Vec::new()));
}
pub(crate) fn take_leaf_steps() -> Vec<String> {
    LEAF_STEPS.with(|s| s.borrow_mut().take()).unwrap_or_default()
}
/// The steps recorded so far on this thread, which goes on recording.
pub(crate) fn peek_leaf_steps() -> Vec<String> {
    LEAF_STEPS.with(|s| s.borrow().clone()).unwrap_or_default()
}
pub(crate) fn record_leaf_step(step: impl FnOnce() -> String) {
    LEAF_STEPS.with(|s| {
        if let Some(steps) = s.borrow_mut().as_mut() {
            steps.push(step());
        }
    });
}

/// Treat the NEXT created leaf as exposing `cgroup.kill`. Supplies the single fact a temp
/// directory cannot, so every step AFTER the check — the `cgroup.procs` open, the report
/// channel, and the unwind that removes the leaf — runs for real, against the kernel's own
/// errnos, on any Linux host.
pub(crate) fn set_force_kill_supported(on: bool) {
    FORCE_KILL_SUPPORTED.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_supported() -> bool {
    FORCE_KILL_SUPPORTED.with(|f| f.replace(false))
}
pub(crate) fn kill_supported_armed() -> bool {
    FORCE_KILL_SUPPORTED.with(|f| f.get())
}

/// Make the NEXT lookup of the own cgroup on this thread read `file` as `/proc/self/cgroup`, with
/// the cgroup filesystem at `root`: the host fact a real spawn cannot be given (an own cgroup this
/// process is refused, or that the mount does not show).
pub(crate) fn set_force_own_cgroup(file: &str, root: &std::path::Path) {
    FORCE_OWN_CGROUP.with(|f| *f.borrow_mut() = Some((file.to_owned(), root.to_path_buf())));
}
pub(crate) fn take_force_own_cgroup() -> Option<(String, std::path::PathBuf)> {
    FORCE_OWN_CGROUP.with(|f| f.borrow_mut().take())
}

/// What a forced placement write does instead of writing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ForcedWrite {
    /// Returns 0, which no file a test can open returns for a one-byte write.
    Returns0,
    /// Fails with this errno (`EBUSY` or `EPERM`, which no file a test can open fails with on
    /// demand).
    FailsWith(i32),
}

/// Make the NEXT placement write do `forced` without writing. A child forked from this thread
/// inherits the flag and takes it.
pub(crate) fn set_force_placement_write_result(forced: ForcedWrite) {
    FORCE_PLACEMENT_WRITE_RESULT.with(|f| f.set(Some(forced)));
}
pub(crate) fn take_force_placement_write_result() -> Option<ForcedWrite> {
    FORCE_PLACEMENT_WRITE_RESULT.with(|f| f.take())
}

/// Put a directory inside the NEXT leaf whose creation fails, just before its unwind runs, so
/// that unwind's `rmdir` fails for real (`ENOTEMPTY`).
pub(crate) fn set_force_occupy_before_unwind(on: bool) {
    FORCE_OCCUPY_BEFORE_UNWIND.with(|f| f.set(on));
}
pub(crate) fn take_force_occupy_before_unwind() -> bool {
    FORCE_OCCUPY_BEFORE_UNWIND.with(|f| f.replace(false))
}
pub(crate) fn occupy_before_unwind_armed() -> bool {
    FORCE_OCCUPY_BEFORE_UNWIND.with(|f| f.get())
}

/// RAII: dropping this clears the hook [`set_after_fork_still_locked`] armed, even if
/// `fork_running` never ran it.
#[must_use = "dropping this immediately clears the armed hook; bind it for the scope that needs it"]
pub(crate) struct AfterForkStillLockedGuard(());
impl Drop for AfterForkStillLockedGuard {
    fn drop(&mut self) {
        AFTER_FORK_STILL_LOCKED.with(|h| *h.borrow_mut() = None);
    }
}

/// Run `hook` in the NEXT `fork_running` call on this thread, after `fork()` and `KillOnDrop`
/// construction, still holding `spawn_lock`. Runs on the forking thread, so it may read
/// [`crate::child::spawn::spawn_lock_held_by_this_thread`].
pub(crate) fn set_after_fork_still_locked(hook: impl FnOnce() + 'static) -> AfterForkStillLockedGuard {
    AFTER_FORK_STILL_LOCKED.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    AfterForkStillLockedGuard(())
}
pub(crate) fn run_after_fork_still_locked() {
    if let Some(hook) = AFTER_FORK_STILL_LOCKED.with(|h| h.borrow_mut().take()) {
        hook();
    }
}

/// RAII: dropping this clears the hook [`set_fork_running_lock_contended`] armed.
#[must_use = "dropping this immediately clears the armed hook; bind it for the scope that needs it"]
pub(crate) struct ForkRunningLockContendedGuard(());
impl Drop for ForkRunningLockContendedGuard {
    fn drop(&mut self) {
        ON_FORK_RUNNING_LOCK_CONTENDED.with(|h| *h.borrow_mut() = None);
    }
}

/// Run `hook` in the NEXT `fork_running` call on this thread if `spawn_lock` is already held when
/// it goes to take it, just before it blocks on the lock.
pub(crate) fn set_fork_running_lock_contended(hook: impl FnOnce() + 'static) -> ForkRunningLockContendedGuard {
    ON_FORK_RUNNING_LOCK_CONTENDED.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    ForkRunningLockContendedGuard(())
}
pub(crate) fn run_fork_running_lock_contended() {
    if let Some(hook) = ON_FORK_RUNNING_LOCK_CONTENDED.with(|h| h.borrow_mut().take()) {
        hook();
    }
}

/// RAII: dropping this clears the fd [`set_fork_running_lock_held_report_fd`] registered, even if
/// `fork_running` never consumed it, so it can't leak into a later call on this thread.
#[must_use = "dropping this immediately clears the registered fd; bind it for the scope that needs it"]
pub(crate) struct ForkRunningLockHeldReportFdGuard(());
impl Drop for ForkRunningLockHeldReportFdGuard {
    fn drop(&mut self) {
        FORK_RUNNING_LOCK_HELD_REPORT_FD.with(|f| f.set(None));
    }
}

/// Give the NEXT `fork_running` call on this thread a pipe write fd; its child writes one byte
/// (`1`/`0`) for whether it inherited `spawn_lock` as held. `fork_running` takes the fd once,
/// before forking.
pub(crate) fn set_fork_running_lock_held_report_fd(fd: std::os::fd::RawFd) -> ForkRunningLockHeldReportFdGuard {
    FORK_RUNNING_LOCK_HELD_REPORT_FD.with(|f| f.set(Some(fd)));
    ForkRunningLockHeldReportFdGuard(())
}
pub(crate) fn take_fork_running_lock_held_report_fd() -> Option<std::os::fd::RawFd> {
    FORK_RUNNING_LOCK_HELD_REPORT_FD.with(|f| f.take())
}

/// Run `hook` in the NEXT `CgroupLeaf::terminate` on this thread, once it has read `cgroup.procs`
/// and before it signals any member: the window in which a listed member can leave the leaf.
pub(crate) fn set_after_procs_read(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&AFTER_PROCS_READ, hook)
}
pub(crate) fn run_after_procs_read() {
    crate::oneshot_hook::fire(&AFTER_PROCS_READ);
}

/// Run `hook` in the NEXT `CgroupLeaf::terminate` on this thread, once it has pinned its first
/// member by a pidfd and before it places that member: the window in which a pinned member can
/// exit and be reaped.
pub(crate) fn set_after_terminate_pin(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&AFTER_TERMINATE_PIN, hook)
}
pub(crate) fn run_after_terminate_pin() {
    crate::oneshot_hook::fire(&AFTER_TERMINATE_PIN);
}

/// A signal `CgroupLeaf::terminate` sent a member: the pid its pidfd names (`None` once that
/// process is reaped, or where it cannot be read), the route of the send, and the signal's number.
pub(crate) type MemberTerm = (Option<u32>, crate::send_log::Via, i32);

/// Notes a signal `signo` sent to the leaf member `pid` by `sys` on this thread, once answered; the
/// route is the syscall's own, and a pidfd's pid is read from its fdinfo.
pub(crate) fn record_member_term(sys: crate::containment::unix::Sys<'_>, pid: u32, signo: i32) {
    use crate::containment::unix::Sys;
    use crate::identity::{pidfd_pid_in, HostKernel, PidfdTarget, ProcDir};
    use crate::send_log::Via;
    let entry = match sys {
        Sys::Pidfd(pidfd, _) => {
            let pid = ProcDir::open()
                .map_err(crate::identity::ViewUnreadable::from)
                .and_then(|dir| pidfd_pid_in(&HostKernel, &dir, pidfd))
                .map_err(|why| {
                    log::debug!(
                        "record_member_term: the pidfd's pid was not read: {report}",
                        report = crate::error::Report(&why)
                    );
                })
                .ok()
                .and_then(|target| match target {
                    PidfdTarget::Pid(pid) if pid > 0 => Some(pid),
                    PidfdTarget::Pid(_) | PidfdTarget::Reaped => None,
                });
            (pid, Via::Pidfd, signo)
        }
        Sys::Group(_) | Sys::Process(_) => (Some(pid), Via::Pid, signo),
    };
    MEMBER_TERMS.with(|t| t.borrow_mut().push(entry));
}

/// The `SIGTERM`s this thread's `CgroupLeaf::terminate` sent members since the last call.
pub(crate) fn take_member_terms() -> Vec<MemberTerm> {
    MEMBER_TERMS.with(|t| std::mem::take(&mut *t.borrow_mut()))
}

/// Pumps started and ended, per leaf name, process-wide.
static PUMPS: std::sync::Mutex<Vec<(std::ffi::OsString, bool)>> = std::sync::Mutex::new(Vec::new());

/// Record a pump starting (`ended == false`) or ending on the leaf named `name`.
pub(crate) fn record_pump(name: &std::ffi::OsStr, ended: bool) {
    PUMPS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push((name.to_os_string(), ended));
}
/// How many pumps started and ended on the leaf named `name`.
pub(crate) fn pumps_of(name: &str) -> (usize, usize) {
    let pumps = PUMPS.lock().unwrap_or_else(|e| e.into_inner());
    let of = |ended| {
        pumps
            .iter()
            .filter(|(n, e)| n.as_os_str() == name && *e == ended)
            .count()
    };
    (of(false), of(true))
}

/// How many drain watches were armed on each leaf name, process-wide.
static ARMS: std::sync::Mutex<Vec<std::ffi::OsString>> = std::sync::Mutex::new(Vec::new());

pub(crate) fn record_arm(name: &std::ffi::OsStr) {
    ARMS.lock().unwrap_or_else(|e| e.into_inner()).push(name.to_os_string());
}
/// How many drain watches were armed on the leaf named `name`.
#[cfg(feature = "tokio")]
pub(crate) fn arms_of(name: &str) -> usize {
    ARMS.lock()
        .unwrap_or_else(|e| e.into_inner())
        .iter()
        .filter(|n| n.as_os_str() == name)
        .count()
}

/// Pump seams, per leaf name, process-wide: a leaf's pump is a thread of its own.
static PUMP_SEAMS: std::sync::Mutex<Vec<(std::ffi::OsString, PumpSeam)>> = std::sync::Mutex::new(Vec::new());

enum PumpSeam {
    /// Fail the pump the next time its watch is readable.
    Fail,
    /// Report, for each batch the pump takes in, whether it notifies.
    Batches(std::sync::mpsc::Sender<bool>),
}

/// Make the pump of the leaf named `name` fail the next time its watch is readable, as a failed
/// `read` of the inotify instance would. Take semantics.
pub(crate) fn set_force_pump_failure(name: &str) {
    PUMP_SEAMS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push((name.into(), PumpSeam::Fail));
}
pub(crate) fn take_force_pump_failure(name: &std::ffi::OsStr) -> bool {
    let mut seams = PUMP_SEAMS.lock().unwrap_or_else(|e| e.into_inner());
    let at = seams
        .iter()
        .position(|(n, s)| n.as_os_str() == name && matches!(s, PumpSeam::Fail));
    at.map(|at| seams.remove(at)).is_some()
}

/// Send, for each batch the pump of the leaf named `name` takes in, whether it notifies. The pump
/// sends before it broadcasts, so a wait that a batch wakes has that batch already sent.
/// `watcher::fail`'s broadcast sends none.
pub(crate) fn set_pump_batch_notifier(name: &str, notify: std::sync::mpsc::Sender<bool>) {
    PUMP_SEAMS
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .push((name.into(), PumpSeam::Batches(notify)));
}
pub(crate) fn notify_pump_batch(name: &std::ffi::OsStr, notified: bool) {
    for (n, seam) in PUMP_SEAMS.lock().unwrap_or_else(|e| e.into_inner()).iter() {
        if let (true, PumpSeam::Batches(notify)) = (n.as_os_str() == name, seam) {
            _ = notify.send(notified);
        }
    }
}

/// Make `KillOnDrop::drop`'s NEXT `waitid` on this thread report one synthetic `EINTR` before its
/// real call, exercising the retry loop deterministically. Consumed by that one iteration.
pub(crate) fn set_force_kill_on_drop_waitid_eintr(on: bool) {
    FORCE_KILL_ON_DROP_WAITID_EINTR.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_on_drop_waitid_eintr() -> bool {
    FORCE_KILL_ON_DROP_WAITID_EINTR.with(|f| f.replace(false))
}

/// Make `KillOnDrop::drop`'s NEXT `pidfd_send_signal` on this thread fail with `EPERM`, without
/// sending a real signal. Consumed by that call.
pub(crate) fn set_force_kill_on_drop_kill_failure(on: bool) {
    FORCE_KILL_ON_DROP_KILL_FAILURE.with(|f| f.set(on));
}
pub(crate) fn take_force_kill_on_drop_kill_failure() -> bool {
    FORCE_KILL_ON_DROP_KILL_FAILURE.with(|f| f.replace(false))
}

/// Run `hook` when the next leaf on this thread starts to settle its placement verdict
/// (`CgroupLeaf::take_placement`); the guard clears it on drop.
pub(crate) fn set_on_take_placement(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&ON_TAKE_PLACEMENT, hook)
}
pub(crate) fn run_on_take_placement() {
    crate::oneshot_hook::fire(&ON_TAKE_PLACEMENT);
}

/// Run `hook` in the NEXT `/proc` state read on this thread, just before it reads: the window in
/// which the child can exit and its number change hands, after the look that found it running.
pub(crate) fn set_before_state_read(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&BEFORE_STATE_READ, hook)
}
pub(crate) fn run_before_state_read() {
    crate::oneshot_hook::fire(&BEFORE_STATE_READ);
}

/// While the guard lives, this thread reads every pidfd's cgroup id as `id`.
pub(crate) fn force_pidfd_cgroup_id(id: u64) -> ForcedPidfdCgroupId {
    FORCED_PIDFD_CGROUP_ID.with(|f| f.set(Some(id)));
    ForcedPidfdCgroupId(())
}

#[must_use = "the id is read again as soon as the guard is dropped"]
pub(crate) struct ForcedPidfdCgroupId(());

impl Drop for ForcedPidfdCgroupId {
    fn drop(&mut self) {
        FORCED_PIDFD_CGROUP_ID.with(|f| f.set(None));
    }
}

pub(crate) fn forced_pidfd_cgroup_id() -> Option<u64> {
    FORCED_PIDFD_CGROUP_ID.with(Cell::get)
}

/// While the guard lives, capturing a leaf's subtree on this thread fails with `errno`, as its
/// cgroup id read does once the leaf's filesystem stops giving ids.
pub(crate) fn fail_subtree(errno: i32) -> FailSubtree {
    SUBTREE_FAILS.with(|f| f.set(Some(errno)));
    FailSubtree(())
}

#[must_use = "the subtree is captured again as soon as the guard is dropped"]
pub(crate) struct FailSubtree(());

impl Drop for FailSubtree {
    fn drop(&mut self) {
        SUBTREE_FAILS.with(|f| f.set(None));
    }
}

/// A step of `CgroupLeaf::terminate`'s `SIGTERM` to one member.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TerminateStep {
    /// The `pidfd_open` that pins the member.
    Pin,
    /// The read of whether the pinned member has exited.
    Exited,
    /// The `pidfd_send_signal`.
    Send,
}

/// While the guard lives, `step` of each member's `SIGTERM` in `CgroupLeaf::terminate` on this
/// thread fails with `errno`, and the call it stands for is not made.
pub(crate) fn fail_terminate(step: TerminateStep, errno: i32) -> FailTerminate {
    TERMINATE_FAILS.with(|f| f.set(Some((step, errno, false))));
    FailTerminate(())
}

/// [`fail_terminate`] for the first member's `step` only: the members after it are not refused.
pub(crate) fn fail_terminate_once(step: TerminateStep, errno: i32) -> FailTerminate {
    TERMINATE_FAILS.with(|f| f.set(Some((step, errno, true))));
    FailTerminate(())
}

#[must_use = "terminate's steps run again as soon as the guard is dropped"]
pub(crate) struct FailTerminate(());

impl Drop for FailTerminate {
    fn drop(&mut self) {
        TERMINATE_FAILS.with(|f| f.set(None));
    }
}

/// The errno `step` fails with, if a [`fail_terminate`] guard is live for it. A
/// [`fail_terminate_once`] refusal is spent by the call that gets it.
pub(crate) fn terminate_fails(step: TerminateStep) -> Option<i32> {
    let (failing, errno, once) = TERMINATE_FAILS.with(Cell::get)?;
    if failing != step {
        return None;
    }
    if once {
        TERMINATE_FAILS.with(|f| f.set(None));
    }
    Some(errno)
}

pub(crate) fn subtree_fails() -> Option<i32> {
    SUBTREE_FAILS.with(Cell::get)
}

/// A hook given the path, relative to the leaf, of each cgroup a descendant walk is about to open.
type WalkHook = Box<dyn FnMut(&std::path::Path)>;

/// While the guard lives, run `hook` with the path, relative to the leaf, of each cgroup a
/// descendant walk on this thread is about to open (`dir::find_descendant`), so a test can remove
/// one mid-walk.
pub(crate) fn set_before_walk_open(hook: impl FnMut(&std::path::Path) + 'static) -> BeforeWalkOpen {
    BEFORE_WALK_OPEN.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    BeforeWalkOpen(())
}

#[must_use = "the hook is cleared as soon as the guard is dropped"]
pub(crate) struct BeforeWalkOpen(());

impl Drop for BeforeWalkOpen {
    fn drop(&mut self) {
        BEFORE_WALK_OPEN.with(|h| h.borrow_mut().take());
    }
}

pub(crate) fn run_before_walk_open(path: &std::path::Path) {
    let hook = BEFORE_WALK_OPEN.with(|h| h.borrow_mut().take());
    if let Some(mut hook) = hook {
        hook(path);
        BEFORE_WALK_OPEN.with(|h| {
            h.borrow_mut().get_or_insert(hook);
        });
    }
}

/// The cgroup, the step, the errno, and how many times the step passes before it fails.
type WalkFailure = (std::path::PathBuf, WalkStep, i32, usize);

/// While the guard lives, `step` of the walk on this thread at the cgroup `path`, relative to the
/// leaf (`.` is the leaf itself), fails with `errno`, as the OS answers a refusal that cannot be
/// provoked on a real cgroup.
pub(crate) fn fail_walk_step(path: &str, step: WalkStep, errno: i32) -> FailWalkStep {
    fail_walk_step_after(path, step, errno, 0)
}

/// [`fail_walk_step`], once the step has passed `passes` times at `path`: for [`WalkStep::Entries`],
/// the failure comes at entry number `passes`, after the entries before it were read.
pub(crate) fn fail_walk_step_after(path: &str, step: WalkStep, errno: i32, passes: usize) -> FailWalkStep {
    WALK_FAILURE.with(|f| *f.borrow_mut() = Some((path.into(), step, errno, passes)));
    FailWalkStep(())
}

#[must_use = "the step succeeds again as soon as the guard is dropped"]
pub(crate) struct FailWalkStep(());

impl Drop for FailWalkStep {
    fn drop(&mut self) {
        WALK_FAILURE.with(|f| f.borrow_mut().take());
    }
}

pub(crate) fn walk_step_failure(path: &std::path::Path, step: WalkStep) -> Option<i32> {
    WALK_FAILURE.with(|f| match &mut *f.borrow_mut() {
        Some((at, failing, errno, passes)) if at == path && *failing == step => {
            if *passes == 0 {
                Some(*errno)
            } else {
                *passes -= 1;
                None
            }
        }
        _ => None,
    })
}

/// While the guard lives, run `hook` with the path, relative to the leaf, of each cgroup the sweep
/// on this thread (`dir::remove_children`) is about to remove, so a test can change the tree
/// between the sweep's listing and its removals.
pub(crate) fn set_before_sweep_remove(hook: impl FnMut(&std::path::Path) + 'static) -> BeforeSweepRemove {
    BEFORE_SWEEP_REMOVE.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    BeforeSweepRemove(())
}

#[must_use = "the hook is cleared as soon as the guard is dropped"]
pub(crate) struct BeforeSweepRemove(());

impl Drop for BeforeSweepRemove {
    fn drop(&mut self) {
        BEFORE_SWEEP_REMOVE.with(|h| h.borrow_mut().take());
    }
}

pub(crate) fn run_before_sweep_remove(path: &std::path::Path) {
    let hook = BEFORE_SWEEP_REMOVE.with(|h| h.borrow_mut().take());
    if let Some(mut hook) = hook {
        hook(path);
        BEFORE_SWEEP_REMOVE.with(|h| {
            h.borrow_mut().get_or_insert(hook);
        });
    }
}

/// While the guard lives, a leaf's cgroup id on this thread fails with `errno`, as
/// `name_to_handle_at` does on a kernel without `CONFIG_FHANDLE` (`ENOSYS`).
pub(crate) fn fail_cgroup_id(errno: i32) -> FailCgroupId {
    CGROUP_ID_FAILS.with(|f| f.set(Some(errno)));
    FailCgroupId(())
}

#[must_use = "the id reads again as soon as the guard is dropped"]
pub(crate) struct FailCgroupId(());

impl Drop for FailCgroupId {
    fn drop(&mut self) {
        CGROUP_ID_FAILS.with(|f| f.set(None));
    }
}

pub(crate) fn cgroup_id_fails() -> Option<i32> {
    CGROUP_ID_FAILS.with(Cell::get)
}

/// While the guard lives, a leaf's read of whether it is live, before its removal on this thread,
/// fails with `errno`, as an `openat` refused `EMFILE` does.
pub(crate) fn fail_liveness_read(errno: i32) -> FailLivenessRead {
    LIVENESS_READ_FAILS.with(|f| f.set(Some(errno)));
    FailLivenessRead(())
}

#[must_use = "the liveness reads again as soon as the guard is dropped"]
pub(crate) struct FailLivenessRead(());

impl Drop for FailLivenessRead {
    fn drop(&mut self) {
        LIVENESS_READ_FAILS.with(|f| f.set(None));
    }
}

pub(crate) fn liveness_read_fails() -> Option<i32> {
    LIVENESS_READ_FAILS.with(Cell::get)
}