cosca 0.8.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
//! The teardowns of a Windows child over a real `CREATE_SUSPENDED` process, whose calls a
//! [`FakeProcess`] answers where a test must make the OS refuse, fail or slow down: a failed
//! spawn's ([`tear_down_failed_spawn`]) and the drop's ([`OwnedChild::tear_down`]).
//!
//! A "UAC handle" is a handle a UAC elevation returned, opened without `PROCESS_TERMINATE` (the
//! access of a higher-integrity child), so its `TerminateProcess` is denied. A row that says "a fake
//! answers" needs an answer no real handle gives: a `CreateProcess` handle is never refused and
//! never fails a wait.

use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::time::Duration;

use windows::core::HRESULT;
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, HANDLE};
use windows::Win32::System::Threading::{
    OpenProcess, TerminateProcess, CREATE_SUSPENDED, EXTENDED_STARTUPINFO_PRESENT, PROCESS_QUERY_LIMITED_INFORMATION,
    PROCESS_SYNCHRONIZE, STARTUPINFOEXW,
};

use super::proc::create_process;
use crate::child::drop_teardown::Torn;
use crate::child::lifecycle::Wording;
use crate::child::owned::owned_tests::teardown_lines::{HANDED_BACK, LEFT};
use crate::child::owned::teardown::{Disposition, Kill, Past};
use crate::child::owned::{ChildWaitOutcome, OwnedChild};
use crate::child::spawn::held_teardown::tear_down_failed_spawn;
use crate::child::spawn::policy::SpawnPolicy;
use crate::child::spawn::Diagnosis;
use crate::error::ChildFate;
use crate::identity::ProcessId;
use crate::os_process::child::{ExitRecord, KillRefusal, OsChild};
use crate::os_process::fake::{FakeProcess, ReapAnswer};
use crate::os_process::windows::{uac_access, WindowsProcess};
use crate::test_spawn::console_flags::NO_WINDOW;

const KIND: std::io::ErrorKind = std::io::ErrorKind::Other;

/// A `CREATE_SUSPENDED` process that never exits on its own; dropped, it is killed and reaped by a
/// direct `TerminateProcess`, so a test of a no-op kill cannot hang.
struct Suspended {
    owned: OwnedChild,
    pid: u32,
}

impl Suspended {
    fn spawn() -> Suspended {
        let mut cmdline: Vec<u16> = "cmd /C exit 0\0".encode_utf16().collect();
        let mut si = STARTUPINFOEXW::default();
        let (proc, pid) = create_process(
            None,
            &mut cmdline,
            &mut si,
            None,
            &None,
            EXTENDED_STARTUPINFO_PRESENT.0 | CREATE_SUSPENDED.0 | NO_WINDOW,
        )
        .expect("spawn suspended");
        Suspended {
            owned: OwnedChild::new(Box::new(WindowsProcess::for_child(proc, pid))),
            pid,
        }
    }

    fn handle(&self) -> HANDLE {
        HANDLE(self.owned.os_handle().as_raw_handle())
    }

    fn id(&self) -> ProcessId {
        ProcessId::of(self.pid).found().expect("identity")
    }

    /// A second handle with every right, for a teardown to consume while `self` stays the way to
    /// end the process.
    fn duplicate(&self) -> OwnedHandle {
        self.owned
            .os_handle()
            .try_clone_to_owned()
            .expect("duplicate the process handle")
    }

