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
//! `proc_state` reads a child's state only through the checked `/proc` view.

use super::{proc_state, read_proc_state, StateUnknown};
use crate::containment::cgroup::test_support::{handle_of, pidfd_of};
use crate::identity::{FakeKernel, HostKernel, DIVERGED_REASON, UNREADABLE_STATUS_REASON};
use crate::test_child::namespaces as ns;
use crate::test_child::{fixture_path, member_command, StdChild};
use crate::test_groups::{namespaces, pidfd_group_signal, Group};

#[skuld::test]
fn a_live_process_has_a_state_under_the_ordinary_view() {
    assert!(proc_state(
        &HostKernel,
        handle_of(std::process::id(), &pidfd_of(std::process::id()))
    )
    .is_some());
}

/// Mutant: "the state is the field after the state" (`Z` becomes the next field).
#[skuld::test]
fn an_unreaped_exited_child_is_a_zombie() {
    let mut child = crate::test_spawn::spawn(&mut std::process::Command::new("true")).expect("spawn true");
    let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
    loop {
        // SAFETY: a well-formed `waitid`; `info` is an owned, zeroed `siginfo_t`. WNOWAIT leaves
        // the child unreaped.
        let rc = unsafe {
            libc::waitid(
                libc::P_PID,
                child.id() as libc::id_t,
                &mut info,
                libc::WEXITED | libc::WNOWAIT,
            )
        };
        if rc == 0 {
            break;
        }
        let err = std::io::Error::last_os_error();
        assert_eq!(err.raw_os_error(), Some(libc::EINTR), "waitid: {err}");
    }
    assert_eq!(read_proc_state(&HostKernel, child.id()).ok(), Some('Z'));
    assert_eq!(
        proc_state(&HostKernel, handle_of(child.id(), &pidfd_of(child.id()))),
        Some('Z'),
        "its pidfd says it exited"
    );
    child.wait().expect("reap");
}

/// The highest pid the kernel allows is never handed out (`pid_max` is at most 2^22).
#[skuld::test]
fn a_nonexistent_pid_has_no_state_under_the_ordinary_view() {
    let pid = u32::MAX - 1;
    assert_eq!(
        proc_state(&HostKernel, handle_of(pid, &pidfd_of(std::process::id()))),
        None
    );
    let Err(StateUnknown::Skipped(e)) = read_proc_state(&HostKernel, pid) else {
        panic!("expected Skipped");
    };
    assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
}

/// A `stat` read that is a refusal (see `identity::Refusal`) is an unknown state whose cause and
/// debug line say what cosca requires, with the refusing errno below. `EPERM` is one when the
/// checked directory refuses `self/stat` too.
#[skuld::test]
fn a_refused_stat_read_is_an_unknown_state_that_names_openat2() {
    crate::log_capture::install();
    let me = std::process::id();
    for errno in [libc::ENOSYS, libc::EPERM] {
        let kernel = FakeKernel::over(&HostKernel)
            .same_view()
            .on_read(&format!("{me}/stat"), Err(errno))
            .on_read("self/stat", Err(libc::ENODEV));
        let Err(StateUnknown::Refused(e)) = read_proc_state(&kernel, me) else {
            panic!("{errno}: expected Refused");
        };
        let said = crate::error::Report(&e).to_string();
        assert!(said.contains("requires openat2"), "{errno}: {said}");
        assert!(
            crate::error::first_os_code(&e).is_some_and(|code| code == errno || code == libc::ENODEV),
            "{errno}: {said}"
        );

        let mark = crate::log_capture::mark();
        assert_eq!(proc_state(&kernel, handle_of(me, &pidfd_of(me))), None);
        let records =
            crate::log_capture::records_since_on_current_thread(mark, &format!("pid {me}'s state is unknown"));
        assert!(
            records.iter().any(|(_, line)| line.contains("requires openat2")),
            "{errno}: {records:?}"
        );
    }
}

