cosca 0.9.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
//! macOS: the child reports its own unique id before `exec`.
//!
//! macOS has no pidfd, so nothing pins a pid. A parent that read a fresh child's unique id by pid
//! after `spawn()` would race a foreign reap and a reuse of the number: it would take a stranger's
//! id for the child's. So the child reads `proc_pidinfo(getpid(), PROC_PIDUNIQIDENTIFIERINFO)`
//! itself, in a `pre_exec` hook, and writes the answer to a pipe the parent reads after `spawn()`.
//!
//! The hook is async-signal-safe: it reads atomics, makes one `proc_pidinfo` call (a direct
//! `__proc_info` syscall) and one `write` of at most `PIPE_BUF` bytes, which is atomic. The pipe is
//! made on the shared [`fd_channel`](super::fd_channel) skeleton, and the hook is registered
//! before every other so `fd_map`'s `dup2` onto its number cannot come first.
//!
//! A refused read is reported, then the hook fails: `exec` never runs, the spawn is an `Err`, and
//! std collects the child. Two things make the spawn `Ok` with the same report, and the same refusal:
//! a signal that kills the child between the report and std's own errno write, and an exposed std
//! error pipe (below), whose errno write goes nowhere the parent sees. [`Report::ChildRefused`] on an
//! `Ok` spawn is then a corpse, which `adopted_id` maps to `DiedBeforeExec` and nothing collects.
//!
//! `spawn()` returning `Ok` does not mean the child execed: std reads EOF on its own close-on-exec
//! pipe both after a successful `exec` and after a child killed by a signal before it. So the
//! report may be missing on `Ok`, and [`Report::Missing`] says so.
//!
//! Nor does it mean the child has reported yet. With two of this process's fds 0 to 2 closed, std's
//! close-on-exec pipe takes one of the child's stdio numbers, so std returns before the child's
//! hooks run, and a failed `exec` is
//! invisible to it. [`Channel::run`] checks for that condition before the spawn, and every id from
//! such a spawn is [`Report::Late`], whether or not it beat the parent's first read: the program may
//! have started and std's own spawn is not trusted, so the spawn tears the child down through its
//! unique id. The report hook is registered first, so the child either writes its report or dies
//! without one: when the first read finds the pipe empty but open after an `Ok` spawn,
//! [`FirstRead::finish`] watches the pipe and the child until one of the two happens (see
//! [`await_report`] for why the pipe's EOF is not enough). An id that came only then is late too. A
//! failed spawn leaves no child to wait on, so its pipe is read once.

use std::io;
use std::os::fd::{AsRawFd, OwnedFd};
use std::sync::Arc;

use super::fd_channel::{self, publish_ends, Shared};
use super::SpawnLockGuard;
use crate::error::Error;

/// A report's tag: the value is the child's unique id.
const REPORT_ID: u32 = 1;
/// A report's tag: the child's own read failed; the value is its errno.
const REPORT_ERRNO: u32 = 2;
/// A report is a native-endian `u32` tag, then a native-endian `u64` value. At most `PIPE_BUF`,
/// so its `write` is atomic.
const REPORT_LEN: usize = 12;

/// What the parent found in the pipe.
#[derive(Debug)]
pub(crate) enum Report {
    /// The child's own unique id.
    Id(u64),
    /// The child's own read was refused with this errno; its hook then failed before `exec`.
    ChildRefused(i32),
    /// No report, or a short one, and either every copy of the write end closed or the child is gone:
    /// the child died before it could write it (before `exec`).
    Missing,
    /// The child's own unique id, from a spawn that may have returned before the child reported (see
    /// the module doc).
    Late(u64),
    /// No report yet, and the pipe still open. [`FirstRead::finish`] waits it out for a spawn that
    /// returned `Ok`, so only a failed spawn's caller sees it.
    Unwritten,
    /// This process's own read of the pipe failed.
    ReadFailed(io::Error),
    /// The wait for the report failed.
    WaitFailed(io::Error),
    /// A tag no hook writes.
    BadTag(u32),
}

/// The hook is registered; the pipe is not yet made. See [`register`].
pub(crate) struct Pending {
    shared: Arc<Shared>,
}

/// The pipe to one child. Consumed by [`run`](Self::run).
pub(crate) struct Channel {
    read_end: OwnedFd,
    write_end: OwnedFd,
    shared: Arc<Shared>,
}

/// Registers the reporting hook on `cmd`, before any other hook.
pub(crate) fn register(cmd: &mut std::process::Command) -> Pending {
    // Thread-locals are not visible in the forked child, so capture the seam before the fork.
    #[cfg(test)]
    let seam = seams::armed();
    // SAFETY: the hook is async-signal-safe: it reads atomics and makes only direct syscalls
    // (`proc_pidinfo`, `write`, and in tests `kill`) on stack buffers. It allocates nothing, takes
    // no lock and never panics.
    let shared = unsafe {
        fd_channel::register(cmd, move |shared| {
            report(
                shared,
                #[cfg(test)]
                seam,
            )
        })
    };
    Pending { shared }
}

