cosca 0.5.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
//! A debugger stand-in for tests: a helper process that attaches to one of the test's own
//! children with `ptrace`, as a debugger would, so tests can drive the "child held by a tracer"
//! paths deterministically.
//!
//! The helper is a separate process, never the tracee's parent: attaching reparents the tracee
//! to the helper, which is the shape (`ECHILD` in the parent, the zombie handed back after the
//! tracer's reap) that a real debugger creates. It is a re-exec of this test binary, filtered to
//! [`uh_helper_entry`], and takes its inputs from env vars (libtest rejects unknown options):
//!
//! - `COSCA_UH_ROLE=helper` marks the re-exec; without it the `#[skuld::test]` is a no-op;
//! - `COSCA_UH_MODE` is `auto` or `hold` ([`Mode`]);
//! - `COSCA_UH_FORCE=<tag>:<directive>[,…]` injects results and events (transition tests only);
//! - `COSCA_UH_TRACE=1` adds a `state <name>` report on entry to every state (transition tests
//!   only);
//! - `COSCA_UH_MARKER` frames the reports.
//!
//! Its stdin is the *signal pipe*: the pid as a first `pid <n>` line, then one byte per signal,
//! and EOF to end the session. Its stdout is the *report pipe*. The state machine and its
//! transition table are in [`machine`].
//!
//! **Entitlement (measured on CI).** macOS refuses `ptrace` attach with `EPERM` to an ad-hoc
//! signed tracer unless the tracee carries `com.apple.security.get-task-allow` or the tracer
//! carries `com.apple.security.cs.debugger`. So the helper runs from a copy of this binary
//! ad-hoc signed with `cs.debugger`, made per helper in a temporary directory, which lets it
//! attach to any child of the test.
//!
//! **Contract: it behaves like a debugger, for the signals cosca's tests send.** A tracer owns
//! the tracee's signal delivery: XNU hands it every signal as a stop, except a `SIGKILL` sent
//! while the tracee is stopped, which lands on its next release. A `SIGKILL` the tracer does see
//! lands on release whatever the tracer passes on (xnu `kern_sig.c`, `psignal_internal` and
//! `issignal`). So the helper promises only what a debugger does, for the sequences its tests
//! drive:
//!
//! - It attaches, holds the tracee stopped under `S1:hold`, and continues it.
//! - It continues each stop and passes its signal on ([`machine`]'s **Signals**): `SIGTERM`,
//!   `SIGCONT` and `SIGKILL` at once; the first default-action `SIGTSTP` or `SIGTTIN` after the
//!   detach, unless a later `SIGCONT` drops it. The detached tracee is then stopped by that
//!   signal, or by the detach's own `SIGSTOP` (sometimes on macOS 26; see [`Report::Detached`]).
//! - It ends by detaching, by reaping the exited tracee (which hands the zombie back), or by
//!   exiting while tracing, where XNU kills the tracee.
//!
//! It does not promise, as no debugger does, to deliver a signal as an untraced process would
//! get it. Outside the contract, and not bugs:
//!
//! - a caught or ignored stop signal, which is kept and re-sent after the detach like a default
//!   one: a handler runs late, or never if the tracee exits while traced;
//! - a signal sent while another is pending or being passed on, or during the attach or
//!   detach: the helper's `SIGSTOP` clears a pending `SIGCONT`, and a `SIGCONT` cancels the
//!   `SIGSTOP` S2 or S4 waits for, so the helper waits on;
//! - a blocked or thread-directed signal;
//! - `SIGTSTP`, `SIGTTIN` or `SIGTTOU` in an orphaned process group, which XNU discards for a
//!   traced process.
//!
//! A test asserts the preconditions of each signal the contract passes on before it attaches
//! (`tracer_tests::assert_receives`), so a broken one fails instead of hanging. `SIGKILL` and
//! `SIGSTOP` have none.

use std::io::Write as _;

mod attach;
mod machine;
mod sys;

pub(crate) use attach::{attach_settled, settled_stop, AttachError};

const DEFAULT_MARKER: &str = "@@cosca-uh@@";