    /// A handle that lacks `PROCESS_TERMINATE`, so its `TerminateProcess` is denied.
    fn without_terminate_right(&self) -> OwnedHandle {
        // SAFETY: plain `OpenProcess` on the live pid `self` pins.
        let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, self.pid) }
            .expect("open without PROCESS_TERMINATE");
        // SAFETY: `h` is a fresh owned handle from `OpenProcess`.
        unsafe { OwnedHandle::from_raw_handle(h.0) }
    }

    /// End the process with exit code 0, which only a process no earlier `TerminateProcess` has
    /// claimed takes: a real kill (exit 1) has already marked the thread terminated, so a later
    /// call cannot change the exit code. That call returns success or `ERROR_ACCESS_DENIED`
    /// depending on timing.
    fn end_with_code_zero(&self) -> impl FnOnce() + 'static {
        let handle = self.handle();
        move || {
            // SAFETY: `self` outlives every use of the hook, and holds the handle open.
            match unsafe { TerminateProcess(handle, 0) } {
                Ok(()) => {}
                Err(e) if e.code() == HRESULT::from_win32(ERROR_ACCESS_DENIED.0) => {}
                Err(e) => panic!("TerminateProcess(handle, 0) failed: {e:?}"),
            }
        }
    }

    /// Block until the process has exited, through `self`'s own wait.
    fn wait_for_exit(&self) -> std::process::ExitStatus {
        match self.owned.wait(None) {
            Ok(crate::child::owned::ChildWaitOutcome::Exited(crate::os_process::child::ExitRecord::Status(s))) => s,
            other => panic!("expected an exit status, got {other:?}"),
        }
    }
}

impl Drop for Suspended {
    fn drop(&mut self) {
        // SAFETY: `self` holds the process handle open.
        _ = unsafe { TerminateProcess(self.handle(), 1) };
        _ = self.owned.wait(None);
    }
}

/// A fake that answers from its tables and, past them, from the real `handle` of the process `pid`,
/// as a `CreateProcess` handle is built.
fn real(handle: OwnedHandle, pid: u32) -> FakeProcess {
    FakeProcess::over(Box::new(WindowsProcess::for_child(handle, pid)))
}

/// A [`WindowsProcess`] over a handle a UAC elevation returned, which allows what it was granted:
/// the access is read from `handle`, as the launch reads it.
fn uac_process(handle: OwnedHandle, pid: u32) -> WindowsProcess {
    let granted = uac_access(HANDLE(handle.as_raw_handle()));
    WindowsProcess::for_uac(handle, pid, granted)
}

/// [`real`] for a handle a UAC elevation returned.
fn uac(handle: OwnedHandle, pid: u32) -> FakeProcess {
    FakeProcess::over(Box::new(uac_process(handle, pid)))
}

/// An [`OwnedChild`] over `fake`, and `fake` for the test to read what it was asked.
fn owned(fake: FakeProcess) -> (OwnedChild, FakeProcess) {
    (OwnedChild::new(Box::new(fake.clone())), fake)
}

// A failed spawn's teardown =====

/// Both ways a caller disposes of a child its failed spawn's teardown could not collect.
const DISPOSITIONS: [Disposition; 2] = [Disposition::Leave, Disposition::HandBack];

/// A failed spawn's teardown of `child`, as a caller that knows `past` of its handle and disposes of
/// an uncollected child as `disposition` says, with the wait for a killed child warning past
/// `warn_after`; its fate, and the child if it was handed back.
fn after_a_failed_spawn(
    child: OwnedChild,
    id: Option<ProcessId>,
    past: Past,
    disposition: Disposition,
    warn_after: Option<Duration>,
) -> (ChildFate, Option<crate::Unreaped>) {
    let torn = tear_down_failed_spawn(
        child,
        id,
        past,
        disposition,
        SpawnPolicy {
            teardown_warn_after: warn_after,
            ..SpawnPolicy::SYNC
        },
        &mut Diagnosis::default(),
    );
    (torn.fate, torn.unreaped)
}

