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
//! A child held by a tracer, as a debugger holds it: the parent's `waitid` answers `ECHILD` for
//! it, yet it is not reaped. `TRACER`-group tests, run in CI only.

use std::time::Instant;

use crate::identity::{HostKernel, Kernel, UniqRead};
use crate::os_process::macos::kqueue::test_hooks;
use crate::test_groups::{tracer_group, Group};
use crate::test_support::tracer::{self, Mode, Report};

/// A tracee held by a tracer, its handle, and the stdin that ends it.
fn held() -> (crate::Child, crate::PipeWriter) {
    held_over(HostKernel)
}

/// [`held`] over `kernel`, the one its spawn and its box ask.
fn held_over(kernel: impl Kernel + Send + 'static) -> (crate::Child, crate::PipeWriter) {
    let (mut tracee, _) = tracer::spawn_tracee_over(tracer::Tracee::Plain, kernel);
    let stdin = tracee.stdin().expect("the tracee's stdin is piped");
    (tracee, stdin)
}

/// Runs `wait(tracee)` on a thread and returns once that thread is about to block on its first
/// `poll` of a kqueue, whose knote is registered: no event can be lost after that.
///
/// `at_block` runs on the waiter's thread at that block, after the test thread was told: a test
/// that looks at the block parks it there until its wake is staged (see
/// [`look_after_staging`]).
fn blocked_in<'s, G, R: Send + 's>(
    scope: &'s std::thread::Scope<'s, '_>,
    tracee: &'s crate::Child,
    arm: impl FnOnce() -> G + Send + 's,
    wait: impl FnOnce(&'s crate::Child) -> R + Send + 's,
    at_block: impl FnOnce(&crate::wait::block_probe::Block<'_>) + Send + 'static,
) -> std::thread::ScopedJoinHandle<'s, R> {
    let (blocked_tx, blocked_rx) = std::sync::mpsc::channel();
    let waiter = scope.spawn(move || {
        let _armed = arm();
        let mut at_block = Some(at_block);
        let _blocked = crate::wait::block_probe::on_each_block(move |block| {
            if block.n == Some(1) {
                _ = blocked_tx.send(());
                if let Some(at_block) = at_block.take() {
                    at_block(block);
                }
            }
        });
        wait(tracee)
    });
    blocked_rx.recv().expect("the waiter must reach its blocking poll");
    waiter
}

/// The `at_block` of a [`blocked_in`] that looks at its block: waits until the test thread has
/// staged its wake (`staged.send(())`), then looks at the wait's kqueue (`ready()`) and answers on
/// the receiver. A test thread that panicked before it staged dropped the sender: the waiter
/// panics, ending its wait, instead of blocking the scope's join for ever.
///
/// A look that finds nothing is ended by the test's hand-back, whose `NOTE_EXIT` XNU re-fires on the
/// watch's kqueue, and the assertion on the look fails.
fn look_after_staging() -> (
    impl FnOnce(&crate::wait::block_probe::Block<'_>) + Send + 'static,
    std::sync::mpsc::Sender<()>,
    std::sync::mpsc::Receiver<Option<bool>>,
) {
    let (staged_tx, staged_rx) = std::sync::mpsc::channel::<()>();
    let (looked_tx, looked_rx) = std::sync::mpsc::channel();
    let look = move |block: &crate::wait::block_probe::Block<'_>| {
        staged_rx
            .recv()
            .expect("the test thread panicked before it staged its wake");
        _ = looked_tx.send(block.ready());
    };
    (look, staged_tx, looked_rx)
}

/// [`blocked_in`] for `tracee.wait()`, which blocks on the reap kqueue.
fn wait_blocked<'s, G>(
    scope: &'s std::thread::Scope<'s, '_>,
    tracee: &'s crate::Child,
    arm: impl FnOnce() -> G + Send + 's,
) -> std::thread::ScopedJoinHandle<'s, Result<std::process::ExitStatus, crate::error::Error>> {
    blocked_in(scope, tracee, arm, |tracee| tracee.wait(), |_| {})
}