thread_local! {
    /// This thread's helpers launched and not yet reaped.
    static UNREAPED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

fn unreaped_helpers() -> usize {
    UNREAPED.get()
}

/// What the helper does once the traced tracee exits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mode {
    /// Reap it at once, handing the zombie back to the test.
    Auto,
    /// Report `exited` with the tracee a zombie on the helper's own list, and reap it only on
    /// the next signal byte or EOF.
    Hold,
}

impl Mode {
    fn as_env(self) -> &'static str {
        match self {
            Mode::Auto => "auto",
            Mode::Hold => "hold",
        }
    }
}

/// What ends a wait the helper reports with [`Report::Blocking`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Until {
    /// The signal pipe's EOF, among other events.
    Eof,
    /// Only the tracee's exit.
    Exit,
}

/// A report from the helper.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Report {
    /// The tracee is traced and running again.
    Attached,
    /// [`Mode::Hold`] only: the tracee has exited and is a zombie on the helper's list.
    Exited,
    /// The helper reaped the tracee, so XNU has handed the zombie back to the test.
    Reaped,
    /// The tracee is no longer traced and is the test's child again. Every signal that stopped
    /// it, but the `SIGSTOP`s the attach and the detach sent, was delivered: a stop signal is
    /// re-sent after the detach, unless a later `SIGCONT` cancelled it (see [`machine`]).
    /// Measured on CI: on macOS 15 the tracee runs, or is job-stopped by the re-sent signal; on
    /// macOS 26 it may instead stay stopped by the detach's `SIGSTOP`, against which XNU discards
    /// the re-sent one. So the test ends it with `SIGKILL` through its handle, which ends it
    /// either way.
    Detached,
    /// The protocol failed in `state`.
    Error { cause: Cause, state: String },
    /// `COSCA_UH_TRACE=1` only: entry into the named state.
    State(String),
    /// The helper is about to wait in `state` with no timeout.
    Blocking { state: String, until: Until },
}

/// Why an [`Report::Error`] happened.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Cause {
    /// A syscall failed with this errno.
    Errno(i32),
    /// An event arrived where the table allows none (`NOTE_EXIT`, `SIGNAL`, `EOF`).
    Event(String),
}

impl Report {
    fn parse(text: &str) -> Report {
        match text {
            "attached" => Report::Attached,
            "exited" => Report::Exited,
            "reaped" => Report::Reaped,
            "detached" => Report::Detached,
            _ => {
                if let Some(rest) = text.strip_prefix("error ") {
                    let (cause, state) = rest
                        .split_once(' ')
                        .unwrap_or_else(|| panic!("malformed tracer helper error report: {text:?}"));
                    let cause = match cause.parse() {
                        Ok(errno) => Cause::Errno(errno),
                        Err(_) => Cause::Event(cause.to_string()),
                    };
                    Report::Error {
                        cause,
                        state: state.to_string(),
                    }
                } else if let Some(name) = text.strip_prefix("state ") {
                    Report::State(name.to_string())
                } else if let Some(rest) = text.strip_prefix("blocking ") {
                    let until = match rest.rsplit_once(' ') {
                        Some((state, "eof")) => (state, Until::Eof),
                        Some((state, "exit")) => (state, Until::Exit),
                        _ => panic!("malformed tracer helper blocking report: {text:?}"),
                    };
                    Report::Blocking {
                        state: until.0.to_string(),
                        until: until.1,
                    }
                } else {
                    panic!("unrecognized tracer helper report: {text:?}")
                }
            }
        }
    }
}

/// The report pipe's reader. A report is a line carrying the marker, anywhere in it; every
/// other line (the helper's libtest banner, or its panic output) is echoed to stderr.
struct Reports {
    rx: std::io::BufReader<std::process::ChildStdout>,
    marker: String,
}

