cosca 0.8.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
//! The `communicate` rows that hold on every platform. `pump_tests.rs` holds the Unix-only ones:
//! those about signals and `RLIMIT_NPROC`, which Windows does not have.

use std::io;

use super::{merge, Finished, Pump};
use crate::error::Error;
use crate::pipe::{PipeReader, PipeWriter};
use crate::stdio::Fd;
use crate::test_child::Console;
use crate::test_pattern::pattern_bytes;
use crate::Stdio;

/// A child running `unix` under `/bin/sh -c` or `windows` under `cmd /C`, with all three standard
/// streams piped.
pub(super) fn shell(unix: &str, windows: &str) -> crate::Child {
    let mut c = crate::test_child::command(Console::Hidden);
    if cfg!(windows) {
        c.args(["cmd", "/C", windows]);
    } else {
        c.args(["/bin/sh", "-c", unix]);
    }
    c.stdin(Stdio::pipe()).expect("stdin");
    c.stdout(Stdio::pipe()).expect("stdout");
    c.stderr(Stdio::pipe()).expect("stderr");
    c.spawn().expect("spawn")
}

/// A child that exits without reading its input ends the input: `communicate` returns what it
/// printed, not an error. The input is larger than a pipe buffer, so the write is still in progress
/// when the child exits.
///
/// Mutant: a broken pipe on stdin is an `Err`.
#[skuld::test]
fn a_child_that_stops_reading_stdin_ends_the_input() {
    let mut child = shell("echo out; exit 3", "echo out& exit 3");
    let input = vec![b'x'; 1 << 20];
    let out = child.communicate(Some(&input)).expect("communicate");
    assert_eq!(out.status.code(), Some(3));
    assert_eq!(out.stdout, if cfg!(windows) { &b"out\r\n"[..] } else { &b"out\n"[..] });
}

/// `path` as text for a command line that does not quote it, refused if the shell (`cmd` on Windows,
/// `sh` elsewhere) would read part of it as syntax.
fn unquotable(path: &std::path::Path) -> String {
    let path = path.display().to_string();
    let syntax: &[char] = if cfg!(windows) {
        &['"', '%', '!', '&', '|', '<', '>', '(', ')', '^', ',', ';', '=']
    } else {
        &[
            '"', '\'', '\\', '$', '`', '&', '|', ';', '<', '>', '(', ')', '*', '?', '[', ']', '{', '}',
        ]
    };
    assert!(
        !path.contains(|c: char| c.is_whitespace() || syntax.contains(&c)),
        "the temp path {path} has whitespace or a character the shell reads as syntax: set TMPDIR (TEMP on Windows) to a path that has not"
    );
    path
}

/// Each output stream is read while the other is idle: a child that fills stderr past a pipe
/// buffer before it writes stdout, and the reverse, both finish.
///
/// Mutant: stdout is read to EOF before stderr is read at all, or the reverse.
#[skuld::test]
fn each_stream_is_read_while_the_other_is_idle() {
    // `cmd` cannot make output of a size, so both shells print a file of that size. The path cannot
    // be quoted in the command: the spawn escapes a `"` in an argument as `\"`, which `cmd` does not
    // read. So the path must hold nothing the shell treats as syntax.
    let dir = tempfile::tempdir().expect("tempdir");
    let big = dir.path().join("big");
    let expected = pattern_bytes(1_000_000);
    std::fs::write(&big, &expected).expect("write the file");
    let big = unquotable(&big);
    for (unix, windows) in [
        (
            format!("cat {big} >&2; cat {big}"),
            format!("type {big} 1>&2& type {big}"),
        ),
        (
            format!("cat {big}; cat {big} >&2"),
            format!("type {big}& type {big} 1>&2"),
        ),
    ] {
        let mut child = shell(&unix, &windows);
        let out = child.communicate(None).expect("communicate");
        assert!(out.status.success(), "{unix}");
        assert!(out.stdout == expected, "stdout, {unix}");
        assert!(out.stderr == expected, "stderr, {unix}");
    }
}

