cosca 0.10.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
//! Windows fixtures for the tests that prove a `CTRL_BREAK` arrived: a re-exec'd member with a
//! chosen console-ctrl disposition, optionally the root of a grandchild in its own console process
//! group, and the caller's side of its handshake.
//!
//! A break lands asynchronously, and the OS runs a console handler on a thread it creates in the
//! target, so "did it see a break yet?" has no answer a caller can trust. The tests built on these
//! assert first that the break was sent to the expected group ([`assert_break_sent_to`], which reads
//! the sender's own record) and only then wait, with no deadline, for the member's own evidence:
//! its handler's ack, or its exit code. A call that sent nothing fails that assertion instead of
//! leaving the wait unbounded, and nothing is released that could race the break. The sender must
//! therefore run in a process of this binary: a probe in another binary has no record to read.

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};

use super::{accept_or_die, ack, fixture_argv, Console, IDENTITY_READ};
use crate::containment::windows::observe::CtrlSend;
use crate::stop::proxy::protocol::{CtrlEvent, ProxyAnswer};

pub(crate) mod console_less;
pub(crate) mod nested;

/// The fully-qualified libtest path of [`fixture_ctrl_break_member`].
pub(crate) const MEMBER_TEST: &str = "test_child::ctrl_break::fixture_ctrl_break_member";

/// The `127.0.0.1:<port>` address the member connects to. Its presence also tells the fixture it
/// was re-exec'd deliberately rather than picked up by an ordinary suite run.
const ADDR_ENV: &str = "COSCA_FIXTURE_CTRL_BREAK_ADDR";
/// The member's tag byte: `R` for a root, `G` for the grandchild it starts.
const TAG_ENV: &str = "COSCA_FIXTURE_CTRL_BREAK_TAG";
/// The member's [`Handler`].
const HANDLER_ENV: &str = "COSCA_FIXTURE_CTRL_BREAK_HANDLER";
/// Set on a root: the [`Handler`] of the grandchild it starts.
const GRANDCHILD_ENV: &str = "COSCA_FIXTURE_CTRL_BREAK_GRANDCHILD";

/// How a member answers a console control event.
#[derive(Clone, Copy)]
pub(crate) enum Handler {
    /// No handler: a delivered break ends it with [`STATUS_CONTROL_C_EXIT`].
    Default,
    /// Writes `B` to its control socket on `CTRL_BREAK` and keeps running.
    Ack,
    /// [`Ack`](Handler::Ack), and writes `C` on `CTRL_C`, so the ack says which event arrived. It
    /// clears "Ctrl+C is ignored" for itself, which a process inherits from a parent that has it
    /// set and a group's leader is created with, so a `CTRL_C` always reaches its handler.
    AckEvent,
    /// Handles every event and keeps running, so only a kill ends it.
    Ignore,
}

impl Handler {
    fn name(self) -> &'static str {
        match self {
            Handler::Default => "default",
            Handler::Ack => "ack",
            Handler::AckEvent => "ack-event",
            Handler::Ignore => "ignore",
        }
    }
}

/// The exit code of a process a delivered `CTRL_BREAK` ended through the default disposition. A
/// kill gives `1`, and a break that lands before the process could handle it `0xC0000142`.
pub(crate) const STATUS_CONTROL_C_EXIT: i32 = 0xC000_013A_u32 as i32;

/// The argv of a re-exec'd [`fixture_ctrl_break_member`]; see [`fixture_argv`].
pub(crate) fn member_argv() -> [&'static str; 5] {
    fixture_argv(MEMBER_TEST)
}

/// The environment of a root member that connects to `addr`, answers with `handler`, and starts a
/// grandchild answering with `grandchild` when given. Apply it after
/// [`scrub_env`](crate::test_reexec::scrub_env).
pub(crate) fn member_env(addr: &str, handler: Handler, grandchild: Option<Handler>) -> Vec<(&'static str, String)> {
    let mut env = vec![
        (ADDR_ENV, addr.to_owned()),
        (TAG_ENV, "R".to_owned()),
        (HANDLER_ENV, handler.name().to_owned()),
        (ack::ACK_ENV, "1".to_owned()),
    ];
    if let Some(grandchild) = grandchild {
        env.push((GRANDCHILD_ENV, grandchild.name().to_owned()));
    }
    env
}