/// An `OwnedChild` wait blocked while a tracer holds the child stays blocked through the child's
/// exit, and returns the status once the tracer hands the zombie back. `try_wait` meanwhile says
/// running.
///
/// Mutant: a by-pid `ECHILD` taken for a foreign reap: the wait returns `ECHILD`.
#[skuld::test]
fn a_wait_blocked_across_the_exit_and_the_hand_back_returns_the_status(#[fixture(tracer_group)] _group: &Group) {
    let (tracee, stdin) = held();
    let mut helper = tracer::start(Mode::Auto).attach_shared(&tracee);
    assert_eq!(helper.recv(), Report::Attached);
    std::thread::scope(|s| {
        let waiter = wait_blocked(s, &tracee, || ());
        assert_eq!(tracee.try_wait().expect("try_wait"), None, "a held child is running");
        drop(stdin);
        assert_eq!(helper.recv(), Report::Reaped);
        let status = waiter.join().expect("waiter").expect("the wait ends with the status");
        assert!(status.success(), "{status:?}");
    });
}

/// `kill` reaches a held child, the tracer hands the zombie back, and the wait returns the kill.
///
/// Mutant: `kill` refused for a pid the start read cannot see, or a wait that gives up on `ECHILD`.
#[skuld::test]
fn kill_ends_a_held_child_and_the_wait_returns_the_kill(#[fixture(tracer_group)] _group: &Group) {
    let (tracee, _stdin) = held();
    let mut helper = tracer::start(Mode::Auto).attach_shared(&tracee);
    assert_eq!(helper.recv(), Report::Attached);
    assert_eq!(tracee.try_wait().expect("try_wait"), None, "a held child is running");
    tracee.kill().expect("kill");
    assert_eq!(helper.recv(), Report::Reaped);
    drop(helper);
    let status = tracee.wait().expect("the handed-back zombie is ours to reap");
    assert_eq!(
        std::os::unix::process::ExitStatusExt::signal(&status),
        Some(libc::SIGKILL)
    );
}

/// A tracee that has exited, as a zombie on the tracer's own list, is still running for its
/// parent: `ECHILD`, and its tracer is alive, so the wait continues until the tracer hands it back.
///
/// Mutant: an `ECHILD` for a resolvable pid taken for a reap once nothing traces it (a held
/// zombie is no longer flagged as traced): the wait and `try_wait` answer `ECHILD`.
#[skuld::test]
fn a_zombie_a_tracer_holds_is_running_until_the_hand_back(#[fixture(tracer_group)] _group: &Group) {
    let (tracee, stdin) = held();
    let mut helper = tracer::start(Mode::Hold).attach_shared(&tracee);
    assert_eq!(helper.recv(), Report::Attached);
    std::thread::scope(|s| {
        let waiter = wait_blocked(s, &tracee, || ());
        drop(stdin);
        assert_eq!(helper.recv(), Report::Exited);
        assert_eq!(
            tracee.try_wait().expect("try_wait"),
            None,
            "a held zombie is not ours yet"
        );
        helper.signal();
        assert_eq!(helper.recv(), Report::Reaped);
        let status = waiter.join().expect("waiter").expect("the wait ends with the status");
        assert!(status.success(), "{status:?}");
    });
}

/// A tracee whose tracer holds its zombie has exited for the grace watch, though XNU sends its
/// `NOTE_EXIT` to the tracer alone: the look reads the zombie itself, so the watch ends with the
/// tracer still holding it. While the tracee runs, the held look is a `Recheck`, so it reads as
/// running at an expired deadline.
///
/// The unbounded watch runs on a thread of its own and must not block: a block is the mutant's. The
/// test thread then ends it with the hand-back, whose `NOTE_EXIT` XNU re-fires on the exit watch's
/// kqueue; the knote stays pending whether the watch's poll has begun or
/// not, so no ordering is needed. The assertion that the watch made no block fails after that.
///
/// Mutant: `exited_by` waits on the exit watch alone, which fires only at the hand-back: the
/// unbounded watch blocks.
#[skuld::test]
fn a_zombie_a_tracer_holds_has_exited_for_the_grace_watch_before_the_hand_back(
    #[fixture(tracer_group)] _group: &Group,
) {
    let (tracee, stdin) = held();
    let mut helper = tracer::start(Mode::Hold).attach_shared(&tracee);
    assert_eq!(helper.recv(), Report::Attached);
    assert!(
        !tracee.proc.exited_by(Some(Instant::now())).expect("a held live root"),
        "a held root that runs has not exited"
    );
    drop(stdin);
    assert_eq!(helper.recv(), Report::Exited);
    let (blocked, exited) = std::thread::scope(|s| {
        let (tx, rx) = std::sync::mpsc::channel();
        let watcher = s.spawn({
            let (tracee, tx) = (&tracee, tx.clone());
            move || {
                let _blocked = crate::wait::block_probe::on_blocking({
                    let tx = tx.clone();
                    move || _ = tx.send(true)
                });
                let exited = tracee.proc.exited_by(None);
                _ = tx.send(false);
                exited
            }
        });
        let blocked = rx.recv().expect("the watcher reports a block or its end");
        if blocked {
            helper.signal();
        }
        (blocked, watcher.join().expect("watcher"))
    });
    if blocked {
        assert_eq!(helper.recv(), Report::Reaped);
    }
    assert!(
        !blocked,
        "the watch must end on the held zombie, not block until the hand-back"
    );
    assert!(exited.expect("a held zombie"), "the held zombie has exited");
    assert_eq!(
        tracee.try_wait().expect("try_wait"),
        None,
        "a held zombie is not ours yet"
    );
    helper.signal();
    assert_eq!(helper.recv(), Report::Reaped);
    let status = tracee.wait().expect("the handed-back zombie is ours to reap");
    assert!(status.success(), "{status:?}");
}