impl Pending {
    /// Makes the pipe and publishes its write end to the hook. `_lock` is the witness that no other
    /// cosca fork can inherit the ends before they are close-on-exec.
    pub(crate) fn open(self, _lock: &SpawnLockGuard) -> Result<Channel, Error> {
        let (read_end, write_end) = crate::pipe::pair().map_err(|e| Error::Io(crate::error::io_context("pipe", e)))?;
        let (write_end, read_end) = publish_ends(&self.shared, OwnedFd::from(write_end), OwnedFd::from(read_end))?;
        set_nonblocking(&read_end)?;
        Ok(Channel {
            read_end,
            write_end,
            shared: self.shared,
        })
    }
}

/// Non-blocking, so a stray copy of the write end (a foreign fork) cannot hang the read.
fn set_nonblocking(fd: &OwnedFd) -> Result<(), Error> {
    // SAFETY: `fcntl` on an fd this function borrows.
    let flags = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
    // SAFETY: as above.
    if flags < 0 || unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
        return Err(Error::Io(crate::error::io_context("fcntl", io::Error::last_os_error())));
    }
    Ok(())
}

impl Channel {
    /// Runs `spawn` with the pipe published, then reads what the child reported, once. The read
    /// comes with the spawn's result either way. `pid_of` names the child of a spawn that returned
    /// `Ok`. Runs under `spawn_lock`; the caller drops the guard before [`FirstRead::finish`], whose
    /// wait has no bound.
    pub(crate) fn run<T, E>(
        self,
        spawn: impl FnOnce() -> Result<T, E>,
        pid_of: impl FnOnce(&T) -> Option<u32>,
    ) -> (Result<T, E>, FirstRead) {
        let Channel {
            read_end,
            write_end,
            shared,
        } = self;
        let exposed = std_pipe_exposed();
        let spawned = spawn();
        shared.withdraw();
        // Closed before the read, so a child that never wrote leaves the pipe at EOF.
        drop(write_end);
        #[cfg(test)]
        seams::before_first_read(&read_end);
        let report = read_report(&read_end);
        let pid = spawned.as_ref().ok().and_then(|child| {
            let pid = pid_of(child);
            debug_assert!(pid.is_some(), "a freshly spawned child has a pid");
            pid
        });
        #[cfg(test)]
        seams::first_read_done(pid);
        let first = FirstRead {
            read_end,
            report,
            pid,
            exposed,
        };
        (spawned, first)
    }
}

/// What [`Channel::run`] read, before any wait for the report.
pub(crate) struct FirstRead {
    read_end: OwnedFd,
    report: Report,
    /// The child of a spawn that returned `Ok`.
    pid: Option<u32>,
    /// Whether std's error pipe could take a stdio number of the child (see [`std_pipe_exposed`]).
    exposed: bool,
}

impl FirstRead {
    /// The report: the first read's, or, for a spawn that returned `Ok` with the pipe still empty,
    /// what [`await_report`] waits for. An id from a spawn whose std error pipe was exposed is
    /// [`Report::Late`]. May block without a bound, so `spawn_lock` must be released first. The wait's
    /// reads of the child's place and tracer ask `kernel`, the spawn's.
    pub(crate) fn finish(self, kernel: &dyn crate::identity::Kernel) -> Report {
        #[cfg(any(test, debug_assertions))]
        debug_assert!(
            !super::spawn_lock_held_by_this_thread(),
            "the wait for a unique-id report must not hold spawn_lock"
        );
        let FirstRead {
            read_end,
            report,
            pid,
            exposed,
        } = self;
        match (report, pid) {
            (Report::Unwritten, Some(pid)) => await_report(kernel, &read_end, pid),
            (Report::Id(id), Some(_)) if exposed => Report::Late(id),
            // A failed spawn leaves no child to wait on: std collected it, or tokio dropped it and
            // its pid with it. Its report came already or never comes, so the read stands.
            (report, _) => report,
        }
    }
}

/// Whether the pipe std's spawn opens to learn of a failed `exec` takes one of fds 0 to 2 for its
/// write end. The child replaces each of those with its own stdio before any hook runs, so std
/// returns before the report and cannot see whether the `exec` ran. std makes its own pipe on the
/// two lowest free fds (std 1.96 `sys/process/unix`: `pipe`). Read under `spawn_lock`, just before
/// the spawn.
///
/// Another thread can change fds 0 to 2 between this read and the spawn, and the check then answers
/// for a state that is gone, in both directions:
/// - A close exposes std's pipe unseen. An id the first read misses is still late, but one it finds
///   is adopted, though std could not see the `exec`.
/// - An open hides an exposure the check saw. std's pipe lands above stdio and std does see the
///   `exec`, but `true` was already answered: [`FirstRead::finish`] makes the id late, and the spawn
///   tears down a child that did `exec` and fails with an error that says its `exec` cannot be
///   confirmed.
///
/// Both are routed to #192, and closed for good when cosca makes its own error channel in place of
/// std's (the untangling's PXc), which never lands on a stdio number.
fn std_pipe_exposed() -> bool {
    // SAFETY: `F_GETFD` only reads a descriptor's flags, and fails only with `EBADF`.
    let free = (0..=2)
        .filter(|&fd| unsafe { libc::fcntl(fd, libc::F_GETFD) } == -1)
        .count();
    free >= 2
}