/// A `stat` the checked `/proc` would not read across a mount (`EXDEV`, `ELOOP`) is named so in the
/// unknown state, not left a bare errno. Mutant: "the leaf's state read keeps the raw errno".
#[skuld::test]
fn a_stat_beyond_a_mount_is_an_unknown_state_that_says_so() {
    let me = std::process::id();
    for errno in [libc::EXDEV, libc::ELOOP] {
        let kernel = FakeKernel::over(&HostKernel)
            .same_view()
            .on_read(&format!("{me}/stat"), Err(errno));
        let why = read_proc_state(&kernel, me).expect_err("no state");
        let said = crate::error::Report(&why).to_string();
        assert!(said.contains("lies beyond a mount"), "{errno}: {said}");
    }
}

/// What an unknown state wraps is its `source()`: the skipped read's `io::Error`, the refusal's
/// error, the layer of an unreadable stat (the OS error is below that layer), and an unusable view.
/// Each is built by the read that produced it.
#[skuld::test]
fn an_unknown_state_has_what_it_wraps_as_its_source() {
    let me = std::process::id();
    let stat = format!("{me}/stat");
    let over = || FakeKernel::over(&HostKernel).same_view();

    let skipped = read_proc_state(&over().on_read(&stat, Err(libc::ENOENT)), me).expect_err("no state");
    assert!(matches!(skipped, StateUnknown::Skipped(_)), "{skipped:?}");
    let source = std::error::Error::source(&skipped).expect("a skipped stat has a source");
    assert_eq!(
        source
            .downcast_ref::<std::io::Error>()
            .and_then(std::io::Error::raw_os_error),
        Some(libc::ENOENT)
    );

    let refused = read_proc_state(&over().on_read(&stat, Err(libc::ENOSYS)), me).expect_err("no state");
    assert!(matches!(refused, StateUnknown::Refused(_)), "{refused:?}");
    let source = std::error::Error::source(&refused).expect("a refused stat has a source");
    assert!(source.downcast_ref::<crate::error::Error>().is_some(), "{source}");

    let unreadable = read_proc_state(&over().on_read(&stat, Err(libc::EIO)), me).expect_err("no state");
    assert!(matches!(unreadable, StateUnknown::Unreadable(_)), "{unreadable:?}");
    let source = std::error::Error::source(&unreadable).expect("an unreadable stat has a source");
    let cause = source
        .downcast_ref::<crate::error::Error>()
        .expect("the source is the read's failure as an error");
    assert_eq!(crate::error::first_os_code(cause), Some(libc::EIO), "{cause}");
    assert!(crate::error::said(cause).contains(&stat), "{cause}");

    let view = StateUnknown::View(crate::identity::ProcOpenFailure::opening(rustix::io::Errno::IO).into());
    let source = std::error::Error::source(&view).expect("an unusable view has a source");
    assert!(
        source.downcast_ref::<crate::identity::ViewUnreadable>().is_some(),
        "{source}"
    );
}

/// An `EPERM` whose re-check of `self/stat` fails is an unknown state whose chain holds both failures,
/// so the debug line `proc_state` logs has the pid's own `EPERM` beside the re-check's error. Mutant:
/// "the unknown state keeps the re-check's failure and drops the pid's `EPERM`".
#[skuld::test]
fn an_unknown_state_after_a_failed_recheck_keeps_the_pids_eperm() {
    let me = std::process::id();
    let kernel = FakeKernel::over(&HostKernel)
        .same_view()
        .on_read(&format!("{me}/stat"), Err(libc::EPERM))
        .on_read("self/stat", Err(libc::EIO));

    let why = read_proc_state(&kernel, me).expect_err("no state");

    let said = crate::error::said(&why);
    let members = crate::error::several_in(&why).unwrap_or_else(|| panic!("a list of both failures: {said}"));
    let codes: Vec<_> = members.iter().map(|m| crate::error::first_os_code(*m)).collect();
    assert_eq!(codes, [Some(libc::EIO), Some(libc::EPERM)], "{said}");
}

