use std::cell::RefCell;
use std::ffi::{OsStr, OsString};
use std::os::fd::{AsFd, AsRawFd, OwnedFd};
use rustix::process::{pidfd_send_signal, waitid, Signal, WaitId, WaitIdOptions};
use super::{
channel, spawn, Failure, Program, Progress, Record, RefusalKind, Reporter, SpawnError, Spawned, Status, StepFailure,
};
use crate::child::spawn::spawn_lock;
use crate::os_process::linux::fork::{
clone_with_pidfd, fails_with, fallback, fork_with_pidfd, CloneKind, Fork, ForkFn, NewChild,
};
use crate::test_support::{close_every_descriptor_above_stdio, exit_status, settled};
type Steps<'a> = &'a dyn Fn() -> Result<(), StepFailure>;
type ReportingSteps<'a> = &'a dyn Fn(Reporter) -> Result<(), StepFailure>;
fn program(candidate: &str, argv: &[&str], env: &[(&str, &str)]) -> Program {
candidates(&[candidate], argv, env)
}
fn candidates(paths: &[&str], argv: &[&str], env: &[(&str, &str)]) -> Program {
let paths: Vec<&OsStr> = paths.iter().map(OsStr::new).collect();
let argv: Vec<&OsStr> = argv.iter().map(OsStr::new).collect();
let env = env.iter().map(|(k, v)| (OsString::from(k), OsString::from(v)));
Program::new(&paths, &argv, env).expect("no NUL")
}
fn tool(candidate: &str) -> Program {
program(candidate, &[candidate], &[])
}
const STEP_EXIT: i32 = 117;
fn start(kind: CloneKind, fork: ForkFn, program: &Program, steps: Steps<'_>) -> Result<Spawned, SpawnError> {
start_reporting(kind, fork, program, &|_| steps())
}
fn start_reporting(
kind: CloneKind,
fork: ForkFn,
program: &Program,
steps: ReportingSteps<'_>,
) -> Result<Spawned, SpawnError> {
let _lock = spawn_lock();
unsafe { spawn(kind, fork, program, &[], &mut |reporter| steps(reporter), STEP_EXIT) }
}
fn started(kind: CloneKind, program: &Program, steps: Steps<'_>) -> Spawned {
start(kind, fork_with_pidfd, program, steps)
.unwrap_or_else(|e| panic!("the spawn of a {kind:?} child failed: {e:?}"))
}
fn started_reporting(kind: CloneKind, program: &Program, steps: ReportingSteps<'_>) -> Spawned {
start_reporting(kind, fork_with_pidfd, program, steps)
.unwrap_or_else(|e| panic!("the spawn of a {kind:?} child failed: {e:?}"))
}
fn terminating_signal(child: &NewChild) -> Option<i32> {
let done = waitid(WaitId::PidFd(child.pidfd.as_fd()), WaitIdOptions::EXITED)
.expect("waitid on the pidfd")
.expect("a blocking wait returns a status");
done.terminating_signal()
}
fn write_record(writer: &OwnedFd, record: Record) {
let written = rustix::io::write(writer, &record.encode()).expect("write a record");
assert_eq!(written, 4);
}
fn assert_nonblocking(status: &Status) {
let flags = rustix::fs::fcntl_getfl(status.as_fd()).unwrap();
assert!(
flags.contains(rustix::fs::OFlags::NONBLOCK),
"the status read end must not block"
);
}
#[skuld::test]
fn the_status_reads_records_in_order_and_a_failure_sticks() {
let (mut status, writer) = channel(CloneKind::Plain, &[]).expect("a channel");
assert_nonblocking(&status);
assert_eq!(status.progress().unwrap(), Progress::Pending);
write_record(&writer, Record::Ready);
assert_eq!(status.progress().unwrap(), Progress::Ready);
assert_eq!(status.progress().unwrap(), Progress::Ready);
write_record(&writer, Record::Failed(Failure::Exec(libc::ENOENT)));
let failed = Progress::Failed(Failure::Exec(libc::ENOENT));
assert_eq!(status.progress().unwrap(), failed);
assert_eq!(status.progress().unwrap(), failed, "a failure is the answer for good");
let (mut status, writer) = channel(CloneKind::Plain, &[]).expect("a channel");
write_record(&writer, Record::Ready);
write_record(
&writer,
Record::Failed(Failure::Step(StepFailure {
kind: 3,
value: libc::EACCES as u16,
})),
);
assert_eq!(
status.progress().unwrap(),
Progress::Failed(Failure::Step(StepFailure {
kind: 3,
value: libc::EACCES as u16
})),
"both records are in the pipe: the failure is the answer"
);
let (mut status, writer) = channel(CloneKind::Plain, &[]).expect("a channel");
drop(writer);
assert_eq!(status.progress().unwrap(), Progress::Ended { ready: false });
let (mut status, writer) = channel(CloneKind::Plain, &[]).expect("a channel");
write_record(&writer, Record::Ready);
drop(writer);
assert_eq!(status.progress().unwrap(), Progress::Ended { ready: true });
}
fn assert_garbage_ends_the_channel(garbage: &[u8]) {
let (mut status, writer) = channel(CloneKind::Plain, &[]).expect("a channel");
rustix::io::write(&writer, garbage).unwrap();
let first = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| status.progress()));
if cfg!(debug_assertions) {
assert!(first.is_err(), "{garbage:?} is a bug in debug builds");
} else {
assert_eq!(first.unwrap().unwrap_err().kind(), std::io::ErrorKind::InvalidData);
}
write_record(&writer, Record::Ready);
assert_eq!(
status.progress().unwrap_err().kind(),
std::io::ErrorKind::InvalidData,
"a whole record after {garbage:?} is not decoded"
);
assert!(status.could_have_started().is_err());
}
#[skuld::test]
fn a_short_status_read_ends_the_channel_as_an_error() {
assert_garbage_ends_the_channel(&[1, 2]);
}
#[skuld::test]
fn a_record_of_no_kind_ends_the_channel_as_an_error() {
assert_garbage_ends_the_channel(&(0x0100u32 << 16 | 7).to_ne_bytes());
}
#[skuld::test]
fn an_exec_that_fails_gives_its_errno_record() {
let missing = tool("/nonexistent/cosca-b5-core");
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let mut spawned = started(kind, &missing, &|| Ok(()));
let progress = if kind == CloneKind::Vfork {
spawned.status.progress().unwrap()
} else {
settled(&mut spawned.status)
};
assert_eq!(progress, Progress::Failed(Failure::Exec(libc::ENOENT)), "{kind:?}");
assert!(!spawned.status.could_have_started().unwrap(), "{kind:?}");
assert_eq!(exit_status(&spawned.child), 127, "{kind:?}");
}
}
fn file_in(dir: &std::path::Path, name: &str, body: &str, mode: u32) -> String {
use std::os::unix::fs::PermissionsExt;
let path = dir.join(name);
std::fs::write(&path, body).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
path.into_os_string().into_string().expect("a UTF-8 path")
}
#[skuld::test]
fn an_exec_that_finds_no_file_goes_on_to_the_next_candidate() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("file");
std::fs::write(&file, b"x").unwrap();
let under_a_file = format!("{}/tool", file.display());
let gone = format!("{}/gone", dir.path().display());
let exits_7 = file_in(dir.path(), "exits-7", "#!/bin/sh\nexit 7\n", 0o755);
let exits_7 = exits_7.as_str();
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let spawned = started(
kind,
&candidates(&[&gone, &under_a_file, exits_7], &["tool"], &[]),
&|| Ok(()),
);
assert_eq!(exit_status(&spawned.child), 7, "{kind:?}");
let mut none = started(kind, &candidates(&[&gone, &under_a_file], &["tool"], &[]), &|| Ok(()));
assert_eq!(
settled(&mut none.status),
Progress::Failed(Failure::Exec(libc::ENOTDIR)),
"{kind:?}: the last candidate's error"
);
}
}
#[skuld::test]
fn an_exec_that_fails_otherwise_ends_the_candidates() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let ran = file_in(
dir.path(),
"ran-it",
&format!("#!/bin/sh\necho > '{}'\n", marker.display()),
0o755,
);
let denied = file_in(dir.path(), "denied", "#!/bin/sh\n", 0o644);
let no_format = file_in(dir.path(), "no-format", "exit 5\n", 0o755);
for (first, errno) in [(&denied, libc::EACCES), (&no_format, libc::ENOEXEC)] {
let mut spawned = started(
CloneKind::Vfork,
&candidates(&[first, &ran], &["tool"], &[]),
&|| Ok(()),
);
assert_eq!(
spawned.status.progress().unwrap(),
Progress::Failed(Failure::Exec(errno)),
"{first}"
);
assert_eq!(exit_status(&spawned.child), 127, "{first}");
assert!(!marker.exists(), "{first}: the next candidate ran");
}
}
#[skuld::test]
fn an_exec_enoent_of_a_file_that_exists_ends_the_candidates() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let later = tempfile::tempdir().unwrap();
let ran = file_in(
later.path(),
"tool",
&format!("#!/bin/sh\necho > '{}'\n", marker.display()),
0o755,
);
let no_interpreter = file_in(dir.path(), "tool", "#!/nonexistent/cosca-interpreter\n", 0o755);
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let mut spawned = started(kind, &candidates(&[&no_interpreter, &ran], &["tool"], &[]), &|| Ok(()));
assert_eq!(
settled(&mut spawned.status),
Progress::Failed(Failure::Exec(libc::ENOENT)),
"{kind:?}"
);
assert_eq!(exit_status(&spawned.child), 127, "{kind:?}");
assert!(!marker.exists(), "{kind:?}: the later candidate ran");
}
}
#[skuld::test]
fn a_later_candidate_that_is_not_a_file_is_skipped_and_one_that_cannot_be_examined_stops() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let ran = file_in(
dir.path(),
"ran-it",
&format!("#!/bin/sh\necho > '{}'\nexit 7\n", marker.display()),
0o755,
);
let gone = format!("{}/gone", dir.path().display());
let a_directory = dir.path().join("a-directory");
std::fs::create_dir(&a_directory).unwrap();
let a_directory = a_directory.to_str().unwrap();
let looped = dir.path().join("loop");
std::os::unix::fs::symlink(&looped, &looped).unwrap();
let looped = looped.to_str().unwrap();
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let spawned = started(kind, &candidates(&[&gone, a_directory, &ran], &["tool"], &[]), &|| {
Ok(())
});
assert_eq!(exit_status(&spawned.child), 7, "{kind:?}: the file after the directory");
assert!(marker.exists(), "{kind:?}");
std::fs::remove_file(&marker).unwrap();
let mut stopped = started(kind, &candidates(&[&gone, looped, &ran], &["tool"], &[]), &|| Ok(()));
assert_eq!(
settled(&mut stopped.status),
Progress::Failed(Failure::Exec(libc::ELOOP)),
"{kind:?}"
);
assert_eq!(exit_status(&stopped.child), 127, "{kind:?}");
assert!(
!marker.exists(),
"{kind:?}: the candidate after an unexaminable one ran"
);
}
}
#[skuld::test]
fn a_step_that_fails_gives_its_record_and_the_program_never_runs() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let ran = program(
"/bin/sh",
&["sh", "-c", "echo > \"$1\"", "sh", marker.to_str().unwrap()],
&[],
);
let failure = StepFailure {
kind: 9,
value: libc::EACCES as u16,
};
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let mut spawned = started(kind, &ran, &|| Err(failure));
assert_eq!(
settled(&mut spawned.status),
Progress::Failed(Failure::Step(failure)),
"{kind:?}"
);
assert_eq!(
exit_status(&spawned.child),
STEP_EXIT,
"{kind:?}: a failed step ends the child with the caller's code, not an exec failure's 127"
);
assert!(!marker.exists(), "{kind:?}: the program ran");
}
}
#[skuld::test]
fn a_child_that_dies_before_ready_is_not_started() {
let program = tool("/bin/true");
let mut spawned = started(CloneKind::Vfork, &program, &|| {
unsafe { libc::_exit(5) }
});
let progress = spawned.status.progress().unwrap();
assert!(
matches!(progress, Progress::Pending | Progress::Ended { ready: false }),
"{progress:?}"
);
assert!(!spawned.status.could_have_started().unwrap(), "{progress:?}");
assert_eq!(exit_status(&spawned.child), 5);
assert_eq!(settled(&mut spawned.status), Progress::Ended { ready: false });
}
#[skuld::test]
fn a_child_that_was_ready_and_execed_is_started() {
let exits_3 = program("/bin/sh", &["sh", "-c", "exit 3"], &[]);
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let mut spawned = started(kind, &exits_3, &|| Ok(()));
let progress = settled(&mut spawned.status);
assert_eq!(progress, Progress::Ended { ready: true }, "{kind:?}");
assert!(spawned.status.could_have_started().unwrap(), "{kind:?}");
assert_eq!(exit_status(&spawned.child), 3, "{kind:?}");
}
}
unsafe fn clone_fallback(kind: CloneKind) -> Result<Fork, i32> {
unsafe { fallback(|_| fails_with(libc::ENOSYS), clone_with_pidfd, kind) }
}
#[skuld::test]
fn the_vfork_kind_returns_only_after_the_child_ran_its_steps() {
let nonblocking_pipe = || {
let (read, write) = std::io::pipe().unwrap();
let flags = rustix::fs::fcntl_getfl(&read).unwrap() | rustix::fs::OFlags::NONBLOCK;
rustix::fs::fcntl_setfl(&read, flags).unwrap();
(read, write)
};
let program = tool("/bin/true");
for (path, fork) in [
("clone3", fork_with_pidfd as ForkFn),
("clone(2)", clone_fallback as ForkFn),
] {
let (witness_read, witness_write) = nonblocking_pipe();
let w = witness_write.as_raw_fd();
let spawned = start(CloneKind::Vfork, fork, &program, &move || {
unsafe { libc::write(w, b"x".as_ptr().cast(), 1) };
Ok(())
})
.unwrap_or_else(|e| panic!("{path}: the vfork spawn failed: {e:?}"));
let mut byte = [0u8; 1];
assert_eq!(
rustix::io::read(&witness_read, &mut byte),
Ok(1),
"{path}: the spawn returned before the child ran its steps"
);
exit_status(&spawned.child);
let (witness_read, witness_write) = nonblocking_pipe();
let w = witness_write.as_raw_fd();
let (release_read, release_write) = std::io::pipe().unwrap();
let held = held_until_released(&release_read, &release_write);
let spawned = start(CloneKind::Plain, fork, &program, &move || {
held()?;
unsafe { libc::write(w, b"x".as_ptr().cast(), 1) };
Ok(())
})
.unwrap_or_else(|e| panic!("{path}: the plain spawn failed: {e:?}"));
assert_eq!(
rustix::io::read(&witness_read, &mut byte),
Err(rustix::io::Errno::AGAIN),
"{path}: the plain child ran its steps past the hold before the parent released it"
);
drop(release_write);
assert_eq!(exit_status(&spawned.child), 0, "{path}");
assert_eq!(rustix::io::read(&witness_read, &mut byte), Ok(1), "{path}");
}
}
thread_local! {
static HOLDER: RefCell<Option<NewChild>> = const { RefCell::new(None) };
}
unsafe fn holder_then_fork(kind: CloneKind) -> Result<Fork, i32> {
match unsafe { fork_with_pidfd(CloneKind::Plain) }? {
Fork::Child => loop {
unsafe { libc::pause() };
},
Fork::Parent(holder) => HOLDER.with(|h| *h.borrow_mut() = Some(holder)),
}
unsafe { fork_with_pidfd(kind) }
}
struct Holder;
impl Drop for Holder {
fn drop(&mut self) {
if let Some(holder) = HOLDER.with(|h| h.borrow_mut().take()) {
pidfd_send_signal(&holder.pidfd, Signal::KILL).expect("kill the holder");
exit_status_or_signal(&holder);
}
}
}
fn exit_status_or_signal(child: &NewChild) {
waitid(WaitId::PidFd(child.pidfd.as_fd()), WaitIdOptions::EXITED)
.expect("waitid on the pidfd")
.expect("a blocking wait returns a status");
}
#[skuld::test]
fn a_fork_without_exec_holding_the_channel_does_not_hold_the_return() {
let _holder = Holder;
let program = tool("/bin/true");
let mut spawned = start(CloneKind::Vfork, holder_then_fork, &program, &|| Ok(())).expect("the vfork spawn returns");
assert_nonblocking(&spawned.status);
let progress = spawned.status.progress().unwrap();
assert_eq!(
progress,
Progress::Ready,
"the pipe has a second writer, so it has not ended"
);
assert!(spawned.status.could_have_started().unwrap());
exit_status(&spawned.child);
}
unsafe fn both_refused(kind: CloneKind) -> Result<Fork, i32> {
unsafe { fallback(|_| fails_with(libc::ENOSYS), |_| fails_with(libc::EPERM), kind) }
}
unsafe fn eagain(_: CloneKind) -> Result<Fork, i32> {
fails_with(libc::EAGAIN)
}
#[skuld::test]
fn a_clone_refused_on_both_paths_is_unsupported() {
let program = tool("/bin/true");
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let refused = start(kind, both_refused, &program, &|| Ok(())).err();
assert!(
matches!(refused, Some(SpawnError::Unsupported(RefusalKind::Eperm))),
"{kind:?}: {refused:?}"
);
let other = start(kind, eagain, &program, &|| Ok(())).err();
assert!(
matches!(other, Some(SpawnError::Fork(libc::EAGAIN))),
"{kind:?}: {other:?}"
);
}
}
#[skuld::test]
fn the_child_gets_exactly_the_env_block_built_in_the_parent() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("environ");
let dump = program(
"/bin/sh",
&["sh", "-c", "cat /proc/$$/environ > \"$1\"", "sh", out.to_str().unwrap()],
&[("COSCA_B5_ONE", "1"), ("COSCA_B5_TWO", "two words")],
);
let spawned = started(CloneKind::Vfork, &dump, &|| Ok(()));
assert_eq!(exit_status(&spawned.child), 0);
assert_eq!(
std::fs::read(&out).unwrap(),
b"COSCA_B5_ONE=1\0COSCA_B5_TWO=two words\0"
);
}
#[skuld::test]
fn a_full_fd_table_is_a_pipe_error() {
let Some(done) = crate::test_own_process::own_process(
crate::test_own_process::test_path!(a_full_fd_table_is_a_pipe_error),
crate::test_spawn::spawn,
) else {
return;
};
let program = tool("/bin/true");
let _restore = crate::test_child::exhaust_fds(&done);
let refused = start(CloneKind::Plain, fork_with_pidfd, &program, &|| Ok(())).err();
assert!(matches!(refused, Some(SpawnError::Pipe(libc::EMFILE))), "{refused:?}");
}
#[skuld::test]
fn a_program_killed_after_its_exec_is_started_and_not_failed() {
let suicidal = program("/bin/sh", &["sh", "-c", "kill -KILL $$"], &[]);
let mut spawned = started(CloneKind::Plain, &suicidal, &|| Ok(()));
assert_eq!(settled(&mut spawned.status), Progress::Ended { ready: true });
assert_eq!(terminating_signal(&spawned.child), Some(libc::SIGKILL));
}
fn held_until_released(
release_read: &std::io::PipeReader,
release_write: &std::io::PipeWriter,
) -> impl Fn() -> Result<(), StepFailure> {
let (r, w) = (release_read.as_raw_fd(), release_write.as_raw_fd());
move || {
unsafe {
libc::close(w);
let mut byte = 0u8;
libc::read(r, (&mut byte as *mut u8).cast(), 1);
}
Ok(())
}
}
#[skuld::test]
fn after_a_plain_clone_an_empty_channel_could_still_start() {
let (release_read, release_write) = std::io::pipe().unwrap();
let steps = held_until_released(&release_read, &release_write);
let mut spawned = started(CloneKind::Plain, &tool("/bin/true"), &steps);
assert_eq!(spawned.status.progress().unwrap(), Progress::Pending);
assert!(spawned.status.could_have_started().unwrap());
drop(release_write);
assert_eq!(settled(&mut spawned.status), Progress::Ended { ready: true });
assert_eq!(exit_status(&spawned.child), 0);
}
const SIGPIPE_BIT: u64 = 1 << (libc::SIGPIPE - 1);
fn status_dump() -> Program {
program(
"/bin/sh",
&[
"sh",
"-c",
"while IFS= read -r line; do printf '%s\\n' \"$line\"; done < /proc/$$/status",
],
&[],
)
}
fn signal_mask(dump: &str, field: &str) -> u64 {
let hex = dump
.lines()
.find_map(|line| line.strip_prefix(field))
.unwrap_or_else(|| panic!("no {field} line in the program's status"));
u64::from_str_radix(hex.trim(), 16).expect("a hexadecimal mask")
}
fn status_of_a_program_whose_parent_stopped_reading(steps: impl Fn(Reporter) + 'static) -> String {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("status");
let out_c = std::ffi::CString::new(out.to_str().unwrap()).unwrap();
let dump = status_dump();
let (release_read, release_write) = std::io::pipe().unwrap();
let hold = held_until_released(&release_read, &release_write);
let Spawned { child, status } = started_reporting(CloneKind::Plain, &dump, &move |reporter| {
unsafe {
let file = libc::open(out_c.as_ptr(), libc::O_WRONLY | libc::O_CREAT, 0o644);
libc::dup2(file, 1);
libc::close(file);
}
steps(reporter);
hold()
});
drop(status);
drop(release_write);
assert_eq!(exit_status(&child), 0);
std::fs::read_to_string(out).unwrap()
}
fn block_sigpipe() {
unsafe {
let mut default: libc::sigaction = std::mem::zeroed();
default.sa_sigaction = libc::SIG_DFL;
libc::sigaction(libc::SIGPIPE, &default, std::ptr::null_mut());
let mut set: libc::sigset_t = std::mem::zeroed();
libc::sigaddset(&mut set, libc::SIGPIPE);
libc::sigprocmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
}
}
#[skuld::test]
fn a_child_whose_parent_stopped_reading_still_execs_with_its_signals_as_inherited() {
let dump = status_of_a_program_whose_parent_stopped_reading(|_| {
unsafe {
let mut default: libc::sigaction = std::mem::zeroed();
default.sa_sigaction = libc::SIG_DFL;
libc::sigaction(libc::SIGPIPE, &default, std::ptr::null_mut());
}
});
assert_eq!(signal_mask(&dump, "SigPnd:") & SIGPIPE_BIT, 0, "{dump}");
assert_eq!(signal_mask(&dump, "SigBlk:") & SIGPIPE_BIT, 0, "{dump}");
}
#[skuld::test]
fn a_blocked_sigpipe_raised_by_a_record_write_is_not_left_pending_for_the_program() {
let dump = status_of_a_program_whose_parent_stopped_reading(|_| block_sigpipe());
assert_eq!(signal_mask(&dump, "SigPnd:") & SIGPIPE_BIT, 0, "{dump}");
assert_ne!(
signal_mask(&dump, "SigBlk:") & SIGPIPE_BIT,
0,
"the mask the child inherited is back: {dump}"
);
}
#[skuld::test]
fn a_sigpipe_pending_before_the_record_writes_still_reaches_the_program() {
let dump = status_of_a_program_whose_parent_stopped_reading(|_| {
block_sigpipe();
unsafe {
let pid = libc::syscall(libc::SYS_getpid);
let tid = libc::syscall(libc::SYS_gettid);
libc::syscall(libc::SYS_tgkill, pid, tid, libc::SIGPIPE);
}
});
assert_ne!(
signal_mask(&dump, "SigPnd:") & SIGPIPE_BIT,
0,
"the signal pending before the writes is gone: {dump}"
);
assert_ne!(signal_mask(&dump, "SigBlk:") & SIGPIPE_BIT, 0, "{dump}");
}
#[skuld::test]
fn a_ready_record_that_cannot_be_written_stops_the_child_before_its_exec() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let ran = program(
"/bin/sh",
&["sh", "-c", "echo > \"$1\"", "sh", marker.to_str().unwrap()],
&[],
);
let mut spawned = started(CloneKind::Plain, &ran, &|| {
close_every_descriptor_above_stdio();
Ok(())
});
assert_eq!(exit_status(&spawned.child), STEP_EXIT);
assert_eq!(settled(&mut spawned.status), Progress::Ended { ready: false });
assert!(!marker.exists(), "the program ran with no ready record written");
}
fn report_failed(errno: i32) -> StepFailure {
StepFailure {
kind: 6,
value: errno as u16,
}
}
#[skuld::test]
fn the_status_keeps_the_first_report_beside_the_other_records() {
let (mut status, writer) = channel(CloneKind::Plain, &[]).expect("a channel");
assert_eq!(status.reported(), None);
write_record(&writer, Record::Reported(0));
assert_eq!(
status.progress().unwrap(),
Progress::Pending,
"a report is not the ready record"
);
assert_eq!(status.reported(), Some(0));
write_record(&writer, Record::Reported(9));
write_record(&writer, Record::Ready);
assert_eq!(status.progress().unwrap(), Progress::Ready);
assert_eq!(status.reported(), Some(0), "the first report stays");
write_record(&writer, Record::Failed(Failure::Exec(libc::ENOENT)));
assert_eq!(
status.progress().unwrap(),
Progress::Failed(Failure::Exec(libc::ENOENT))
);
assert_eq!(status.reported(), Some(0));
}
#[skuld::test]
fn a_steps_report_is_read_by_the_parent_and_the_program_runs() {
let exits_3 = program("/bin/sh", &["sh", "-c", "exit 3"], &[]);
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let mut spawned = started_reporting(kind, &exits_3, &|reporter| {
unsafe { reporter.report(0) }.map_err(report_failed)?;
unsafe { reporter.report(7) }.map_err(report_failed)
});
assert_eq!(
settled(&mut spawned.status),
Progress::Ended { ready: true },
"{kind:?}"
);
assert_eq!(spawned.status.reported(), Some(0), "{kind:?}: the first report");
assert_eq!(exit_status(&spawned.child), 3, "{kind:?}");
}
}
#[skuld::test]
fn a_report_before_a_failed_step_is_readable_beside_the_failure() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join("ran");
let ran = program(
"/bin/sh",
&["sh", "-c", "echo > \"$1\"", "sh", marker.to_str().unwrap()],
&[],
);
let failure = report_failed(libc::EPERM);
for kind in [CloneKind::Vfork, CloneKind::Plain] {
let mut spawned = started_reporting(kind, &ran, &|reporter| {
unsafe { reporter.report(libc::EPERM as u16) }.map_err(report_failed)?;
Err(failure)
});
assert_eq!(
settled(&mut spawned.status),
Progress::Failed(Failure::Step(failure)),
"{kind:?}"
);
assert_eq!(spawned.status.reported(), Some(libc::EPERM as u16), "{kind:?}");
assert_eq!(exit_status(&spawned.child), STEP_EXIT, "{kind:?}");
assert!(!marker.exists(), "{kind:?}: the program ran");
}
}
#[skuld::test]
fn a_report_that_cannot_be_written_is_its_errno() {
let mut spawned = started_reporting(CloneKind::Plain, &tool("/bin/true"), &|reporter| {
close_every_descriptor_above_stdio();
let written = unsafe { reporter.report(1) };
unsafe { libc::_exit(if written == Err(libc::EBADF) { 41 } else { 42 }) }
});
assert_eq!(exit_status(&spawned.child), 41);
assert_eq!(settled(&mut spawned.status), Progress::Ended { ready: false });
}
#[skuld::test]
fn a_report_to_a_parent_that_stopped_reading_is_no_error_and_leaves_no_sigpipe() {
let dump = status_of_a_program_whose_parent_stopped_reading(|reporter| {
block_sigpipe();
if unsafe { reporter.report(1) }.is_err() {
unsafe { libc::_exit(43) }
}
});
assert_eq!(signal_mask(&dump, "SigPnd:") & SIGPIPE_BIT, 0, "{dump}");
assert_ne!(
signal_mask(&dump, "SigBlk:") & SIGPIPE_BIT,
0,
"the mask the child inherited is back: {dump}"
);
}