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
//! Test seams for the pidfd handshake. Thread-local where the spawning thread reads them; what the
//! helper thread needs is taken on the spawning thread and carried to it in [`HelperSeams`]. Every
//! arming function returns a guard that disarms on drop.

use std::cell::{Cell, RefCell};
use std::collections::VecDeque;
use std::io;
use std::os::fd::{AsFd, AsRawFd, OwnedFd};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex, PoisonError};

use rustix::io::Errno;

/// What the next child does around its report.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ChildFault {
    None,
    /// Its hook fails before it reports: the child exits before `exec`, std reports it.
    Fail,
    /// It kills itself before it reports: std reads that as a success.
    Sigkill,
    /// It kills itself after it sent its pidfd, before it reads its verdict.
    SigkillAfterReport,
    /// It reads one byte from this fd, inherited across the fork, before it reports.
    Gate(i32),
    /// After it sent its pidfd: it closes its copies of `parent_ends` (so its read ends at EOF if
    /// the parent's go-ahead never comes), lets any process trace it, writes its pid (four
    /// native-endian bytes) to `ready`, reads one byte from `gate`, then kills itself. All fds are
    /// inherited across the fork.
    #[cfg_attr(
        not(feature = "tokio"),
        allow(dead_code, reason = "only the tokio spawn's tracer test uses it")
    )]
    TracedThenSigkillAfterReport {
        ready: i32,
        gate: i32,
        parent_ends: [i32; 2],
    },
}

impl ChildFault {
    /// Before the report. Async-signal-safe.
    pub(super) fn apply(self) -> io::Result<()> {
        match self {
            ChildFault::Fail => Err(io::Error::from_raw_os_error(libc::EIO)),
            ChildFault::Sigkill => kill_self(),
            ChildFault::Gate(fd) => {
                read_gate(fd);
                Ok(())
            }
            ChildFault::None | ChildFault::SigkillAfterReport | ChildFault::TracedThenSigkillAfterReport { .. } => {
                Ok(())
            }
        }
    }

    /// After the report. Async-signal-safe.
    pub(super) fn apply_after_report(self) -> io::Result<()> {
        match self {
            ChildFault::SigkillAfterReport => kill_self(),
            ChildFault::TracedThenSigkillAfterReport {
                ready,
                gate,
                parent_ends,
            } => {
                for fd in parent_ends {
                    // SAFETY: a plain `close` of this child's copy of a number the test gave.
                    unsafe { libc::close(fd) };
                }
                crate::test_support::foreign_tracer::allow_any_tracer_now()?;
                let pid = rustix::process::getpid().as_raw_nonzero().get().to_ne_bytes();
                // SAFETY: a write of this frame's four bytes; a pipe takes them whole.
                if unsafe { libc::write(ready, pid.as_ptr().cast(), pid.len()) } != 4 {
                    return Err(io::Error::last_os_error());
                }
                read_gate(gate);
                kill_self()
            }
            ChildFault::None | ChildFault::Fail | ChildFault::Sigkill | ChildFault::Gate(_) => Ok(()),
        }
    }
}

/// Reads one byte from `fd`. Async-signal-safe.
fn read_gate(fd: i32) {
    let mut byte = 0u8;
    // SAFETY: a one-byte read into this frame; retried on `EINTR` only.
    while unsafe { libc::read(fd, (&raw mut byte).cast(), 1) } < 0
        && io::Error::last_os_error().kind() == io::ErrorKind::Interrupted
    {}
}

fn kill_self() -> io::Result<()> {
    // Async-signal-safe: rustix's `linux_raw` backend makes `getpid` and `kill` raw syscalls.
    match rustix::process::kill_process(rustix::process::getpid(), rustix::process::Signal::KILL) {
        // SIGKILL does not return to the caller.
        Ok(()) => Err(io::Error::from_raw_os_error(libc::EIO)),
        Err(e) => Err(io::Error::from_raw_os_error(e.raw_os_error())),
    }
}