/// The debug line of an unknown state carries the OS error of the view that could not be used, once:
/// each layer of the chain says only its own words.
#[skuld::test]
fn the_line_of_an_unknown_state_says_the_os_error_once() {
    crate::log_capture::install();
    let me = std::process::id();
    let kernel = FakeKernel::over(&HostKernel).open_proc_fails(rustix::io::Errno::MFILE);
    let mark = crate::log_capture::mark();

    assert_eq!(proc_state(&kernel, handle_of(me, &pidfd_of(me))), None);

    let records = crate::log_capture::records_since_on_current_thread(mark, &format!("pid {me}'s state is unknown"));
    let os_error = std::io::Error::from(rustix::io::Errno::MFILE).to_string();
    assert!(
        records.iter().any(|(_, line)| line.matches(&os_error).count() == 1),
        "{records:?}"
    );
}

/// What a stat that could not be read says is its own: the OS error is the `source()`, not
/// repeated in the text.
#[skuld::test]
fn an_unknown_state_says_what_failed_and_not_the_os_error() {
    let os_error = std::io::Error::from_raw_os_error(libc::EIO).to_string();
    let me = std::process::id();
    let kernel = FakeKernel::over(&HostKernel)
        .same_view()
        .on_read(&format!("{me}/stat"), Err(libc::EIO));
    let unreadable = read_proc_state(&kernel, me).expect_err("no state").to_string();
    assert!(!unreadable.contains(&os_error), "{unreadable}");
    let view = StateUnknown::View(crate::identity::ProcOpenFailure::opening(rustix::io::Errno::IO).into()).to_string();
    assert!(!view.contains(&os_error), "{view}");
}

#[skuld::test]
fn an_unparsable_stat_is_named() {
    assert!(matches!(
        super::state_from_stat(b"garbage".to_vec()),
        Err(StateUnknown::Unparsable(s)) if s == b"garbage"
    ));
}

/// Mutant: "read `/proc/{pid}/stat` by path whatever the view", and "every non-Same view is
/// the same cause".
#[skuld::test]
fn no_state_is_read_when_the_view_is_diverged_or_unassessable() {
    let me = std::process::id();
    let diverged = FakeKernel::over(&HostKernel).diverged_view();
    match read_proc_state(&diverged, me).expect_err("no state") {
        StateUnknown::View(v) => assert_eq!(v.reason, DIVERGED_REASON),
        other => panic!("{other:?}"),
    }
    assert_eq!(proc_state(&diverged, handle_of(me, &pidfd_of(me))), None);

    let unreadable = FakeKernel::over(&HostKernel).unreadable_view();
    match read_proc_state(&unreadable, me).expect_err("no state") {
        StateUnknown::View(v) => assert_eq!(v.reason, UNREADABLE_STATUS_REASON),
        other => panic!("{other:?}"),
    }
    assert_eq!(proc_state(&unreadable, handle_of(me, &pidfd_of(me))), None);
}

/// pid 1 of a new pid namespace whose `/proc` is still the outer one: `/proc/1` is the outer
/// init, whose state says nothing about this process.
#[skuld::test]
fn namespaces_an_outer_procfs_gives_no_state(#[fixture(namespaces)] _group: &Group) {
    ns::run(fixture_path!(fixture_state_outer));
}

#[skuld::test]
fn fixture_state_outer() {
    if !ns::is_child() {
        return;
    }
    ns::enter_new_pid_ns_for_children();
    ns::run(fixture_path!(fixture_state_inner));
}

#[skuld::test]
fn fixture_state_inner() {
    if !ns::is_child_in_new_pid_ns() {
        return;
    }
    let outer = std::fs::read("/proc/1/stat").expect("the outer /proc/1/stat is readable by path");
    assert!(
        crate::identity::stat_parse::parse_state(&outer).is_some(),
        "control: read by path, pid 1 has a state: {outer:?}"
    );
    assert_eq!(proc_state(&HostKernel, handle_of(1, &pidfd_of(1))), None);
}