impl Reports {
    /// The next report, or `None` at EOF: the helper, the pipe's only writer, has exited.
    fn next(&mut self) -> Option<Report> {
        use std::io::BufRead as _;
        loop {
            let mut line = String::new();
            if self
                .rx
                .read_line(&mut line)
                .expect("read the tracer helper's report pipe")
                == 0
            {
                return None;
            }
            if let Some(text) = self.echo(&line) {
                return Some(Report::parse(text.trim()));
            }
        }
    }

    /// Reads to EOF without parsing, and stops at a read error: for a test that is already
    /// failing, where a panic would abort the process.
    fn discard_rest(&mut self) {
        use std::io::BufRead as _;
        let mut line = String::new();
        while self.rx.read_line(&mut line).is_ok_and(|n| n > 0) {
            self.echo(&line);
            line.clear();
        }
    }

    /// Echoes `line` to stderr, and returns the report text if it is one.
    fn echo<'l>(&self, line: &'l str) -> Option<&'l str> {
        let Some(idx) = line.find(self.marker.as_str()) else {
            if !line.trim().is_empty() {
                // One formatted argument, so one `write`: the helper shares this stderr.
                let echo = format!("tracer helper stdout: {line}");
                eprint!("{echo}");
            }
            return None;
        };
        let text = &line[idx + self.marker.len()..];
        let echo = format!("tracer helper report: {}\n", text.trim());
        eprint!("{echo}");
        Some(text)
    }
}

/// A running helper and its pipes. [`Session::finish`], or else its `Drop`, is the only
/// teardown: it closes the signal pipe, reads the report pipe to EOF (proof the helper has
/// exited), then reaps the helper through its own handle.
///
/// EOF ends the helper except while it waits for the tracee's exit (a `blocking <state> exit`
/// report). Dropping it there would wait on a tracee the test may keep alive, so the teardown
/// kills the helper instead, as it does for a test that is already failing, and then fails the
/// test naming the state. XNU kills a tracee its killed tracer still traced.
struct Session {
    helper: std::process::Child,
    signal_tx: Option<std::process::ChildStdin>,
    /// `None` once a test closes the report pipe (the EPIPE row's test).
    reports: Option<Reports>,
    /// The state of the last report read, if it was a wait for the tracee's exit.
    awaits_exit: Option<String>,
    finished: bool,
    /// Holds the signed copy the helper runs from; removed after the helper is reaped.
    _exe_dir: tempfile::TempDir,
    /// `!Send`: [`UNREAPED`] counts per thread, so the helper is reaped on the thread that
    /// launched it.
    _thread: std::marker::PhantomData<*const ()>,
}

impl Session {
    fn signal_tx(&mut self) -> &mut std::process::ChildStdin {
        self.signal_tx.as_mut().expect("the signal pipe is already closed")
    }

    fn next_report(&mut self) -> Option<Report> {
        let report = self.reports.as_mut().expect("the report pipe is already closed").next();
        self.awaits_exit = match &report {
            Some(Report::Blocking {
                state,
                until: Until::Exit,
            }) => Some(state.clone()),
            _ => None,
        };
        report
    }

    /// Tears the helper down (see [`Session`]) and returns its exit status.
    fn finish(&mut self) -> std::process::ExitStatus {
        debug_assert!(!self.finished, "the tracer helper is already torn down");
        self.finished = true;
        let panicking = std::thread::panicking();
        let stuck = self.awaits_exit.take();
        if panicking || stuck.is_some() {
            if let Err(e) = self.helper.kill() {
                eprintln!("could not kill the tracer helper: {e}");
            }
        }
        drop(self.signal_tx.take());
        if let Some(reports) = &mut self.reports {
            if panicking || stuck.is_some() {
                reports.discard_rest();
            } else {
                while reports.next().is_some() {}
            }
        }
        let status = self.helper.wait().expect("reap the tracer helper");
        debug_assert!(
            UNREAPED.get() > 0,
            "the tracer helper was reaped on a thread that did not launch it"
        );
        UNREAPED.set(UNREAPED.get() - 1);
        if let Some(state) = stuck {
            if !panicking {
                panic!(
                    "the test dropped the tracer helper while it waited in {state} for the tracee's \
                     exit, which EOF does not end; it was killed instead. Read its reports through \
                     the terminal one first"
                );
            }
        }
        status
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        let status = self.finish();
        // With its report pipe closed by the test, the helper's libtest fails to print its
        // summary, so only a helper that could report is held to a clean exit.
        if self.reports.is_some() && !std::thread::panicking() {
            assert!(
                status.success(),
                "the tracer helper failed ({status}); its output is above"
            );
        }
    }
}