type VerdictHook = Box<dyn FnOnce(Option<u32>)>;

thread_local! {
    static DONE_FD_FAILURE: Cell<Option<Errno>> = const { Cell::new(None) };
    static CHILD_PIDFD_OPEN_FAILURE: Cell<Option<Errno>> = const { Cell::new(None) };
    #[cfg(feature = "tokio")]
    static UNEXECUTED_WAIT_FAILURE: Cell<Option<Errno>> = const { Cell::new(None) };
    static CHILD_FAULT: Cell<ChildFault> = const { Cell::new(ChildFault::None) };
    static SPAWNS: Cell<usize> = const { Cell::new(0) };
    static LEAKED: Cell<Option<Option<u32>>> = const { Cell::new(None) };
    static PROBE: RefCell<Option<HelperProbe>> = const { RefCell::new(None) };
    static SEND_ERRNOS: RefCell<VecDeque<Errno>> = const { RefCell::new(VecDeque::new()) };
    static VERDICT_HOOK: RefCell<Option<VerdictHook>> = const { RefCell::new(None) };
    static HOLDER_ARMED: Cell<bool> = const { Cell::new(false) };
    static HOLDER: RefCell<Option<Holder>> = const { RefCell::new(None) };
    static ENDS_ARMED: Cell<bool> = const { Cell::new(false) };
    static ENDS: Cell<Option<Ends>> = const { Cell::new(None) };
    static AFTER_SPAWN: RefCell<Option<VerdictHook>> = const { RefCell::new(None) };
    static WAIT_OVER: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static PARENT_END_SHUT: Cell<Option<bool>> = const { Cell::new(None) };
    static BEFORE_AWAITING: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
    static VERDICT_GUARDED: Cell<bool> = const { Cell::new(false) };
    static WATCH_FAULT: Cell<Option<WatchFault>> = const { Cell::new(None) };
    static UNWOUND: Cell<Option<Unwound>> = const { Cell::new(None) };
}

// Unwinding =====

/// What a `run` that unwound had done by the time its guards ran.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Unwound {
    /// The parent's end read EOF, so the helper could end whatever copies of the child's end exist.
    pub(crate) eof_reached: bool,
    /// The helper probe's gate was open, if a probe was armed.
    pub(crate) probe_open: Option<bool>,
}

/// What the last `run` on this thread that unwound saw.
pub(crate) fn take_unwound() -> Option<Unwound> {
    UNWOUND.with(Cell::take)
}

/// Declared before the production guards, so it drops after them: on an unwind it records what they
/// did, then finishes what they should have, so a regression fails at an assert and not by leaving
/// the scope to join a helper that is never released.
pub(super) struct UnwindChecks<'a> {
    parent_end: &'a OwnedFd,
    probe: Option<HelperProbe>,
}

impl<'a> UnwindChecks<'a> {
    pub(super) fn new(parent_end: &'a OwnedFd, seams: &HelperSeams) -> Self {
        UNWOUND.with(|u| u.set(None));
        UnwindChecks {
            parent_end,
            probe: seams.probe.clone(),
        }
    }
}

impl Drop for UnwindChecks<'_> {
    fn drop(&mut self) {
        if !std::thread::panicking() {
            return;
        }
        let eof_reached = !probe_shut_read(self.parent_end);
        let probe_open = self.probe.as_ref().map(|p| {
            let open = p.gate.is_open();
            p.release();
            open
        });
        UNWOUND.with(|u| {
            u.set(Some(Unwound {
                eof_reached,
                probe_open,
            }))
        });
    }
}

/// Whether the parent's end has NOT read EOF; if so, shuts it so the helper can end.
fn probe_shut_read(parent_end: &OwnedFd) -> bool {
    use rustix::event::{PollFd, PollFlags};

    let mut fds = [PollFd::new(parent_end, PollFlags::RDHUP)];
    crate::wait::any_ready_now(&mut fds).expect("poll the parent's end");
    let reached = fds[0].revents().contains(PollFlags::RDHUP);
    if !reached {
        _ = rustix::net::shutdown(parent_end, rustix::net::Shutdown::Both);
    }
    !reached
}