/// A zombie that launchd holds has exited for the grace watch, with a long grace unspent. The tracer's
/// hold is the real state, and its record reads as launchd's zombie while the watch looks, as when the
/// tracer died while the tracee was exiting.
///
/// Mutant: the look reads past the exit watch only for a parent that is a tracer, not for launchd.
#[skuld::test]
fn a_zombie_launchd_holds_has_exited_for_the_grace_watch_at_once(#[fixture(tracer_group)] _group: &Group) {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    use crate::identity::{short_info, FakeKernel, LAUNCHD};

    let kernel = Arc::new(FakeKernel::over(&HostKernel));
    let (tracee, stdin) = held_over(Arc::clone(&kernel));
    let pid = tracee.pid();
    let launchd_holds = Arc::new(AtomicBool::new(false));
    kernel.state_every_short_bsd(pid, {
        let launchd_holds = Arc::clone(&launchd_holds);
        move || {
            if launchd_holds.load(Ordering::SeqCst) {
                Ok(short_info(LAUNCHD, libc::SZOMB))
            } else {
                HostKernel.short_bsd(pid)
            }
        }
    });
    let mut helper = tracer::start(Mode::Hold).attach_shared(&tracee);
    assert_eq!(helper.recv(), Report::Attached);
    drop(stdin);
    assert_eq!(helper.recv(), Report::Exited);
    {
        launchd_holds.store(true, Ordering::SeqCst);
        let long = Instant::now() + std::time::Duration::from_secs(3600);
        assert!(
            tracee.proc.exited_by(Some(long)).expect("a zombie launchd holds"),
            "the zombie has exited: no grace is spent on it"
        );
        launchd_holds.store(false, Ordering::SeqCst);
    }
    helper.signal();
    assert_eq!(helper.recv(), Report::Reaped);
    let status = tracee.wait().expect("the handed-back zombie is ours to reap");
    assert!(status.success(), "{status:?}");
}

/// A real tracer that attaches while the grace watch is blocked (`graceful_shutdown`'s wait, here
/// [`OwnedChild::exited_by`](crate::child::owned::OwnedChild::exited_by) with no deadline): the
/// attach's `SIGSTOP` wakes the watch on its own kqueue, its look finds another process holding the
/// child, and the watch ends once the tracer holds the child's zombie. XNU sends that `NOTE_EXIT` to
/// the tracer alone.
///
/// The watch's block is looked at once the attach is staged (`blocked_in` with `look_after_staging`). The ordering edge
/// is the helper's `attached`: it follows `PT_ATTACH`, which sends the `SIGSTOP`, and XNU posts
/// `NOTE_SIGNAL` before any disposition check.
///
/// Mutant: the exit wait registers no `NOTE_SIGNAL`, or blocks on the shared exit kqueue, whose
/// `NOTE_EXIT` is withheld: the look finds nothing.
#[skuld::test]
fn a_tracer_that_attaches_during_the_grace_watch_wakes_it(#[fixture(tracer_group)] _group: &Group) {
    let (tracee, stdin) = held();
    std::thread::scope(|s| {
        let (look, staged, looked) = look_after_staging();
        let watcher = blocked_in(s, &tracee, || (), |tracee| tracee.proc.exited_by(None), look);
        let mut helper = tracer::start(Mode::Hold).attach_shared(&tracee);
        assert_eq!(helper.recv(), Report::Attached);
        staged.send(()).expect("the waiter is at its block");
        let look = looked.recv().expect("the waiter looks at its block");
        drop(stdin);
        assert_eq!(helper.recv(), Report::Exited);
        if look != Some(true) {
            helper.signal();
            assert_eq!(helper.recv(), Report::Reaped);
        }
        let exited = watcher.join().expect("watcher").expect("the watch");
        assert_eq!(
            look,
            Some(true),
            "the attach's SIGSTOP must leave the watch an event to wake on"
        );
        assert!(exited, "the held zombie has exited");
        helper.signal();
        assert_eq!(helper.recv(), Report::Reaped);
    });
    let status = tracee.wait().expect("the handed-back zombie is ours to reap");
    assert!(status.success(), "{status:?}");
}