/// A failed spawn's teardown with warnings on, whose child has already exited by the time it looks,
/// does not warn, under either disposition. The handle is a UAC handle, so only its signalled state
/// shows the exit.
///
/// Mutant: the look at the child's exit finds it late whatever its handle says.
#[skuld::test]
fn a_failed_spawn_teardown_of_an_exited_child_with_warnings_on_does_not_warn() {
    for disposition in DISPOSITIONS {
        let owner = Suspended::spawn();
        let id = owner.id();
        let (child, _fake) = owned(uac(owner.without_terminate_right(), owner.pid));
        owner.end_with_code_zero()();
        owner.wait_for_exit();

        crate::log_capture::install();
        let mark = crate::log_capture::mark();
        let (fate, unreaped) =
            after_a_failed_spawn(child, Some(id), Past::Clean, disposition, Some(Duration::from_secs(1)));

        assert_eq!(fate, ChildFate::Reaped, "{disposition:?}");
        assert!(
            unreaped.is_none(),
            "a collected child is handed back by none: {disposition:?}"
        );
        let warns = crate::log_capture::records_since_on_current_thread(mark, "still waiting");
        assert!(warns.is_empty(), "{disposition:?}: {warns:?}");
    }
}

/// A failed spawn's teardown with warnings on whose child is still running when it looks (the kill is
/// forced to be refused as an exit under way, so nothing ends it until the wait blocks) warns once,
/// naming the pid, and goes on to the wait, under either disposition. The child is really
/// unsignalled: nothing overrides the look.
///
/// Mutants: the look finds the child exited whatever its handle says; the warn drops the pid.
#[skuld::test]
fn a_failed_spawn_teardown_of_a_running_child_with_warnings_on_warns_once_naming_it() {
    for disposition in DISPOSITIONS {
        let owner = Suspended::spawn();
        let (child, _fake) = owned(real(owner.duplicate(), owner.pid));
        let refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
        crate::log_capture::install();
        let mark = crate::log_capture::mark();
        // Ends the process once the wait blocks, which is after the look.
        let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
        let (fate, unreaped) = after_a_failed_spawn(child, None, Past::Clean, disposition, Some(Duration::ZERO));

        refusal.assert_fired();
        assert_eq!(
            fate,
            ChildFate::Reaped,
            "the wait goes on past the warn: {disposition:?}"
        );
        assert!(
            unreaped.is_none(),
            "a collected child is handed back by none: {disposition:?}"
        );
        let warns = crate::log_capture::records_since_on_current_thread(mark, "still waiting");
        assert_eq!(warns.len(), 1, "one warn: {disposition:?}: {warns:?}");
        assert!(
            warns[0].1.contains(&format!("child {} ", owner.pid)),
            "the warn names the child: {warns:?}"
        );
    }
}

/// A failed spawn's teardown whose `TerminateProcess` is denied on a live child (a UAC handle) asked
/// nothing to exit: it looks once, never waits, answers `Running { id }` and warns of the refusal
/// once. A UAC handle may be refused for permission, so the contract holds.
///
/// Mutants: the failed-kill arm falls through to the wait; it answers without the look; the failed
/// `TerminateProcess` is warned of where it is made, as well as by the teardown.
#[skuld::test]
fn a_failed_spawn_teardown_with_a_denied_terminate_is_running_and_does_not_wait() {
    let owner = Suspended::spawn();
    let id = owner.id();
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (child, fake) = owned(uac(owner.without_terminate_right(), owner.pid));
    // Ends the process once a wait blocks, so a teardown that waits fails the checks below instead of
    // hanging.
    crate::wait::block_probe::take();
    let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
    let (fate, unreaped) = after_a_failed_spawn(child, Some(id), Past::Clean, Disposition::Leave, None);
    assert!(unreaped.is_none(), "a teardown that leaves its child hands none back");
    assert_eq!(fate, ChildFate::Running { id: Some(id) });
    assert_eq!(fake.looks(), 1, "one look, and no wait");
    assert_eq!(
        crate::wait::block_probe::take(),
        [],
        "a failed kill is never followed by a wait"
    );
    let warned = crate::log_capture::warns_since(mark, "");
    assert_eq!(warned.len(), 1, "one warn for one refusal: {warned:?}");
    assert!(
        warned[0].starts_with(&format!(
            "teardown after a failed spawn: child {} could not be terminated",
            owner.pid
        )),
        "{warned:?}"
    );
}