// The watch =====

/// How the next watch of an unreported child fails.
#[derive(Clone, Copy, Debug)]
pub(crate) enum WatchFault {
    /// Its `pidfd_open` fails with this.
    Open(Errno),
    /// Its `pidfd_open` succeeds and the move above the stdio slots fails with this.
    Move(Errno),
    /// Its peek at the pidfd fails with this, which no real peek does.
    Peek(Errno),
    /// The child is taken to be running, and its poll fails with this.
    Poll(Errno),
}

/// Disarms the done-fd failure on drop.
#[must_use = "dropping this disarms the failure at once"]
pub(crate) struct ArmedDoneFdFailure(());

/// Make the NEXT [`Pending::open`](super::Pending::open) on this thread fail making its done fd.
pub(crate) fn fail_done_fd(errno: Errno) -> ArmedDoneFdFailure {
    DONE_FD_FAILURE.with(|f| f.set(Some(errno)));
    ArmedDoneFdFailure(())
}

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

pub(super) fn take_done_fd_failure() -> Option<Errno> {
    DONE_FD_FAILURE.with(Cell::take)
}

/// Disarms the child's `pidfd_open` failure on drop.
#[must_use = "dropping this disarms the failure at once"]
pub(crate) struct ArmedChildPidfdOpen(());

/// Make the NEXT spawn's child answer its own `pidfd_open` with `errno`. The child makes that call
/// after the fork, where a [`Kernel`](crate::identity::Kernel) fake's tables cannot be consulted.
pub(crate) fn fail_child_pidfd_open(errno: Errno) -> ArmedChildPidfdOpen {
    CHILD_PIDFD_OPEN_FAILURE.with(|f| f.set(Some(errno)));
    ArmedChildPidfdOpen(())
}

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

pub(super) fn take_child_pidfd_open_failure() -> Option<Errno> {
    CHILD_PIDFD_OPEN_FAILURE.with(Cell::take)
}

/// Disarms the failure of the wait for an unexecuted child's exit on drop.
#[cfg(feature = "tokio")]
#[must_use = "dropping this disarms the failure at once"]
pub(crate) struct ArmedUnexecutedWaitFailure(());

/// Make the NEXT wait on this thread for an unexecuted child's exit
/// ([`await_unexecuted_exit`](super::await_unexecuted_exit)) fail with `errno`, after its kill.
#[cfg(feature = "tokio")]
pub(crate) fn fail_unexecuted_wait(errno: Errno) -> ArmedUnexecutedWaitFailure {
    UNEXECUTED_WAIT_FAILURE.with(|f| f.set(Some(errno)));
    ArmedUnexecutedWaitFailure(())
}

#[cfg(feature = "tokio")]
impl Drop for ArmedUnexecutedWaitFailure {
    fn drop(&mut self) {
        UNEXECUTED_WAIT_FAILURE.with(|f| f.set(None));
    }
}

#[cfg(feature = "tokio")]
pub(super) fn take_unexecuted_wait_failure() -> Option<Errno> {
    UNEXECUTED_WAIT_FAILURE.with(Cell::take)
}

/// Disarms the watch fault on drop.
#[must_use = "dropping this disarms the fault at once"]
pub(crate) struct ArmedWatchFault(());

/// Make the NEXT watch of an unreported child fail as `fault` says.
pub(crate) fn fail_watch(fault: WatchFault) -> ArmedWatchFault {
    WATCH_FAULT.with(|f| f.set(Some(fault)));
    ArmedWatchFault(())
}

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

pub(super) fn watch_open_errno() -> Option<Errno> {
    match WATCH_FAULT.with(Cell::get) {
        Some(WatchFault::Open(errno)) => {
            WATCH_FAULT.with(|f| f.set(None));
            Some(errno)
        }
        _ => None,
    }
}

