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
//! The sync `Child` asks its own handle whether the root is still its child: [`RootState`]. The
//! drop and the failed-spawn cleanup act on that answer, not on the root's start token alone.

use crate::log_capture::warns_since;
use crate::signal::RootState;
use crate::test_child::Console;

/// After this handle's own wait the root is still a zombie of ours: `Unreaped`, and nothing around
/// it warns.
///
/// Mutant: `RootHandle::state` reads a root whose exit was recorded as `Reaped`.
#[skuld::test]
fn state_after_own_wait_is_unreaped_without_a_warn() {
    crate::log_capture::install();
    let child = crate::test_child::command(Console::Hidden)
        .args(["true"])
        .spawn()
        .expect("spawn");
    child.wait().expect("wait");

    let mark = crate::log_capture::mark();
    let state = child.proc.state();
    drop(child);

    assert!(matches!(state, RootState::Unreaped), "{state:?}");
    assert_eq!(warns_since(mark, ""), Vec::<String>::new());
}

#[cfg(target_os = "linux")]
mod linux {
    use super::*;
    use crate::containment::unix::fault::record_kill_group;
    use crate::send_log::{Capture, Via};
    use crate::signal::Sig;
    use crate::test_child::pid_reuse::{in_fresh_pid_ns, reap_behind_and_reuse, sigusr1_and_wait};
    use crate::test_groups::namespaces;
    use crate::ContainMode;

    fn session_blocker() -> (crate::Child, crate::PipeWriter) {
        session_blocker_reporting(None)
    }

    /// [`session_blocker`] whose spawn reports `elevation`: a child launched behind that backend.
    fn session_blocker_reporting(
        elevation: Option<crate::elevation::ElevationReport>,
    ) -> (crate::Child, crate::PipeWriter) {
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        cmd.stdin(stdin).expect("set stdin");
        cmd.contain_with(ContainMode::Session);
        cmd.set_elevation_report(elevation);
        (cmd.spawn().expect("spawn"), writer)
    }

    /// A process-group child reaped behind its back, its pid reused, and the number read as the
    /// child's own identity (a same-tick reuse): the number still reads as the root, so only the
    /// child's own pidfd shows the reap. The drop sends no `killpg` by the group's number.
    ///
    /// Mutant: the drop takes no evidence from the handle (`DropView::read` ignores
    /// `proc.state()`).
    fn drop_after_foreign_reap_and_same_tick_reuse_body() {
        let recorder = record_kill_group();
        let (mut child, writer) = session_blocker();
        assert!(
            child.tree.signals_a_group_for_test(),
            "the test needs a group named by the root's pid, which ContainMode::Session makes"
        );
        let root = child.id().expect(crate::test_child::IDENTITY_READ);
        drop(writer);
        let reuser = reap_behind_and_reuse(root.pid());
        child.proc.number_reads_always(crate::identity::Resolved::Found(root));

        drop(child);

        assert_eq!(
            recorder.killed(),
            Vec::<i32>::new(),
            "no killpg by a reaped root's number"
        );
        assert_eq!(
            sigusr1_and_wait(reuser),
            Some(libc::SIGUSR1),
            "the reuser must have been signalled by the test alone"
        );
    }
    in_fresh_pid_ns!(
        namespaces_sync_pgroup_drop_after_foreign_reap_and_same_tick_reuse_sends_no_killpg,
        fixture_sync_pgroup_drop_root_reads_as_reuser_driver,
        fixture_sync_pgroup_drop_root_reads_as_reuser_init,
        drop_after_foreign_reap_and_same_tick_reuse_body
    );

