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
use std::os::fd::{AsRawFd, OwnedFd};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;

use crate::test_child::Console;

use super::{
    adopted_id, await_report, failed_spawn_error, read_report, register, seams, set_nonblocking, Report, Unadoptable,
};
use crate::error::Error;
use crate::identity::kinfo::kinfo_proc;
use crate::identity::{FakeKernel, HostKernel};
use crate::test_child::blocker;
use crate::wait::block_probe::{self, on_blocking, on_each_block};

/// A non-blocking pipe, as the parent's read end is.
fn pipe() -> (OwnedFd, std::io::PipeWriter) {
    let (r, w) = std::io::pipe().expect("pipe");
    let r = OwnedFd::from(r);
    set_nonblocking(&r).expect("non-blocking");
    (r, w)
}

fn report_bytes(tag: u32, value: u64) -> Vec<u8> {
    let mut bytes = tag.to_ne_bytes().to_vec();
    bytes.extend_from_slice(&value.to_ne_bytes());
    bytes
}

/// Mutant: `read_report` takes the value for the wrong field.
#[skuld::test]
fn a_report_with_an_id_reads_as_the_id() {
    use std::io::Write;
    let (r, mut w) = pipe();
    w.write_all(&report_bytes(1, 0xfeed_beef_1234)).unwrap();
    assert!(matches!(read_report(&r), Report::Id(0xfeed_beef_1234)));
}

/// Mutant: the errno tag reads as an id.
#[skuld::test]
fn a_report_with_an_errno_reads_as_the_childs_refusal() {
    use std::io::Write;
    let (r, mut w) = pipe();
    w.write_all(&report_bytes(2, libc::EPERM as u64)).unwrap();
    assert!(matches!(read_report(&r), Report::ChildRefused(e) if e == libc::EPERM));
}

/// A child killed mid-write leaves a few bytes and EOF. Mutant: a short read is taken as an id.
#[skuld::test]
fn a_short_report_then_eof_is_missing() {
    use std::io::Write;
    let (r, mut w) = pipe();
    w.write_all(&report_bytes(1, 7)[..5]).unwrap();
    drop(w);
    assert!(matches!(read_report(&r), Report::Missing));
}

/// A child killed before it wrote leaves an empty pipe, at EOF once the write end closes. Mutant:
/// EOF is a fabricated errno.
#[skuld::test]
fn an_empty_pipe_at_eof_is_missing() {
    let (r, w) = pipe();
    drop(w);
    assert!(matches!(read_report(&r), Report::Missing));
}

/// The channel's read end is non-blocking, so a stray copy of the write end (a foreign fork) cannot
/// hang the read: an open, empty pipe reads as `Unwritten`.
///
/// Mutant: `open` does not call `set_nonblocking` (the read would block).
#[skuld::test]
fn the_channels_read_end_is_non_blocking() {
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let pending = register(&mut cmd);
    let guard = crate::child::spawn::spawn_lock();
    let channel = pending.open(&guard).expect("open");
    // SAFETY: `fcntl` on an fd the channel owns.
    let flags = unsafe { libc::fcntl(channel.read_end.as_raw_fd(), libc::F_GETFL) };
    assert_ne!(flags & libc::O_NONBLOCK, 0, "the read end must be non-blocking");
    assert!(matches!(read_report(&channel.read_end), Report::Unwritten));
}

/// An open, empty pipe is not a child that died: it may not have written yet.
///
/// Mutant: an open, empty pipe reads as `Missing`.
#[skuld::test]
fn an_open_empty_pipe_is_unwritten_not_missing() {
    let (r, _w) = pipe();
    set_nonblocking(&r).expect("non-blocking");
    assert!(matches!(read_report(&r), Report::Unwritten));
}

/// Mutant: an unknown tag reads as an id.
#[skuld::test]
fn an_unknown_tag_is_a_bad_tag() {
    use std::io::Write;
    let (r, mut w) = pipe();
    w.write_all(&report_bytes(99, 0)).unwrap();
    assert!(matches!(read_report(&r), Report::BadTag(99)));
}

/// Mutant: a missing report keeps a fabricated errno, or is described as running, or as a program
/// that may have started.
#[skuld::test]
fn a_missing_report_is_a_child_that_died_before_exec() {
    let not_adopted = adopted_id(Report::Missing, 4242).expect_err("no id");
    assert_eq!(not_adopted.why, Unadoptable::DiedBeforeExec);
    let Error::Io(e) = not_adopted.error else {
        panic!("a missing report is an io error, not an Unassessable refusal")
    };
    assert!(e.to_string().contains("died before exec"), "{e}");
    assert_eq!(e.raw_os_error(), None, "no errno is made up");
}