/// Connects, installs its [`Handler`], writes its tag, and blocks on a read of its socket until the
/// caller closes it (then exits 0) or something ends it. A root with [`GRANDCHILD_ENV`] set starts
/// that grandchild after its tag, with no creation flags (`Console::Asked`: not the test helpers'
/// default `CREATE_NO_WINDOW`, which would give it a console of its own), so it stays in the root's
/// console process group, and then writes the grandchild's pid (4 bytes, little-endian). The grandchild connects to
/// the same address with tag `G`. The root holds the grandchild's process handle while it lives, so
/// the pid stays the grandchild's.
///
/// The tag is the readiness edge: the member cannot write it before it runs its own code, which on
/// Windows is also after the console has registered it and after its handler is installed.
#[skuld::test]
fn fixture_ctrl_break_member() {
    let Some(addr) = std::env::var_os(ADDR_ENV) else {
        return; // picked up by an ordinary suite run — deliberately inert
    };
    let addr = addr.into_string().expect("utf8 addr");
    let tag = std::env::var(TAG_ENV).expect("the member's tag");
    let mut sock = ack::connect_control(&addr).expect("connect the control socket");
    let handler = std::env::var(HANDLER_ENV).expect("the member's handler");
    match handler.as_str() {
        "default" => {}
        "ack" => install_ack(&sock, false),
        "ack-event" => install_ack(&sock, true),
        "ignore" => install_ignore(),
        other => panic!("unknown handler {other:?}"),
    }
    sock.write_all(tag.as_bytes()).expect("write the tag");
    let _grandchild = std::env::var(GRANDCHILD_ENV).ok().map(|handler| {
        let grandchild = crate::test_spawn::spawn_with(
            crate::test_reexec::command(std::env::current_exe().expect("current_exe"))
                // `[1..]`: skip `fixture_argv`'s slot-0 placeholder; `std::process::Command` supplies argv[0].
                .args(&member_argv()[1..])
                .env(TAG_ENV, "G")
                .env(HANDLER_ENV, handler)
                .env_remove(GRANDCHILD_ENV)
                .stdout(std::process::Stdio::null()),
            0,
            crate::test_spawn::console_flags::Console::Asked,
        )
        .expect("spawn the grandchild");
        sock.write_all(&grandchild.id().to_le_bytes())
            .expect("report the grandchild's pid");
        grandchild
    });
    sock.flush().expect("flush");
    let mut sink = [0u8; 1];
    _ = sock.read(&mut sink);
}

/// Acks a `CTRL_BREAK` by writing `B` through a clone of `sock`, and keeps the process running. Only
/// `CTRL_BREAK` is acked, so a stray `CTRL_C` or `CTRL_CLOSE` cannot pass for it. With `names_event`
/// a `CTRL_C` is acked too, by `C`, and "Ctrl+C is ignored" is cleared for this process.
fn install_ack(sock: &TcpStream, names_event: bool) {
    use std::sync::{Mutex, OnceLock};

    use windows::core::BOOL;
    use windows::Win32::System::Console::{SetConsoleCtrlHandler, CTRL_BREAK_EVENT, CTRL_C_EVENT};

    // The handler runs on a thread the OS creates, not in signal context, so allocating I/O is
    // fine. Nothing in it may panic: unwinding out of an `extern "system"` fn aborts.
    static ACK: OnceLock<(Mutex<TcpStream>, bool)> = OnceLock::new();
    unsafe extern "system" fn ack(event: u32) -> BOOL {
        let byte = match event {
            CTRL_BREAK_EVENT => b'B',
            CTRL_C_EVENT if ACK.get().is_some_and(|(_, names_event)| *names_event) => b'C',
            _ => return BOOL(0), // not handled: the default disposition applies
        };
        let Some(Ok(mut sock)) = ACK.get().map(|(sock, _)| sock.lock()) else {
            return BOOL(0);
        };
        match sock.write_all(&[byte]).and_then(|()| sock.flush()) {
            Ok(()) => BOOL(1), // handled: keep running
            Err(_) => BOOL(0),
        }
    }
    ACK.set((
        Mutex::new(sock.try_clone().expect("clone the control socket")),
        names_event,
    ))
    .expect("one handler per process");
    // SAFETY: installing a console ctrl handler has no preconditions.
    unsafe { SetConsoleCtrlHandler(Some(ack), true) }.expect("install the ctrl handler");
    if names_event {
        // SAFETY: as above; a null routine with `false` clears this process's "ignore Ctrl+C".
        unsafe { SetConsoleCtrlHandler(None, false) }.expect("clear the Ctrl+C ignore");
    }
}