/// A failed spawn's teardown whose kill fails on a child that has exited collects it from the look
/// and warns of nothing, under either disposition: the child is collected, so none is handed back.
/// The handle may be refused for permission, as a UAC handle's is.
///
/// Mutant: the failed-kill arm answers `Running` without looking, and warns.
#[skuld::test]
fn a_failed_spawn_teardown_with_a_failed_terminate_of_an_exited_child_is_reaped_silently() {
    for disposition in DISPOSITIONS {
        let owner = Suspended::spawn();
        let id = owner.id();
        crate::log_capture::install();
        let mark = crate::log_capture::mark();
        let fake = FakeProcess::new([])
            .with_kill_refusal(KillRefusal::Permission)
            .reaps([ReapAnswer::Reaped(ExitRecord::Status(
                std::process::ExitStatus::default(),
            ))])
            .signals([Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))]);
        let (child, fake) = owned(fake);
        let (fate, unreaped) = after_a_failed_spawn(child, Some(id), Past::Clean, disposition, None);
        assert_eq!(fate, ChildFate::Reaped, "{disposition:?}");
        assert!(
            unreaped.is_none(),
            "a collected child is handed back by none: {disposition:?}"
        );
        assert_eq!(fake.looks(), 1);
        let warned = crate::log_capture::warns_since(mark, "");
        assert_eq!(warned, Vec::<String>::new(), "nothing is left running: {disposition:?}");
    }
}

/// The kill is delivered to a live process and the wait after it fails (a caller that expects
/// anything of its handle, as when a look on it failed): the fate is `Killed`, and the kill is what
/// ended it (exit code 1). The child is uncollected: handed back under `HandBack`, warned of as left
/// under `Leave`.
///
/// Mutants: the teardown answers `Unknown` for any failed wait; the kill sends nothing, so the
/// process never exits and the owner's wait hangs; the teardown waits a second time; `HandBack` drops
/// the child, or says it is left.
#[skuld::test]
fn a_failed_spawn_teardown_with_a_delivered_terminate_and_a_failed_wait_is_killed() {
    for disposition in DISPOSITIONS {
        let owner = Suspended::spawn();
        let (child, fake) = owned(real(owner.duplicate(), owner.pid).reaps([ReapAnswer::Err(KIND)]));
        crate::log_capture::install();
        let mark = crate::log_capture::mark();
        let (fate, unreaped) = after_a_failed_spawn(child, None, Past::WaitMayFail, disposition, None);
        assert_eq!(fate, ChildFate::Killed, "{disposition:?}");
        assert_eq!(
            unreaped.is_some(),
            disposition == Disposition::HandBack,
            "an uncollected child is handed back by HandBack alone: {disposition:?}"
        );
        assert_eq!(fake.looks(), 1, "the teardown made the wait that failed");
        assert_eq!(
            owner.wait_for_exit().code(),
            Some(1),
            "the teardown's kill must have ended it"
        );
        // Said as every teardown says a failed wait, under the failed spawn's name.
        let warns = crate::log_capture::records_since_on_current_thread(mark, "");
        let where_it_went = match disposition {
            Disposition::Leave => LEFT,
            Disposition::HandBack => HANDED_BACK,
        };
        assert_eq!(
            warns,
            [(
                log::Level::Warn,
                format!(
                    "teardown after a failed spawn: teardown of child {}: the wait failed: {}{where_it_went}",
                    owner.pid,
                    crate::child::owned::owned_tests::teardown_lines::wait_error(),
                )
            )],
            "{disposition:?}"
        );
    }
}

/// A caller that expects a wait on its handle to succeed is told when it did not: a failed wait after
/// a delivered kill is a breach of the contract, asserted where the warn is logged, after it. A fake
/// answers the failed wait.
///
/// Mutant: `warn_teardown` asserts nothing.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "a wait on a child's own handle failed")]
fn a_failed_wait_on_a_handle_the_spawn_expected_to_wait_on_breaks_the_contract() {
    let owner = Suspended::spawn();
    let (child, _fake) = owned(real(owner.duplicate(), owner.pid).reaps([ReapAnswer::Err(KIND)]));
    crate::log_capture::install();
    after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}