/// A refusal under `Ok` is a child killed between its report and std's own pipe: the hook failed
/// the spawn, so the program did not start.
///
/// Mutant: it is reported as a child that may have started.
#[skuld::test]
fn a_refusal_under_an_ok_spawn_means_the_program_did_not_start() {
    let not_adopted = adopted_id(Report::ChildRefused(libc::EPERM), 9).expect_err("no id");
    assert_eq!(not_adopted.why, Unadoptable::DiedBeforeExec);
    assert_eq!(
        crate::error::first_os_code(&not_adopted.error),
        Some(libc::EPERM),
        "the errno is the source"
    );
    let Error::Unassessable { detail, .. } = not_adopted.error else {
        panic!("a refusal is Unassessable")
    };
    assert!(detail.contains("did not start"), "{detail}");
    assert!(
        !detail.contains("errno"),
        "the cause is the source, not the detail: {detail}"
    );
}

/// Mutant: the parent's own read failure is taken for the child's refusal, or for a program that did
/// not start.
///
/// Mutant: the failure's text is the detail's too, so the chain says it twice.
#[skuld::test]
fn a_failed_read_is_unassessable_with_its_error_and_not_a_corpse() {
    for failed in [
        Report::ReadFailed(std::io::Error::from_raw_os_error(libc::EIO)),
        Report::WaitFailed(std::io::Error::from_raw_os_error(libc::EIO)),
    ] {
        let not_adopted = adopted_id(failed, 7).expect_err("no id");
        assert_eq!(not_adopted.why, Unadoptable::Unverified);
        assert_eq!(crate::error::first_os_code(&not_adopted.error), Some(libc::EIO));
        let Error::Unassessable { detail, source } = not_adopted.error else {
            panic!("a failed read is Unassessable")
        };
        assert!(source.is_some());
        let os_text = std::io::Error::from_raw_os_error(libc::EIO).to_string();
        assert!(
            !detail.contains(&os_text),
            "the cause is the source, not the detail: {detail}"
        );
    }
}

/// A report that came after the spawn returned does not show the child died: it ran its hook, and
/// may have run the program, so it is not taken for a corpse. Its id is kept, to tear it down by.
///
/// Mutant: it is taken for a child that died before `exec`, or its id is dropped.
#[skuld::test]
fn a_late_report_may_have_started_and_keeps_its_id() {
    let not_adopted = adopted_id(Report::Late(77), 31).expect_err("not adopted");
    assert_eq!(not_adopted.why, Unadoptable::Late(77));
    let error = not_adopted.error;
    let said = crate::error::said(&error);
    assert!(
        !said.contains("died before exec"),
        "a late child is not a corpse: {said}"
    );
    assert!(said.contains("exec cannot be confirmed"), "{said}");
    assert!(said.contains("at least two of"), "{said}");
    assert!(
        matches!(error, Error::Io(ref e) if e.raw_os_error().is_none()),
        "{error:?}"
    );
}

/// Only the child's own refusal changes a failed spawn's error.
///
/// Mutant: any report state maps to the refusal.
#[skuld::test]
fn only_a_childs_refusal_changes_a_failed_spawns_error() {
    let original = || Error::Io(std::io::Error::from_raw_os_error(libc::ENOENT));
    for report in [
        Report::Missing,
        Report::ReadFailed(std::io::Error::from_raw_os_error(libc::EIO)),
        Report::Id(1),
    ] {
        let kept = failed_spawn_error(original(), &report);
        assert!(
            matches!(&kept, Error::Io(e) if e.raw_os_error() == Some(libc::ENOENT)),
            "{report:?}: {kept:?}"
        );
    }
    assert!(matches!(
        failed_spawn_error(original(), &Report::ChildRefused(libc::EPERM)),
        Error::Unassessable { .. }
    ));
}