/// Handles every console control event, so the process keeps running.
fn install_ignore() {
    use windows::core::BOOL;
    use windows::Win32::System::Console::SetConsoleCtrlHandler;

    unsafe extern "system" fn ignore(_event: u32) -> BOOL {
        BOOL(1)
    }
    // SAFETY: installing a console ctrl handler has no preconditions.
    unsafe { SetConsoleCtrlHandler(Some(ignore), true) }.expect("install the ctrl handler");
}

// The caller's side =====

/// A [`fixture_ctrl_break_member`] root answering with `handler`, after its handshake, and the
/// grandchild it starts in its console process group when `grandchild` is given. It is spawned
/// contained (`mode`), or as a nested member when the caller is itself contained; `configure` is
/// applied to the command last. The root's socket keeps it running while held.
pub(crate) fn spawn_member(
    handler: Handler,
    grandchild: Option<Handler>,
    mode: crate::ContainMode,
    configure: impl FnOnce(&mut crate::Command),
) -> (crate::Child, TcpStream, Option<Grandchild>) {
    spawn_member_with(handler, grandchild, Some(mode), configure)
}

/// [`spawn_member`] for a member that is not contained.
pub(crate) fn spawn_uncontained_member(
    handler: Handler,
    configure: impl FnOnce(&mut crate::Command),
) -> (crate::Child, TcpStream) {
    let (child, sock, _) = spawn_member_with(handler, None, None, configure);
    (child, sock)
}

/// [`spawn_member`] with `mode` as the containment, or none.
fn spawn_member_with(
    handler: Handler,
    grandchild: Option<Handler>,
    mode: Option<crate::ContainMode>,
    configure: impl FnOnce(&mut crate::Command),
) -> (crate::Child, TcpStream, Option<Grandchild>) {
    let (listener, addr) = crate::test_child::registration_rendezvous();
    let mut cmd = crate::test_child::command(Console::Asked);
    cmd.executable(std::env::current_exe().expect("current_exe"))
        .args(member_argv());
    crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
    for (key, value) in member_env(&addr, handler, grandchild) {
        cmd.env(key, value);
    }
    if let Some(mode) = mode {
        cmd.contain_with(mode);
    }
    configure(&mut cmd);
    let child = cmd.spawn().expect("spawn the root");
    let mut sock = accept_root(&listener, child.id().expect(IDENTITY_READ));
    let grand = grandchild.map(|_| accept_grandchild(&listener, &mut sock));
    (child, sock, grand)
}

/// Require that `pid` shares our console, after its handshake: a break to a group outside it is
/// accepted and lost.
pub(crate) fn assert_in_our_console(pid: u32, who: &str) {
    assert_eq!(
        in_our_console(pid),
        Some(true),
        "{who} must share our console for the break to be deliverable"
    );
}

/// Read the `B` an acking member writes when its handler receives the break. Call it only after
/// [`assert_break_sent_to`]: the read has no deadline.
pub(crate) fn assert_acked(sock: &mut TcpStream, who: &str) {
    assert_acked_event(sock, who, CtrlEvent::CtrlBreak);
}

/// Read the byte an acking member writes when its handler receives `event` (`B` for a break, `C` for
/// Ctrl+C), and require that it is the one for `event`. The read has no deadline: call it only after
/// the call that sent the event has answered that it did.
pub(crate) fn assert_acked_event(sock: &mut TcpStream, who: &str, event: CtrlEvent) {
    let (byte, name) = match event {
        CtrlEvent::CtrlBreak => (b'B', "CTRL_BREAK"),
        CtrlEvent::CtrlC => (b'C', "CTRL_C"),
    };
    let mut ack = [0u8; 1];
    sock.read_exact(&mut ack)
        .unwrap_or_else(|e| panic!("{who} must acknowledge the {name}: {e}"));
    assert_eq!(ack, [byte], "{who} acked something other than {name}");
}

/// Accepts the root member `root` (death-watched) and reads its tag.
pub(crate) fn accept_root(listener: &TcpListener, root: crate::identity::ProcessId) -> TcpStream {
    accept_tagged(listener, root, b'R')
}