// What each handle kind allows: the contract of a kill's refusal =====

/// Each kind of Windows handle states what its kill may be refused for, from how its constructor
/// built it: a `CreateProcess` handle holds `PROCESS_TERMINATE`, so never; a UAC elevation's handle
/// from the access it was granted.
///
/// Mutants: `for_uac` takes the handle for a `CreateProcess` one, or a granted right for a missing one.
#[skuld::test]
fn each_windows_handle_kind_states_what_its_kill_may_be_refused_for() {
    let owner = Suspended::spawn();
    let kind = |process: WindowsProcess| process.kill_refusal();
    assert_eq!(
        kind(WindowsProcess::for_child(owner.duplicate(), owner.pid)),
        KillRefusal::Never
    );
    assert_eq!(
        kind(uac_process(owner.duplicate(), owner.pid)),
        KillRefusal::Never,
        "a UAC handle granted PROCESS_TERMINATE"
    );
    assert_eq!(
        kind(uac_process(owner.without_terminate_right(), owner.pid)),
        KillRefusal::Permission,
        "a UAC handle that was not"
    );
}

/// A `CreateProcess` handle holds `PROCESS_TERMINATE`, so its kill is never refused: a refusal for
/// want of permission breaks the contract too. A fake answers the refusal.
///
/// Mutant: `for_child` allows a refusal of permission.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never refused")]
fn a_kill_of_a_createprocess_handle_refused_for_permission_breaks_the_contract() {
    let owner = Suspended::spawn();
    let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
    let (child, _fake) = owned(real(owner.duplicate(), owner.pid).signals([Err(denied)]));
    crate::log_capture::install();
    after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}

/// The same for a UAC elevation's handle that was granted `PROCESS_TERMINATE`.
///
/// Mutant: `for_uac` allows a refusal of permission whatever it was granted.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never refused")]
fn a_kill_of_a_uac_handle_granted_terminate_refused_for_permission_breaks_the_contract() {
    let owner = Suspended::spawn();
    let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
    let (child, _fake) = owned(uac(owner.duplicate(), owner.pid).signals([Err(denied)]));
    crate::log_capture::install();
    after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}

/// A kill of a handle that may be refused for permission (a UAC handle) is refused only for that: any
/// other refusal breaks the contract. A fake answers the refusal.
///
/// Mutant: `warn_teardown` does not read the refusal's kind.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "refused for a reason other than permission")]
fn a_kill_refused_for_another_reason_than_permission_breaks_the_contract() {
    crate::log_capture::install();
    let fake = FakeProcess::new([])
        .with_kill_refusal(KillRefusal::Permission)
        .reaps([ReapAnswer::Reaped(ExitRecord::Status(
            std::process::ExitStatus::default(),
        ))])
        .signals([Err(std::io::Error::from(std::io::ErrorKind::Other))]);
    let (child, _fake) = owned(fake);
    after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}

/// What a handle may be refused for is its constructor's, not its past's: a look that failed excuses a
/// failed wait, and no refusal against the handle's allowance.
///
/// Mutant: `Past::WaitMayFail` waives the check of a refusal against what the handle allows.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never refused")]
fn a_failed_look_does_not_excuse_a_refusal_of_a_handle_that_is_never_refused() {
    crate::log_capture::install();
    let fake = FakeProcess::new([])
        .with_kill_refusal(KillRefusal::Never)
        .reaps([ReapAnswer::Reaped(ExitRecord::Status(
            std::process::ExitStatus::default(),
        ))])
        .signals([Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))]);
    let (child, _fake) = owned(fake);
    after_a_failed_spawn(child, None, Past::WaitMayFail, Disposition::Leave, None);
}