pub(super) fn watch_peek_errno() -> Option<Errno> {
    match WATCH_FAULT.with(Cell::get) {
        Some(WatchFault::Peek(errno)) => {
            WATCH_FAULT.with(|f| f.set(None));
            Some(errno)
        }
        _ => None,
    }
}

/// Whether a poll fault is armed: the peek is then skipped, as if it answered `Running`.
pub(super) fn watch_poll_armed() -> bool {
    matches!(WATCH_FAULT.with(Cell::get), Some(WatchFault::Poll(_)))
}

pub(super) fn watch_poll_errno() -> Option<Errno> {
    match WATCH_FAULT.with(Cell::get) {
        Some(WatchFault::Poll(errno)) => {
            WATCH_FAULT.with(|f| f.set(None));
            Some(errno)
        }
        _ => None,
    }
}

pub(super) fn watch_move_errno() -> Option<Errno> {
    match WATCH_FAULT.with(Cell::get) {
        Some(WatchFault::Move(errno)) => {
            WATCH_FAULT.with(|f| f.set(None));
            Some(errno)
        }
        _ => None,
    }
}

/// Disarms the after-spawn hook on drop.
#[must_use = "dropping this disarms the hook at once"]
pub(crate) struct AfterSpawn(());

/// Run `hook` once on the spawning thread, with the child's pid if the spawn succeeded, when the
/// NEXT `run`'s `spawn()` has returned: this thread still holds the child's end, and nothing has
/// yet waited on the child or the helper. Fires whatever `spawn()` answered.
pub(crate) fn after_spawn_returns_do(hook: impl FnOnce(Option<u32>) + 'static) -> AfterSpawn {
    AFTER_SPAWN.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    AfterSpawn(())
}

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

pub(super) fn spawn_returned(pid: Option<u32>) {
    if let Some(hook) = AFTER_SPAWN.with(|h| h.borrow_mut().take()) {
        hook(pid);
    }
}

/// Run `hook` once on this thread when the next `run`, its spawn returned, is about to block until
/// the helper is done or the child has exited. Not reached if the wait is skipped or answered at
/// once.
pub(crate) fn before_awaiting_the_child_do(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&BEFORE_AWAITING, hook)
}

pub(super) fn before_awaiting_the_child() {
    crate::oneshot_hook::fire(&BEFORE_AWAITING);
}

/// Run `hook` once on this thread when the next `run`'s wait for the child is over, whatever it
/// answered: the place for a release that must happen on every path, so a fixture held for the
/// wait that a regression skips cannot hang the test.
pub(crate) fn wait_over_do(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
    crate::oneshot_hook::arm(&WAIT_OVER, hook)
}

pub(super) fn wait_over() {
    crate::oneshot_hook::fire(&WAIT_OVER);
}

/// Fires the wait-over hook when dropped, unwinding included, if it has not fired: a panic on the
/// spawning thread between `spawn()` returning and the wait's end must still release what the hook
/// holds, or the scope joins a helper that waits for it. A hook that itself panics here is
/// contained: a second panic during an unwind would abort.
#[must_use = "dropping this fires the hook at once"]
pub(super) struct WaitOverOnDrop;

impl Drop for WaitOverOnDrop {
    fn drop(&mut self) {
        _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(wait_over));
    }
}

// The child =====

/// Disarms the child fault on drop.
#[must_use = "dropping this disarms the fault at once"]
pub(crate) struct ArmedChildFault(());

/// Make the NEXT spawn's child do `fault`.
pub(crate) fn arm_child_fault(fault: ChildFault) -> ArmedChildFault {
    CHILD_FAULT.with(|f| f.set(fault));
    ArmedChildFault(())
}

impl Drop for ArmedChildFault {
    fn drop(&mut self) {
        CHILD_FAULT.with(|f| f.set(ChildFault::None));
    }
}

/// Taken once by `register`.
pub(super) fn child_fault() -> ChildFault {
    CHILD_FAULT.with(|f| f.replace(ChildFault::None))
}

// Counters =====