/// A file mounted over a child's `stat` is not read.
#[skuld::test]
fn namespaces_a_stat_mounted_over_gives_no_state(#[fixture(namespaces)] _group: &Group) {
    ns::run(fixture_path!(fixture_state_overmount));
}

#[skuld::test]
fn fixture_state_overmount() {
    if !ns::is_child() {
        return;
    }
    ns::enter_private_mount_ns();
    let mut child = StdChild::spawn(&mut member_command(0));
    crate::test_child::await_member_ready(&mut child);
    let pid = child.id();
    assert!(
        proc_state(&HostKernel, handle_of(pid, &pidfd_of(pid))).is_some(),
        "the member has a state before the mount"
    );
    let scratch = tempfile::tempdir().expect("tempdir");
    let fake = scratch.path().join("stat");
    let zeros = ["0"; 16].join(" ");
    std::fs::write(&fake, format!("{pid} (fake) Z 1 1 {zeros} 1 0\n")).expect("write the fake stat");
    ns::bind_over(&fake, std::path::Path::new(&format!("/proc/{pid}/stat")));
    assert_eq!(proc_state(&HostKernel, handle_of(pid, &pidfd_of(pid))), None);
}

/// A closed descriptor breaks the owned-fd contract of the poll, which debug builds assert (release
/// builds answer an error, which [`a_pidfd_that_polls_in_error_gives_no_state`] covers).
///
/// Mutant: the poll's `POLLNVAL` debug assertion is removed.
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "POLLNVAL")]
fn a_closed_pidfd_breaks_the_polls_contract() {
    use std::os::fd::{AsRawFd, BorrowedFd};

    let file = std::fs::File::open("/dev/null").expect("open /dev/null");
    let closed = file.as_raw_fd();
    drop(file);
    // SAFETY: `closed` is no longer open, and the borrow lives only for the poll, which reports
    // that (`POLLNVAL`) and reads nothing.
    let pidfd = unsafe { BorrowedFd::borrow_raw(closed) };
    let child = crate::containment::ChildHandle {
        pid: std::process::id(),
        pidfd,
    };
    let _ = proc_state(&HostKernel, child);
}

/// A pidfd that cannot be polled says nothing about the child: no state, not "exited". Here the poll
/// reports `POLLERR` (a pipe's write end whose reader is closed), which is an error in every
/// profile and below the debug assertion.
///
/// Mutant: any ready poll reads as exit (`POLLERR` included).
#[skuld::test]
fn a_pidfd_that_polls_in_error_gives_no_state() {
    use std::os::fd::AsFd as _;

    let (reader, writer) = std::io::pipe().expect("a pipe");
    drop(reader);
    let child = crate::containment::ChildHandle {
        pid: std::process::id(),
        pidfd: writer.as_fd(),
    };
    assert_eq!(proc_state(&HostKernel, child), None);
}

/// A thread-group leader that exits while other threads run reads `Z` in `/proc` with the pidfd
/// unexited: the group has not exited, so that is no state of the child.
///
/// Mutant: a `/proc` state of `Z` is returned as it reads.
#[skuld::test]
fn a_thread_group_whose_leader_exited_has_no_state() {
    use std::io::BufRead;

    let mut cmd = crate::test_child::fixture_command(fixture_path!(fixture_leader_exits));
    cmd.stdin(std::process::Stdio::piped());
    let mut child = StdChild::spawn(&mut cmd);
    let pid = child.id();
    let pidfd = pidfd_of(pid);
    // The fixture announces once its leader is a zombie: its first stderr line is the gate's.
    let mut stderr = std::io::BufReader::new(child.stderr.take().expect("piped stderr"));
    let mut seen = String::new();
    loop {
        let mut line = String::new();
        let read = stderr.read_line(&mut line).expect("read the fixture");
        seen.push_str(&line);
        assert_ne!(read, 0, "the fixture ended before its leader exited: {seen}");
        if line.trim() == LEADER_EXITED {
            break;
        }
    }

    assert_eq!(
        read_proc_state(&HostKernel, pid).ok(),
        Some('Z'),
        "control: /proc shows the leader's state"
    );
    assert_eq!(proc_state(&HostKernel, handle_of(pid, &pidfd)), None);
}