/// How long the wait runs before it says what it is waiting on. A test sets its own.
const SAY_WAITING_AFTER: std::time::Duration = std::time::Duration::from_secs(1);

/// Blocks until the report of child `pid` is in `read_end`, or the child is gone, then answers what
/// the pipe holds: [`Report::Late`] for an id (it arrived after the spawn returned), and
/// [`Report::Missing`] for nothing from a child that is gone, which never reached its report.
///
/// The pipe's EOF alone cannot end the wait. `std::io::pipe` on macOS is `pipe()`, then a separate
/// `FD_CLOEXEC`, so any process another thread starts in between (not only a fork that never execs)
/// inherits the write end and holds the EOF off for as long as it lives. So one kqueue watches the
/// pipe (`EVFILT_READ`) and the child (`EVFILT_PROC`, `NOTE_EXIT | NOTE_SIGNAL`), and [`check`] asks
/// after the child once the watch is registered and again on every wake. The child is gone when that
/// registration answers `ESRCH`, when `NOTE_EXIT` comes, or when the check finds it gone; the pipe
/// is then read once more.
///
/// A traced child's `NOTE_EXIT` reaches this process only at its tracer's hand-back, so a live
/// tracer that holds the child's zombie keeps the wait going; see
/// [`TracerWatch`](crate::wait::macos::TracerWatch) for how the wait watches the tracer chain.
///
/// Residual: a foreign reaper reaps the child and another child of ours takes its pid before the
/// registration; the wait then lasts as long as that process, unless the pipe hits EOF first.
///
/// Past one second it warns, once, naming what it waits for.
fn await_report(kernel: &dyn crate::identity::Kernel, read_end: &OwnedFd, pid: u32) -> Report {
    #[cfg(test)]
    if seams::wait_is_refused() {
        return Report::WaitFailed(io::Error::other("test seam: the wait for a report was entered"));
    }
    match watch(kernel, read_end, pid) {
        Ok(Watch::Pipe(report)) => {
            #[cfg(test)]
            seams::woke(seams::Wake::Pipe);
            report
        }
        Ok(Watch::ChildGone) => {
            #[cfg(test)]
            seams::woke(seams::Wake::ChildGone);
            // Whatever the child wrote is in the pipe by now.
            match read_report(read_end) {
                Report::Id(id) => Report::Late(id),
                Report::Unwritten => Report::Missing,
                report => report,
            }
        }
        Err(e) => Report::WaitFailed(e),
    }
}

/// What ended a [`watch`].
enum Watch {
    /// The pipe had something to read, or hit EOF: the report as read, an id as [`Report::Late`].
    Pipe(Report),
    /// The child is gone.
    ChildGone,
}

/// The kqueue wait of [`await_report`].
fn watch(kernel: &dyn crate::identity::Kernel, read_end: &OwnedFd, pid: u32) -> io::Result<Watch> {
    use crate::os_process::macos::kqueue::{Event, Kqueue, Subscription};
    use crate::wait::macos::{OnTracer, TracerWatch};
    use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent};

    let kq = Kqueue::new().map_err(Error::into_io)?;
    let pipe = Subscription::Readable {
        fd: read_end.as_raw_fd(),
        low_water: 1,
    };
    kq.subscribe(pipe).map_err(Error::into_io)?;
    // Registered before the first check, so a child that exits after it fires `NOTE_EXIT`, and one a
    // tracer attaches to fires `NOTE_SIGNAL`.
    let child = Subscription::Process {
        pid,
        signals: true,
        reap: false,
    };
    match kq.subscribe(child) {
        Ok(()) => {}
        Err(e) if crate::error::first_os_code(&e) == Some(libc::ESRCH) => return Ok(Watch::ChildGone),
        Err(e) => return Err(e.into_io()),
    }
    let mut tracer = TracerWatch::default();
    let blank = KEvent::new(0, EventFilter::EVFILT_READ, EvFlags::empty(), FilterFlag::empty(), 0, 0);
    // A batch: events past it stay pending for the next call.
    let mut events = [blank; 8];
    let started = std::time::Instant::now();
    // In a test, only one that opted in: a loaded runner
    // could pass a second, and no verdict may depend on elapsed time.
    #[cfg(not(test))]
    let say_after = Some(SAY_WAITING_AFTER);
    #[cfg(test)]
    let say_after = seams::say_waiting_after();
    let mut warned = false;
    loop {
        // Read before asking about the child: the report may have come since the last read.
        match read_report(read_end) {
            Report::Unwritten => {}
            Report::Id(id) => return Ok(Watch::Pipe(Report::Late(id))),
            report => return Ok(Watch::Pipe(report)),
        }
        let recheck = match check(kernel, pid)? {
            Check::Gone => return Ok(Watch::ChildGone),
            Check::Running => None,
            Check::Traced(by) => match tracer.held_by(kernel, &kq, by)? {
                OnTracer::Block => None,
                OnTracer::Recheck(after) if after.is_zero() => continue,
                OnTracer::Recheck(after) => Some(after),
            },
        };
        let warn_in = say_after
            .filter(|_| !warned)
            .map(|after| after.saturating_sub(started.elapsed()));
        let timeout = match (recheck, warn_in) {
            (Some(recheck), Some(warn_in)) => Some(recheck.min(warn_in)),
            (recheck, warn_in) => recheck.or(warn_in),
        };
        let timeout = timeout.map(crate::os_process::macos::kqueue::kevent_timeout);
        // Records every call, a warning due at once (zero) included, as `about_to_block` does for
        // every `kevent` that may block: a hook can end a wait that would otherwise spin on it.
        #[cfg(test)]
        kq.about_to_block(timeout);
        let n = match kq.native().kevent(&[], &mut events, timeout) {
            Ok(n) => n,
            Err(nix::errno::Errno::EINTR) => continue,
            Err(e) => return Err(e.into()),
        };
        if !warned && say_after.is_some_and(|after| started.elapsed() >= after) {
            warned = true;
            log::warn!(
                "the spawned child {pid} has not reported its unique id after 1 s; waiting for its report, or \
                 for it to exit"
            );
        }
        let woke: Vec<Event> = events[..n].iter().filter_map(Event::from_kevent).collect();
        if woke
            .iter()
            .any(|e| matches!(e, Event::Process { pid: p, exited: true, .. } if *p == pid))
        {
            return Ok(Watch::ChildGone);
        }
        // Any other wake (a signal to the child, a tracer's exit or signal, the pipe, a timer) reads
        // the pipe and checks the child again.
        for event in &woke {
            tracer.fired(event, pid);
        }
    }
}