/// How many times `run` reached its fork on this thread.
pub(crate) fn spawns() -> usize {
    SPAWNS.with(Cell::get)
}

pub(crate) fn reset_spawns() {
    SPAWNS.with(|c| c.set(0));
}

pub(super) fn count_spawn() {
    SPAWNS.with(|c| c.set(c.get() + 1));
}

pub(crate) fn reset_leaked_pid() {
    LEAKED.with(|c| c.set(None));
}

/// The pid of the last child a spawn left unreaped; `Some(None)` if it had no pid.
pub(crate) fn take_leaked_pid() -> Option<Option<u32>> {
    LEAKED.with(Cell::take)
}

pub(super) fn leaked_pid(pid: Option<u32>) {
    LEAKED.with(|c| c.set(Some(pid)));
}

// A process that holds copies of both ends =====

struct Holder {
    release: OwnedFd,
    pidfd: OwnedFd,
}

/// Releases and reaps the holder on drop, whether or not it was forked.
#[must_use = "dropping this disarms the holder, or releases the one forked"]
pub(crate) struct ArmedHolder(());

/// Make the NEXT `run` on this thread fork, just before its spawn, a process that execs nothing
/// and holds copies of both ends of the channel until this guard drops, as a fork by another
/// thread would.
pub(crate) fn arm_fork_holder() -> ArmedHolder {
    HOLDER_ARMED.with(|a| a.set(true));
    ArmedHolder(())
}

impl Drop for ArmedHolder {
    fn drop(&mut self) {
        HOLDER_ARMED.with(|a| a.set(false));
        if let Some(holder) = HOLDER.with(|h| h.borrow_mut().take()) {
            drop(holder.release);
            let reaped = rustix::process::waitid(
                rustix::process::WaitId::PidFd(holder.pidfd.as_fd()),
                rustix::process::WaitIdOptions::EXITED,
            );
            assert!(reaped.is_ok(), "reap the holder: {reaped:?}");
        }
    }
}

/// Called by `run` with `spawn_lock` held, both ends open, and the helper started.
pub(super) fn fork_holder_if_armed() {
    if !HOLDER_ARMED.with(|a| a.replace(false)) {
        return;
    }
    let (release_r, release_w) = std::io::pipe().expect("pipe");
    let (release_r, release_w) = (OwnedFd::from(release_r), OwnedFd::from(release_w));
    let (r, w) = (release_r.as_raw_fd(), release_w.as_raw_fd());
    // SAFETY: the copy makes only async-signal-safe calls (`close`, `read`, `_exit`), and the
    // caller holds `spawn_lock`.
    let pid = unsafe { libc::fork() };
    if pid == 0 {
        // SAFETY: as above; it waits for the release end's EOF, then exits.
        unsafe {
            libc::close(w);
            let mut byte = 0u8;
            while libc::read(r, (&raw mut byte).cast(), 1) < 0 && *libc::__errno_location() == libc::EINTR {}
            libc::_exit(0);
        }
    }
    assert!(pid > 0, "fork the holder: {}", io::Error::last_os_error());
    drop(release_r);
    // Blocked on its release end, so it is this process's unreaped child: its number is its own.
    let pidfd = rustix::process::pidfd_open(
        rustix::process::Pid::from_raw(pid).expect("a forked pid is positive"),
        rustix::process::PidfdFlags::empty(),
    )
    .expect("the holder's pidfd");
    HOLDER.with(|h| {
        *h.borrow_mut() = Some(Holder {
            release: release_w,
            pidfd,
        })
    });
}

// Shutdown probes =====

/// What the armed end probes saw in one `run`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Ends {
    /// Whether, once `spawn()` returned and the spawning thread had closed its copy, this process
    /// still held a copy of the child's end. A held copy keeps the helper from reading EOF when the
    /// child dies, so the wait for the child can then hang on an unrelated process.
    pub(crate) child_end_copy_held: bool,
    /// Whether the parent's end read EOF once the wait for the child was over, whatever copies of
    /// the child's end exist.
    pub(crate) eof_reached: bool,
    /// Whether the parent forced that EOF (a child that exited while a copy of its end was held).
    pub(crate) eof_forced: bool,
}

