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
use std::time::Duration;

use crate::identity::ProcessId;
use crate::os_process::drive::exited_held;
use crate::os_process::{kill, open, terminate, Exit};
use crate::signal::{Sent, Sig};
use crate::test_child::{held_contained_blocker_without_cgroup, wait_until_zombie};
use crate::test_groups::{tracer_group, Group};

/// A live blocker, its stdin (held open so it stays alive) and its identity.
fn blocker() -> (crate::Child, crate::PipeWriter, ProcessId) {
    let (child, stdin) = held_contained_blocker_without_cgroup(crate::Stdio::null());
    let id = child.id().expect(crate::test_child::IDENTITY_READ);
    (child, stdin, id)
}

#[skuld::test]
fn one_open_serves_look_signal_and_wait() {
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    assert!(matches!(p.exited().unwrap(), Exit::Running(_)));
    assert!(!exited_held(&*p, Some(Duration::ZERO)).unwrap());
    assert_eq!(p.signal(Sig::Kill).unwrap(), Sent::Delivered);
    assert!(exited_held(&*p, None).unwrap());
    child.wait().unwrap();
}

#[skuld::test]
fn open_after_reap_is_none() {
    let (child, _stdin, id) = blocker();
    child.kill().unwrap();
    child.wait().unwrap();
    // The handle's end consumes the zombie, which a wait leaves.
    drop(child);
    assert!(open(id).unwrap().is_none());
}

#[skuld::test]
fn open_with_wrong_start_token_is_none_and_sends_nothing() {
    let (child, _stdin, id) = blocker();
    let other = id.with_other_value();
    assert!(open(other).unwrap().is_none());
    // Still running: the right identity opens and sees no exit.
    let p = open(id).unwrap().expect("the blocker is alive");
    assert!(!exited_held(&*p, Some(Duration::ZERO)).unwrap());
    child.kill().unwrap();
    child.wait().unwrap();
}

#[skuld::test]
fn exited_before_first_look_returns_true() {
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    child.kill().unwrap();
    wait_until_zombie(id.pid());
    assert!(exited_held(&*p, Some(Duration::ZERO)).unwrap());
    child.wait().unwrap();
}

/// Mutant: `ESRCH` is an error, or a reaped process is reported `Delivered`.
#[skuld::test]
fn signal_after_exit_is_gone() {
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    child.kill().unwrap();
    child.wait().unwrap();
    // The handle's end consumes the zombie, which a wait leaves.
    drop(child);
    assert_eq!(p.signal(Sig::Kill).unwrap(), Sent::Gone);
    // A reaped process reads as exited, too (POLLHUP).
    assert!(exited_held(&*p, Some(Duration::ZERO)).unwrap());
}

/// Mutant: a look hands out some other fd to wait on. The kernel names a pidfd's process in its
/// `fdinfo`.
#[skuld::test]
fn the_wait_is_on_the_pidfd_of_the_process() {
    use std::os::fd::AsRawFd;
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    match p.exited().unwrap() {
        Exit::Running(crate::os_process::WaitFor::Readable(fd)) => {
            let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", fd.as_raw_fd())).unwrap();
            assert!(
                info.lines().any(|line| line == format!("Pid:	{}", id.pid())),
                "not a pidfd of {}: {info}",
                id.pid()
            );
        }
        other => panic!("a live process reads Running(Readable): {other:?}"),
    }
    child.kill().unwrap();
    child.wait().unwrap();
}

/// Mutant: `terminate` sends `SIGKILL`.
#[skuld::test]
fn terminate_sends_sigterm_and_the_blocker_exits() {
    use std::os::unix::process::ExitStatusExt;
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    terminate(&*p).unwrap();
    assert_eq!(
        child.wait().unwrap().signal(),
        Some(rustix::process::Signal::TERM.as_raw())
    );
}

#[skuld::test]
fn kill_sends_sigkill_and_the_blocker_exits() {
    use std::os::unix::process::ExitStatusExt;
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    kill(&*p).unwrap();
    assert_eq!(
        child.wait().unwrap().signal(),
        Some(rustix::process::Signal::KILL.as_raw())
    );
}