/// The same for a refusal for a reason other than permission, of a handle that may be refused for
/// permission.
///
/// Mutant: `Past::WaitMayFail` waives the check of a refusal's kind.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "refused for a reason other than permission")]
fn a_failed_look_does_not_excuse_a_refusal_for_another_reason_than_permission() {
    crate::log_capture::install();
    let fake = FakeProcess::new([])
        .with_kill_refusal(KillRefusal::Permission)
        .reaps([ReapAnswer::Reaped(ExitRecord::Status(
            std::process::ExitStatus::default(),
        ))])
        .signals([Err(std::io::Error::from(std::io::ErrorKind::Other))]);
    let (child, _fake) = owned(fake);
    after_a_failed_spawn(child, None, Past::WaitMayFail, Disposition::Leave, None);
}

/// A failed spawn that hands its child back, whose `TerminateProcess` is denied on a live child (a UAC
/// handle), comes back with the child, still running and nothing sent to it, and says so once.
///
/// Mutants: the child is dropped, or reported reaped; the kill is sent anyway (the child exits 1);
/// the warn says the child is left.
#[skuld::test]
fn a_failed_spawn_teardown_with_a_denied_terminate_hands_the_child_back() {
    let owner = Suspended::spawn();
    let id = owner.id();
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let child = OwnedChild::new(Box::new(uac_process(owner.without_terminate_right(), owner.pid)));

    let (fate, unreaped) = after_a_failed_spawn(child, Some(id), Past::Clean, Disposition::HandBack, None);

    assert_eq!(fate, ChildFate::Running { id: Some(id) });
    let unreaped = unreaped.expect("a refused kill under HandBack hands the child back");
    assert_eq!((unreaped.pid(), unreaped.id()), (Some(owner.pid), Some(id)));
    let warns = crate::log_capture::records_since_on_current_thread(mark, "handed back to the caller");
    assert_eq!(warns.len(), 1, "{warns:?}");
    // Ends it with code 0, which a process the teardown had killed (code 1) would not report.
    owner.end_with_code_zero()();
    let status = unreaped.wait().expect("wait for the handed-back child");
    assert_eq!(status.code(), Some(0), "nothing was sent to the child: {status:?}");
}

/// What failed in a failed spawn's teardown of `child` (a refused kill, a failed wait), as the
/// `cleanup` of the error the spawn returns, with the child's fate and the child it handed back.
fn failed_spawn_cleanup(child: OwnedChild, id: Option<ProcessId>, past: Past) -> crate::child::drop_teardown::Torn {
    tear_down_failed_spawn(
        child,
        id,
        past,
        Disposition::HandBack,
        SpawnPolicy::SYNC,
        &mut Diagnosis::default(),
    )
}

/// A kill the OS refuses is a failure of the spawn's teardown: it is in the error's `cleanup`, with
/// the refusal's code, beside the fate and the child handed back.
///
/// Mutant: the teardown reports the refusal to the log alone.
#[skuld::test]
fn a_failed_spawn_teardown_with_a_denied_terminate_reports_the_refusal_as_its_cleanup() {
    let owner = Suspended::spawn();
    let id = owner.id();
    let child = OwnedChild::new(Box::new(uac_process(owner.without_terminate_right(), owner.pid)));

    let Torn {
        fate,
        unreaped,
        cleanup,
    } = failed_spawn_cleanup(child, Some(id), Past::Clean);

    assert_eq!(fate, ChildFate::Running { id: Some(id) });
    let cleanup = cleanup.expect("the refused kill is the teardown's failure");
    assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
    assert_eq!(
        crate::error::first_os_code(&**cleanup.first()),
        Some(ERROR_ACCESS_DENIED.0 as i32),
        "{cleanup:?}"
    );
    assert!(
        crate::error::said(&**cleanup.first()).starts_with(&crate::error::io_said("killing the child: ")),
        "{cleanup:?}"
    );
    owner.end_with_code_zero()();
    unreaped
        .expect("handed back")
        .wait()
        .expect("wait for the handed-back child");
}