/// A piped stdin that gets no input, or an empty one, is closed at once: the child sees EOF.
///
/// Mutant: the stdin pipe is held open until the child exits.
#[skuld::test]
fn no_input_closes_stdin() {
    for input in [None, Some(&[][..])] {
        let mut child = shell("cat", "sort");
        let out = child.communicate(input).expect("communicate");
        assert!(out.status.success(), "{input:?}");
        assert!(out.stdout.is_empty(), "{input:?}");
    }
}

/// Input for a child whose stdin is not piped is an `InvalidInput` error, and the streams that are
/// piped are left in place for the next call.
///
/// Mutant: the bytes are dropped and `communicate` returns `Ok`.
#[skuld::test]
fn input_without_a_piped_stdin_is_invalid_input() {
    let mut c = crate::test_child::command(Console::Hidden);
    if cfg!(windows) {
        c.args(["cmd", "/C", "echo out"]);
    } else {
        c.args(["/bin/sh", "-c", "echo out"]);
    }
    c.stdin(Stdio::null()).expect("stdin");
    c.stdout(Stdio::pipe()).expect("stdout");
    let mut child = c.spawn().expect("spawn");
    let error = child.communicate(Some(b"x")).expect_err("input has nowhere to go");
    assert!(
        matches!(&error, crate::error::Error::Io(e) if e.kind() == std::io::ErrorKind::InvalidInput),
        "{error:?}"
    );
    let out = child.communicate(None).expect("the pipes were not taken");
    assert_eq!(out.stdout, if cfg!(windows) { &b"out\r\n"[..] } else { &b"out\n"[..] });
}

// Errors of the shared merge =====
//
// `Pump::assemble` takes the platform's way of making an end ready as closures, and the state the
// platform's loop feeds (`wrote`, `Collected::took`) is shared, so these rows run the merge with
// closures of their own and no loop.

/// A child's three ends, and the child, which must outlive them being closed.
fn ends() -> (crate::Child, Option<PipeWriter>, Option<PipeReader>, Option<PipeReader>) {
    let mut child = shell("cat", "sort");
    let stdin = child.take_stdin_writer();
    let stdout = child.take_reader(Fd::STDOUT);
    let stderr = child.take_reader(Fd::STDERR);
    (child, stdin, stdout, stderr)
}

fn refused() -> io::Error {
    io::Error::new(io::ErrorKind::PermissionDenied, "refused")
}

fn kind<T>(result: io::Result<T>) -> Option<io::ErrorKind> {
    result.err().map(|e| e.kind())
}

/// An end that cannot be made ready fails its own stream and no other, whichever of stdout and
/// stderr it is.
///
/// Mutant: the failure of one end is dropped, or reported on the other stream.
#[skuld::test]
fn an_end_that_cannot_be_made_ready_fails_only_its_stream() {
    let (_child, stdin, stdout, _stderr) = ends();
    let finished = Pump::<(), ()>::assemble(stdin, &[], stdout, None, |_| Ok(()), |_| Err(refused())).finish();
    assert_eq!(kind(finished.stdout), Some(io::ErrorKind::PermissionDenied));
    assert!(finished.stderr.expect("stderr was not opened").is_empty());
    assert!(finished.stdin.is_ok());

    let (_child, stdin, _stdout, stderr) = ends();
    let finished = Pump::<(), ()>::assemble(stdin, &[], None, stderr, |_| Ok(()), |_| Err(refused())).finish();
    assert_eq!(kind(finished.stderr), Some(io::ErrorKind::PermissionDenied));
    assert!(finished.stdout.expect("stdout was not opened").is_empty());
    assert!(finished.stdin.is_ok());
}