/// A thread that asks `is_alive` while the grace watch is blocked takes nothing from it: the attach
/// that follows still wakes the watch, which ends once the tracer holds the zombie. The watch's
/// kqueue is its own, and `is_alive` reads only the shared exit watch.
///
/// The watch's block is looked at once the attach is staged and `is_alive` has run after it
/// (`blocked_in` with `look_after_staging`), so a wake `is_alive` took is a look that finds nothing. The ordering edge
/// is the helper's `attached`: it follows `PT_ATTACH`, which sends the `SIGSTOP`, and XNU posts
/// `NOTE_SIGNAL` before any disposition check.
///
/// Mutant: the watch blocks on a kqueue that `is_alive` reads, which takes the attach's event.
#[skuld::test]
fn is_alive_during_the_grace_watch_does_not_swallow_its_wake(#[fixture(tracer_group)] _group: &Group) {
    let (tracee, stdin) = held();
    std::thread::scope(|s| {
        let (look, staged, looked) = look_after_staging();
        let watcher = blocked_in(s, &tracee, || (), |tracee| tracee.proc.exited_by(None), look);
        assert_eq!(tracee.is_alive(), crate::identity::Liveness::Alive);
        let mut helper = tracer::start(Mode::Hold).attach_shared(&tracee);
        assert_eq!(helper.recv(), Report::Attached);
        // Whatever it answers for a held child, it must not take the watch's wake.
        let _liveness = tracee.is_alive();
        staged.send(()).expect("the waiter is at its block");
        let look = looked.recv().expect("the waiter looks at its block");
        drop(stdin);
        assert_eq!(helper.recv(), Report::Exited);
        if look != Some(true) {
            helper.signal();
            assert_eq!(helper.recv(), Report::Reaped);
        }
        let exited = watcher.join().expect("watcher").expect("the watch");
        assert_eq!(
            look,
            Some(true),
            "is_alive must not take the attach's SIGSTOP from the watch"
        );
        assert!(exited, "the held zombie has exited");
        helper.signal();
        assert_eq!(helper.recv(), Report::Reaped);
    });
    let status = tracee.wait().expect("the handed-back zombie is ours to reap");
    assert!(status.success(), "{status:?}");
}

/// The live blocker [`tracer::spawn_tracee`] makes, its stdin (closing it ends the tracee), and its
/// unique id.
fn tracee_with_unique() -> (crate::Child, crate::PipeWriter, u64) {
    let (mut tracee, _) = tracer::spawn_tracee(tracer::Tracee::Plain);
    let stdin = tracee.stdin().expect("the tracee's stdin is piped");
    let unique = match HostKernel.unique_info(tracee.pid()) {
        UniqRead::Found(info) => info.unique_id,
        other => panic!("the tracee's unique id: {other:?}"),
    };
    (tracee, stdin, unique)
}