/// Disarms the end probes on drop.
#[must_use = "dropping this disarms the probes at once"]
pub(crate) struct ArmedEndProbes(());

/// Probe the NEXT `run` on this thread; [`take_ends`] reads what it saw. Each probe shuts what it
/// found wrong, so a regression fails its test at an assert rather than hanging it.
pub(crate) fn arm_end_probes() -> ArmedEndProbes {
    ENDS_ARMED.with(|a| a.set(true));
    ENDS.with(|e| e.set(None));
    ArmedEndProbes(())
}

impl Drop for ArmedEndProbes {
    fn drop(&mut self) {
        ENDS_ARMED.with(|a| a.set(false));
    }
}

/// What the last armed `run` on this thread saw.
pub(crate) fn take_ends() -> Option<Ends> {
    ENDS.with(Cell::take)
}

/// One `run`'s end probes, if armed.
pub(super) struct EndProbes {
    /// The child's end: its device and inode, which name the socket in every descriptor table.
    child_end: Option<(u64, u64)>,
    held: bool,
    forced: bool,
}

impl EndProbes {
    pub(super) fn start(child_end: &OwnedFd) -> Self {
        use std::os::unix::fs::MetadataExt;

        let armed = ENDS_ARMED.with(|a| a.replace(false));
        let child_end = armed.then(|| {
            let meta = std::fs::File::from(child_end.try_clone().expect("clone the child's end")).metadata();
            let meta = meta.expect("stat the child's end");
            (meta.dev(), meta.ino())
        });
        EndProbes {
            child_end,
            held: false,
            forced: false,
        }
    }

    /// After the spawning thread closed its copy: any descriptor of this process still naming the
    /// child's end is a leak. It is shut, so the helper can end.
    pub(super) fn check_copies_closed(&mut self) {
        use std::os::fd::{BorrowedFd, RawFd};
        use std::os::unix::fs::{FileTypeExt, MetadataExt};

        let Some((dev, ino)) = self.child_end else { return };
        let entries = std::fs::read_dir("/proc/self/fd").expect("list this process's descriptors");
        for entry in entries.flatten() {
            let Ok(meta) = std::fs::metadata(entry.path()) else {
                continue;
            };
            if !(meta.file_type().is_socket() && meta.dev() == dev && meta.ino() == ino) {
                continue;
            }
            let Ok(fd) = entry.file_name().to_string_lossy().parse::<RawFd>() else {
                continue;
            };
            self.held = true;
            // SAFETY: a descriptor of this process, open when listed; only shut, never closed.
            _ = rustix::net::shutdown(unsafe { BorrowedFd::borrow_raw(fd) }, rustix::net::Shutdown::Both);
        }
    }

    pub(super) fn forced_eof(&mut self) {
        self.forced = true;
    }

    /// Once the wait for the child is over: the parent's end must read EOF. If not, shuts it.
    pub(super) fn finish(self, parent_end: &OwnedFd) {
        use rustix::event::{PollFd, PollFlags};

        if self.child_end.is_none() {
            return;
        }
        // `RDHUP` is reported only if asked for: a read side shut, by `shutdown` or by the peer's
        // last close.
        let mut fds = [PollFd::new(parent_end, PollFlags::RDHUP)];
        crate::wait::any_ready_now(&mut fds).expect("poll the parent's end");
        let eof_reached = fds[0].revents().contains(PollFlags::RDHUP);
        if !eof_reached {
            _ = rustix::net::shutdown(parent_end, rustix::net::Shutdown::Both);
        }
        ENDS.with(|e| {
            e.set(Some(Ends {
                child_end_copy_held: self.held,
                eof_reached,
                eof_forced: self.forced,
            }))
        });
    }
}