/// A held process that its owner has reaped is gone: both acts are `Ok`. Mutant: `ESRCH` is an
/// error.
#[skuld::test]
fn kill_and_terminate_of_a_held_process_that_is_gone_are_ok() {
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    child.kill().unwrap();
    child.wait().unwrap();
    kill(&*p).unwrap();
    terminate(&*p).unwrap();
}

/// `Process::kill` promises the raw errno of a refused kill. Mutant: `signal` wraps the errno in
/// an `io_context`, so `raw_os_error()` is `None`.
#[skuld::test]
fn refused_signal_keeps_its_raw_errno() {
    let (child, _stdin, id) = blocker();
    let p = open(id).unwrap().expect("a live process opens");
    let refused = crate::signal::seams::refuse_kills();
    let err = p.signal(Sig::Kill).unwrap_err();
    drop(refused);
    let crate::error::Error::Io(e) = err else {
        panic!("expected Error::Io, got {err:?}");
    };
    assert_eq!(e.raw_os_error(), Some(libc::EPERM), "{e:?}");
    assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied);
    child.kill().unwrap();
    child.wait().unwrap();
}

// OsChild =====

/// A look at a running child hands out the child's own pidfd to wait on.
#[skuld::test]
fn try_observe_of_a_running_child_waits_on_its_pidfd() {
    use std::os::fd::AsRawFd;

    use crate::os_process::child::{adopted_blocker, TryObserveOutcome};
    use crate::os_process::WaitFor;
    let (os, _id, stdin) = adopted_blocker();
    let TryObserveOutcome::Running(WaitFor::Readable(fd)) = os.try_observe().unwrap() else {
        panic!("a running child is waited on its pidfd");
    };
    assert_eq!(fd.as_raw_fd(), os.os_handle().as_raw_fd());
    drop(stdin);
    assert!(exited_held(&*os, None).unwrap());
    assert!(matches!(os.try_observe().unwrap(), TryObserveOutcome::Exited(_)));
}

/// A look at an exited child sees its record and consumes nothing: it says so again, and the
/// consuming reap that follows still has the record.
///
/// Mutant: the look is a consuming `waitid`.
#[skuld::test]
fn try_observe_of_an_exited_child_leaves_the_record_for_the_reap() {
    use crate::os_process::child::{adopted_blocker, TryObserveOutcome};
    use crate::wait::exit_only::Reap;
    let (os, _id, stdin) = adopted_blocker();
    drop(stdin);
    assert!(exited_held(&*os, None).unwrap());
    for _ in 0..2 {
        assert!(matches!(os.try_observe().unwrap(), TryObserveOutcome::Exited(_)));
    }
    assert!(matches!(os.try_reap().unwrap(), Reap::Reaped(_)));
}

/// A reap of a running child consumes nothing.
///
/// Mutant: the reap answers a record for a child that has not exited.
#[skuld::test]
fn try_reap_of_a_running_child_has_nothing_to_consume() {
    use crate::os_process::child::adopted_blocker;
    use crate::wait::exit_only::Reap;
    let (os, _id, _stdin) = adopted_blocker();
    assert!(matches!(os.try_reap().unwrap(), Reap::Running));
}

/// A reap of an exited child consumes its record once; the child is then foreign.
///
/// Mutant: a second reap hands the record out again, or answers `Running`.
#[skuld::test]
fn try_reap_of_an_exited_child_reaps_once_then_is_foreign() {
    use crate::os_process::child::{adopted_blocker, Foreign};
    use crate::wait::exit_only::Reap;
    let (os, _id, stdin) = adopted_blocker();
    drop(stdin);
    assert!(exited_held(&*os, None).unwrap());
    assert!(matches!(os.try_reap().unwrap(), Reap::Reaped(_)));
    assert!(matches!(os.try_reap().unwrap(), Reap::Foreign(Foreign::Gone)));
}

/// A peek of an exited child sees its record and consumes nothing: the reap that follows has it.
///
/// Mutant: the peek is a consuming `waitid`.
#[skuld::test]
fn peek_of_an_exited_child_consumes_nothing() {
    use crate::os_process::child::{adopted_blocker, PeekOutcome};
    use crate::wait::exit_only::Reap;
    let (os, _id, stdin) = adopted_blocker();
    drop(stdin);
    assert!(exited_held(&*os, None).unwrap());
    assert!(matches!(os.peek().unwrap(), PeekOutcome::Exit(_)));
    assert!(matches!(os.peek().unwrap(), PeekOutcome::Exit(_)));
    assert!(matches!(os.try_reap().unwrap(), Reap::Reaped(_)));
}