/// What [`check`] found.
enum Check {
    /// A child of this process that has not exited.
    Running,
    /// This process's child, held by this tracer.
    Traced(u32),
    /// Exited, reaped, or not this process's child: no report is coming.
    Gone,
}

/// Where `pid` is, by a `waitid` that consumes nothing. An exit record is [`Check::Gone`].
///
/// `ECHILD` alone is not: while a tracer holds our child, its parent's `waitid` answers `ECHILD`
/// too. So the pid is asked who forked it and who holds it ([`origin`](crate::identity::origin)). A
/// process this one forked is [`Check::Traced`] by the process that holds it, unless that is
/// launchd: XNU gives launchd a child whose tracer exited while the child was exiting, so it is
/// gone. Any other answer means the child is gone. A read that is refused is an error.
fn check(kernel: &dyn crate::identity::Kernel, pid: u32) -> io::Result<Check> {
    use crate::identity::{origin, Origin, LAUNCHD};
    use crate::os_process::child::PeekOutcome;
    use crate::wait::exit_only::{peek, Target};
    Ok(match peek(&Target::pid(kernel, pid, None))? {
        PeekOutcome::Running => Check::Running,
        PeekOutcome::Exit(_) => Check::Gone,
        PeekOutcome::Foreign(_) => match origin(kernel, pid) {
            Origin::Ours { parent } if parent == LAUNCHD => Check::Gone,
            // A tracer detached between the two reads: the child is ours again, and its own
            // `NOTE_EXIT` reaches this process.
            Origin::Ours { parent } if parent == std::process::id() => Check::Running,
            Origin::Ours { parent } => Check::Traced(parent),
            Origin::NotOurs | Origin::Gone => Check::Gone,
            Origin::Refused(errno) => {
                return Err(crate::error::io_context(
                    format!("pid {pid}: whether it is this process's child could not be read"),
                    io::Error::from_raw_os_error(errno),
                ))
            }
            Origin::Unreadable => {
                return Err(io::Error::other(format!(
                    "pid {pid}: whether it is this process's child could not be read (kinfo_proc refused)"
                )))
            }
        },
    })
}

/// Reads one report from the non-blocking `read_end`.
fn read_report(read_end: &OwnedFd) -> Report {
    #[cfg(test)]
    if let Some(errno) = seams::parent_read_fails() {
        return Report::ReadFailed(io::Error::from_raw_os_error(errno));
    }
    #[cfg(test)]
    if seams::parent_read_finds_nothing() {
        return Report::Unwritten;
    }
    let mut buf = [0u8; REPORT_LEN];
    let mut got = 0;
    while got < REPORT_LEN {
        // SAFETY: the pointer and length name the unfilled tail of `buf`.
        let n = unsafe { libc::read(read_end.as_raw_fd(), buf[got..].as_mut_ptr().cast(), REPORT_LEN - got) };
        if n > 0 {
            got += n as usize;
        } else if n == 0 {
            return Report::Missing;
        } else {
            let e = io::Error::last_os_error();
            match e.raw_os_error() {
                Some(libc::EINTR) => {}
                Some(libc::EAGAIN) => return Report::Unwritten,
                _ => return Report::ReadFailed(e),
            }
        }
    }
    let tag = u32::from_ne_bytes(buf[..4].try_into().expect("four bytes"));
    let value = u64::from_ne_bytes(buf[4..].try_into().expect("eight bytes"));
    match tag {
        REPORT_ID => Report::Id(value),
        REPORT_ERRNO => Report::ChildRefused(value as i32),
        other => Report::BadTag(other),
    }
}