    /// A peek that fails on the root's own pidfd cannot show the root is reaped or not: the drop
    /// names `RootState::Unknown`, skips the channels that name the tree by the root's number, and
    /// still kills the root, through its pidfd.
    ///
    /// Mutant: `Unknown` is taken as `Reaped` (no root kill, and the log names no `Unknown`).
    #[skuld::test]
    fn a_failed_root_peek_skips_number_named_channels_and_still_kills_the_root() {
        #[cfg(target_os = "linux")]
        let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
        crate::log_capture::install();
        let recorder = record_kill_group();
        let (mut child, writer) = session_blocker();
        // Released once the drop's root kill returned, so a drop that sent none ends it with 0.
        let blocker = crate::child::spawn::fault::release_at_drop_kill(writer);
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));

        drop(child);

        fake.assert_peeks_exhausted();
        blocker.assert_killed();
        assert!(
            crate::log_capture::contains_since(mark, "RootState::Unknown"),
            "the drop must name the unknown root state"
        );
        assert_eq!(
            recorder.killed(),
            Vec::<i32>::new(),
            "no killpg by an unconfirmed root's number"
        );
        assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Pidfd)]);
        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "one warn for the event: {warns:?}");
        assert!(
            warns[0].contains(&format!("pgid {pid}")),
            "the warn names the group left alone: {warns:?}"
        );
        assert!(
            !crate::log_capture::contains_since(mark, "kill_tree()"),
            "no wait happened and kill_tree has no RootState gate: no remedy to name"
        );
    }

    /// The records are labelled by the caller: a failed spawn's cleanup does not call itself a drop,
    /// in the warn or in the read's `debug` line.
    ///
    /// Mutants: the report hardcodes "Child::drop"; `DropView::read` hardcodes "Child::drop"; the
    /// cleanup leaves the handle armed, so its drop warns "already reaped" about a `Child` the
    /// caller never received.
    #[skuld::test]
    fn the_unknown_warn_names_its_caller() {
        crate::log_capture::install();
        let _recorder = record_kill_group();
        let (mut child, writer) = session_blocker();
        // Released once the cleanup's root kill returned, before its reap.
        let blocker = crate::child::spawn::fault::release_between_kill_and_wait(writer);
        let mark = crate::log_capture::mark();
        // The number is unreadable too, so the read says so in a `debug` line of its own.
        let fake = child.proc.script_over(|f| {
            f.peeks([Err(std::io::Error::other("forced peek failure"))])
                .number_reads([(
                    crate::identity::Resolved::Unknown,
                    crate::identity::UnknownCause::default(),
                )])
        });

        let err = crate::child::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
            .expect_err("the spawn fails");

        fake.assert_peeks_exhausted();
        fake.assert_number_reads_exhausted();
        blocker.assert_killed();
        // The cleanup's error and the Unknown warn report it; the handle it drops afterwards is
        // disarmed and says nothing more.
        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "{warns:?} ({err:?})");
        assert!(warns[0].starts_with("finish_elevated:"), "{warns:?}");
        let read = crate::log_capture::records_since_on_current_thread(mark, "could not be read either");
        assert_eq!(read.len(), 1, "{read:?}");
        assert!(read[0].1.starts_with("finish_elevated:"), "{read:?}");
    }

    /// An unknown root behind a live elevation front the drop leaves running is one event, so one
    /// warn: it names the unknown state and the front.
    ///
    /// Mutants: the drop warns of the unknown root before it checks the front's gate, then again
    /// of the front; the one warn omits the front.
    #[skuld::test]
    fn an_unknown_root_behind_a_closed_front_gate_warns_once() {
        crate::log_capture::install();
        let recorder = record_kill_group();
        let (mut child, writer) = session_blocker_reporting(crate::child::front_kill_tests::sudo_report());
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        // The gate's two looks at the front see it run; the read after them sees the failed peek.
        let fake = child.proc.script_over(|f| {
            f.peeks([
                Ok(crate::os_process::child::PeekOutcome::Running),
                Ok(crate::os_process::child::PeekOutcome::Running),
                Err(std::io::Error::other("forced peek failure")),
            ])
        });

        drop(child);
        drop(writer);

        fake.assert_peeks_exhausted();
        assert_eq!(recorder.killed(), Vec::<i32>::new());
        assert!(sends.entries().is_empty(), "{:?}", sends.entries());
        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "one warn for the event: {warns:?}");
        assert!(
            warns[0].contains("RootState::Unknown") && warns[0].contains("left running"),
            "{warns:?}"
        );
    }

    /// With the root's number unreadable too, the debug line does not claim the root is treated as
    /// not reaped: its handle could not say, and the number-named kills are skipped.
    ///
    /// Mutant: the line keeps its "treating the root as not reaped" text.
    #[skuld::test]
    fn an_unknown_root_with_an_unreadable_number_does_not_claim_not_reaped() {
        crate::log_capture::install();
        let _recorder = record_kill_group();
        let (mut child, writer) = session_blocker();
        let blocker = crate::child::spawn::fault::release_at_drop_kill(writer);
        let mark = crate::log_capture::mark();
        let fake = child.proc.script_over(|f| {
            f.peeks([Err(std::io::Error::other("forced peek failure"))])
                .number_reads([(
                    crate::identity::Resolved::Unknown,
                    crate::identity::UnknownCause::default(),
                )])
        });

        drop(child);

        fake.assert_peeks_exhausted();
        fake.assert_number_reads_exhausted();
        blocker.assert_killed();
        assert!(
            !crate::log_capture::contains_since(mark, "treating the root as not reaped"),
            "{:?}",
            crate::log_capture::records_since(mark, "number")
        );
        assert!(
            crate::log_capture::contains_since(mark, "could not be read either; kills by that number are skipped"),
            "the line must say what happens instead: {:?}",
            crate::log_capture::records_since(mark, "number")
        );
    }

    /// The same read, for a failed spawn's cleanup: the tree kill is skipped and the tree is not
    /// marked killed, so a later drop still warns about what was left.
    ///
    /// Mutant: the skip marks the tree killed (or runs the kill, which marks it).
    #[skuld::test]
    fn a_failed_root_peek_does_not_mark_the_tree_killed() {
        let recorder = record_kill_group();
        let (mut child, _writer) = session_blocker();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));
        let view = crate::containment::DropView::read(
            crate::containment::dispatch::TeardownCaller::Drop,
            child.pid(),
            child.id,
            &child.proc,
            &child.tree,
        );
        fake.assert_peeks_exhausted();
        assert!(matches!(view.root, RootState::Unknown(_)), "{:?}", view.root);

        let unsure = crate::test_support::stated_root::StatedRoot::with_state(child.pid(), || {
            crate::signal::RootState::Unknown(std::sync::Arc::new(std::io::Error::other("forced peek failure")))
        });
        let kill = child.tree.kill(Some(&unsure)).outcome();
        assert!(kill.skipped().is_some(), "the number-named kill must be skipped");
        child.tree.settle(kill, true).answer.expect("a skip is not an error");

        assert!(!child.tree.is_killed(), "a skipped kill must not mark the tree killed");
        assert_eq!(recorder.killed(), Vec::<i32>::new());
    }

    /// A `kill_tree` on a root whose handle cannot say whether it is reaped sends nothing by the
    /// root's number, and kills the root through its pidfd, which names it exactly. The failure says
    /// the root was killed, so `graceful_shutdown_tree` reaps it before it returns the error.
    ///
    /// Mutant: the failure says the root was not killed.
    #[skuld::test]
    fn kill_tree_after_a_failed_root_peek_says_it_killed_the_root_through_its_pidfd() {
        let _old_kernel = crate::containment::unix::fault::refuse_pidfd_group_flag();
        let recorder = record_kill_group();
        let (mut child, writer) = session_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));

        let failure = child
            .kill_tree_after("kill_tree", None, None)
            .wait()
            .expect_err("the number may name another process");

        fake.assert_peeks_exhausted();
        assert!(failure.root_ended, "{:?}", failure.error);
        assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Pidfd)]);
        assert_eq!(
            recorder.killed(),
            Vec::<i32>::new(),
            "no killpg by an unconfirmed number"
        );
        drop(writer);
        crate::test_child::assert_killed("the root", child.wait().expect("reap the root"));
    }
}

