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
//! `Command::spawn_suspended` and `SuspendedChild`, on real frozen children.
//!
//! Every Windows child is a windowless `more.com` blocker (no console window on a developer's
//! desktop), held by a pipe the test keeps, so it ends only when the code under test kills it.
//! `more.com` exits 0 on EOF, so a kill that sent nothing fails on how the child ended.

use static_assertions::assert_impl_all;

use crate::test_child::Console;

use crate::child::SuspendedChild;
#[cfg(not(windows))]
use crate::error::Error;

assert_impl_all!(SuspendedChild: Send);

/// What `spawn_suspended` is refused with off Windows.
#[cfg(not(windows))]
#[skuld::test]
fn spawn_suspended_is_unsupported_off_windows() {
    let mut cmd = crate::test_child::command(Console::Hidden);
    cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
    cmd.kill_on_drop(false);

    let err = cmd.spawn_suspended().expect_err("there is no frozen spawn here");

    let Error::Unsupported { op, .. } = &err else {
        panic!("expected Unsupported, got {err:?}");
    };
    assert_eq!(op, "spawn_suspended");
    assert!(!cmd.kill_on_drop_flag(), "the refusal must leave the command as it was");
}

#[cfg(windows)]
mod on_windows {
    use windows::Win32::Foundation::{CloseHandle, HANDLE};
    use windows::Win32::System::Threading::{
        OpenProcess, TerminateProcess, WaitForSingleObject, INFINITE, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
    };

    use super::Console;
    use crate::containment::windows::fault::{force_next, Step};
    use crate::error::{ChildFate, Error};
    use crate::test_frozen::{limit_flags, InitialThread, Remote, ResumeOnDrop};
    use crate::Containment;

    const ERROR_ACCESS_DENIED: u32 = 5;

    /// A windowless blocker that exits 0 once its stdin closes; `raw` routes it to the raw
    /// `CreateProcessW` backend by giving it an `executable()`.
    fn blocker(raw: bool) -> crate::Command {
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        if raw {
            cmd.executable(crate::test_child::BLOCKER_ARGV[0]);
        }
        cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
        cmd.stdout(crate::Stdio::null()).expect("stdout null");
        cmd.stderr(crate::Stdio::null()).expect("stderr null");
        cmd
    }

    /// Both spawn backends, so a backend that drops the hold fails its own leg.
    const BACKENDS: [bool; 2] = [false, true];

    /// [`blocker`] with a stdin whose write end the test holds, for a frozen child the test drops.
    fn held_blocker(raw: bool) -> (crate::Command, crate::PipeWriter) {
        let mut cmd = blocker(raw);
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        cmd.stdin(stdin).expect("stdin");
        (cmd, writer)
    }

    /// For a frozen child that the code under test tears down (a drop, a failed resume): release the
    /// stdin `writer` and resume the frozen thread after the teardown's kill. An unsent kill lets
    /// the blocker exit 0, which `assert_reaps_killed` rejects.
    fn release_at_teardown_kill(
        frozen: &crate::child::SuspendedChild,
        writer: crate::PipeWriter,
    ) -> crate::child::spawn::fault::TeardownBlocker {
        let thread = InitialThread::of(frozen.pid());
        crate::child::spawn::fault::release_at_drop_kill((writer, ResumeOnDrop(thread)))
    }

    /// Kill `child`, then release its stdin: it exits 0 on EOF, so an unsent kill shows.
    fn end(mut child: crate::Child) {
        let stdin = child.stdin().expect("the blocker's piped stdin");
        child.kill().expect("kill the resumed child");
        drop(stdin);
        crate::test_child::assert_killed("the resumed child", child.wait().expect("reap the resumed child"));
    }

    /// [`end`] for children alive at once. A child dropped while still holding its stdin blocks in
    /// the drop's wait, so every stdin is released before any assertion and before any child can
    /// drop: `stdins` is declared after `children`, so a panic anywhere unwinds it first.
    fn end_all(mut children: Vec<crate::Child>) {
        let stdins: Vec<_> = children
            .iter_mut()
            .map(|child| child.stdin().expect("the blocker's piped stdin"))
            .collect();
        for child in &mut children {
            child.kill().expect("kill the resumed child");
        }
        drop(stdins);
        for child in children {
            crate::test_child::assert_killed("the resumed child", child.wait().expect("reap the resumed child"));
        }
    }