/// A helper that has not been told its tracee yet (state S-1).
pub(crate) struct Pending {
    session: Session,
}

/// Launches a helper for client tests, without transition traces or injections.
pub(crate) fn start(mode: Mode) -> Pending {
    launch(mode, None)
}

/// Launches a helper with `COSCA_UH_TRACE=1` and the injections in `force`, for the transition
/// tests.
pub(crate) fn start_forced(mode: Mode, force: &str) -> Pending {
    launch(mode, Some(force))
}

fn launch(mode: Mode, force: Option<&str>) -> Pending {
    let exe_dir = tempfile::tempdir().expect("create a directory for the signed helper");
    let exe = debugger_signed_copy(exe_dir.path());
    let marker = DEFAULT_MARKER.to_string();
    let mut cmd = crate::test_reexec::command(exe);
    cmd.args(crate::test_reexec::fixture_args(crate::test_child::fixture_path!(
        uh_helper_entry
    )))
    .env("COSCA_UH_ROLE", "helper")
    .env("COSCA_UH_MODE", mode.as_env())
    .env("COSCA_UH_MARKER", &marker)
    .stdin(std::process::Stdio::piped())
    .stdout(std::process::Stdio::piped())
    // Inherited: the probe's lines and a failing helper's messages reach this test's stderr.
    .stderr(std::process::Stdio::inherit());
    match force {
        Some(force) => cmd.env("COSCA_UH_TRACE", "1").env("COSCA_UH_FORCE", force),
        // Not inherited from the test's own environment into a client's helper.
        None => cmd.env_remove("COSCA_UH_TRACE").env_remove("COSCA_UH_FORCE"),
    };
    // Under `spawn_lock()` (via `test_spawn`): macOS pipes get `FD_CLOEXEC` after `pipe()`, so a
    // concurrent fork could otherwise inherit this helper's pipe ends.
    let mut helper = crate::test_spawn::spawn(&mut cmd).expect("spawn the tracer helper");
    UNREAPED.set(UNREAPED.get() + 1);
    let signal_tx = helper.stdin.take().expect("the helper's stdin is piped");
    let rx = std::io::BufReader::new(helper.stdout.take().expect("the helper's stdout is piped"));
    Pending {
        session: Session {
            helper,
            signal_tx: Some(signal_tx),
            reports: Some(Reports { rx, marker }),
            awaits_exit: None,
            finished: false,
            _exe_dir: exe_dir,
            _thread: std::marker::PhantomData,
        },
    }
}

/// Copies this test binary into `dir` and ad-hoc signs the copy with
/// `com.apple.security.cs.debugger`, which macOS requires of a tracer (see the module docs).
pub(crate) fn debugger_signed_copy(dir: &std::path::Path) -> std::path::PathBuf {
    const ENTITLEMENTS: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict><key>com.apple.security.cs.debugger</key><true/></dict></plist>
"#;
    let exe = dir.join("tracer-helper");
    let plist = dir.join("entitlements.plist");
    let codesign = {
        // Writes and the fork under one guard, as `test_child::cwd_and_path_tools` does: no
        // concurrent fork may hold the copy's writable descriptor.
        let _guard = crate::child::spawn::spawn_lock();
        std::fs::copy(std::env::current_exe().expect("current_exe"), &exe).expect("copy the test binary");
        std::fs::write(&plist, ENTITLEMENTS).expect("write the entitlements plist");
        let mut cmd = std::process::Command::new("/usr/bin/codesign");
        cmd.args(["--sign", "-", "--force", "--entitlements"])
            .arg(&plist)
            .arg(&exe)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());
        // `test_spawn::spawn` would re-take the non-reentrant lock; `_guard` is spawn_lock.
        #[allow(
            clippy::disallowed_methods,
            reason = "`_guard` is spawn_lock, held over the copy and the fork"
        )]
        cmd.spawn().expect("spawn codesign")
    };
    let out = codesign.wait_with_output().expect("wait for codesign");
    assert!(
        out.status.success(),
        "codesign of the tracer helper failed ({}): {}{}",
        out.status,
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr),
    );
    exe
}