/// An stdin end that cannot be made ready fails the stdin stream, and the input is not written.
///
/// Mutant: the failure is dropped, so the call reports the input as delivered.
#[skuld::test]
fn a_stdin_that_cannot_be_made_ready_fails_the_stdin_stream() {
    let (_child, stdin, stdout, stderr) = ends();
    let pump = Pump::<(), ()>::assemble(stdin, b"input", stdout, stderr, |_| Err(refused()), |_| Ok(()));
    assert!(pump.feed.is_none());
    let finished = pump.finish();
    assert_eq!(kind(finished.stdin), Some(io::ErrorKind::PermissionDenied));
    assert!(finished.stdout.is_ok() && finished.stderr.is_ok());
}

/// An end whose reads fail, for the stdout of a pump, and the stdin end the child keeps: Unix, a
/// loopback connection whose peer closed with `SO_LINGER` 0, a reset that `poll` reports readable
/// and `read` fails as `ECONNRESET`; Windows, the child's own stdin writer, which `ReadFile` refuses
/// as access denied.
fn unreadable(stdin: Option<PipeWriter>) -> (Option<PipeWriter>, PipeReader) {
    #[cfg(unix)]
    {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let end = std::net::TcpStream::connect(listener.local_addr().expect("address")).expect("connect");
        let (peer, _) = listener.accept().expect("accept");
        rustix::net::sockopt::set_socket_linger(&peer, Some(std::time::Duration::ZERO)).expect("linger");
        drop(peer);
        (stdin, PipeReader::from(std::os::fd::OwnedFd::from(end)))
    }
    #[cfg(windows)]
    {
        let writer = stdin.expect("the child's stdin");
        (None, PipeReader::from(std::os::windows::io::OwnedHandle::from(writer)))
    }
}

/// The loop of the platform's pump ends a stream whose read fails and fails that stream alone: the
/// other stream's bytes are all collected.
///
/// Mutant: the loop reads a failed read as the stream's EOF, drops the error, or stops the loop.
#[skuld::test]
fn a_read_the_loop_gets_an_error_from_fails_its_stream_and_keeps_the_others_bytes() {
    let mut child = shell("echo keep >&2", "echo keep>&2");
    let (stdin, bad) = unreadable(child.take_stdin_writer());
    let mut pump = Pump::new(stdin, &[], Some(bad), child.take_reader(Fd::STDERR));
    pump.run().expect("a read error does not fail the loop");
    let finished = pump.finish();
    assert!(finished.stdout.is_err(), "stdout's read error is its own");
    assert_eq!(
        finished.stderr.expect("stderr"),
        if cfg!(windows) {
            &b"keep\r\n"[..]
        } else {
            &b"keep\n"[..]
        }
    );
    child.wait().expect("wait");
}

/// A read error on a stream ends and fails that stream, and the bytes of the other stay. This row
/// pins `Collected::took`, the bookkeeping both platforms' loops share;
/// the row above reaches the loop's own handling.
///
/// Mutant: a read error on one stream discards the other's bytes, or is read as its EOF.
#[skuld::test]
fn a_read_error_fails_its_stream_and_keeps_the_others_bytes() {
    let reset = || io::Error::from(io::ErrorKind::ConnectionReset);

    let (_child, stdin, stdout, stderr) = ends();
    let mut pump = Pump::<(), ()>::assemble(stdin, &[], stdout, stderr, |_| Ok(()), |_| Ok(()));
    assert!(pump.stderr.collected.took(Ok(3), b"abc"));
    assert!(!pump.stdout.collected.took(Err(reset()), &[]));
    let finished = pump.finish();
    assert_eq!(kind(finished.stdout), Some(io::ErrorKind::ConnectionReset));
    assert_eq!(finished.stderr.expect("stderr"), b"abc");

    let (_child, stdin, stdout, stderr) = ends();
    let mut pump = Pump::<(), ()>::assemble(stdin, &[], stdout, stderr, |_| Ok(()), |_| Ok(()));
    assert!(pump.stdout.collected.took(Ok(3), b"abc"));
    assert!(!pump.stderr.collected.took(Err(reset()), &[]));
    let finished = pump.finish();
    assert_eq!(kind(finished.stderr), Some(io::ErrorKind::ConnectionReset));
    assert_eq!(finished.stdout.expect("stdout"), b"abc");
}