/// A child `spawn` returned `Ok` for that cannot be adopted.
#[derive(Debug)]
pub(crate) struct NotAdopted {
    pub(crate) error: Error,
    pub(crate) why: Unadoptable,
}

/// Why a child cannot be adopted, which decides what the spawn does with it and what it answers.
/// Only a [`Late`](Self::Late) child is signalled and waited on by pid, each act checked against its
/// id. Without a unique id nothing in cosca acts on a macOS pid, because nothing pins the number
/// against a foreign reap (`SIGCHLD` ignored, or a `waitpid(-1)` reaper) and its reuse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Unadoptable {
    /// It died before `exec`, so only a corpse is left, and the program did not start.
    DiedBeforeExec,
    /// Its unique id arrived only after its spawn returned ([`Report::Late`]). The program may have
    /// started, and std's own spawn is not trusted, so the child is torn down through this id.
    Late(u64),
    /// Its report could not be read or is malformed: it has no verified identity, so it cannot be
    /// signalled and is left with a warning (leak and warn), and the program may have started.
    Unverified,
}

/// The spawn's unique id, or why the child cannot be adopted, for a spawn that returned `Ok`.
pub(crate) fn adopted_id(report: Report, pid: u32) -> Result<u64, NotAdopted> {
    let not = |why, error| Err(NotAdopted { error, why });
    match report {
        Report::Id(id) => Ok(id),
        // The hook fails its spawn after reporting a refusal, so `Ok` is a child killed between its
        // report and std's own errno write, or one whose std error pipe was exposed: the same refusal,
        // with the program not started.
        Report::ChildRefused(errno) => not(Unadoptable::DiedBeforeExec, refused_error(errno)),
        Report::Missing => not(
            Unadoptable::DiedBeforeExec,
            Error::Io(io::Error::other(format!(
                "the spawned child {pid} died before exec; the program did not start"
            ))),
        ),
        Report::Late(id) => not(
            Unadoptable::Late(id),
            Error::Io(io::Error::other(format!(
                "the spawned child {pid}'s exec cannot be confirmed: at least two of this process's descriptors 0 to 2 \
                 were closed at its spawn, so std's own error pipe could not show it; the child was not adopted"
            ))),
        ),
        Report::Unwritten => {
            debug_assert!(false, "`FirstRead::finish` waits out an unwritten report");
            not(
                Unadoptable::Unverified,
                Error::Unassessable {
                    detail: format!("pid {pid}: its unique-id report is still unwritten; the child was not adopted"),
                    source: None,
                },
            )
        }
        Report::ReadFailed(e) => not(
            Unadoptable::Unverified,
            Error::Unassessable {
                detail: format!("pid {pid}: its unique-id report could not be read; the child was not adopted"),
                source: Some(Error::io_cause(e)),
            },
        ),
        Report::WaitFailed(e) => not(
            Unadoptable::Unverified,
            Error::Unassessable {
                detail: format!("pid {pid}: the wait for its unique-id report failed; the child was not adopted"),
                source: Some(Error::io_cause(e)),
            },
        ),
        Report::BadTag(tag) => {
            debug_assert!(false, "a unique-id report with tag {tag}");
            not(
                Unadoptable::Unverified,
                Error::Unassessable {
                    detail: format!(
                        "pid {pid}: its unique-id report is malformed (tag {tag}); the child was not adopted"
                    ),
                    source: None,
                },
            )
        }
    }
}

/// The error for a failed spawn: only the child's own refusal changes it, because only then did the
/// hook fail the spawn. Any other report state keeps std's error, and is logged: a failed read of the
/// report, or wait for it, at warn, since std's `Io` has no slot for it; the rest at debug.
pub(crate) fn failed_spawn_error(error: Error, report: &Report) -> Error {
    match report {
        Report::ChildRefused(errno) => refused_error(*errno),
        Report::ReadFailed(failure) => warn_beside_the_spawn(error, "the read of", failure),
        Report::WaitFailed(failure) => warn_beside_the_spawn(error, "the wait for", failure),
        other => {
            debug_assert!(
                !matches!(other, Report::BadTag(_)),
                "a unique-id report is malformed: {other:?}"
            );
            log::debug!(
                "the spawn failed ({report}); the child's unique-id report was {other:?}",
                report = crate::error::Report(&error)
            );
            error
        }
    }
}

/// Logs at warn that the spawn failed with `spawn` and that `step`, with the child's unique-id
/// report as its object ("the read of", "the wait for"), failed with `failure` too, and answers
/// `spawn`: std's `Io` has no slot for `failure`.
fn warn_beside_the_spawn(spawn: Error, step: &str, failure: &io::Error) -> Error {
    log::warn!(
        "the spawn failed ({report}), and so did {step} the child's unique-id report: {failure}",
        report = crate::error::Report(&spawn),
        failure = crate::error::Report(failure)
    );
    spawn
}