/// A zombie only its tracer sees has a readable pidfd and no record: a look asks for a recheck, not
/// for a wait on a pidfd that would return at once for ever. The tracer then hands the zombie back
/// and the look has the record.
///
/// Mutant: the look answers `Running(Readable)`, which spins its holder.
#[skuld::test]
fn try_observe_of_a_zombie_only_its_tracer_sees_is_recheck(#[fixture(tracer_group)] _group: &Group) {
    use std::os::fd::AsRawFd as _;

    use crate::os_process::child::{adopt_std, TryObserveOutcome};
    use crate::test_child::reaped_elsewhere::kill_own_child;
    use crate::test_support::foreign_tracer::{self, REAP};

    let (child, _stdin) = crate::test_child::blocker_with(foreign_tracer::allow_any_tracer).into_parts();
    let id = ProcessId::of(child.id()).found().expect("identity");
    let os = adopt_std(child, id).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
    let mut tracer = foreign_tracer::spawn_helper(id.pid());
    // Setup: the test ends the tracee itself.
    kill_own_child(id.pid());
    // The exit, which the tracer alone can see: the pidfd turns readable.
    let mut fds = [libc::pollfd {
        fd: os.os_handle().as_raw_fd(),
        events: libc::POLLIN,
        revents: 0,
    }];
    loop {
        // SAFETY: `fds` is one valid `pollfd`.
        let r = unsafe { libc::poll(fds.as_mut_ptr(), 1, -1) };
        if r == 1 {
            break;
        }
        let e = std::io::Error::last_os_error();
        assert!(r == -1 && e.raw_os_error() == Some(libc::EINTR), "poll: {e}");
    }
    assert!(matches!(os.try_observe().unwrap(), TryObserveOutcome::Recheck));
    tracer.send(REAP);
    tracer.expect("reaped");
    assert!(matches!(os.try_observe().unwrap(), TryObserveOutcome::Exited(_)));
    tracer.finish();
}

/// A Linux box owns the kernel it was built with, lends it through its `OwnedChild`, and lets it go
/// with the box: the row the test stated before the hand-over answers, and the test's own handle on
/// the kernel is the only one left once the box is dropped.
///
/// Mutant: the box lends a host kernel, drops its kernel at construction, or keeps it past its drop.
#[skuld::test]
fn a_linux_child_owns_and_lends_the_kernel_it_was_built_with() {
    use std::sync::Arc;

    use crate::identity::FakeKernel;
    use crate::os_process::linux::LinuxProcess;

    let target = rustix::process::Pid::from_raw(4242).expect("a positive pid");
    // The box's end looks through its kernel first, and a pidfd of this process, which is no child of
    // it, is `ECHILD` there: a foreign reap, with nothing to consume.
    let kernel = Arc::new(
        FakeKernel::new()
            .on_signal_probe(target, Err(rustix::io::Errno::PERM))
            .on_peek(std::process::id(), Err(rustix::io::Errno::CHILD)),
    );
    let stand_in = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
        .expect("a pidfd of this process");
    let owned = crate::child::owned::OwnedChild::new(
        Box::new(LinuxProcess::new(Arc::clone(&kernel), None, stand_in)),
        crate::elevation::front::TrackedKind::Own,
    );
    assert_eq!(Arc::strong_count(&kernel), 2, "the box owns a handle on the kernel");

    assert_eq!(owned.kernel().signal_probe(target), Err(rustix::io::Errno::PERM));

    drop(owned);
    assert_eq!(Arc::strong_count(&kernel), 1, "dropping the box releases the kernel");
    assert_eq!(kernel.peeks_left(), 0, "the box's end looked through its kernel");
}