/// Accepts `root` (death-watched) and reads its tag, which must be `tag`.
pub(crate) fn accept_tagged(listener: &TcpListener, root: crate::identity::ProcessId, tag: u8) -> TcpStream {
    let mut sock = accept_or_die(listener, root);
    let mut got = [0u8; 1];
    sock.read_exact(&mut got).expect("the root's tag");
    assert_eq!(got, [tag], "wrong root tag");
    sock
}

/// Spawns the GUI-subsystem testbin as a contained root, and returns it with its control socket,
/// which keeps it running while held, after its handshake. Such an image never attaches to its
/// spawner's console, so it has none to detach: no break reaches it, with no console host
/// bookkeeping to wait for, and only a kill ends it. Its creation flags are the ordinary contained
/// ones, so the child records a group the flags do not put in a console of its own.
pub(crate) fn spawn_consoleless_root() -> (crate::Child, TcpStream) {
    spawn_gui_root(|_| {})
}

/// [`spawn_consoleless_root`], with `configure` applied to the command last.
pub(crate) fn spawn_gui_root(configure: impl FnOnce(&mut crate::Command)) -> (crate::Child, TcpStream) {
    let (listener, addr) = crate::test_child::registration_rendezvous();
    let mut cmd = crate::test_child::command(Console::Asked);
    gui_root_command(&mut cmd, &addr);
    configure(&mut cmd);
    let child = cmd.spawn().expect("spawn the GUI-subsystem root");
    let sock = accept_tagged(&listener, child.id().expect(IDENTITY_READ), b'G');
    (child, sock)
}

/// [`spawn_gui_root`] for the tokio `Child`.
#[cfg(feature = "tokio")]
pub(crate) async fn spawn_gui_root_async(
    configure: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, TcpStream) {
    let (listener, addr) = crate::test_child::registration_rendezvous();
    let mut cmd = crate::test_child::tokio_command(Console::Asked);
    gui_root_command(cmd.as_sync_mut(), &addr);
    configure(&mut cmd);
    let child = cmd.spawn().await.expect("spawn the GUI-subsystem root");
    let sock = accept_tagged(&listener, child.id().expect(IDENTITY_READ), b'G');
    (child, sock)
}

/// What a command needs to start the GUI-subsystem testbin as a contained root that reports to `addr`.
fn gui_root_command(cmd: &mut crate::Command, addr: &str) {
    // `args` is the whole argv, program name included.
    cmd.executable(super::testbin("cosca_testbin_gui"))
        .args(["cosca_testbin_gui", addr]);
    crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
    cmd.env(ack::ACK_ENV, "1");
    cmd.contain();
}

/// The grandchild a root member started: its control socket, which keeps it running while held,
/// and a handle on its process.
pub(crate) struct Grandchild {
    pub(crate) sock: TcpStream,
    pub(crate) exit: ExitWatch,
}

/// Reads the grandchild's pid from the root's socket (after [`accept_root`]), opens its process,
/// then accepts its connection (death-watched) and reads its tag. The root holds the grandchild's
/// handle while it lives, and the caller holds the root's socket, so the pid cannot be reissued
/// before the open.
pub(crate) fn accept_grandchild(listener: &TcpListener, root_sock: &mut TcpStream) -> Grandchild {
    let mut pid = [0u8; 4];
    root_sock.read_exact(&mut pid).expect("the grandchild's pid");
    let pid = u32::from_le_bytes(pid);
    let exit = ExitWatch::open(pid);
    let id = crate::identity::ProcessId::of(pid)
        .found()
        .expect("the grandchild resolves while the root holds its handle");
    let mut sock = accept_or_die(listener, id);
    let mut tag = [0u8; 1];
    sock.read_exact(&mut tag).expect("the grandchild's tag");
    assert_eq!(&tag, b"G", "wrong grandchild tag");
    Grandchild { sock, exit }
}

/// A contained [`Handler::Ignore`] root after its handshake, and its control socket, which keeps it
/// running while held (it leaves with 0 once the socket closes). For a test whose root only a kill
/// ends and which sends a break first: the handshake is the readiness edge, so the break cannot land
/// before the root could handle it.
pub(crate) fn spawn_ignoring_root() -> (crate::Child, TcpStream) {
    let (child, sock, _) = spawn_member(Handler::Ignore, None, crate::ContainMode::Strongest, |_| {});
    (child, sock)
}