/// The same group, asked of its identity: `/proc` shows the leader `Z`, but the process has not
/// exited, and its pidfd, which is what a `pidfs` id is proved and polled by, says so. The fixture
/// announces only once `/proc` shows the leader `Z` (the real condition, so the assertion cannot
/// pass for want of waiting).
///
/// Mutant: `is_alive` reads the state letter from `/proc` (`Dead`).
#[skuld::test]
fn a_thread_group_whose_leader_exited_is_alive_to_its_pidfs_identity(
    #[fixture(pidfd_group_signal)] _group: &crate::test_groups::Group,
) {
    use std::io::BufRead;

    use crate::identity::{Existence, Liveness, ProcessId, Resolved};

    let mut cmd = crate::test_child::fixture_command(fixture_path!(fixture_leader_exits));
    cmd.stdin(std::process::Stdio::piped());
    let mut child = StdChild::spawn(&mut cmd);
    let pid = child.id();
    let mut stderr = std::io::BufReader::new(child.stderr.take().expect("piped stderr"));
    let mut seen = String::new();
    loop {
        let mut line = String::new();
        let read = stderr.read_line(&mut line).expect("read the fixture");
        seen.push_str(&line);
        assert_ne!(read, 0, "the fixture ended before its leader exited: {seen}");
        if line.trim() == LEADER_EXITED {
            break;
        }
    }

    assert_eq!(
        read_proc_state(&HostKernel, pid).ok(),
        Some('Z'),
        "control: /proc shows the leader's state"
    );
    let Resolved::Found(id) = ProcessId::of(pid) else {
        panic!("a live group has an identity")
    };
    assert!(id.pidfs_ino().is_some(), "a pidfs host makes pidfs ids");
    assert_eq!(id.exists(), Existence::Present);
    assert_eq!(id.is_alive(), Liveness::Alive);
}

const LEADER_EXITED: &str = "COSCA_LEADER_EXITED";

/// `SIGUSR2`'s handler: ends the one thread it runs on. `exit` (not `exit_group`) leaves the rest of
/// the group running.
extern "C" fn end_this_thread(_: libc::c_int) {
    // SAFETY: a raw `exit` of the calling thread; no other state is touched.
    unsafe { libc::syscall(libc::SYS_exit, 0) };
}

#[skuld::test]
fn fixture_leader_exits() {
    if !ns::is_child() {
        return;
    }
    let pid = std::process::id();
    // The harness runs this on a thread of its own, with the process's main thread (the group's
    // leader) waiting for it. The leader is ended by a signal to it alone.
    // SAFETY: installs a handler that only makes a raw `exit` system call.
    unsafe {
        libc::signal(
            libc::SIGUSR2,
            end_this_thread as extern "C" fn(libc::c_int) as libc::sighandler_t,
        )
    };
    // SAFETY: signals the leader thread of this process, whose tid is the pid.
    let sent = unsafe { libc::syscall(libc::SYS_tgkill, pid, pid, libc::SIGUSR2) };
    assert_eq!(sent, 0, "tgkill: {}", std::io::Error::last_os_error());
    // The leader is a zombie only once it has exited, which this thread cannot otherwise observe.
    while super::read_proc_state(&HostKernel, pid).ok() != Some('Z') {
        std::thread::yield_now();
    }
    eprintln!("{LEADER_EXITED}");
    // Holds the group until the test closes stdin.
    let mut sink = Vec::new();
    _ = std::io::Read::read_to_end(&mut std::io::stdin(), &mut sink);
    // SAFETY: ends the process, whose leader is long gone.
    unsafe { libc::_exit(0) };
}