impl Pending {
    /// Sends the tracee's pid (S-1 → S0). Panics unless `tracee` is still this process's
    /// unreaped child, whose pid nothing else can hold.
    ///
    /// Takes `&mut`: `Child::wait`/`try_wait` take `&self`, so only an exclusive borrow stops the
    /// test from reaping the tracee (and freeing its pid for reuse) while the helper may still
    /// act on it.
    pub(crate) fn attach(self, tracee: &mut crate::Child) -> TracerHelper<'_> {
        self.attach_pid(tracee)
    }

    /// [`attach`](Pending::attach) for a test whose subject is the tracee's own handle, which
    /// waits, kills and polls it while the helper holds it. Only the handle's shared methods are
    /// reachable, and the test must not reap the tracee through anything else.
    pub(crate) fn attach_shared(self, tracee: &crate::Child) -> TracerHelper<'_> {
        self.attach_pid(tracee)
    }

    /// [`attach`](Pending::attach) for a tracee that is tokio's own child, which the test moves
    /// into the handle under test: no borrow ties the two, so the test must not reap the tracee
    /// through anything but that handle while the helper holds it.
    #[cfg(feature = "tokio")]
    pub(crate) fn attach_tokio(self, tracee: &::tokio::process::Child) -> TracerHelper<'static> {
        let pid = tracee.id().expect("an unreaped tokio child has a pid");
        self.attach_pid_number(pid)
    }

    fn attach_pid(self, tracee: &crate::Child) -> TracerHelper<'_> {
        self.attach_pid_number(tracee.id().pid())
    }

    fn attach_pid_number<'a>(mut self, pid: u32) -> TracerHelper<'a> {
        if let Err(e) = sys::peek_child(pid) {
            panic!(
                "attach: the tracee {pid} is not this process's unreaped child (waitid: errno {e}), \
                 so its pid may name another process"
            );
        }
        let tx = self.session.signal_tx();
        writeln!(tx, "pid {pid}").expect("send the pid line to the tracer helper");
        tx.flush().expect("flush the pid line");
        TracerHelper {
            session: self.session,
            _tracee: std::marker::PhantomData,
        }
    }
}

/// A helper with its tracee. While it lives the test cannot reach the tracee. Dropping it tears
/// the helper down before the borrow of the tracee ends.
pub(crate) struct TracerHelper<'a> {
    session: Session,
    _tracee: std::marker::PhantomData<&'a ()>,
}

impl TracerHelper<'_> {
    /// Blocks for the next report, skipping [`Report::Blocking`]. Panics at EOF: a test reads
    /// only reports the protocol promises.
    pub(crate) fn recv(&mut self) -> Report {
        loop {
            match self.session.next_report() {
                Some(Report::Blocking { .. }) => {}
                Some(report) => return report,
                None => panic!("the tracer helper exited before the report this test waits for"),
            }
        }
    }

    /// Writes one signal byte.
    pub(crate) fn signal(&mut self) {
        let tx = self.session.signal_tx();
        tx.write_all(b"x").expect("write a signal byte");
        tx.flush().expect("flush the signal byte");
    }
}

/// The exit status of a tracee spawned to catch `SIGTERM`, once it gets one.
pub(crate) const SIGTERM_EXIT: i32 = 15;