/// Whether `fd`'s socket is shut both ways (`POLLHUP`, a check that does not block). If not, shuts
/// it, so a mutant that forgot fails its test at an assert rather than hanging it.
fn probe_shut(fd: &OwnedFd) -> bool {
    use rustix::event::{PollFd, PollFlags};

    let mut fds = [PollFd::new(fd, PollFlags::empty())];
    crate::wait::any_ready_now(&mut fds).expect("poll the channel");
    let shut = fds[0].revents().contains(PollFlags::HUP);
    if !shut {
        _ = rustix::net::shutdown(fd, rustix::net::Shutdown::Both);
    }
    shut
}

/// Whether the last `run` on this thread's helper had shut the parent's end when it finished.
pub(crate) fn parent_end_shut() -> Option<bool> {
    PARENT_END_SHUT.with(Cell::take)
}

// The helper =====

/// Disarms the forced errnos on drop.
#[must_use = "dropping this disarms the forced errnos at once"]
pub(crate) struct ForcedGoSend(());

/// Make the NEXT `run`'s sends of GO fail with `errnos`, one per attempt; later attempts are real.
pub(crate) fn force_go_send_errnos(errnos: impl IntoIterator<Item = Errno>) -> ForcedGoSend {
    SEND_ERRNOS.with(|s| *s.borrow_mut() = errnos.into_iter().collect());
    ForcedGoSend(())
}

impl Drop for ForcedGoSend {
    fn drop(&mut self) {
        SEND_ERRNOS.with(|s| s.borrow_mut().clear());
    }
}

/// Disarms the held verdict on drop.
#[must_use = "dropping this disarms the held verdict at once"]
pub(crate) struct HeldVerdict(());

/// Make the NEXT `run`'s helper wait, once it has the child's report, until the spawn has returned
/// and the child's end is shut; `hook` runs on the spawning thread just before the helper goes on,
/// with the child's pid. Only for a child that dies without its verdict: one that waits for it
/// would never let the spawn return.
pub(crate) fn hold_verdict_until_spawn_returns(hook: impl FnOnce(Option<u32>) + 'static) -> HeldVerdict {
    VERDICT_HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
    HeldVerdict(())
}

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

#[derive(Clone, Default)]
struct Gate(Arc<(Mutex<bool>, Condvar)>);

impl Gate {
    fn wait(&self) {
        let (lock, condvar) = &*self.0;
        let mut open = lock.lock().unwrap_or_else(PoisonError::into_inner);
        while !*open {
            open = condvar.wait(open).unwrap_or_else(PoisonError::into_inner);
        }
    }

    fn is_open(&self) -> bool {
        *self.0 .0.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn open(&self) {
        let (lock, condvar) = &*self.0;
        *lock.lock().unwrap_or_else(PoisonError::into_inner) = true;
        condvar.notify_all();
    }
}

/// One `run`'s seams, taken on the spawning thread.
#[derive(Clone, Default)]
pub(crate) struct HelperSeams {
    probe: Option<HelperProbe>,
    send_errnos: Arc<Mutex<VecDeque<Errno>>>,
    /// Makes the helper's move of the received pidfd above the stdio slots fail with this.
    move_errno: Arc<Mutex<Option<Errno>>>,
    verdict: Option<Gate>,
    parent_end_shut: Arc<Mutex<Option<bool>>>,
}

pub(super) fn take_helper_seams() -> HelperSeams {
    HelperSeams {
        probe: PROBE.with(|p| p.borrow_mut().take()),
        send_errnos: Arc::new(Mutex::new(SEND_ERRNOS.with(|s| std::mem::take(&mut *s.borrow_mut())))),
        verdict: VERDICT_HOOK.with(|h| h.borrow().is_some()).then(Gate::default),
        parent_end_shut: Arc::default(),
        ..HelperSeams::default()
    }
}

impl HelperSeams {
    /// The helper, at its very end.
    pub(super) fn finish(&self) {
        if let Some(probe) = &self.probe {
            probe.wait_gate_then_finish();
        }
    }