/// The error for a child that could not read its own unique id (`errno`). It is a refusal, not a
/// vanish.
pub(crate) fn refused_error(errno: i32) -> Error {
    Error::Unassessable {
        detail: "the spawned child could not read its own unique id; it was stopped before exec, so the program did not start"
            .into(),
        source: Some(Error::io_cause(io::Error::from_raw_os_error(errno))),
    }
}

/// The hook: the child reads its own unique id and writes the report. Async-signal-safe.
fn report(shared: &Shared, #[cfg(test)] seam: seams::Armed) -> io::Result<()> {
    #[cfg(test)]
    seam.await_gate();
    #[cfg(test)]
    if let Some(errno) = seam.fail_before_report() {
        return Err(io::Error::from_raw_os_error(errno));
    }
    #[cfg(test)]
    let read = seam.read(shared.child_end());
    #[cfg(not(test))]
    let read = crate::identity::own_unique_id();
    let (tag, value) = match read {
        Ok(id) => (REPORT_ID, id),
        Err(errno) => (REPORT_ERRNO, errno as u64),
    };
    let mut buf = [0u8; REPORT_LEN];
    buf[..4].copy_from_slice(&tag.to_ne_bytes());
    buf[4..].copy_from_slice(&value.to_ne_bytes());
    loop {
        // SAFETY: `buf` is valid for `REPORT_LEN` bytes.
        let n = unsafe { libc::write(shared.child_end(), buf.as_ptr().cast(), REPORT_LEN) };
        if n == REPORT_LEN as isize {
            #[cfg(test)]
            seam.await_after_gate();
            return match tag {
                REPORT_ERRNO => Err(io::Error::from_raw_os_error(value as i32)),
                _ => Ok(()),
            };
        }
        if n < 0 {
            let e = io::Error::last_os_error();
            if e.raw_os_error() == Some(libc::EINTR) {
                continue;
            }
            return Err(e);
        }
        // A short or empty write of a message under `PIPE_BUF` breaks the pipe's contract.
        return Err(io::Error::from_raw_os_error(libc::EIO));
    }
}

/// Test seams. Thread-local, armed on the thread that spawns, captured at [`register`].
#[cfg(test)]
pub(crate) mod seams {
    use std::cell::Cell;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum Force {
        None,
        /// The child's own read fails with this errno.
        Errno(i32),
        /// The child is killed by `SIGKILL` before it reports.
        KillSelf,
        /// The hook fails with this errno before it reports.
        FailBeforeReport(i32),
        /// The hook reads one byte from this fd before it reports.
        Gate(std::os::fd::RawFd),
    }

    /// A gate the hook blocks on: the test holds both ends, and a byte written releases the child.
    struct Gate {
        read: std::io::PipeReader,
        write: std::io::PipeWriter,
        /// Released by the parent's first read of the report, rather than by the test.
        at_first_read: bool,
    }

    impl Gate {
        fn new(at_first_read: bool) -> Gate {
            let (read, write) = std::io::pipe().expect("the gate pipe");
            Gate {
                read,
                write,
                at_first_read,
            }
        }

        fn release(mut self) {
            use std::io::Write;
            self.write.write_all(b"r").expect("release the held child");
        }
    }

    /// What [`on_first_read`] runs: the child's pid.
    type FirstReadHook = Box<dyn FnOnce(u32)>;

    thread_local! {
        static FORCE: Cell<Force> = const { Cell::new(Force::None) };
        static PARENT_READ_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
        static PARENT_READ_UNWRITTEN: Cell<bool> = const { Cell::new(false) };
        static WAIT_REFUSED: Cell<bool> = const { Cell::new(false) };
        static GATE: std::cell::RefCell<Option<Gate>> = const { std::cell::RefCell::new(None) };
        static AFTER_GATE: std::cell::RefCell<Option<Gate>> = const { std::cell::RefCell::new(None) };
        static ON_FIRST_READ: std::cell::RefCell<Option<FirstReadHook>> = const { std::cell::RefCell::new(None) };
        static WAKE: Cell<Option<Wake>> = const { Cell::new(None) };
    }

    /// What a hook registered on this thread was armed with: the force, and the read end of the
    /// gate it blocks on after its report.
    #[derive(Debug, Clone, Copy)]
    pub(super) struct Armed(Force, Option<std::os::fd::RawFd>);

    /// Blocks until a byte can be read from `fd`, or it is at end of file. Async-signal-safe: `read`
    /// into a stack byte.
    fn await_byte(fd: std::os::fd::RawFd) {
        let mut byte = 0u8;
        loop {
            // SAFETY: one byte into a stack variable.
            let n = unsafe { libc::read(fd, (&raw mut byte).cast(), 1) };
            // SAFETY: `__error` is this thread's errno location.
            if n < 0 && unsafe { *libc::__error() } == libc::EINTR {
                continue;
            }
            return;
        }
    }

    impl Armed {
        /// The child's read, as the seam shapes it. Async-signal-safe.
        pub(super) fn fail_before_report(self) -> Option<i32> {
            match self.0 {
                Force::FailBeforeReport(errno) => Some(errno),
                _ => None,
            }
        }