// Precedence of the merge -----

fn exit_zero() -> std::process::ExitStatus {
    #[cfg(unix)]
    use std::os::unix::process::ExitStatusExt;
    #[cfg(windows)]
    use std::os::windows::process::ExitStatusExt;
    std::process::ExitStatus::from_raw(0)
}

fn finished(stdin: io::Result<()>, stdout: io::Result<Vec<u8>>, stderr: io::Result<Vec<u8>>) -> Finished {
    Finished { stdin, stdout, stderr }
}

fn failed(kind: io::ErrorKind) -> io::Error {
    io::Error::from(kind)
}

/// The I/O kind of the one failure `error` is: an `Io`.
fn io_kind(error: &Error) -> io::ErrorKind {
    match error {
        Error::Io(e) => e.kind(),
        other => panic!("not an I/O error: {other:?}"),
    }
}

/// The streams a merge's warn lines name, in order.
fn warned_streams(mark: usize) -> Vec<String> {
    crate::log_capture::records_since_on_current_thread(mark, "communicate")
        .into_iter()
        .map(|(level, line)| {
            assert_eq!(level, log::Level::Warn, "{line}");
            ["pump", "stdout", "stderr", "stdin"]
                .into_iter()
                .find(|stream| line.contains(&format!("{stream}:")))
                .unwrap_or_else(|| panic!("no stream named: {line}"))
                .to_owned()
        })
        .collect()
}

/// The first failure is the answer as it is, in the order wait, pump, stdout, stderr, stdin. When it has
/// a slot (the wait's `Unassessable` here) the later ones are its cause, in that order, none dropped,
/// each naming its stream.
///
/// Mutant: any two of the five swapped, the wait's error after a stream's, a later failure dropped, or
/// a carried failure that names no stream.
#[skuld::test]
fn a_first_failure_with_a_slot_carries_every_later_one_in_order_naming_its_stream() {
    use io::ErrorKind::{BrokenPipe, NotFound, PermissionDenied, Unsupported};
    let wait = Error::Unassessable {
        detail: "the wait".into(),
        source: None,
    };
    let all = finished(
        Err(failed(Unsupported)),
        Err(failed(PermissionDenied)),
        Err(failed(NotFound)),
    );
    let answer = merge(Err(wait), Some(failed(BrokenPipe)), all).expect_err("everything failed");
    assert!(
        matches!(&answer, Error::Unassessable { detail, .. } if detail == "the wait"),
        "{answer:?}"
    );
    let below = answer.failures_below();
    let kinds: Vec<_> = below.iter().map(|e| io_kind(e)).collect();
    assert_eq!(kinds, [BrokenPipe, PermissionDenied, NotFound, Unsupported]);
    for (peer, stream) in below.iter().zip(["pump", "stdout", "stderr", "stdin"]) {
        let named = peer.io_errors().next().map(ToString::to_string);
        assert_eq!(named.as_deref(), Some(stream), "{peer:?}");
    }
}