    /// The spawning thread, where it joins the helper.
    pub(super) fn release_probe(&self) {
        if let Some(probe) = &self.probe {
            probe.release();
        }
    }

    pub(super) fn take_send_errno(&self) -> Option<Errno> {
        self.send_errnos
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .pop_front()
    }

    /// Seams for a helper that fails to move the pidfd it received, with `errno`.
    pub(crate) fn failing_move(errno: Errno) -> Self {
        HelperSeams {
            move_errno: Arc::new(Mutex::new(Some(errno))),
            ..HelperSeams::default()
        }
    }

    pub(super) fn take_move_errno(&self) -> Option<Errno> {
        self.move_errno.lock().unwrap_or_else(PoisonError::into_inner).take()
    }

    /// The helper, once it has the child's report.
    pub(super) fn wait_verdict(&self) {
        if let Some(gate) = &self.verdict {
            gate.wait();
        }
    }

    /// The spawning thread, once the spawn has returned and the wait for the child is over.
    pub(super) fn release_verdict(&self, pid: Option<u32>) {
        if let Some(gate) = &self.verdict {
            if let Some(hook) = VERDICT_HOOK.with(|h| h.borrow_mut().take()) {
                hook(pid);
            }
            gate.open();
        }
    }

    /// Opens the held verdict when dropped, unwinding included: a panic on the spawning thread (a
    /// hook, an assert) must fail the test, not leave the helper parked where the scope joins it.
    ///
    /// The helper probe's gate opens too, but only when unwinding: opened at a normal exit it would
    /// release a helper nobody joined.
    pub(super) fn open_on_drop(&self) -> OpenOnDrop {
        VERDICT_GUARDED.with(|g| g.set(true));
        OpenOnDrop {
            verdict: self.verdict.clone(),
            probe: self.probe.clone(),
        }
    }

    /// The helper, as it shuts the parent's end.
    pub(super) fn record_parent_end_shut(&self, fd: &OwnedFd) {
        *self.parent_end_shut.lock().unwrap_or_else(PoisonError::into_inner) = Some(probe_shut(fd));
    }

    /// The spawning thread, after the join.
    pub(super) fn publish(&self) {
        let shut = self
            .parent_end_shut
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        PARENT_END_SHUT.with(|c| c.set(shut));
    }
}

/// See [`HelperSeams::open_on_drop`].
#[must_use = "dropping this opens the gate at once"]
pub(super) struct OpenOnDrop {
    verdict: Option<Gate>,
    probe: Option<HelperProbe>,
}

/// Whether an [`OpenOnDrop`] is live on this thread.
pub(crate) fn verdict_guarded() -> bool {
    VERDICT_GUARDED.with(Cell::get)
}

impl Drop for OpenOnDrop {
    fn drop(&mut self) {
        VERDICT_GUARDED.with(|g| g.set(false));
        if let Some(gate) = &self.verdict {
            gate.open();
        }
        if let Some(probe) = self.probe.as_ref().filter(|_| std::thread::panicking()) {
            probe.release();
        }
    }
}

/// Holds the helper at its very end until the spawning thread reaches its join, then records
/// that it finished. A helper nobody joins is still held, and never finishes.
#[derive(Clone)]
pub(crate) struct HelperProbe {
    gate: Gate,
    finished: Arc<AtomicBool>,
}

impl HelperProbe {
    fn wait_gate_then_finish(&self) {
        self.gate.wait();
        self.finished.store(true, Ordering::Release);
    }

    fn release(&self) {
        self.gate.open();
    }

    /// Whether the helper thread has run to its end.
    pub(crate) fn finished(&self) -> bool {
        self.finished.load(Ordering::Acquire)
    }
}

/// Arms a probe for the NEXT spawn's helper.
pub(crate) fn arm_helper_probe() -> HelperProbe {
    let probe = HelperProbe {
        gate: Gate::default(),
        finished: Arc::new(AtomicBool::new(false)),
    };
    PROBE.with(|p| *p.borrow_mut() = Some(probe.clone()));
    probe
}