/// A real tracer that attaches while the wait is blocked: the attach's `SIGSTOP` wakes the wait
/// through the child's `NOTE_SIGNAL`, before anything else happens to the child. The wait then
/// watches the tracer; the child's exit and the tracer's hand-back end it with the child's status.
/// The attach's `SIGSTOP` is the only wake of the wait's first block.
///
/// Each staged wake is looked at, at its block (`on_rounds`). Round 0's ordering edge is the helper's
/// `attached`: it follows `PT_ATTACH`, which sends the `SIGSTOP`, and XNU posts `NOTE_SIGNAL` before any
/// disposition check. Round 1's is the helper's `reaped`: it follows the helper's `wait4`, which
/// hands the zombie back and re-fires `NOTE_EXIT` to this process.
///
/// Mutant: the wait registers no `NOTE_SIGNAL` on the child: the look at the first staged wake finds
/// nothing.
#[skuld::test]
fn a_tracer_that_attaches_during_a_wait_wakes_it(#[fixture(tracer_group)] _group: &Group) {
    use std::cell::RefCell;
    use std::rc::Rc;

    let (tracee, stdin, unique) = tracee_with_unique();
    let pid = tracee.pid();
    let owned = super::macos::watch(HostKernel, pid, unique);
    let pending = RefCell::new(Some(tracer::start(Mode::Auto)));
    let helper = Rc::new(RefCell::new(None));
    let stdin = RefCell::new(Some(stdin));
    let (_rounds, looks) = super::macos::on_rounds({
        let helper = Rc::clone(&helper);
        move |round| match round {
            0 => {
                let mut attached = pending.borrow_mut().take().expect("the helper").attach_unheld(pid);
                assert_eq!(attached.recv(), Report::Attached);
                *helper.borrow_mut() = Some(attached);
                true
            }
            1 => {
                drop(stdin.borrow_mut().take());
                let mut helper = helper.borrow_mut();
                let helper = helper.as_mut().expect("the helper attached in round 0");
                assert_eq!(helper.recv(), Report::Reaped);
                true
            }
            _ => false,
        }
    });
    let outcome = owned.wait(None);
    assert_eq!(
        looks.get(),
        [(0, Some(true)), (1, Some(true))],
        "the attach's SIGSTOP, then the hand-back's NOTE_EXIT, must each leave the wait an event to wake on"
    );
    drop(helper.borrow_mut().take());
    let status = super::fixtures::status(outcome);
    assert!(status.success(), "{status:?}");
}

/// A child whose real tracer is itself traced by a second one: the wait walks the chain and
/// registers the second tracer too, whose signals then wake it. A `SIGCONT` to the second tracer,
/// which leaves a running process running, shows the registration. The child's exit and its
/// tracer's hand-back end the wait with the child's status. The `SIGCONT` is the only wake of the
/// wait's first block.
///
/// Each staged wake is looked at, at its block (`on_rounds`). Round 0's ordering edge is the
/// `kill(2)`: XNU's `psignal_internal` posts `NOTE_SIGNAL` to the target's knotes before it returns,
/// ahead of any disposition check; the signal goes to the outer helper, so no other event is on the
/// wait's kqueue. Round 1's is the inner helper's `reaped`: it follows the inner helper's `wait4`,
/// which hands the zombie back and re-fires `NOTE_EXIT` to this process.
///
/// Mutant: the walk stops at the child's tracer: the look at the first staged wake finds nothing.
#[skuld::test]
fn a_wait_on_a_child_whose_tracer_is_traced_watches_that_tracers_tracer(#[fixture(tracer_group)] _group: &Group) {
    use std::cell::RefCell;
    use std::rc::Rc;

    let (tracee, stdin, unique) = tracee_with_unique();
    let pid = tracee.pid();
    let mut inner = tracer::start(Mode::Auto).attach_unheld(pid);
    assert_eq!(inner.recv(), Report::Attached);
    let mut outer = tracer::start(Mode::Auto).attach_unheld(inner.helper_pid());
    assert_eq!(outer.recv(), Report::Attached);
    let outer_pid = outer.helper_pid();
    let stdin = RefCell::new(Some(stdin));
    let inner = Rc::new(RefCell::new(inner));
    let owned = super::macos::watch(HostKernel, pid, unique);
    let (rounds, looks) = super::macos::on_rounds({
        let inner = Rc::clone(&inner);
        move |round| match round {
            0 => {
                test_hooks::send_signal(outer_pid, libc::SIGCONT);
                true
            }
            1 => {
                drop(stdin.borrow_mut().take());
                assert_eq!(inner.borrow_mut().recv(), Report::Reaped);
                true
            }
            _ => false,
        }
    });
    let outcome = owned.wait(None);
    assert_eq!(
        looks.get(),
        [(0, Some(true)), (1, Some(true))],
        "the SIGCONT to the tracer's tracer, then the hand-back's NOTE_EXIT, must each leave the wait an event to wake on"
    );
    // The inner helper's exit goes to the outer one, its tracer and parent, which hands it back
    // when it reaps it; until then this process's reap of it fails with `ECHILD`.
    inner.borrow_mut().close_signal_pipe();
    assert_eq!(outer.recv(), Report::Reaped);
    // The hook holds a handle on the inner helper too.
    drop(rounds);
    drop(inner);
    drop(outer);
    let status = super::fixtures::status(outcome);
    assert!(status.success(), "{status:?}");
}