/// What [`uh_tracee_fixture`] does besides reading stdin.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Tracee {
    Plain,
    /// Leads a process group of its own: the tracee for `SIGTSTP` and `SIGTTIN`, which XNU
    /// discards in an orphaned group. Its `pg_jobc` changes only when the tracee, the test or the
    /// tracer exits or changes group (xnu `kern_proc.c`, `fixjobc`). Its parent's group can be
    /// orphaned under a shell without job control, and under plain `cargo test` the other tests'
    /// orphaned grandchildren each decrement that group's `pg_jobc` when they exit
    /// (`kern_exit.c`), so it can reach 0.
    OwnGroup,
    /// Exits with [`SIGTERM_EXIT`] on `SIGTERM`.
    CatchSigterm,
    /// Holds a thread it created with `pthread_create_suspended_np` and never starts.
    UnstartedThread,
    /// [`Tracee::OwnGroup`] that ignores `SIGTSTP`: breaks one precondition of the helper's
    /// contract, for the tests that check the preconditions are asserted.
    IgnoreSigtstp,
    /// [`Tracee::OwnGroup`] that blocks `SIGTSTP` on every thread: as [`Tracee::IgnoreSigtstp`].
    /// It blocks it on its first thread, then re-executes itself, so the new image's threads all
    /// inherit the mask.
    BlockSigtstp,
    /// Leads a session of its own, so its process group is orphaned: as
    /// [`Tracee::IgnoreSigtstp`].
    OwnSession,
}

/// The start of the line [`uh_tracee_fixture`] writes once it is set up, followed by what it
/// reads of itself then: `blocked=<n> pgrp=<n> caught=<n> ignored=<n>`.
const TRACEE_READY: &str = "uh-tracee-ready";

/// What a tracee fixture reported of itself once it was set up. Each mask has bit `signal - 1`
/// for each signal.
#[derive(Debug)]
pub(crate) struct Ready {
    /// The signals its threads block. Every thread inherits the mask the first thread had, and
    /// the fixture sets no other.
    pub(crate) blocked: u32,
    /// Its process group.
    pub(crate) pgrp: libc::pid_t,
    /// The signals it has a handler for.
    pub(crate) caught: u32,
    /// The signals it has set to `SIG_IGN`.
    pub(crate) ignored: u32,
}

impl Ready {
    fn parse(fields: &str) -> Option<Ready> {
        let mut values = [None; 4];
        for field in fields.split_whitespace() {
            let (key, value) = field.split_once('=')?;
            let at = ["blocked", "pgrp", "caught", "ignored"]
                .iter()
                .position(|k| *k == key)?;
            values[at] = Some(value.parse::<i64>().ok()?);
        }
        let [Some(blocked), Some(pgrp), Some(caught), Some(ignored)] = values else {
            return None;
        };
        Some(Ready {
            blocked: u32::try_from(blocked).ok()?,
            pgrp: libc::pid_t::try_from(pgrp).ok()?,
            caught: u32::try_from(caught).ok()?,
            ignored: u32::try_from(ignored).ok()?,
        })
    }
}

/// Spawns [`uh_tracee_fixture`] of `kind`, uncontained, with a piped stdin (closing it ends the
/// tracee), and waits until it is set up. Its handlers and signal mask are then final: the test
/// may read them and attach.
pub(crate) fn spawn_tracee(kind: Tracee) -> (crate::Child, Ready) {
    let exe = std::env::current_exe().expect("current_exe");
    let mut cmd = crate::Command::new();
    cmd.executable(&exe)
        .args(crate::test_child::fixture_argv(crate::test_child::fixture_path!(
            uh_tracee_fixture
        )))
        .env("COSCA_UH_ROLE", "tracee")
        .env("COSCA_UH_KIND", format!("{kind:?}"));
    crate::test_reexec::scrub_env(|var| _ = cmd.env_remove(var));
    cmd.stdin(crate::Stdio::pipe()).expect("stdin pipe");
    cmd.stdout(crate::Stdio::pipe()).expect("stdout pipe");
    cmd.stderr(crate::Stdio::null()).expect("stderr null");
    let mut tracee = cmd.spawn().expect("spawn the tracee fixture");
    let ready = await_ready(&mut tracee);
    (tracee, ready)
}