/// A failed read of the report, or wait for it, beside a failed spawn: std's `Io` answers, and the
/// failure, which it has no slot for, is warned of once.
///
/// Mutant: the failure is only logged at debug, or the answer is replaced.
#[skuld::test]
fn a_failed_report_read_or_wait_beside_a_failed_spawn_is_warned_of_and_stds_error_answers() {
    crate::log_capture::install();
    for (report, step) in [
        (
            Report::ReadFailed(std::io::Error::other("report failure 4a2d")),
            "the read of",
        ),
        (
            Report::WaitFailed(std::io::Error::other("report failure 4a2d")),
            "the wait for",
        ),
    ] {
        let mark = crate::log_capture::mark();
        let kept = failed_spawn_error(Error::Io(std::io::Error::from_raw_os_error(libc::ENOENT)), &report);
        assert!(
            matches!(&kept, Error::Io(e) if e.raw_os_error() == Some(libc::ENOENT)),
            "{report:?}: {kept:?}"
        );
        let warns = crate::log_capture::warns_since(mark, "report failure 4a2d");
        assert_eq!(
            warns,
            [format!(
                "the spawn failed ({}), and so did {step} the child's unique-id report: report failure 4a2d",
                crate::error::said(&kept)
            )],
            "{report:?}"
        );
    }
}

/// Runs `cmd` through a channel, as a spawn does.
fn run_through_channel(cmd: &mut std::process::Command) -> (std::io::Result<std::process::Child>, Report) {
    let pending = register(cmd);
    let guard = crate::child::spawn::spawn_lock();
    let channel = pending.open(&guard).expect("open");
    #[allow(clippy::disallowed_methods, reason = "spawn_lock is held by `guard`")]
    let (spawned, first) = channel.run(|| cmd.spawn(), |c| Some(c.id()));
    drop(guard);
    (spawned, first.finish(&HostKernel))
}

/// A program that cannot be exec'd fails the spawn after the hook reported an id: std's own error
/// stays, and it is not an `Unassessable` refusal.
///
/// Mutant: a failed spawn with an id report is mapped to the refusal.
#[skuld::test]
fn a_nonexistent_program_fails_with_stds_io_error() {
    let mut cmd = std::process::Command::new("/nonexistent/cosca-no-such-program");
    let (spawned, report) = run_through_channel(&mut cmd);
    let io_error = spawned.expect_err("exec fails");
    assert!(matches!(report, Report::Id(_)), "{report:?}");
    let mapped = failed_spawn_error(Error::Io(io_error), &report);
    assert!(matches!(mapped, Error::Io(_)), "{mapped:?}");
}

/// The id a child reports is the one `proc_pidinfo` gives for it from outside.
///
/// Mutant: `own_unique_id` reads another flavor or another pid.
#[skuld::test]
fn own_unique_id_is_the_unique_id_of_this_process() {
    use crate::identity::{HostKernel, Kernel as _, UniqRead};
    let own = crate::identity::own_unique_id().expect("own id");
    let UniqRead::Found(by_pid) = HostKernel.unique_info(std::process::id()) else {
        panic!("this process has a unique id")
    };
    assert_eq!(own, by_pid.unique_id);
}

/// A child killed by a signal before it reports: `spawn()` is `Ok`, the report is `Missing`.
///
/// Mutant: a missing report on `Ok` is read as an errno.
#[skuld::test]
fn a_child_killed_before_its_report_is_missing_on_ok() {
    let _forced = seams::force_child_killed_before_report();
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let (spawned, report) = run_through_channel(&mut cmd);
    let mut child = spawned.expect("std reports Ok for a child killed before exec");
    assert!(matches!(report, Report::Missing), "{report:?}");
    child.wait().expect("reap the corpse");
}

/// A report found unwritten, and a child killed by a signal after that: the spawn waits on the
/// pipe, and the child's death closes it with no report, so the program did not start. The seam closes
/// the report pipe's write end before the child dies, and the parent's first read is forced to find
/// nothing.
///
/// Mutants: the spawn does not wait, and answers that the program may have started; the wait answers
/// a failure (`WaitFailed`), which is no proof the program did not start.
#[skuld::test]
fn an_unwritten_report_then_a_killed_child_is_answered_died_before_exec() {
    let _killed = seams::force_child_killed_before_report();
    let _unwritten = seams::find_the_report_unwritten();
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(["/usr/bin/true"]);
    let error = cmd
        .spawn()
        .expect_err("a child killed before its report is not adopted");
    assert!(
        !matches!(error, Error::MayHaveStarted { .. }),
        "the program did not start: {error:?}"
    );
    let said = crate::error::said(&error);
    assert!(
        said.contains("died before exec; the program did not start"),
        "the spawn is answered as a child that died before exec: {said}"
    );
}

// The wait for a report =====