    // Refusals =====

    #[skuld::test]
    fn spawn_suspended_with_elevate_is_unsupported_and_takes_nothing_from_the_command() {
        let mut cmd = blocker(false);
        cmd.elevate();

        let err = cmd.spawn_suspended().expect_err("a frozen spawn cannot be elevated");

        let Error::Unsupported { op, .. } = &err else {
            panic!("expected Unsupported, got {err:?}");
        };
        assert!(op.contains("elevate"), "{op}");
        assert!(
            cmd.fds().contains_key(&crate::Fd::STDIN),
            "a refusal before anything is taken must leave the stdio configuration in place"
        );
    }

    #[skuld::test]
    fn spawn_suspended_with_breakaway_and_contain_is_unsupported() {
        let mut cmd = blocker(false);
        cmd.contain().breakaway_from_job();

        let err = cmd.spawn_suspended().expect_err("breakaway and contain are refused");

        let Error::Unsupported { op, .. } = &err else {
            panic!("expected Unsupported, got {err:?}");
        };
        assert!(op.contains("breakaway_from_job"), "{op}");
    }

    // The window =====

    /// Suspend count 1 is the kernel's statement that the initial thread has run nothing.
    #[skuld::test]
    fn frozen_child_has_executed_no_instruction_before_resume() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().expect("spawn suspended");
            let thread = InitialThread::of(frozen.pid());
            assert_eq!(thread.suspend_count(), 1, "raw={raw}: frozen until resumed");

            let child = frozen.resume().expect("resume");