/// [`spawn_tracee`] for a raw tokio child, with a piped stdin: closing it ends the tracee.
#[cfg(feature = "tokio")]
pub(crate) async fn spawn_tracee_tokio(kind: Tracee) -> (::tokio::process::Child, ::tokio::process::ChildStdin) {
    use ::tokio::io::AsyncBufReadExt as _;
    let exe = std::env::current_exe().expect("current_exe");
    let mut child = crate::test_spawn::spawn_tokio(
        ::tokio::process::Command::from(crate::test_reexec::command(exe))
            .args(crate::test_reexec::fixture_args(crate::test_child::fixture_path!(
                uh_tracee_fixture
            )))
            .env("COSCA_UH_ROLE", "tracee")
            .env("COSCA_UH_KIND", format!("{kind:?}"))
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::null()),
    )
    .expect("spawn the tracee fixture");
    let stdin = child.stdin.take().expect("the tracee's stdin is piped");
    let mut lines = ::tokio::io::BufReader::new(child.stdout.take().expect("the tracee's stdout is piped")).lines();
    loop {
        let line = lines
            .next_line()
            .await
            .expect("read the tracee's stdout")
            .expect("the tracee exited before it was ready");
        if line.trim().starts_with(TRACEE_READY) {
            return (child, stdin);
        }
    }
}

/// Reads the tracee's stdout up to its [`TRACEE_READY`] line. Panics at EOF: the tracee exited
/// first. The tracee writes nothing to the pipe after that line, so it is dropped here.
fn await_ready(tracee: &mut crate::Child) -> Ready {
    use std::io::BufRead as _;
    let mut stdout = std::io::BufReader::new(tracee.stdout().expect("the tracee's stdout is piped"));
    loop {
        let mut line = String::new();
        let n = stdout.read_line(&mut line).expect("read the tracee's stdout");
        assert!(n > 0, "the tracee exited before it was ready");
        if let Some(fields) = line.trim().strip_prefix(TRACEE_READY) {
            return Ready::parse(fields).unwrap_or_else(|| panic!("malformed tracee ready line: {line:?}"));
        }
    }
}