/// Arms a hook on the wait's first block that drops `copy`, a copy of the write end, so a wait that
/// blocks where it should not ends at EOF and fails its test's assertion instead of hanging.
fn release_on_block(copy: std::io::PipeWriter) -> block_probe::Armed {
    on_blocking(move || drop(copy))
}

/// An id that is already in the pipe is a late report.
///
/// Mutant: the wait answers `Id`, not `Late`.
#[skuld::test]
fn awaiting_a_written_report_answers_late() {
    use std::io::Write;
    let child = blocker();
    let (r, mut w) = pipe();
    w.write_all(&report_bytes(1, 0xabc)).unwrap();
    assert!(matches!(await_report(&HostKernel, &r, child.id()), Report::Late(0xabc)));
}

/// A pipe whose every write end closed with nothing written is EOF: no report.
///
/// Mutant: the wait answers `Unwritten`.
#[skuld::test]
fn awaiting_a_closed_empty_pipe_answers_missing() {
    let child = blocker();
    let (r, w) = pipe();
    drop(w);
    let report = await_report(&HostKernel, &r, child.id());
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// The wait blocks until a report arrives, and the pipe's readability is what ends it. The hook on
/// the wait's first block writes the report and looks at the wait's kqueue for the pipe's event.
/// The child stays alive, so only the pipe can end a correct wait. A wait that missed it is ended by
/// the child's exit instead, never left hanging: the first block ends the child when no pipe event
/// is pending, and any later block ends it too.
///
/// Mutants: the wait returns at once with nothing; it does not register `EVFILT_READ` (no pipe
/// event); it takes a readable pipe for a spurious wake (a second block, and the child's exit ends
/// the wait).
#[skuld::test]
fn awaiting_is_woken_by_the_report_through_the_pipe() {
    use std::cell::{Cell, RefCell};
    use std::io::Write;
    use std::rc::Rc;
    let mut child = blocker();
    let (r, w) = pipe();
    let stdin = Rc::new(RefCell::new(child.stdin.take()));
    let writer = RefCell::new(Some(w));
    let pending = Rc::new(Cell::new(None));
    let blocks = Rc::new(Cell::new(None));
    let _hook = on_each_block({
        let (stdin, pending, blocks) = (Rc::clone(&stdin), Rc::clone(&pending), Rc::clone(&blocks));
        move |block| {
            blocks.set(block.n);
            if block.n == Some(1) {
                let mut w = writer.borrow_mut().take().expect("the report's writer");
                w.write_all(&report_bytes(1, 0xdef)).unwrap();
                pending.set(block.ready());
                if pending.get() == Some(true) {
                    return;
                }
            }
            drop(stdin.borrow_mut().take());
        }
    });
    let _ = seams::take_wake();
    let report = await_report(&HostKernel, &r, child.id());
    assert_eq!(pending.get(), Some(true), "the wait must watch the pipe");
    assert_eq!(blocks.get(), Some(1), "a readable pipe ends the wait");
    assert_eq!(seams::take_wake(), Some(seams::Wake::Pipe));
    assert!(matches!(report, Report::Late(0xdef)), "{report:?}");
}

/// A child that exited without reporting, while another copy of the write end stays open (as a fork
/// that inherited it holds one): the pipe never hits EOF, but the child is gone, so the report never
/// comes. The wait answers `Missing` without blocking.
///
/// Mutant: the wait watches the pipe alone, so it blocks until every copy of the write end closes.
#[skuld::test]
fn awaiting_a_child_that_exited_unreported_answers_missing_without_blocking() {
    let mut child = blocker();
    let (r, copy) = pipe();
    drop(child.stdin.take());
    crate::test_child::wait_until_zombie(child.id());
    let _release = release_on_block(copy);
    block_probe::take();
    let report = await_report(&HostKernel, &r, child.id());
    assert_eq!(block_probe::take(), [], "a child already gone is not waited for");
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// A child that exits during the wait ends it, through the watch on the child, even while another
/// copy of the write end stays open. The hook on the wait's first block ends the child, waits until
/// it is a zombie, then drops that copy, so the next wake has both events pending and says which
/// one ended the wait.
///
/// Mutant: the wait watches the pipe alone.
#[skuld::test]
fn awaiting_a_child_that_exits_during_the_wait_is_ended_by_its_exit() {
    let mut child = blocker();
    let pid = child.id();
    let stdin = child.stdin.take();
    let (r, copy) = pipe();
    let _hook = on_blocking(move || {
        drop(stdin);
        crate::test_child::wait_until_zombie(pid);
        drop(copy);
    });
    let report = await_report(&HostKernel, &r, pid);
    assert_eq!(
        seams::take_wake(),
        Some(seams::Wake::ChildGone),
        "the child's exit ends the wait"
    );
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// A pid that names no child of this process (as after a foreign reap and a reuse of the number by
/// another process) shows the child gone: `waitid` answers `ECHILD`, and the wait does not block.
/// The test's own parent stands in for the stranger.
///
/// Mutant: `ECHILD` is not taken as the child gone, so the wait watches the stranger.
#[skuld::test]
fn awaiting_a_pid_that_is_not_our_child_answers_missing_without_blocking() {
    let (r, copy) = pipe();
    // SAFETY: `getppid` has no preconditions.
    let stranger = unsafe { libc::getppid() } as u32;
    let _release = release_on_block(copy);
    block_probe::take();
    let report = await_report(&HostKernel, &r, stranger);
    assert_eq!(block_probe::take(), [], "a stranger is not waited for");
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// A pid no process holds (a child this test reaped) cannot be watched: the registration's
/// `ESRCH` shows the child gone, and the wait does not block.
///
/// Mutant: the registration's `ESRCH` is an error (`ReadFailed`).
#[skuld::test]
fn awaiting_a_reaped_pid_answers_missing_without_blocking() {
    let child = blocker();
    let pid = child.id();
    drop(child);
    let (r, copy) = pipe();
    let _release = release_on_block(copy);
    block_probe::take();
    let report = await_report(&HostKernel, &r, pid);
    assert_eq!(block_probe::take(), [], "a reaped child is not waited for");
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// The `kinfo_proc` of the live child `pid` this process forked, held by `parent`.
fn forked_by_us_held_by(pid: u32, parent: u32) -> kinfo_proc {
    kinfo_proc::of_host_held_by(pid, std::process::id() as libc::pid_t, parent as libc::pid_t)
}

/// A kernel that reads the live child `pid` as forked by this process and held by whom `holder`
/// says at each read, and is the host's otherwise.
fn held_by_whom(pid: u32, holder: &Arc<AtomicU32>) -> FakeKernel<'static> {
    let holder = Arc::clone(holder);
    FakeKernel::over(&HostKernel).on_every_kinfo(pid, move || forked_by_us_held_by(pid, holder.load(Ordering::SeqCst)))
}

/// A child that launchd holds, whose parent at a tracer's attach is this process: its tracer died
/// while it was exiting, and XNU gave it to launchd. It is gone, and the wait answers `Missing`
/// without blocking. The child really runs; its `waitid` and its parents are stated rows.
///
/// Mutant: the check takes a child this process forked for running, whoever holds it.
#[skuld::test]
fn awaiting_a_child_launchd_holds_after_its_tracer_died_answers_missing_without_blocking() {
    let child = blocker();
    let pid = child.id();
    let (r, copy) = pipe();
    let kernel = FakeKernel::over(&HostKernel)
        .on_peek(pid, Err(crate::child::lifecycle::echild()))
        .on_every_kinfo(pid, move || forked_by_us_held_by(pid, crate::identity::LAUNCHD));
    let _release = release_on_block(copy);
    block_probe::take();
    let report = await_report(&kernel, &r, pid);
    assert_eq!(block_probe::take(), [], "a child launchd holds is not waited for");
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// A child whose tracer dies while the child is exiting: XNU sends the child's `NOTE_EXIT` to the
/// tracer alone, then gives the child to launchd, so no event of the child's reaches this process.
/// The wait watches the tracer as well, and the tracer's exit makes it check the child again, which
/// finds launchd holding it: `Missing`. A live `cat` stands in for the tracer. The child really runs;
/// its `waitid` and its parents are stated rows: held by the stand-in while that runs, by launchd once it
/// has exited. The hook on the wait's first block ends the stand-in and looks for an event pending on
/// the wait's kqueue; if there is none, it drops a copy of the write end, so a wait that missed the
/// tracer's exit ends at EOF instead of hanging.
///
/// Mutant: the wait does not watch the tracer.
#[skuld::test]
fn awaiting_a_child_whose_tracer_dies_during_its_exit_is_woken_by_the_tracers_exit() {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    let child = blocker();
    let pid = child.id();
    let mut tracer = blocker();
    let tracer_pid = tracer.id();
    let (r, copy) = pipe();
    // The child stays `ECHILD` to this process throughout.
    let holder = Arc::new(AtomicU32::new(tracer_pid));
    let kernel = held_by_whom(pid, &holder).on_every_peek(pid, || Err(crate::child::lifecycle::echild()));
    let pending = Rc::new(Cell::new(None));
    let tracer_stdin = RefCell::new(tracer.stdin.take());
    let copy = RefCell::new(Some(copy));
    let _hook = on_each_block({
        let pending = Rc::clone(&pending);
        move |block| {
            if block.n == Some(1) {
                drop(tracer_stdin.borrow_mut().take());
                crate::test_child::wait_until_zombie(tracer_pid);
                holder.store(crate::identity::LAUNCHD, Ordering::SeqCst);
                pending.set(block.ready());
                if pending.get() == Some(true) {
                    return;
                }
            }
            drop(copy.borrow_mut().take());
        }
    });
    let _ = seams::take_wake();
    let report = await_report(&kernel, &r, pid);
    assert_eq!(pending.get(), Some(true), "the tracer's exit must wake the wait");
    assert_eq!(
        seams::take_wake(),
        Some(seams::Wake::ChildGone),
        "the check after the tracer's exit ends the wait"
    );
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// A tracer that attaches after the wait's check: XNU reparents the child to it and sends the child
/// `SIGSTOP` (see `wait::macos::TracerWatch`). The wait watches the child's signals,
/// so it checks again, finds the tracer and watches it too; the tracer's exit, with launchd then
/// holding the child, ends the wait: `Missing`. A live `cat` stands in for the tracer. The child
/// really runs; its `waitid` and its parents are stated rows: running until the attach, then held by the
/// stand-in, then by launchd once that has exited. A `SIGCONT` to the child stands in for the
/// attach's `SIGSTOP`. Each of the two hooks looks for an event pending on the wait's kqueue; if
/// there is none, it drops a copy of the write end, so a wait that missed it ends at EOF instead of
/// hanging.
///
/// Mutant: the wait registers no `NOTE_SIGNAL` on the child.
#[skuld::test]
fn awaiting_a_child_a_tracer_attaches_to_late_is_woken_by_the_attach() {
    use std::cell::{Cell, RefCell};
    use std::rc::Rc;

    use crate::os_process::macos::kqueue::test_hooks::send_signal;
    let child = blocker();
    let pid = child.id();
    let mut tracer = blocker();
    let tracer_pid = tracer.id();
    let (r, copy) = pipe();
    // Running for the first check, then `ECHILD` throughout.
    let holder = Arc::new(AtomicU32::new(std::process::id()));
    let kernel = held_by_whom(pid, &holder)
        .on_peek(pid, Ok(None))
        .on_every_peek(pid, || Err(crate::child::lifecycle::echild()));
    let (attach_woke, exit_woke) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(None)));
    let tracer_stdin = RefCell::new(tracer.stdin.take());
    let copy = RefCell::new(Some(copy));
    let _hook = on_each_block({
        let (attach_woke, exit_woke) = (Rc::clone(&attach_woke), Rc::clone(&exit_woke));
        move |block| {
            let woke = match block.n {
                Some(1) => {
                    holder.store(tracer_pid, Ordering::SeqCst);
                    send_signal(pid, libc::SIGCONT);
                    attach_woke.set(block.ready());
                    attach_woke.get()
                }
                Some(2) => {
                    drop(tracer_stdin.borrow_mut().take());
                    crate::test_child::wait_until_zombie(tracer_pid);
                    holder.store(crate::identity::LAUNCHD, Ordering::SeqCst);
                    exit_woke.set(block.ready());
                    exit_woke.get()
                }
                _ => None,
            };
            if woke != Some(true) {
                drop(copy.borrow_mut().take());
            }
        }
    });
    let _ = seams::take_wake();
    let report = await_report(&kernel, &r, pid);
    assert_eq!(attach_woke.get(), Some(true), "the attach's signal must wake the wait");
    assert_eq!(
        exit_woke.get(),
        Some(true),
        "the wait must block again, watching the tracer, and its exit must wake it"
    );
    assert_eq!(seams::take_wake(), Some(seams::Wake::ChildGone));
    assert!(matches!(report, Report::Missing), "{report:?}");
}

/// A failed spawn's child was collected by std, or tokio dropped it with its pid, so there is no
/// child to wait on: the report is read once. A copy of the write end held elsewhere (as a foreign
/// fork holds one) keeps the empty pipe open, so it reads `Unwritten`.
///
/// Mutant: the spawn waits for the report after a failed spawn (the refused wait answers
/// `WaitFailed`).
#[skuld::test]
fn a_failed_spawn_reads_the_report_once_and_does_not_wait() {
    let mut cmd = std::process::Command::new("/usr/bin/true");
    let pending = register(&mut cmd);
    let guard = crate::child::spawn::spawn_lock();
    let channel = pending.open(&guard).expect("open");
    let _foreign_copy = channel.write_end.try_clone().expect("dup the write end");
    let _refused = seams::refuse_the_wait();
    let (spawned, first) = channel.run(|| Err::<(), ()>(()), |_| unreachable!("a failed spawn has no child"));
    drop(guard);
    let report = first.finish(&HostKernel);
    assert!(spawned.is_err());
    assert!(matches!(report, Report::Unwritten), "{report:?}");
}

// The wait's timeouts =====

/// The `warn`s on this thread since `mark` that say a child has not reported its id.
fn waiting_warns(mark: usize) -> usize {
    crate::log_capture::warns_since(mark, "has not reported its unique id").len()
}

/// A wait on `child` (a [`blocker`]) whose checks find it held by `tracer` (another live child),
/// with the first `gone_walks` tracer walks finding the tracer gone (its unique-id read is a row that
/// says so). The hook on block `release_at` drops a copy of the write end, so the wait ends at EOF.
/// Answers the report and each `kevent`'s timeout, one per block.
fn await_held(
    child: u32,
    tracer: u32,
    gone_walks: usize,
    say_after: std::time::Duration,
    release_at: u32,
) -> (Report, Vec<Option<std::time::Duration>>) {
    use std::cell::RefCell;

    use crate::identity::UniqRead;
    let (r, copy) = pipe();
    let kernel = (0..gone_walks).fold(
        FakeKernel::over(&HostKernel)
            .on_every_peek(child, || Err(crate::child::lifecycle::echild()))
            .on_every_kinfo(child, move || forked_by_us_held_by(child, tracer)),
        |kernel, _| kernel.on_unique_info(tracer, UniqRead::Gone),
    );
    let _warn = seams::warn_after(say_after);
    let copy = RefCell::new(Some(copy));
    let _hook = on_each_block(move |block| {
        if block.n == Some(release_at) {
            drop(copy.borrow_mut().take());
        }
    });
    block_probe::take();
    let report = await_report(&kernel, &r, child);
    (report, block_probe::take())
}

/// A walk that finds the tracer gone checks again at once without blocking, then blocks for no
/// longer than the backoff asks, while the warning is far off.
///
/// Mutants: the wait blocks with no timeout on `Recheck(after)`; `Recheck(0)` blocks.
#[skuld::test]
fn a_tracer_found_gone_arms_the_wait_with_its_backoff() {
    let child = blocker();
    let tracer = blocker();
    let (report, timeouts) = await_held(child.id(), tracer.id(), 2, std::time::Duration::from_secs(3600), 1);
    assert!(matches!(report, Report::Missing), "{report:?}");
    assert_eq!(
        timeouts,
        [Some(std::time::Duration::from_millis(1))],
        "a re-check at once does not block"
    );
}

/// The wait blocks for the sooner of the backoff and the time left to its warning.
///
/// Mutants: the backoff alone times the block; the later of the two does.
#[skuld::test]
fn a_wait_held_by_a_tracer_blocks_for_the_sooner_of_its_backoff_and_its_warning() {
    crate::log_capture::install();
    let child = blocker();
    let tracer = blocker();
    let (report, timeouts) = await_held(child.id(), tracer.id(), 3, std::time::Duration::ZERO, 2);
    assert!(matches!(report, Report::Missing), "{report:?}");
    let ms = std::time::Duration::from_millis;
    assert_eq!(
        timeouts,
        [Some(ms(0)), Some(ms(2))],
        "the warning, due at once, times the first block; the backoff alone the next"
    );
}

/// The wait warns once, when its warning is due, and blocks with no timeout after that.
///
/// Mutants: the warning repeats on every block; it never fires.
#[skuld::test]
fn a_wait_warns_once_that_the_report_is_late() {
    use std::cell::RefCell;
    crate::log_capture::install();
    let child = blocker();
    let (r, copy) = pipe();
    let _warn = seams::warn_after(std::time::Duration::ZERO);
    let copy = RefCell::new(Some(copy));
    let _hook = on_each_block(move |block| {
        if block.n == Some(2) {
            drop(copy.borrow_mut().take());
        }
    });
    let mark = crate::log_capture::mark();
    block_probe::take();
    let report = await_report(&HostKernel, &r, child.id());
    assert!(matches!(report, Report::Missing), "{report:?}");
    assert_eq!(waiting_warns(mark), 1, "one warning, however long the wait");
    let timeouts = block_probe::take();
    assert_eq!(timeouts.first(), Some(&Some(std::time::Duration::ZERO)), "{timeouts:?}");
    assert!(
        timeouts[1..].iter().all(Option::is_none),
        "once it has warned the wait has no timeout: {timeouts:?}"
    );
}

/// A wait in a test warns only under a guard (a verdict must not depend on elapsed time), and the
/// threshold production warns at is 1 s.
///
/// Mutants: a wait with no guard gets a threshold; production's is not 1 s.
#[skuld::test]
fn production_warns_after_one_second_and_a_test_only_with_a_guard() {
    assert_eq!(super::SAY_WAITING_AFTER, std::time::Duration::from_secs(1));
    assert_eq!(seams::say_waiting_after(), None);
}

/// The wait's look at the child asks the kernel the spawn started with: its row says the pid is a
/// running child, where the host, which has no child of that number, says it is gone.
///
/// Mutant: `check` reads through a host kernel.
#[skuld::test]
fn the_look_at_the_child_asks_the_kernel_it_was_given() {
    /// Above macOS's `PID_MAX`: no host process has it.
    const STATED: u32 = 2_000_000_000;
    let kernel = FakeKernel::over(&HostKernel).on_peek(STATED, Ok(None));
    assert!(matches!(super::check(&kernel, STATED), Ok(super::Check::Running)));
}

/// A wait on a child a tracer holds asks the spawn's kernel who forked it and holds it (`origin`),
/// and where the tracer is (`TracerWatch::held_by`): every row stated for them answers, so that the
/// child is a `Traced` one, its tracer is gone, and the next look at the child finds it exited and
/// ends the wait. The host answers none of them, for a tracer no process has.
///
/// Mutants: `check` reads `origin` through a host kernel; `watch` walks the tracer through a host
/// kernel. Either leaves rows untaken, and a wait that blocks is ended at EOF by the released pipe.
#[skuld::test]
fn a_wait_on_a_traced_child_asks_the_kernel_it_was_given_for_the_child_and_its_tracer() {
    use crate::identity::exit_record;
    use crate::os_process::macos::kqueue::Subscription;
    use crate::wait::exit_only::macos_tests::found;

    /// Above macOS's `PID_MAX`: no host process has it.
    const TRACER: u32 = 2_000_000_000;
    let child = blocker();
    let pid = child.id();
    let me = std::process::id() as libc::pid_t;
    // Ids above this process's own, so the child reads as forked after it.
    let (child_unique, tracer_unique) = (u64::MAX - 1, u64::MAX);
    let kernel = FakeKernel::over(&HostKernel)
        // `waitid` answers `ECHILD` while a tracer holds the child, then shows its exit.
        .on_peek(pid, Err(std::io::Error::from_raw_os_error(libc::ECHILD)))
        .on_peek(pid, Ok(Some(exit_record(0))))
        // `origin`: the child was forked by this process and is held by the tracer.
        .on_unique_info(pid, found(child_unique))
        .on_kinfo(pid, kinfo_proc::of_host_held_by(pid, me, TRACER as libc::pid_t))
        .on_unique_info(pid, found(child_unique))
        // `held_by`: the tracer is a process whose registration is refused, so it is gone.
        .on_unique_info(TRACER, found(tracer_unique))
        .on_kinfo(TRACER, kinfo_proc::of_host_held_by(pid, 0, 1))
        .on_unique_info(TRACER, found(tracer_unique))
        .on_subscribe_refused(
            Subscription::Process {
                pid: TRACER,
                signals: true,
                reap: false,
            },
            libc::ESRCH,
        );
    let (r, copy) = pipe();
    let _release = release_on_block(copy);
    block_probe::take();
    let report = await_report(&kernel, &r, pid);
    assert_eq!(
        block_probe::take(),
        [],
        "a child whose tracer is gone is not waited for"
    );
    assert!(matches!(report, Report::Missing), "{report:?}");
    assert!(
        kernel.all_rows_taken(),
        "the child and its tracer were read through the spawn's kernel"
    );
}