        /// Blocks before the report until its gate is released, if the seam says so.
        /// Async-signal-safe.
        pub(super) fn await_gate(self) {
            if let Force::Gate(fd) = self.0 {
                await_byte(fd);
            }
        }

        /// Blocks after the report until its gate is released, if the seam says so.
        /// Async-signal-safe.
        pub(super) fn await_after_gate(self) {
            if let Some(fd) = self.1 {
                await_byte(fd);
            }
        }

        /// `child_end` is the report pipe's write end.
        pub(super) fn read(self, child_end: std::os::fd::RawFd) -> Result<u64, i32> {
            match self.0 {
                Force::None | Force::FailBeforeReport(_) | Force::Gate(_) => crate::identity::own_unique_id(),
                Force::Errno(errno) => Err(errno),
                Force::KillSelf => {
                    // The write end is closed first: the kernel closes a dying process's descriptors
                    // one by one, so std's own pipe could read EOF, and the spawn read the report,
                    // while this one is still open. The parent then sees `Unwritten`, a child that
                    // may yet run, where a test of this seam asks for one that died.
                    // SAFETY: `close`, `kill` and `getpid` are async-signal-safe; the child dies here.
                    unsafe {
                        libc::close(child_end);
                        libc::kill(libc::getpid(), libc::SIGKILL);
                    }
                    Err(libc::EINTR)
                }
            }
        }
    }

    pub(super) fn armed() -> Armed {
        use std::os::fd::AsRawFd;
        let after = AFTER_GATE.with(|g| g.borrow().as_ref().map(|gate| gate.read.as_raw_fd()));
        Armed(FORCE.with(Cell::get), after)
    }

    /// Disarms the force when dropped.
    #[must_use = "dropping this immediately disarms the force; bind it for the probe's duration"]
    pub(crate) struct Forced(());

    impl Drop for Forced {
        fn drop(&mut self) {
            FORCE.with(|f| f.set(Force::None));
        }
    }

    /// The next spawns on this thread have their child's own read fail with `errno`.
    pub(crate) fn force_child_read_errno(errno: i32) -> Forced {
        FORCE.with(|f| f.set(Force::Errno(errno)));
        Forced(())
    }

    /// The next spawns on this thread have their hook fail with `errno` before it reports, as any
    /// failure ahead of it (or std's own `chdir`) fails a spawn with no report written.
    pub(crate) fn force_hook_failure_before_report(errno: i32) -> Forced {
        FORCE.with(|f| f.set(Force::FailBeforeReport(errno)));
        Forced(())
    }

    /// While the guard lives, this thread's own read of a spawn's report fails with `errno`, after
    /// the child ran as it would: the parent cannot tell what the child is doing.
    pub(crate) fn fail_parent_read(errno: i32) -> FailedParentRead {
        PARENT_READ_ERRNO.with(|f| f.set(Some(errno)));
        FailedParentRead(())
    }

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

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

    pub(super) fn parent_read_fails() -> Option<i32> {
        PARENT_READ_ERRNO.with(Cell::get)
    }

    /// This thread's next read of a spawn's report finds it not yet written, as when std's spawn
    /// returned before the child's hooks ran: the child runs on as it would, and the wait that
    /// follows reads the real pipe.
    pub(crate) fn find_the_report_unwritten() -> UnwrittenRead {
        PARENT_READ_UNWRITTEN.with(|f| f.set(true));
        UnwrittenRead(())
    }

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

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

    /// Whether the next read finds nothing; take-once, so the wait that follows reads the real pipe.
    pub(super) fn parent_read_finds_nothing() -> bool {
        PARENT_READ_UNWRITTEN.with(|f| f.replace(false))
    }

    /// While the guard lives, the wait for a report on this thread answers `WaitFailed` at once, so a
    /// test sees by assertion that the wait was entered.
    pub(crate) fn refuse_the_wait() -> RefusedWait {
        WAIT_REFUSED.with(|f| f.set(true));
        RefusedWait(())
    }

    #[must_use = "the wait runs again as soon as the guard is dropped"]
    pub(crate) struct RefusedWait(());

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

    pub(super) fn wait_is_refused() -> bool {
        WAIT_REFUSED.with(Cell::get)
    }

    /// While the guard lives, the next spawn's child on this thread writes its report only after the
    /// parent's first read of it has returned, so the report is late whenever std returned before
    /// the child's hooks ran.
    pub(crate) fn hold_the_report_until_the_first_read() -> HeldReport {
        hold(Gate::new(true))
    }

    /// While the guard lives, the next spawn's child on this thread writes its report only once
    /// [`release_the_report`] is called.
    pub(crate) fn hold_the_report() -> HeldReport {
        hold(Gate::new(false))
    }

    fn hold(gate: Gate) -> HeldReport {
        use std::os::fd::AsRawFd;
        FORCE.with(|f| f.set(Force::Gate(gate.read.as_raw_fd())));
        GATE.with(|g| *g.borrow_mut() = Some(gate));
        HeldReport(())
    }