/// The tracee: sets itself up as `COSCA_UH_KIND` says ([`Tracee`]), writes [`TRACEE_READY`] to
/// stdout and points stdout at `/dev/null` (libtest fails a run whose report it cannot write, and
/// the test drops the pipe), then reads stdin until EOF or one byte, then exits 0. A no-op unless
/// `COSCA_UH_ROLE=tracee`, so an ordinary suite run does not block on stdin.
#[skuld::test]
fn uh_tracee_fixture() {
    if std::env::var("COSCA_UH_ROLE").as_deref() != Ok("tracee") {
        return;
    }
    extern "C" fn exit_on_sigterm(_: libc::c_int) {
        // SAFETY: `_exit` is async-signal-safe.
        unsafe { libc::_exit(SIGTERM_EXIT) }
    }
    let own_group = || {
        nix::unistd::setpgid(nix::unistd::Pid::from_raw(0), nix::unistd::Pid::from_raw(0)).expect("setpgid");
    };
    let kind = std::env::var("COSCA_UH_KIND").expect("COSCA_UH_KIND is set by spawn_tracee");
    match kind.as_str() {
        "Plain" => {}
        "OwnGroup" => own_group(),
        "CatchSigterm" => {
            // SAFETY: the handler calls only `_exit`; this process runs no other test.
            let previous = unsafe { libc::signal(libc::SIGTERM, exit_on_sigterm as *const () as libc::sighandler_t) };
            assert_ne!(previous, libc::SIG_ERR, "install the SIGTERM handler");
        }
        "UnstartedThread" => {
            unsafe extern "C" {
                fn pthread_create_suspended_np(
                    thread: *mut libc::pthread_t,
                    attr: *const libc::pthread_attr_t,
                    start: extern "C" fn(*mut libc::c_void) -> *mut libc::c_void,
                    arg: *mut libc::c_void,
                ) -> libc::c_int;
            }
            extern "C" fn never_runs(_: *mut libc::c_void) -> *mut libc::c_void {
                std::ptr::null_mut()
            }
            let mut thread: libc::pthread_t = 0;
            // SAFETY: valid out-pointer, default attributes, and a start routine that touches
            // nothing.
            let rc =
                unsafe { pthread_create_suspended_np(&mut thread, std::ptr::null(), never_runs, std::ptr::null_mut()) };
            assert_eq!(rc, 0, "pthread_create_suspended_np");
        }
        "IgnoreSigtstp" => {
            own_group();
            // SAFETY: `SIG_IGN` runs no code; this process runs no other test.
            let previous = unsafe { libc::signal(libc::SIGTSTP, libc::SIG_IGN) };
            assert_ne!(previous, libc::SIG_ERR, "ignore SIGTSTP");
        }
        "BlockSigtstp" => {
            let mut set = nix::sys::signal::SigSet::empty();
            set.add(nix::sys::signal::Signal::SIGTSTP);
            set.thread_block().expect("block SIGTSTP");
            reexec_as("BlockedSigtstp");
        }
        "BlockedSigtstp" => own_group(),
        "OwnSession" => {
            nix::unistd::setsid().expect("setsid");
        }
        other => panic!("unknown COSCA_UH_KIND {other:?}"),
    }
    let blocked = nix::sys::signal::SigSet::thread_get_mask().expect("read the signal mask");
    let blocked: libc::sigset_t = *blocked.as_ref();
    // SAFETY: `getpgrp` has no preconditions.
    let pgrp = unsafe { libc::getpgrp() };
    let (mut caught, mut ignored) = (0u32, 0u32);
    for signal in (1..32).filter(|&s| s != libc::SIGKILL && s != libc::SIGSTOP) {
        // SAFETY: a null `act` only reads the action into `old`, a valid out-pointer.
        let mut old: libc::sigaction = unsafe { std::mem::zeroed() };
        let rc = unsafe { libc::sigaction(signal, std::ptr::null(), &mut old) };
        assert_eq!(rc, 0, "read the action of signal {signal}");
        match old.sa_sigaction {
            libc::SIG_DFL => {}
            libc::SIG_IGN => ignored |= 1 << (signal - 1),
            _ => caught |= 1 << (signal - 1),
        }
    }
    let line = format!("\n{TRACEE_READY} blocked={blocked} pgrp={pgrp} caught={caught} ignored={ignored}\n");
    let mut out = std::io::stdout().lock();
    out.write_all(line.as_bytes())
        .and_then(|()| out.flush())
        .expect("report readiness");
    let null = std::fs::File::options()
        .write(true)
        .open("/dev/null")
        .expect("open /dev/null");
    nix::unistd::dup2_stdout(&null).expect("point stdout at /dev/null");
    drop(out);
    let _ = sys::read_byte(0);
}

/// Replaces the fixture's image with a fresh one of `kind`, keeping its pid, argv, environment
/// and the calling thread's signal mask, which becomes the new image's first thread's. Raw
/// `execve`: `std`'s `exec` resets the mask.
fn reexec_as(kind: &str) -> ! {
    use std::os::unix::ffi::OsStrExt as _;
    let c = |bytes: &[u8]| std::ffi::CString::new(bytes).expect("no NUL in argv or the environment");
    let exe = c(std::env::current_exe().expect("current_exe").as_os_str().as_bytes());
    let argv: Vec<_> = std::env::args_os().map(|arg| c(arg.as_bytes())).collect();
    let env: Vec<_> = std::env::vars_os()
        .filter(|(key, _)| key != "COSCA_UH_KIND")
        .map(|(key, value)| c(&[key.as_bytes(), b"=", value.as_bytes()].concat()))
        .chain([c(format!("COSCA_UH_KIND={kind}").as_bytes())])
        .collect();
    let e = nix::unistd::execve(&exe, &argv, &env).unwrap_err();
    panic!("re-execute the tracee fixture: {e}")
}

/// The helper's entry point. A no-op unless `COSCA_UH_ROLE=helper`.
#[skuld::test]
fn uh_helper_entry() {
    if std::env::var("COSCA_UH_ROLE").as_deref() != Ok("helper") {
        return;
    }
    machine::main();
}

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