/// An `Io` first is the answer as it is, in the same order, with its OS code, at every count: no
/// variant's meaning covers a failed pipe. Each later failure is logged at warn, naming its stream and
/// the call, in order.
///
/// Mutants: the `Io` goes below an `Unassessable` once it has peers; a peer is dropped, logged at debug,
/// or names no stream; the order of the five changes.
#[skuld::test]
fn an_io_first_failure_is_the_answer_at_every_count_and_each_later_one_is_a_warn_naming_its_stream() {
    use io::ErrorKind::{BrokenPipe, ConnectionReset, NotFound, PermissionDenied, Unsupported};
    crate::log_capture::install();
    let all = || {
        finished(
            Err(failed(Unsupported)),
            Err(failed(PermissionDenied)),
            Err(failed(NotFound)),
        )
    };

    let mark = crate::log_capture::mark();
    let answer = merge(Ok(exit_zero()), Some(failed(BrokenPipe)), all()).expect_err("everything failed");
    assert_eq!(io_kind(&answer), BrokenPipe, "the pump's failure is first: {answer:?}");
    assert_eq!(warned_streams(mark), ["stdout", "stderr", "stdin"]);

    let mark = crate::log_capture::mark();
    let answer = merge(Ok(exit_zero()), None, all()).expect_err("the streams failed");
    assert_eq!(
        io_kind(&answer),
        PermissionDenied,
        "stdout's failure is first: {answer:?}"
    );
    assert_eq!(warned_streams(mark), ["stderr", "stdin"]);

    let mark = crate::log_capture::mark();
    let no_stdout = finished(Err(failed(Unsupported)), Ok(Vec::new()), Err(failed(NotFound)));
    let answer = merge(Ok(exit_zero()), None, no_stdout).expect_err("two failed");
    assert_eq!(io_kind(&answer), NotFound, "{answer:?}");
    assert_eq!(warned_streams(mark), ["stdin"]);

    let mark = crate::log_capture::mark();
    let only_stdin = finished(Err(failed(ConnectionReset)), Ok(Vec::new()), Ok(Vec::new()));
    let answer = merge(Ok(exit_zero()), None, only_stdin).expect_err("one failed");
    assert_eq!(io_kind(&answer), ConnectionReset, "{answer:?}");
    assert!(warned_streams(mark).is_empty());

    // The wait's own `Io` is first too.
    let mark = crate::log_capture::mark();
    let answer = merge(
        Err(Error::Io(failed(io::ErrorKind::TimedOut))),
        Some(failed(BrokenPipe)),
        all(),
    )
    .expect_err("everything failed");
    assert_eq!(io_kind(&answer), io::ErrorKind::TimedOut, "{answer:?}");
    assert_eq!(warned_streams(mark), ["pump", "stdout", "stderr", "stdin"]);
}

/// A failure of a stream is returned even when the child exited successfully, and no failure
/// leaves the bytes of both streams in the `Output`.
///
/// Mutant: a stream's failure is dropped when the wait succeeds, or the bytes are not returned.
#[skuld::test]
fn a_stream_failure_after_a_successful_exit_is_returned_and_none_returns_the_bytes() {
    let failing = finished(Ok(()), Ok(b"out".to_vec()), Err(failed(io::ErrorKind::NotFound)));
    let answer = merge(Ok(exit_zero()), None, failing).expect_err("stderr failed");
    assert_eq!(
        io_kind(&answer),
        io::ErrorKind::NotFound,
        "a lone failure is the `Io` as it is"
    );

    let out = merge(
        Ok(exit_zero()),
        None,
        finished(Ok(()), Ok(b"out".to_vec()), Ok(b"err".to_vec())),
    )
    .expect("nothing failed");
    assert!(out.status.success());
    assert_eq!((out.stdout, out.stderr), (b"out".to_vec(), b"err".to_vec()));
}

/// A write error on stdin that is not a broken pipe fails the stdin stream and ends the input; a
/// broken pipe only ends it.
///
/// Mutant: any write error is an end of input, or a broken pipe fails the stream.
#[skuld::test]
fn only_a_broken_pipe_is_a_benign_end_of_stdin() {
    let (_child, stdin, stdout, stderr) = ends();
    let mut pump = Pump::<(), ()>::assemble(stdin, b"input", stdout, stderr, |_| Ok(()), |_| Ok(()));
    assert!(pump.feed.is_some());
    pump.wrote(Err(io::Error::from(io::ErrorKind::BrokenPipe)));
    assert!(pump.feed.is_none());
    assert!(pump.finish().stdin.is_ok());

    let (_child, stdin, stdout, stderr) = ends();
    let mut pump = Pump::<(), ()>::assemble(stdin, b"input", stdout, stderr, |_| Ok(()), |_| Ok(()));
    pump.wrote(Err(refused()));
    assert!(pump.feed.is_none());
    assert_eq!(kind(pump.finish().stdin), Some(io::ErrorKind::PermissionDenied));
}