#[cfg(target_os = "macos")]
mod macos {
    use super::*;
    use crate::os_process::child::{Foreign, PeekOutcome};
    use crate::send_log::{Capture, Via};
    use crate::signal::Sig;
    use crate::ContainMode;

    /// A tree-walk child: the walk names no marker holder, so the only sends are the root's own.
    fn walked_blocker() -> (crate::Child, crate::PipeWriter) {
        walked_blocker_reporting(None)
    }

    /// [`walked_blocker`] whose spawn reports `elevation`: a child launched behind that backend.
    fn walked_blocker_reporting(
        elevation: Option<crate::elevation::ElevationReport>,
    ) -> (crate::Child, crate::PipeWriter) {
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        cmd.stdin(stdin).expect("set stdin");
        cmd.contain_with(ContainMode::TreeWalk);
        cmd.set_elevation_report(elevation);
        (cmd.spawn().expect("spawn"), writer)
    }

    /// A root launchd holds is not pinned by this process: it is neither signalled nor waited on by
    /// its pid, and the drop warns once.
    ///
    /// Mutant: `Unpinned` is `Unknown` (the drop kills by pid, and waits).
    #[skuld::test]
    fn an_orphaned_root_is_neither_signalled_nor_waited_on_and_warns_once() {
        crate::log_capture::install();
        let (mut child, writer) = walked_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));

        drop(child);

        fake.assert_peeks_exhausted();
        assert_eq!(sends.entries(), vec![], "nothing may be sent to a root we do not pin");
        assert!(
            crate::test_child::is_unreaped_child(pid),
            "the root was waited on: this process does not pin it"
        );
        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(warns[0].contains("launchd"), "{warns:?}");
        // The test's own child ended and collected, since the drop left it alone.
        drop(writer);
        crate::test_child::wait_until_zombie(pid);
        // SAFETY: `pid` is this test's own zombie child.
        unsafe { libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0) };
    }

    /// A root launchd holds, behind a live elevation front: the front is left running and the root
    /// is not pinned, which is one event, so one warn that names both.
    ///
    /// Mutants: the drop warns of the front apart from the unpinned root; the one warn omits the
    /// front.
    #[skuld::test]
    fn an_orphaned_root_behind_a_closed_front_gate_warns_once() {
        crate::log_capture::install();
        let (mut child, writer) = walked_blocker_reporting(crate::child::front_kill_tests::sudo_report());
        let pid = child.pid();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        // The gate's two looks at the front, which see it run, then the read.
        let fake = child.proc.script_over(|f| {
            f.peeks([
                Ok(PeekOutcome::Running),
                Ok(PeekOutcome::Running),
                Ok(PeekOutcome::Foreign(Foreign::Orphaned)),
            ])
        });

        drop(child);

        fake.assert_peeks_exhausted();
        assert_eq!(sends.entries(), vec![]);
        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(
            warns[0].contains("launchd") && warns[0].contains("left running"),
            "{warns:?}"
        );
        drop(writer);
        crate::test_child::wait_until_zombie(pid);
        // SAFETY: `pid` is this test's own zombie child.
        unsafe { libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0) };
    }

    /// Any other root we cannot get an answer for is still our unreaped child, pinned by us: the
    /// drop still kills it through its handle (the pid, checked against its unique id).
    ///
    /// Mutant: every `Unknown` leaves the root alone.
    #[skuld::test]
    fn an_unknown_root_we_pin_is_still_killed_through_its_handle() {
        crate::log_capture::install();
        let (mut child, writer) = walked_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Err(std::io::Error::other("forced peek failure"))]));

        drop(child);
        drop(writer);

        fake.assert_peeks_exhausted();
        assert_eq!(sends.entries(), vec![(pid, Sig::Kill, Via::Identity)]);
    }

    /// A Session (fd-marker) tree: its holders-only sweep must not signal the root, which holds the
    /// marker like any member but is not pinned by this process.
    fn session_blocker() -> (crate::Child, crate::PipeWriter) {
        let (stdin, writer) = crate::test_child::held_writer_stdin();
        let mut cmd = crate::test_child::command(Console::Hidden);
        cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
        cmd.stdin(stdin).expect("set stdin");
        cmd.contain_with(ContainMode::Session);
        let child = cmd.spawn().expect("spawn");
        assert!(
            child.containment() == crate::containment::Containment::FdMarker,
            "the test needs an fd marker"
        );
        (child, writer)
    }

    /// Mutants: the holders-only sweep does not exclude the unpinned root; the sweep signals no
    /// holder at all (the control fails).
    #[skuld::test]
    fn an_orphaned_root_in_a_session_tree_is_not_signalled_by_the_sweep() {
        crate::log_capture::install();
        let _groups = crate::containment::unix::fault::record_kill_group();
        let holders = crate::containment::fdmarker::fault::record_holder_kills();
        // Control: a root that is a marker holder is swept when the handle says it is reaped, so
        // the assertion below is not vacuous.
        let (mut control, control_writer) = session_blocker();
        let control_pid = control.pid();
        let gone = control
            .proc
            .script_over(|f| f.peeks([Ok(PeekOutcome::Foreign(Foreign::Gone))]));
        drop(control);
        gone.assert_peeks_exhausted();
        drop(control_writer);
        assert!(holders.killed().contains(&control_pid), "{:?}", holders.killed());

        let (mut child, writer) = session_blocker();
        let pid = child.pid();
        let sends = Capture::start();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));

        drop(child);
        drop(writer);

        fake.assert_peeks_exhausted();
        assert!(sends.entries().is_empty(), "{:?}", sends.entries());
        assert!(
            !holders.killed().contains(&pid),
            "swept the root: {:?}",
            holders.killed()
        );
    }

    /// A failed spawn's cleanup leaves an unpinned root alone, and its error says so.
    ///
    /// Mutant: `finish_elevated` signals and waits on the root regardless.
    #[skuld::test]
    fn finish_elevated_leaves_an_orphaned_root_alone() {
        crate::log_capture::install();
        let (mut child, writer) = walked_blocker();
        let sends = Capture::start();
        let mark = crate::log_capture::mark();
        let fake = child
            .proc
            .script_over(|f| f.peeks([Ok(PeekOutcome::Foreign(Foreign::Orphaned))]));

        let err = crate::error::Error::from(
            crate::child::spawn::finish_elevated(child, Err(crate::error::Error::Io(std::io::Error::other("w"))))
                .expect_err("the spawn fails"),
        );
        let detail = crate::test_child::detail_of(&err);
        let (_, fate) = crate::child::spawn::failure::expect_may_have_started_with(err);
        drop(writer);

        fake.assert_peeks_exhausted();
        assert!(sends.entries().is_empty(), "{:?}", sends.entries());
        assert!(detail.contains("left alone"), "{detail}");
        assert_eq!(
            fate,
            crate::error::ChildFate::Gone,
            "a launchd-held zombie, sent nothing, is gone"
        );
        let warns = warns_since(mark, "");
        assert_eq!(warns.len(), 1, "{warns:?}");
        assert!(warns[0].contains("launchd"), "{warns:?}");
    }
}