/// A wait that fails after a delivered kill is a failure of the teardown: it is the `cleanup`.
///
/// Mutant: the failed wait is in the clause's text alone.
#[skuld::test]
fn a_failed_spawn_teardown_with_a_failed_wait_reports_the_wait_as_its_cleanup() {
    let owner = Suspended::spawn();
    let (child, _fake) = owned(real(owner.duplicate(), owner.pid).reaps([ReapAnswer::Err(KIND)]));

    let Torn {
        fate,
        unreaped,
        cleanup,
    } = failed_spawn_cleanup(child, None, Past::WaitMayFail);

    assert_eq!(fate, ChildFate::Killed);
    let cleanup = cleanup.expect("the failed wait is the teardown's failure");
    assert_eq!(cleanup.iter().len(), 1, "{cleanup:?}");
    assert!(
        matches!(&**cleanup.first(), crate::error::Error::Io(e) if e.kind() == KIND)
            && crate::error::said(&**cleanup.first()).starts_with(&crate::error::io_said("waiting for the child: ")),
        "{cleanup:?}"
    );
    drop(unreaped);
}

/// A teardown that ended the child with no failure has no `cleanup`.
///
/// Mutant: an empty list is reported where there is nothing.
#[skuld::test]
fn a_failed_spawn_teardown_that_failed_in_nothing_has_no_cleanup() {
    let owner = Suspended::spawn();
    let (child, _fake) = owned(real(owner.duplicate(), owner.pid));

    let Torn {
        fate,
        unreaped,
        cleanup,
    } = failed_spawn_cleanup(child, None, Past::Clean);

    assert_eq!(fate, ChildFate::Reaped);
    assert!(unreaped.is_none());
    assert!(cleanup.is_none(), "{cleanup:?}");
}

// The drop's teardown =====

/// An [`OwnedChild`] over a duplicate of `owner`'s handle, and the fake under it.
fn handle_over(owner: &Suspended, script: impl FnOnce(FakeProcess) -> FakeProcess) -> (OwnedChild, FakeProcess) {
    owned(script(real(owner.duplicate(), owner.pid)))
}

/// The kill is delivered and the teardown waits for the exit it started, then answers `Reaped`.
///
/// Mutants: `TerminateProcess` a no-op reporting `Ok` or `ERROR_ACCESS_DENIED`, so the process is
/// ended with code 0 once the wait blocks; the wait after an accepted terminate dropped.
#[skuld::test]
fn a_kill_teardown_of_a_child_waits_for_the_exit_it_started() {
    let owner = Suspended::spawn();
    let (handle, _fake) = handle_over(&owner, |fake| fake);
    // Keeps a no-op terminate from hanging the wait; see `Suspended::end_with_code_zero`.
    let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
    let torn = handle.tear_down(
        Some(owner.id()),
        Kill {
            disposition: Disposition::Leave,
            tree: None,
        },
        None,
    );
    assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
    assert!(
        matches!(torn.said(), Some(Wording::Collected(log::Level::Debug, _))),
        "{torn:?}"
    );
    assert!(handle.is_reaped(), "teardown must wait for the exit it started");
    let outcome = handle.wait(None).expect("wait after teardown");
    let ChildWaitOutcome::Exited(ExitRecord::Status(status)) = outcome else {
        panic!("the reaped child answers its status: {outcome:?}");
    };
    assert_eq!(
        status.code(),
        Some(1),
        "teardown must end it with TerminateProcess(1): {status:?}"
    );
}