/// [`spawn_member`] for the tokio `Child`, which is not contained when `mode` is `None`.
#[cfg(feature = "tokio")]
pub(crate) async fn spawn_member_async(
    handler: Handler,
    grandchild: Option<Handler>,
    mode: Option<crate::ContainMode>,
    configure: impl FnOnce(&mut crate::tokio::Command),
) -> (crate::tokio::Child, TcpStream, Option<Grandchild>) {
    let (listener, addr) = crate::test_child::registration_rendezvous();
    let mut cmd = crate::test_child::tokio_command(Console::Asked);
    cmd.executable(std::env::current_exe().expect("current_exe"))
        .args(member_argv());
    crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
    for (key, value) in member_env(&addr, handler, grandchild) {
        cmd.env(key, value);
    }
    if let Some(mode) = mode {
        cmd.contain_with(mode);
    }
    configure(&mut cmd);
    let child = cmd.spawn().await.expect("spawn the root");
    let mut sock = accept_root(&listener, child.id().expect(IDENTITY_READ));
    let grand = grandchild.map(|_| accept_grandchild(&listener, &mut sock));
    (child, sock, grand)
}

/// Assert that the call under test sent exactly one `CTRL_BREAK`, to the group led by `group`.
pub(crate) fn assert_break_sent_to(group: u32) {
    assert_eq!(
        crate::containment::windows::observe::take_ctrl_sends(),
        [CtrlSend::Direct { group }],
        "the call must send one CTRL_BREAK, to the group led by {group}"
    );
}

/// Assert that the call under test asked the proxy to send `event` to the console of `target`, and
/// that the proxy answered `answer`, and nothing else was sent.
pub(crate) fn assert_proxy_answered(target: u32, event: CtrlEvent, answer: ProxyAnswer) {
    assert_eq!(
        crate::containment::windows::observe::take_ctrl_sends(),
        [CtrlSend::Proxy { target, event, answer }],
        "the call must record one answer of the proxy, for {event:?} to {target}"
    );
}

/// Assert that no console event was sent since the last read of the sender's record, directly or
/// through the proxy. This, and not a target's silence, is what shows an op sent nothing.
pub(crate) fn assert_no_break_sent() {
    assert_eq!(
        crate::containment::windows::observe::take_ctrl_sends(),
        Vec::<CtrlSend>::new(),
        "the call must send no console event"
    );
}

/// Assert that `err` is the direct send's refusal of a child that leads no console process group
/// (`Unsupported`, naming `Command::new_process_group`), and that
/// nothing was sent since the last read of the sender's record, directly or through the proxy.
#[track_caller]
pub(crate) fn assert_refused_by_the_direct_send_for_no_group(err: &crate::error::Error) {
    let crate::error::Error::Unsupported { detail, .. } = err else {
        panic!("expected Unsupported, got {err:?}")
    };
    assert!(detail.contains("leads no console process group"), "{detail}");
    assert!(detail.contains("Command::new_process_group"), "{detail}");
    assert_no_break_sent();
}

/// Kill the member (its whole tree when `tree`), then release it: a released member leaves with 0,
/// so code 1 is the kill's.
pub(crate) fn kill_release_reap(child: &crate::Child, sock: TcpStream, tree: bool) {
    if tree {
        child.kill_tree().expect("kill_tree");
    } else {
        child.kill().expect("kill");
    }
    drop(sock);
    let status = child.wait().expect("reap");
    assert_eq!(status.code(), Some(1), "the kill must end the member, got {status:?}");
}

/// [`kill_release_reap`] for the tokio `Child`.
#[cfg(feature = "tokio")]
pub(crate) async fn kill_release_reap_async(child: &mut crate::tokio::Child, sock: TcpStream, tree: bool) {
    if tree {
        child.kill_tree().await.expect("kill_tree");
    } else {
        child.kill().expect("kill");
    }
    drop(sock);
    let status = child.wait().await.expect("reap");
    assert_eq!(status.code(), Some(1), "the kill must end the member, got {status:?}");
}

/// What a reporter writes once every check passed. Anything else read before EOF, or none, means
/// it did not get that far: it panicked, or its filter matched no test.
pub(crate) const DONE: &[u8] = b"K";