    /// Lets the child [`hold_the_report`] holds write its report.
    pub(crate) fn release_the_report() {
        GATE.with(|g| g.borrow_mut().take())
            .expect("a held report to release")
            .release();
    }

    /// While the guard lives, the next spawn's child on this thread stops right after its report,
    /// before any later hook, until [`release_the_child_after_its_report`] is called.
    pub(crate) fn hold_the_child_after_its_report() -> HeldAfterReport {
        AFTER_GATE.with(|g| *g.borrow_mut() = Some(Gate::new(false)));
        HeldAfterReport(())
    }

    #[must_use = "the child is held only while the guard lives"]
    pub(crate) struct HeldAfterReport(());

    impl Drop for HeldAfterReport {
        fn drop(&mut self) {
            AFTER_GATE.with(|g| g.borrow_mut().take());
        }
    }

    /// Lets the child [`hold_the_child_after_its_report`] holds run on.
    pub(crate) fn release_the_child_after_its_report() {
        AFTER_GATE
            .with(|g| g.borrow_mut().take())
            .expect("a child held after its report")
            .release();
    }

    #[must_use = "the report is held only while the guard lives"]
    pub(crate) struct HeldReport(());

    impl Drop for HeldReport {
        fn drop(&mut self) {
            FORCE.with(|f| f.set(Force::None));
            GATE.with(|g| g.borrow_mut().take());
        }
    }

    /// The parent's first read of a report has returned: lets a child held until then write it,
    /// and runs the hook [`on_first_read`] armed.
    pub(super) fn first_read_done(pid: Option<u32>) {
        let gate = GATE.with(|g| {
            let mut g = g.borrow_mut();
            if g.as_ref().is_some_and(|gate| gate.at_first_read) {
                g.take()
            } else {
                None
            }
        });
        if let Some(gate) = gate {
            gate.release();
        }
        let hook = ON_FIRST_READ.with(|h| h.borrow_mut().take());
        if let (Some(hook), Some(pid)) = (hook, pid) {
            hook(pid);
        }
    }

    /// Runs `hook` once with the child's pid, when the parent's first read of the report of a spawn
    /// that returned `Ok` on this thread has returned, before any wait for it.
    pub(crate) fn on_first_read(hook: impl FnOnce(u32) + 'static) -> FirstRead {
        ON_FIRST_READ.with(|h| {
            let previous = h.borrow_mut().replace(Box::new(hook));
            debug_assert!(previous.is_none(), "a first-read hook is already armed");
        });
        FirstRead(())
    }

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

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

    /// What ended the last wait for a report on this thread.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Wake {
        /// The pipe had something to read, or hit EOF.
        Pipe,
        /// The child was gone.
        ChildGone,
    }

    pub(super) fn woke(wake: Wake) {
        WAKE.with(|w| w.set(Some(wake)));
    }

    /// What ended the last wait for a report on this thread, taken.
    pub(crate) fn take_wake() -> Option<Wake> {
        WAKE.with(Cell::take)
    }

    /// The next spawns on this thread have their child killed by `SIGKILL` before it reports, as
    /// any child may be killed by a signal.
    pub(crate) fn force_child_killed_before_report() -> Forced {
        FORCE.with(|f| f.set(Force::KillSelf));
        Forced(())
    }

    thread_local! {
        static REPORT_FIRST: Cell<bool> = const { Cell::new(false) };
        static SAY_AFTER: Cell<Option<std::time::Duration>> = const { Cell::new(None) };
    }

    /// While the guard lives, the parent's first read of a spawn's report on this thread waits until
    /// the pipe has something to read or is at EOF: the report comes before that read, however early
    /// std returned.
    pub(crate) fn let_the_report_come_first() -> ReportFirst {
        REPORT_FIRST.with(|f| f.set(true));
        ReportFirst(())
    }

    #[must_use = "the first read no longer waits once the guard is dropped"]
    pub(crate) struct ReportFirst(());

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

    pub(super) fn before_first_read(read_end: &std::os::fd::OwnedFd) {
        if !REPORT_FIRST.with(Cell::get) {
            return;
        }
        let mut fds = [rustix::event::PollFd::new(read_end, rustix::event::PollFlags::IN)];
        crate::wait::poll_ready(&mut fds).expect("poll the report pipe");
    }

    /// While the guard lives, a wait for a report on this thread warns after `after`. Without the
    /// guard a wait in a test never warns.
    pub(crate) fn warn_after(after: std::time::Duration) -> SayAfter {
        SAY_AFTER.with(|s| s.set(Some(after)));
        SayAfter(())
    }

    #[must_use = "the wait stops warning as soon as the guard is dropped"]
    pub(crate) struct SayAfter(());

    impl Drop for SayAfter {
        fn drop(&mut self) {
            SAY_AFTER.with(|s| s.set(None));
        }
    }

    /// The threshold [`warn_after`] set on this thread, if any.
    pub(super) fn say_waiting_after() -> Option<std::time::Duration> {
        SAY_AFTER.with(Cell::get)
    }
}

#[cfg(test)]
#[path = "unique_report_tests.rs"]
mod unique_report_tests;