            assert_eq!(thread.suspend_count(), 0, "raw={raw}: running after resume");
            end(child);
        }
    }

    /// Something else started a running thread in the frozen child (an EDR agent, a debugger): the
    /// initial thread is still frozen exactly once, so the resume goes through, contained or not.
    #[skuld::test]
    fn resume_succeeds_when_another_party_started_a_running_thread_in_the_frozen_child() {
        for raw in BACKENDS {
            for contain in [false, true] {
                let mut cmd = blocker(raw);
                if contain {
                    cmd.contain();
                }
                let frozen = cmd.spawn_suspended().expect("spawn suspended");
                let _injected = crate::test_frozen::inject_running_thread_into_pid(frozen.pid());

                let child = frozen.resume().unwrap_or_else(|e| {
                    panic!("raw={raw} contain={contain}: a running second thread failed the resume: {e:?}")
                });

                end(child);
            }
        }
    }

    #[skuld::test]
    fn id_recorded_while_frozen_equals_the_resumed_childs_id() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().expect("spawn suspended");
            let recorded = frozen.id().expect(crate::test_child::IDENTITY_READ);

            let child = frozen.resume().expect("resume");

            assert_eq!(child.id(), Some(recorded), "raw={raw}");
            end(child);
        }
    }

    #[skuld::test]
    fn contained_frozen_child_is_inside_its_job_before_resume() {
        for raw in BACKENDS {
            let mut cmd = blocker(raw);
            cmd.contain();
            let frozen = cmd.spawn_suspended().expect("spawn suspended");
            assert!(
                frozen.test_job_handle_contains_self(),
                "raw={raw}: in its job while frozen"
            );

            let child = frozen.resume().expect("resume");

            assert_eq!(child.containment(), Containment::JobObject, "raw={raw}");
            assert!(child.test_job_handle_contains_self(), "raw={raw}");
            end(child);
        }
    }

    #[skuld::test]
    fn uncontained_frozen_child_has_no_cosca_job_and_reports_containment_none() {
        for raw in BACKENDS {
            let frozen = blocker(raw).spawn_suspended().expect("spawn suspended");
            assert!(!frozen.test_job_handle_contains_self(), "raw={raw}: no containment job");
            assert_eq!(frozen.test_containment(), Containment::None, "raw={raw}");

            let child = frozen.resume().expect("resume");

            assert_eq!(child.containment(), Containment::None, "raw={raw}");
            end(child);
        }
    }

    /// The resumed child is armed as a `spawn()` child is, or not, as the command said.
    #[skuld::test]
    fn resumed_child_takes_the_commands_kill_on_drop() {
        for kill_on_drop in [true, false] {
            let mut cmd = blocker(false);
            cmd.contain().kill_on_drop(kill_on_drop);

            let child = cmd
                .spawn_suspended()
                .expect("spawn suspended")
                .resume()
                .expect("resume");

            assert_eq!(child.kill_on_drop, kill_on_drop);
            let Some(job) = child.tree.job_for_test() else {
                panic!("expected a job, got {:?}", child.tree);
            };
            let kills_on_close =
                limit_flags(job).0 & windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0 != 0;
            assert_eq!(kills_on_close, kill_on_drop, "kill_on_drop({kill_on_drop})");
            end(child);
        }
    }

    /// The command's `kill_on_drop` decides what dropping the resumed `Child` does, for every
    /// containment: a resumed child that kept the frozen spawn's forced `true` would be killed by a
    /// command that opted out.
    ///
    /// The `true` leg releases the child's stdin only once the drop's kill returned, so it dies with
    /// the kill's exit code or the leg fails by assertion; the `false` leg keeps the writer, so no EOF
    /// can end the child, and a drop that kills regardless fails that leg's check.
    #[skuld::test]
    fn death_watch_dropping_a_resumed_child_follows_the_commands_kill_on_drop_for_every_containment() {
        for (shape, contain) in [
            ("uncontained", None),
            ("treewalk", Some(crate::ContainMode::TreeWalk)),
            ("strongest", Some(crate::ContainMode::Strongest)),
        ] {
            for kill_on_drop in [true, false] {
                let mut cmd = blocker(false);
                if let Some(mode) = contain {
                    cmd.contain_with(mode);
                }
                cmd.kill_on_drop(kill_on_drop);
                let (stdin, writer) = crate::test_child::held_writer_stdin();
                cmd.stdin(stdin).expect("stdin");
                // Armed legs release the writer once the drop's kill returned; the others keep it,
                // so only a kill could end the child.
                let (teardown, held) = if kill_on_drop {
                    (Some(crate::child::spawn::fault::release_at_drop_kill(writer)), None)
                } else {
                    (None, Some(writer))
                };
                let child = cmd
                    .spawn_suspended()
                    .expect("spawn suspended")
                    .resume()
                    .expect("resume");
                assert_eq!(child.kill_on_drop, kill_on_drop, "{shape}");
                let remote = Remote::open(child.pid());

                drop(child);

                if let Some(teardown) = teardown {
                    remote.wait_for_death();
                    teardown.assert_reaps_killed();
                } else {
                    assert!(
                        !remote.is_dead_now(),
                        "{shape}: kill_on_drop(false) must leave the resumed child running"
                    );
                    remote.end();
                }
                drop(held);
            }
        }
    }

    // Refusals before anything exists =====

    /// A program that does not exist is the plain spawn error, not `MayHaveStarted`, and the command
    /// is as it was: the borrowed `kill_on_drop` and suspended request are put back.
    #[skuld::test]
    fn spawn_suspended_of_a_nonexistent_program_returns_the_plain_error_and_leaves_the_command_as_it_was() {
        for raw in BACKENDS {
            for kill_on_drop in [true, false] {
                let mut cmd = crate::test_child::command(Console::Hidden);
                cmd.args(["cosca-49-no-such-program.exe"]);
                if raw {
                    cmd.executable("cosca-49-no-such-program.exe");
                }
                cmd.kill_on_drop(kill_on_drop);

                let err = cmd.spawn_suspended().expect_err("there is no such program");

                assert!(err.fate().is_none(), "raw={raw}: nothing started, got {err:?}");
                assert!(matches!(err, Error::Io(_)), "raw={raw}: got {err:?}");
                assert_eq!(cmd.kill_on_drop_flag(), kill_on_drop, "raw={raw}");
                assert!(!cmd.flags_request().suspended, "raw={raw}");
            }
        }
    }

    // Drop =====

    /// A dropped frozen child is killed by the `Child` teardown whatever `kill_on_drop` says, for every
    /// containment: the uncontained and `TreeWalk` shapes have no job to end it, so the teardown's
    /// own kill is all that does. It is released and resumed after the teardown's kill (see
    /// `release_at_teardown_kill`), so a drop that does not kill fails the exit-code assertion. The
    /// teardown count shows the drop ran the `Child` teardown, not the job's asynchronous close.
    #[skuld::test]
    fn death_watch_dropping_a_frozen_child_kills_it_whatever_kill_on_drop_says() {
        for (shape, contain) in [
            ("uncontained", None),
            ("treewalk", Some(crate::ContainMode::TreeWalk)),
            ("strongest", Some(crate::ContainMode::Strongest)),
        ] {
            for kill_on_drop in [false, true] {
                let (mut cmd, writer) = held_blocker(false);
                if let Some(mode) = contain {
                    cmd.contain_with(mode);
                }
                cmd.kill_on_drop(kill_on_drop);
                let frozen = cmd.spawn_suspended().expect("spawn suspended");
                // Released and resumed after the drop's kill.
                let teardown = release_at_teardown_kill(&frozen, writer);
                let remote = Remote::open(frozen.pid());
                let teardowns = crate::child::owned::seams::record_root_teardowns();

                drop(frozen);

                remote.wait_for_death();
                assert_eq!(teardowns.count(), 1, "{shape}, kill_on_drop({kill_on_drop})");
                teardown.assert_reaps_killed();
            }
        }
    }

    /// Piped stdout and stderr on a dropped frozen child neither hang the drop nor keep the child
    /// alive.
    #[skuld::test]
    fn death_watch_dropping_a_frozen_child_with_piped_stdio_kills_it_without_hanging() {
        for raw in BACKENDS {
            let (mut cmd, writer) = held_blocker(raw);
            cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
            let frozen = cmd.spawn_suspended().expect("spawn suspended");
            // Released and resumed after the drop's kill.
            let teardown = release_at_teardown_kill(&frozen, writer);
            let remote = Remote::open(frozen.pid());

            drop(frozen);

            remote.wait_for_death();
            teardown.assert_reaps_killed();
        }
    }

    // Failure =====

    #[skuld::test]
    fn a_failed_thread_resume_kills_the_child_and_reports_its_fate() {
        let (mut cmd, writer) = held_blocker(false);
        let frozen = cmd.spawn_suspended().expect("spawn suspended");
        let id = frozen.id().expect(crate::test_child::IDENTITY_READ);
        let teardown = release_at_teardown_kill(&frozen, writer);
        let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);

        let err = frozen.resume().expect_err("the resume was forced to fail");
        drop(forced);

        assert!(matches!(err.fate(), Some(ChildFate::Reaped)), "got {err:?}");
        assert_eq!(
            crate::error::first_os_code(&err),
            Some(ERROR_ACCESS_DENIED as i32),
            "{err:?}"
        );
        assert_eq!(id.is_alive(), crate::identity::Liveness::Dead);
        teardown.assert_reaps_killed();
    }

    /// The failed resume of a frozen child reported as a launch that leaves no front does not say it
    /// is a front's.
    ///
    /// Mutants: `resume` sets the flag from `report.is_some()` or from `TrackedKind::runs_as_another_user`.
    #[skuld::test]
    fn a_failed_resume_of_a_child_without_a_front_sets_no_wrapper_flag() {
        use crate::elevation::elevation_tests::{report, VIAS_WITHOUT_A_FRONT};
        for via in VIAS_WITHOUT_A_FRONT {
            let (mut cmd, writer) = held_blocker(false);
            cmd.set_elevation_report(Some(report(via.clone())));
            let frozen = cmd.spawn_suspended().expect("spawn suspended");
            let teardown = release_at_teardown_kill(&frozen, writer);
            let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);

            let err = frozen.resume().expect_err("the resume was forced to fail");
            drop(forced);

            assert!(
                matches!(
                    err,
                    Error::MayHaveStarted {
                        wrapper_elevated: false,
                        ..
                    }
                ),
                "{via:?}: {err:?}"
            );
            teardown.assert_reaps_killed();
        }
    }

    /// A failed resume whose teardown cannot kill the frozen child leaves it, warned, and hands
    /// nothing back: a child whose initial thread may never run would block an `Unreaped` for ever.
    ///
    /// Mutant: `resume` hands the child back.
    #[skuld::test]
    fn a_failed_resume_of_a_child_whose_kill_is_refused_leaves_it() {
        crate::log_capture::install();
        let (mut cmd, writer) = held_blocker(false);
        let mut frozen = cmd.spawn_suspended().expect("spawn suspended");
        let id = frozen.id().expect(crate::test_child::IDENTITY_READ);
        let remote = Remote::open(id.pid());
        let release = (writer, ResumeOnDrop(InitialThread::of(id.pid())));
        frozen
            .child
            .proc
            .script_over(|f| f.signals([Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))]));
        let forced = force_next(Step::Resume, ERROR_ACCESS_DENIED);
        let mark = crate::log_capture::mark();

        let err = frozen.resume().expect_err("the resume was forced to fail");
        drop(forced);

        let (_, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, release);
        assert_eq!(fate, ChildFate::Running { id: Some(id) });
        assert!(handed_back.is_none(), "resume hands nothing back");
        let warns = crate::log_capture::records_since_on_current_thread(mark, "leaving it running");
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(warns[0].1.starts_with("teardown after a failed run: "), "{warns:?}");
        // The frozen thread runs and the blocker's stdin closes, so the blocker exits.
        drop(handed_back);
        remote.wait_for_death();
    }

    /// A frozen child that wants `kill_on_drop(false)` and whose job refuses the disarm, with the
    /// write end of its stdin.
    fn frozen_with_a_refusing_job() -> (crate::child::SuspendedChild, crate::PipeWriter) {
        let (mut cmd, writer) = held_blocker(false);
        let mut frozen = cmd.spawn_suspended().expect("spawn suspended");
        frozen.child.tree = crate::containment::Tree::contained(crate::containment::Mechanism::Job(
            crate::containment::windows::JobHandle::create_without_set_access_for_test(),
        ));
        frozen.wanted_kill_on_drop = false;
        (frozen, writer)
    }

    #[track_caller]
    fn assert_access_denied(error: &Error) {
        let Error::Io(io) = error else {
            panic!("expected Io, got {error:?}");
        };
        assert_eq!(io.raw_os_error(), Some(ERROR_ACCESS_DENIED as i32), "{io:?}");
    }

    /// `resume` of a `kill_on_drop(false)` child whose job refuses the disarm fails with the
    /// refusal as its cause, and the child is dead.
    ///
    /// Mutant: `resume` ignores the commit's failure and returns the child.
    #[skuld::test]
    fn resume_whose_disarm_is_refused_fails_and_kills_the_child() {
        let (frozen, writer) = frozen_with_a_refusing_job();
        let id = frozen.id().expect(crate::test_child::IDENTITY_READ);

        let err = frozen.resume().expect_err("the disarm was refused");

        let (cause, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, writer);
        assert_access_denied(&cause);
        assert_eq!(fate, ChildFate::Reaped);
        assert!(handed_back.is_none(), "the kill worked, so nothing is handed back");
        assert_eq!(id.is_alive(), crate::identity::Liveness::Dead);
    }

    /// The same refusal with the teardown's kill refused too: the still-running child is handed
    /// back to settle, the one arm of `resume` that does.
    ///
    /// Mutant: `resume` hands nothing back after a successful release.
    #[skuld::test]
    fn resume_whose_disarm_and_kill_are_refused_hands_the_child_back() {
        let (mut frozen, writer) = frozen_with_a_refusing_job();
        let id = frozen.id().expect(crate::test_child::IDENTITY_READ);
        frozen
            .child
            .proc
            .script_over(|f| f.signals([Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))]));

        let err = frozen.resume().expect_err("the disarm was refused");

        let (cause, fate, handed_back) = crate::test_child::expect_may_have_started_parts(err, writer);
        assert_access_denied(&cause);
        assert_eq!(fate, ChildFate::Running { id: Some(id) });
        assert!(!handed_back.is_none(), "resume handed no child back");
        // Releasing the stdin ends the blocker: it exits 0 on EOF.
        handed_back.wait();
    }

    /// Something else killed the frozen process. The process is observed dead (its handle is
    /// signalled) before `resume`, so the answer is not a race with the kill: an error with a fate,
    /// and no hang.
    #[skuld::test]
    fn resume_after_an_external_kill_is_may_have_started_with_a_fate() {
        let frozen = blocker(false).spawn_suspended().expect("spawn suspended");
        // Opened while `frozen` holds the process, so the pid cannot name anything else.
        // SAFETY: plain Win32 calls; the handle is closed below.
        let victim: HANDLE = unsafe { OpenProcess(PROCESS_TERMINATE | PROCESS_SYNCHRONIZE, false, frozen.pid()) }
            .expect("open the frozen child");
        // SAFETY: `victim` is live.
        unsafe {
            TerminateProcess(victim, 1).expect("terminate the frozen child");
            // An event, not a timer: the process object signals when the process is gone.
            WaitForSingleObject(victim, INFINITE);
            _ = CloseHandle(victim);
        }

        let err = frozen.resume().expect_err("a dead child cannot be resumed");

        let fate = err
            .fate()
            .unwrap_or_else(|| panic!("expected MayHaveStarted, got {err:?}"));
        assert!(
            matches!(fate, ChildFate::Reaped | ChildFate::Killed | ChildFate::Gone),
            "{fate:?}"
        );
    }

    /// Something suspended the initial thread during the window. One resume would leave the child
    /// frozen, so `resume` must not return `Ok`.
    #[skuld::test]
    fn resume_when_the_initial_thread_was_suspended_twice_kills_the_child_instead_of_returning_ok() {
        let (mut cmd, writer) = held_blocker(false);
        let frozen = cmd.spawn_suspended().expect("spawn suspended");
        let id = frozen.id().expect(crate::test_child::IDENTITY_READ);
        let teardown = release_at_teardown_kill(&frozen, writer);
        InitialThread::of(id.pid()).suspend_once();

        let err = frozen.resume().expect_err("the child is still frozen after one resume");

        assert!(err.fate().is_some(), "got {err:?}");
        assert_eq!(id.is_alive(), crate::identity::Liveness::Dead);
        teardown.assert_reaps_killed();
    }

    // The command =====

    /// The spawn borrows `kill_on_drop` and the suspended request for its duration only.
    #[skuld::test]
    fn spawn_suspended_leaves_kill_on_drop_and_flags_as_they_were() {
        for kill_on_drop in [true, false] {
            let (mut cmd, writer) = held_blocker(false);
            cmd.kill_on_drop(kill_on_drop);
            let frozen = cmd.spawn_suspended().expect("spawn suspended");
            let teardown = release_at_teardown_kill(&frozen, writer);

            drop(frozen);

            assert_eq!(cmd.kill_on_drop_flag(), kill_on_drop);
            assert!(!cmd.flags_request().suspended);
            teardown.assert_reaps_killed();
        }
    }

    /// A command used for `spawn_suspended` and then for `spawn` yields a running child.
    #[skuld::test]
    fn the_command_spawns_an_ordinary_child_after_a_frozen_one() {
        let (mut cmd, writer) = held_blocker(false);
        let frozen = cmd.spawn_suspended().expect("spawn suspended");
        let teardown = release_at_teardown_kill(&frozen, writer);
        drop(frozen);
        teardown.assert_reaps_killed();

        // A spawn takes the stdio configuration out of the command. Without its own piped stdin the
        // second blocker would read the harness's stdin and, where that is at EOF, exit at once.
        cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
        cmd.stdout(crate::Stdio::null()).expect("stdout null");
        cmd.stderr(crate::Stdio::null()).expect("stderr null");
        let child = crate::child::spawn::spawn_uncommitted(
            &mut cmd,
            crate::child::spawn::policy::SpawnPolicy::SYNC,
            crate::identity::HostKernel,
        )
        .expect("an ordinary spawn");

        assert_eq!(
            InitialThread::of(child.pid()).suspend_count(),
            0,
            "the spawn after a frozen one must run"
        );
        end(child);
    }

    #[skuld::test]
    fn two_frozen_children_can_be_held_at_once_and_resumed_in_either_order() {
        for in_spawn_order in [true, false] {
            let a = blocker(false).spawn_suspended().expect("first");
            let b = blocker(false).spawn_suspended().expect("second");
            let (x, y) = if in_spawn_order { (a, b) } else { (b, a) };
            let (cx, cy) = (x.resume().expect("resume x"), y.resume().expect("resume y"));
            end_all(vec![cx, cy]);
        }
    }

    /// No lock is held across the window: an ordinary spawn completes while another child is frozen.
    #[skuld::test]
    fn spawning_while_another_child_is_frozen_does_not_block() {
        let (mut cmd, writer) = held_blocker(false);
        let frozen = cmd.spawn_suspended().expect("spawn suspended");
        let teardown = release_at_teardown_kill(&frozen, writer);
        let other = blocker(false).spawn().expect("an ordinary spawn while one is frozen");
        end(other);
        drop(frozen);
        teardown.assert_reaps_killed();
    }

    #[skuld::test]
    fn a_suspended_child_resumes_on_another_thread() {
        let frozen = blocker(false).spawn_suspended().expect("spawn suspended");
        let child = std::thread::spawn(move || frozen.resume().expect("resume on another thread"))
            .join()
            .expect("the resuming thread");
        end(child);
    }
}