/// A UAC handle to a live child: the teardown looks once, never waits, and leaves it running. What it
/// could not do comes back for the caller's one warn.
///
/// Mutants: wait for the exit when the kill is refused; a refusal on a handle without the right
/// reads as the exit; the failed `TerminateProcess` is warned of where it is made, as well as by
/// the caller.
#[skuld::test]
fn a_kill_teardown_never_blocks_on_a_handle_without_terminate() {
    let owner = Suspended::spawn();
    let id = owner.id();
    crate::log_capture::install();
    let mark = crate::log_capture::mark();
    let (child, fake) = owned(uac(owner.without_terminate_right(), owner.pid));
    let handle = child;
    // Ends the owner's process once a wait blocks, so a teardown that waits fails the checks below
    // instead of hanging.
    let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
    let torn = handle.tear_down(
        Some(id),
        Kill {
            disposition: Disposition::Leave,
            tree: None,
        },
        None,
    );
    assert_eq!(torn.fate(), ChildFate::Running { id: Some(id) }, "{torn:?}");
    assert!(
        matches!(torn.said(), Some(Wording::Uncollected(text)) if text.contains(&owner.pid.to_string())),
        "{torn:?}"
    );
    assert_eq!(fake.looks(), 1, "teardown looked once and did not wait");
    let warned = crate::log_capture::warns_since(mark, "");
    assert_eq!(
        warned,
        Vec::<String>::new(),
        "the teardown leaves the one warn to its caller"
    );
    assert!(
        matches!(
            handle.wait(Some(crate::wait::now())),
            Ok(ChildWaitOutcome::DeadlinePassed)
        ),
        "nothing ended the child"
    );
}

/// A UAC handle to a child that has exited: its signalled state is the exit, so the child is `Reaped`
/// and nothing is left running.
///
/// Mutant: the teardown reads the refusal by the handle's rights alone, so it leaves a dead child as
/// `Running`.
#[skuld::test]
fn teardown_of_a_handle_without_terminate_to_an_exited_child_reaps_it() {
    let owner = Suspended::spawn();
    let (child, _fake) = owned(uac(owner.without_terminate_right(), owner.pid));
    let handle = child;
    owner.end_with_code_zero()();
    owner.wait_for_exit();
    let torn = handle.tear_down(
        Some(owner.id()),
        Kill {
            disposition: Disposition::Leave,
            tree: None,
        },
        None,
    );
    assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
    assert!(
        matches!(torn.said(), Some(Wording::Collected(log::Level::Debug, _))),
        "{torn:?}"
    );
}

/// A child whose exit is under way but not signalled yet, on a handle that holds
/// `PROCESS_TERMINATE`: the refusal is the exit, and the teardown waits for it.
///
/// Mutant: a refusal is the exit only for a signalled process, so the child is left `Running`.
#[skuld::test]
fn teardown_of_an_exiting_unsignalled_child_reaps_it() {
    let owner = Suspended::spawn();
    let (handle, _fake) = handle_over(&owner, |fake| fake);
    let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
    let _refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
    let torn = handle.tear_down(
        Some(owner.id()),
        Kill {
            disposition: Disposition::Leave,
            tree: None,
        },
        None,
    );
    assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
    assert!(
        matches!(torn.said(), Some(Wording::Collected(log::Level::Debug, _))),
        "{torn:?}"
    );
}

/// The kill delivered nothing (the exit was under way), so, as on every OS, a failed wait shows
/// nothing of what became of the child: `Unknown`. One scripted
/// answer, so a second wait would be the real one and fail the count.
///
/// Mutant: a failed wait is `Killed` whatever the kill did.
#[skuld::test]
fn teardown_of_an_exiting_child_with_a_failed_wait_is_unknown() {
    let owner = Suspended::spawn();
    let (handle, fake) = handle_over(&owner, |fake| fake.reaps([ReapAnswer::Err(KIND)]));
    let _refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
    let torn = handle.tear_down(
        Some(owner.id()),
        Kill {
            disposition: Disposition::Leave,
            tree: None,
        },
        None,
    );
    assert_eq!(torn.fate(), ChildFate::Unknown, "{torn:?}");
    assert_eq!(fake.looks(), 1, "the teardown made the wait that failed");
}