/// A reporter's side of [`drive_reporter`]: connects to the driver at the address in `addr_env`
/// first, so a panic later reaches the driver as EOF. `None` when `addr_env` is unset: the fixture
/// was picked up by an ordinary suite run and stays inert.
pub(crate) fn connect_reporter(addr_env: &str) -> Option<TcpStream> {
    let addr = std::env::var_os(addr_env)?.into_string().expect("utf8 addr");
    Some(ack::connect_control(&addr).expect("connect to the driver"))
}

/// A reporter's last act: [`DONE`], after every check passed.
pub(crate) fn report_done(report: &mut TcpStream) {
    report.write_all(DONE).expect("report");
    report.flush().expect("flush the report");
}

/// The driver of a reporter: a re-exec of this binary running the fixture `test`, which finds the
/// driver's address in `addr_env` (see [`connect_reporter`]). `configure` is applied to the
/// command last. Passes only if the reporter wrote [`DONE`] and exited 0.
pub(crate) fn drive_reporter(test: &str, addr_env: &str, configure: impl FnOnce(&mut crate::Command)) {
    let (listener, addr) = crate::test_child::registration_rendezvous();
    let mut cmd = crate::test_child::command(Console::Asked);
    cmd.executable(std::env::current_exe().expect("current_exe"))
        .args(fixture_argv(test))
        .env(addr_env, addr)
        .env(ack::ACK_ENV, "1");
    crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
    configure(&mut cmd);
    let child = cmd.spawn().expect("spawn the reporter");
    let mut sock = accept_or_die(&listener, child.id().expect(IDENTITY_READ));
    let mut report = Vec::new();
    sock.read_to_end(&mut report).expect("read the report");
    assert_eq!(
        report, DONE,
        "the reporter did not finish its checks; its panic is in its stderr"
    );
    let status = child.wait().expect("reap the reporter");
    assert!(status.success(), "the reporter failed: {status:?}");
}

/// Is `pid` attached to our console? `None` when the probe found no console at all. A break to a
/// group outside our console is accepted and delivered to no one, so a test that waits for a
/// delivered break first requires `Some(true)`, after the member's handshake.
pub(crate) fn in_our_console(pid: u32) -> Option<bool> {
    crate::stop::proxy::run::console_holds(pid).ok()
}

/// A handle on a process that can wait for its exit and read its exit code. Dropping it terminates
/// the process if it still runs: the open handle pins the pid, so that reaches no other process.
pub(crate) struct ExitWatch(windows::Win32::Foundation::HANDLE);

impl ExitWatch {
    fn open(pid: u32) -> ExitWatch {
        use windows::Win32::System::Threading::{
            OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
        };
        // SAFETY: plain Win32 call; `Drop` closes the handle.
        let handle = unsafe {
            OpenProcess(
                PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE,
                false,
                pid,
            )
        }
        .unwrap_or_else(|e| panic!("OpenProcess({pid}): {e}"));
        ExitWatch(handle)
    }

    /// Block until the process has exited, then its exit code.
    pub(crate) fn wait_for_exit_code(&self) -> i32 {
        use windows::Win32::Foundation::WAIT_OBJECT_0;
        use windows::Win32::System::Threading::{GetExitCodeProcess, WaitForSingleObject, INFINITE};
        // SAFETY: `self.0` is a live handle this struct owns.
        let waited = unsafe { WaitForSingleObject(self.0, INFINITE) };
        assert_eq!(waited, WAIT_OBJECT_0, "waiting for the exit: {waited:?}");
        let mut code = 0u32;
        // SAFETY: as above; `code` is a valid out-pointer.
        unsafe { GetExitCodeProcess(self.0, &mut code) }.expect("GetExitCodeProcess");
        code as i32
    }
}

impl Drop for ExitWatch {
    fn drop(&mut self) {
        use windows::Win32::Foundation::CloseHandle;
        use windows::Win32::System::Threading::TerminateProcess;
        // SAFETY: `self.0` is a live handle this struct owns; an exited process makes this fail
        // harmlessly.
        _ = unsafe { TerminateProcess(self.0, 1) };
        // SAFETY: closes the handle `open` returned.
        let closed = unsafe { CloseHandle(self.0) };
        debug_assert!(closed.is_ok(), "CloseHandle: {closed:?}");
    }
}