/// A child whose pid is unknown (a box built over its pidfd alone) is signalled
/// and reaped through the pidfd alone.
///
/// Mutant: a pid is required to signal or to settle the child.
#[skuld::test]
fn a_pidless_linux_child_is_signalled_and_reaped_through_its_pidfd() {
    use crate::child::owned::owned_tests::teardown_lines::said_of;
    use crate::child::owned::teardown::{Disposition, Kill};
    use crate::error::ChildFate;
    use crate::os_process::linux::LinuxProcess;

    let child = crate::test_child::blocker().into_inner();
    let id = ProcessId::of(child.id())
        .found()
        .expect("the live child has an identity");
    let pidfd = crate::child::front_cgroup_tests::pidfd_of(id.pid());
    // std's `Child` neither kills nor reaps on drop; the pidfd is all that is left of it.
    drop(child);
    let owned = crate::child::owned::OwnedChild::new(
        Box::new(LinuxProcess::new(crate::identity::HostKernel, None, pidfd)),
        crate::elevation::front::TrackedKind::Own,
    );
    assert_eq!(owned.pid(), None);
    let torn = owned.tear_down(
        None,
        Kill {
            disposition: Disposition::Leave,
            tree: None,
        },
        None,
    );
    assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
    assert!(matches!(said_of(&torn), Some((log::Level::Debug, _))), "{torn:?}");
}

/// A send through the pidfd of a pid-less child that finds it reaped says "already gone" without a
/// number.
///
/// Mutant: the unknown pid is worded as `child 0`.
#[skuld::test]
fn a_signal_to_a_reaped_pidless_linux_child_is_named_without_a_number() {
    use crate::os_process::linux::LinuxProcess;
    use crate::os_process::OsProcess as _;

    crate::log_capture::install();
    let mut child = crate::test_child::blocker();
    let id = ProcessId::of(child.id())
        .found()
        .expect("the live child has an identity");
    let pidfd = crate::child::front_cgroup_tests::pidfd_of(id.pid());
    let os = LinuxProcess::new(crate::identity::HostKernel, None, pidfd);
    assert_eq!(os.signal(Sig::Kill).expect("kill"), Sent::Delivered);
    child.wait().expect("reap the killed child");
    let mark = crate::log_capture::mark();
    assert_eq!(os.signal(Sig::Kill).expect("a reaped child is gone"), Sent::Gone);
    let said = crate::log_capture::records_since_on_current_thread(mark, "already gone");
    assert_eq!(said.len(), 1, "{said:?}");
    assert!(
        said[0]
            .1
            .contains(&format!("to {}: ", crate::os_process::PIDLESS_CHILD)),
        "{said:?}"
    );
}

/// A pidfd that does not name one of our children is refused. The pidfd of our parent stands in
/// for the pidfd a reused number would open: the confirming `waitid` answers `ECHILD` to it.
///
/// Mutant: `adopt_pidfd` adopts the pidfd it opened without the confirming `waitid`.
#[skuld::test]
fn adopting_a_pidfd_that_is_not_our_child_is_refused() {
    use crate::identity::{FakeKernel, HostKernel};
    use crate::os_process::child::adopt_pidfd;

    let child = crate::test_child::blocker();
    let id = ProcessId::of(child.id())
        .found()
        .expect("the live child has an identity");
    // SAFETY: `getppid` takes no arguments and cannot fail.
    let parent = unsafe { libc::getppid() } as u32;
    let kernel =
        FakeKernel::over(&HostKernel).on_pidfd_open(id.pid(), Ok(crate::child::front_cgroup_tests::pidfd_of(parent)));
    let error = match adopt_pidfd(kernel, id) {
        Ok(_) => panic!("adopted a pidfd that is not our child"),
        Err(refused) => refused,
    };
    let crate::error::Error::Io(e) = &error else {
        panic!("a pidfd that is not our child is an io error: {error:?}")
    };
    assert_eq!(e.raw_os_error(), Some(libc::ECHILD), "{e:?}");
}

/// A child that has exited and not been reaped is still ours: it is adopted, and left unreaped.
///
/// Mutant: the confirming `waitid` refuses an exit record.
#[skuld::test]
fn adopting_an_exited_unreaped_child_succeeds_and_reaps_nothing() {
    use crate::os_process::child::adopt_std;
    use crate::wait::exit_only::Reap;

    let mut child = crate::test_child::blocker().into_inner();
    drop(child.stdin.take());
    let id = ProcessId::of(child.id())
        .found()
        .expect("the live child has an identity");
    wait_until_zombie(id.pid());
    let os = adopt_std(child, id).unwrap_or_else(|(e, _)| panic!("adopt: {e}"));
    assert!(matches!(os.try_reap().unwrap(), Reap::Reaped(_)));
}