use std::cell::RefCell;
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::os::fd::{AsRawFd, OwnedFd, RawFd};
use super::{conclude, start, start_via, OnFailure, Program, Started};
use crate::child::spawn::child_env::child_env_over;
use crate::child::spawn::in_child::InChild;
use crate::child::spawn::policy::SpawnPolicy;
use crate::child::spawn::SpawnFailure;
use crate::containment::cgroup::{CgroupLeaf, NotEntered, NotPlaced};
use crate::error::Error;
use crate::os_process::linux::fork::{fails_with, CloneKind, Fork, ForkFn, NewChild, Path};
use crate::test_own_process::{child_completion, own_process, run, test_filter, test_path};
use crate::test_stdio::RestoreStdio;
use crate::Stdio;
const MISSING: &str = "/nonexistent/cosca-fork-spawn-tests";
fn assert_not_found(spawned: Result<crate::Child, Error>, what: &str) {
match spawned {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::NotFound, "{what}: {e:?}"),
Err(other) => panic!("{what}: expected the exec's ENOENT, got {other:?}"),
Ok(child) => panic!(
"{what}: the spawn of a program that does not exist succeeded (child {:?})",
child.pid()
),
}
}
fn fill_to_the_limit() -> Vec<OwnedFd> {
let stdin = rustix::stdio::stdin();
let mut filled = Vec::new();
loop {
match rustix::io::fcntl_dupfd_cloexec(stdin, 3) {
Ok(fd) => filled.push(fd),
Err(rustix::io::Errno::MFILE) => return filled,
Err(e) => panic!("dup fd 0 above stdio: {e}"),
}
}
}
#[skuld::test]
fn a_child_fd_on_the_status_channels_number_does_not_hide_a_failed_exec() {
const BLOCK_LEN: RawFd = 80;
const SOURCES: RawFd = 24;
const LIMIT: libc::rlim_t = 256;
let Some(done) = own_process(
test_path!(a_child_fd_on_the_status_channels_number_does_not_hide_a_failed_exec),
crate::test_spawn::spawn,
) else {
return;
};
let _limit = crate::test_child::lower_fd_limit(&done, LIMIT);
let filled = fill_to_the_limit();
let free: std::collections::BTreeSet<RawFd> = filled.iter().map(AsRawFd::as_raw_fd).collect();
let start = free
.iter()
.copied()
.find(|&n| (n..n + BLOCK_LEN).all(|m| free.contains(&m)))
.expect("a run of free numbers below the limit for the block");
let block = start..start + BLOCK_LEN;
let first_free = block.start + 3 + SOURCES;
let targets = first_free..first_free + SOURCES;
let (_kept, holes): (Vec<_>, Vec<_>) = filled.into_iter().partition(|fd| !block.contains(&fd.as_raw_fd()));
assert_eq!(holes.len(), block.len(), "the block is made of free numbers");
drop(holes);
{
let stand_ins: Vec<OwnedFd> = (0..first_free - block.start)
.map(|_| rustix::io::fcntl_dupfd_cloexec(rustix::stdio::stdin(), 3).expect("a stand-in for a source"))
.collect();
assert_eq!(stand_ins.last().map(AsRawFd::as_raw_fd), Some(first_free - 1));
let (_status, write) = super::fork_exec::channel(CloneKind::Vfork, &[]).expect("a status channel");
assert!(
targets.contains(&write.as_raw_fd()),
"the channel's write end {} is not among the mapped numbers {targets:?}",
write.as_raw_fd()
);
}
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args([MISSING]);
for target in targets {
cmd.fd(target, Stdio::null()).expect("map a child fd");
}
assert_not_found(cmd.spawn(), "a child fd on every number the channels can take");
}
const SLOTS_ENV: &str = "COSCA_TESTCFG_CLOSED_SLOTS";
const STDIO_ENV: &str = "COSCA_TESTCFG_STDIO";
#[skuld::test]
fn a_failed_exec_is_an_error_with_two_of_fds_0_to_2_closed() {
let path = test_path!(a_failed_exec_is_an_error_with_two_of_fds_0_to_2_closed);
if let Some(done) = child_completion(path) {
let slots = std::env::var(SLOTS_ENV).expect(SLOTS_ENV);
let null = std::env::var(STDIO_ENV).expect(STDIO_ENV) == "null";
let slots: Vec<RawFd> = slots.split(',').map(|s| s.parse().expect("a slot")).collect();
let dir = tempfile::tempdir().expect("tempdir");
for (program, what) in [(MISSING, "a failed exec"), ("/bin/sh", "a program that runs")] {
let (out, err) = (dir.path().join("out"), dir.path().join("err"));
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
if program == MISSING {
cmd.args([program]);
} else {
cmd.args([program, "-c", "echo out; echo err >&2"]);
}
if null {
cmd.stdin(Stdio::null()).expect("stdin");
cmd.stdout(Stdio::null()).expect("stdout");
cmd.stderr(Stdio::null()).expect("stderr");
} else {
let file = |path: &std::path::Path| File::create(path).expect("create");
cmd.stdin(Stdio::from_file(File::open("/dev/null").expect("open")))
.expect("stdin");
cmd.stdout(Stdio::from_file(file(&out))).expect("stdout");
cmd.stderr(Stdio::from_file(file(&err))).expect("stderr");
}
let restore = RestoreStdio::close(&done, &slots);
let spawned = cmd.spawn();
let label = format!(
"{what}, slots {slots:?} closed, stdio {}",
if null { "null" } else { "files" }
);
for &slot in &slots {
let slot_fd = unsafe { rustix::fd::BorrowedFd::borrow_raw(slot) };
assert!(
rustix::io::fcntl_getfd(slot_fd).is_err(),
"{label}: the spawn left a descriptor in the closed slot {slot}"
);
}
drop(restore);
if program == MISSING {
assert_not_found(spawned, &label);
if !null {
assert_eq!(std::fs::read(&out).expect("read"), b"", "{label}: stdout");
assert_eq!(std::fs::read(&err).expect("read"), b"", "{label}: stderr");
}
} else {
let status = spawned
.unwrap_or_else(|e| panic!("{label}: {e:?}"))
.wait()
.expect("wait");
assert!(status.success(), "{label}: {status:?}");
if !null {
assert_eq!(std::fs::read(&out).expect("read"), b"out\n", "{label}: stdout");
assert_eq!(std::fs::read(&err).expect("read"), b"err\n", "{label}: stderr");
}
}
}
return;
}
let failures: Vec<String> = ["files", "null"]
.into_iter()
.flat_map(|stdio| ["1,2", "0,1", "0,2", "0,1,2"].map(|slots| (slots, stdio)))
.filter_map(|(slots, stdio)| {
run(
test_filter(path),
&[(SLOTS_ENV, slots), (STDIO_ENV, stdio)],
crate::test_spawn::spawn,
)
.err()
.map(|failure| format!("slots [{slots}], stdio {stdio}: {failure}"))
})
.collect();
assert!(failures.is_empty(), "{}", failures.join("\n"));
}
thread_local! {
pub(super) static HANDED_OVER: RefCell<Option<NewChild>> = const { RefCell::new(None) };
}
pub(super) unsafe fn hand_over(_kind: CloneKind) -> Result<Fork, i32> {
HANDED_OVER
.with(|child| child.borrow_mut().take())
.map(Fork::Parent)
.ok_or(libc::EAGAIN)
}
fn start_over(fork: ForkFn, placement: Option<(&mut CgroupLeaf, bool)>) -> Result<Started, SpawnFailure> {
let (placement, refusing_placement) = match placement {
Some((channel, refusing)) => (Some(channel), refusing),
None => (None, false),
};
let program = Program::new(&[OsStr::new("/bin/true")], &[OsStr::new("true")], std::iter::empty()).expect("no NUL");
let lock = crate::child::spawn::spawn_lock();
start_via(
fork,
&program,
&mut InChild::default(),
crate::identity::spawn_kernel(crate::identity::HostKernel),
OnFailure {
policy: SpawnPolicy::SYNC,
tracked: crate::elevation::front::TrackedKind::Own,
placement,
refusing_placement,
},
&lock,
)
}
fn hand_over_an_ended_child() -> std::process::Child {
hand_over_a_child_that_exited_with(0)
}
fn hand_over_a_child_that_exited_with(code: i32) -> std::process::Child {
let mut child = std::process::Command::new("/bin/sh");
child.args(["-c", &format!("exit {code}")]);
let child = crate::test_spawn::spawn(&mut child).expect("spawn a child that exits at once");
let pid = child.id();
HANDED_OVER.with(|handed| {
*handed.borrow_mut() = Some(NewChild {
pid: pid as i32,
pidfd: crate::containment::cgroup::test_support::pidfd_of(pid),
path: Path::Clone3,
});
});
child
}
fn assert_torn_down(started: Result<Started, SpawnFailure>, pid: u32) -> String {
let failure = match started {
Ok(started) => panic!("a child with no ready record started: pid {}", started.pid),
Err(failure) => failure,
};
let (cause, _fate) = failure.expect_not_started_with_child();
let said = crate::error::Report(&cause).to_string();
assert!(said.contains("died before exec"), "{cause:?}");
let waited = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
std::ptr::null_mut(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
assert_eq!(
(waited, std::io::Error::last_os_error().raw_os_error()),
(-1, Some(libc::ECHILD)),
"the teardown reaped the child it held"
);
said
}
#[skuld::test]
fn a_child_that_ended_before_exec_is_torn_down_and_the_spawn_did_not_start() {
let child = hand_over_an_ended_child();
let pid = child.id();
assert_torn_down(start_over(hand_over, None), pid);
drop(child);
}
fn test_leaf(dir: &std::path::Path) -> CgroupLeaf {
let leaf_path = dir.join("cosca-fork-spawn-leaf");
std::fs::create_dir(&leaf_path).expect("create the leaf");
std::fs::write(leaf_path.join("cgroup.procs"), "").expect("write cgroup.procs");
CgroupLeaf::for_test_at(leaf_path)
}
fn verdict_of(leaf: &mut CgroupLeaf) -> Result<(), NotEntered> {
let pidfd = crate::containment::cgroup::test_support::pidfd_of(std::process::id());
leaf.take_placement(crate::containment::cgroup::test_support::handle_of(
std::process::id(),
&pidfd,
))
.map_err(|not_placed| match not_placed {
NotPlaced::Absent { report, .. } | NotPlaced::Unreadable { report, .. } => report,
})
}
fn start_placed(
leaf: &mut CgroupLeaf,
procs_fd: RawFd,
refusing: bool,
more: impl FnOnce(&mut InChild),
) -> Result<Started, SpawnFailure> {
start_placed_expecting(leaf, procs_fd, refusing, refusing, more)
}
fn start_placed_expecting(
leaf: &mut CgroupLeaf,
procs_fd: RawFd,
refusing: bool,
expects_refusal: bool,
more: impl FnOnce(&mut InChild),
) -> Result<Started, SpawnFailure> {
let program = Program::new(&[OsStr::new("/bin/true")], &[OsStr::new("true")], std::iter::empty()).expect("no NUL");
let mut steps = InChild::default();
unsafe { steps.place(procs_fd, refusing) };
more(&mut steps);
let lock = crate::child::spawn::spawn_lock();
start(
&program,
&mut steps,
crate::identity::spawn_kernel(crate::identity::HostKernel),
OnFailure {
policy: SpawnPolicy::SYNC,
tracked: crate::elevation::front::TrackedKind::Own,
placement: Some(leaf),
refusing_placement: expects_refusal,
},
&lock,
)
}
fn failing_fd_map(steps: &mut InChild) {
crate::child::spawn::fd_map::install(
steps,
vec![crate::child::spawn::fd_map::FdMapping {
parent_fd: File::open("/dev/null").expect("open /dev/null").into(),
child_fd: i32::MAX,
}],
)
.expect("install the mapping");
}
#[skuld::test]
fn a_child_that_placed_itself_and_ended_before_exec_is_torn_down() {
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
let sink = File::options().write(true).open("/dev/null").expect("open /dev/null");
let failure = match start_placed(&mut leaf, sink.as_raw_fd(), true, failing_fd_map) {
Ok(started) => panic!("a child whose fd map failed started: pid {}", started.pid),
Err(failure) => failure,
};
let (cause, _fate) = failure.expect_not_started_with_child();
assert!(
matches!(&cause, Error::Io(e) if e.raw_os_error() == Some(libc::EBADF)),
"{cause:?}"
);
assert_eq!(
verdict_of(&mut leaf),
Ok(()),
"the child placed itself before its fd map failed"
);
}
#[skuld::test]
fn a_child_that_reported_a_failed_placement_and_went_on_is_not_blamed_on_it() {
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
crate::containment::cgroup::fault::set_force_placement_write_result(
crate::containment::cgroup::fault::ForcedWrite::FailsWith(libc::EBUSY),
);
let failure = match start_placed(&mut leaf, -1, false, failing_fd_map) {
Ok(started) => panic!("a child whose fd map failed started: pid {}", started.pid),
Err(failure) => failure,
};
let (cause, _fate) = failure.expect_not_started_with_child();
assert!(
matches!(&cause, Error::Io(e) if e.raw_os_error() == Some(libc::EBADF)),
"the fd map's EBADF, not the placement's EBUSY: {cause:?}"
);
assert_eq!(verdict_of(&mut leaf), Err(NotEntered::WriteFailed(libc::EBUSY)));
}
#[skuld::test]
fn a_child_whose_placement_was_refused_is_handed_to_the_attach() {
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
crate::containment::cgroup::fault::set_force_placement_write_result(
crate::containment::cgroup::fault::ForcedWrite::FailsWith(libc::EBUSY),
);
let started = start_placed(&mut leaf, -1, true, |_| {})
.unwrap_or_else(|failure| panic!("a refused placement is the attach's to read: {failure:?}"));
assert_eq!(
crate::child::spawn::in_child::exit_code(&started),
Some(super::STEP_EXIT),
"the refused child ended in its placement step"
);
drop(started);
assert_eq!(verdict_of(&mut leaf), Err(NotEntered::WriteFailed(libc::EBUSY)));
}
#[skuld::test]
fn a_child_that_ended_in_its_placement_step_says_so() {
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
crate::containment::cgroup::fault::set_force_placement_write_result(
crate::containment::cgroup::fault::ForcedWrite::FailsWith(libc::EBUSY),
);
let failure = match start_placed_expecting(&mut leaf, -1, true, false, |_| {}) {
Ok(started) => panic!("a child that ended in its placement step started: pid {}", started.pid),
Err(failure) => failure,
};
let (cause, _fate) = failure.expect_not_started_with_child();
let Error::Containment { detail, source } = &cause else {
panic!("a placement step's failure is a containment failure: {cause:?}");
};
assert!(
detail.contains("died before exec in its cgroup placement step: the program never ran"),
"{detail}"
);
assert!(
matches!(source.as_deref(), Some(Error::Io(e)) if e.raw_os_error() == Some(libc::EBUSY)),
"the step's errno is the source: {source:?}"
);
}
#[skuld::test]
fn a_child_that_ended_before_it_reported_its_placement_is_torn_down() {
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
let child = hand_over_a_child_that_exited_with(1);
let pid = child.id();
let said = assert_torn_down(start_over(hand_over, Some((&mut leaf, true))), pid);
assert!(!said.contains("placement"), "{said}");
assert_eq!(verdict_of(&mut leaf), Err(NotEntered::NotReported));
drop(child);
}
#[skuld::test]
#[cfg_attr(
debug_assertions,
should_panic(expected = "reached its execve with no placement report")
)]
fn a_child_with_a_leaf_that_reached_its_exec_without_a_report_asserts() {
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
let started = start_via_the_real_clone(&mut leaf);
#[cfg(not(debug_assertions))]
assert_eq!(verdict_of(&mut leaf), Err(NotEntered::NotReported));
drop(started);
}
fn start_via_the_real_clone(leaf: &mut CgroupLeaf) -> Result<Started, SpawnFailure> {
let program = Program::new(&[OsStr::new("/bin/true")], &[OsStr::new("true")], std::iter::empty()).expect("no NUL");
let lock = crate::child::spawn::spawn_lock();
start_via(
crate::os_process::linux::fork::fork_with_pidfd,
&program,
&mut InChild::default(),
crate::identity::spawn_kernel(crate::identity::HostKernel),
OnFailure {
policy: SpawnPolicy::SYNC,
tracked: crate::elevation::front::TrackedKind::Own,
placement: Some(leaf),
refusing_placement: false,
},
&lock,
)
}
#[skuld::test]
fn an_unreadable_status_channel_is_a_started_spawn_with_a_warning() {
crate::log_capture::install();
let mark = crate::log_capture::mark();
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
let child = hand_over_an_ended_child();
let pid = child.id();
let handed = HANDED_OVER
.with(|handed| handed.borrow_mut().take())
.expect("a handed-over child");
let (status, _write) = super::fork_exec::channel(CloneKind::Vfork, &[]).expect("a status channel");
let read_end = status.as_fd().as_raw_fd();
let directory = File::open("/").expect("open a directory");
assert_eq!(unsafe { libc::dup2(directory.as_raw_fd(), read_end) }, read_end);
let started = conclude(
handed,
status,
crate::identity::spawn_kernel(crate::identity::HostKernel),
OnFailure {
policy: SpawnPolicy::SYNC,
tracked: crate::elevation::front::TrackedKind::Own,
placement: Some(&mut leaf),
refusing_placement: false,
},
)
.unwrap_or_else(|failure| panic!("an unreadable status channel failed the spawn: {failure:?}"));
assert_eq!(started.pid, pid);
assert_eq!(
verdict_of(&mut leaf),
Err(NotEntered::Unknown(libc::EISDIR)),
"the leaf records that the placement is unknown, with the read's errno"
);
let warns = crate::log_capture::warns_since(mark, "its status channel is unreadable");
assert_eq!(warns.len(), 1, "{warns:?}");
assert!(warns[0].contains(&pid.to_string()), "{warns:?}");
drop(started);
drop(child);
}
#[skuld::test]
fn a_status_channel_that_cannot_be_opened_is_not_started_with_emfile_and_no_child() {
unsafe fn no_clone(_: CloneKind) -> Result<Fork, i32> {
panic!("a clone ran although the status channel was not made")
}
let Some(done) = own_process(
test_path!(a_status_channel_that_cannot_be_opened_is_not_started_with_emfile_and_no_child),
crate::test_spawn::spawn,
) else {
return;
};
let restore = crate::test_child::exhaust_fds(&done);
let failure = start_over(no_clone, None);
drop(restore);
match failure.err().expect("no descriptor, no spawn").expect_not_started() {
Error::Io(e) => assert_eq!(e.raw_os_error(), Some(libc::EMFILE), "{e:?}"),
other => panic!("expected Io(EMFILE), got {other:?}"),
}
}
thread_local! {
static CLONED: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
}
unsafe fn clone_then_refuse_new_descriptors(kind: CloneKind) -> Result<Fork, i32> {
let forked = unsafe { crate::os_process::linux::fork::fork_with_pidfd(kind) }?;
if let Fork::Parent(child) = &forked {
CLONED.set(Some(child.pid.unsigned_abs()));
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
unsafe {
libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit);
limit.rlim_cur = 3;
libc::setrlimit(libc::RLIMIT_NOFILE, &limit);
}
}
Ok(forked)
}
#[skuld::test]
fn a_pidfd_that_cannot_be_moved_above_stdio_fails_the_spawn_and_ends_the_child() {
let Some(done) = own_process(
test_path!(a_pidfd_that_cannot_be_moved_above_stdio_fails_the_spawn_and_ends_the_child),
crate::test_spawn::spawn,
) else {
return;
};
let program = Program::new(
&[OsStr::new("/bin/sleep")],
&[OsStr::new("sleep"), OsStr::new("1000")],
std::iter::empty(),
)
.expect("no NUL");
assert_unmovable_pidfd_ends_the_child(start_with_an_unmovable_pidfd(&done, &program, None));
}
#[skuld::test]
fn a_child_whose_pidfd_cannot_be_moved_still_tells_its_leaf_where_it_placed_itself() {
let Some(done) = own_process(
test_path!(a_child_whose_pidfd_cannot_be_moved_still_tells_its_leaf_where_it_placed_itself),
crate::test_spawn::spawn,
) else {
return;
};
let dir = tempfile::tempdir().expect("tempdir");
let mut leaf = test_leaf(dir.path());
let sink = File::options().write(true).open("/dev/null").expect("open /dev/null");
let program = Program::new(
&[OsStr::new("/bin/sleep")],
&[OsStr::new("sleep"), OsStr::new("1000")],
std::iter::empty(),
)
.expect("no NUL");
assert_unmovable_pidfd_ends_the_child(start_with_an_unmovable_pidfd(
&done,
&program,
Some((&mut leaf, sink.as_raw_fd())),
));
assert_eq!(verdict_of(&mut leaf), Ok(()), "the child reported its placement");
}
fn start_with_an_unmovable_pidfd(
done: &crate::test_own_process::Completion,
program: &Program,
placement: Option<(&mut CgroupLeaf, RawFd)>,
) -> Result<Started, SpawnFailure> {
let mut steps = InChild::default();
let leaf = placement.map(|(leaf, procs_fd)| {
unsafe { steps.place(procs_fd, false) };
leaf
});
let mut before = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
assert_eq!(unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut before) }, 0);
let restore = RestoreStdio::close(done, &[0]);
let lock = crate::child::spawn::spawn_lock();
let failure = start_via(
clone_then_refuse_new_descriptors,
program,
&mut steps,
crate::identity::spawn_kernel(crate::identity::HostKernel),
OnFailure {
policy: SpawnPolicy::SYNC,
tracked: crate::elevation::front::TrackedKind::Own,
placement: leaf,
refusing_placement: false,
},
&lock,
);
drop(lock);
assert_eq!(unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &before) }, 0);
drop(restore);
failure
}
#[skuld::test]
fn the_pidfd_is_moved_above_stdio_before_the_status_channel_is_read() {
let Some(done) = own_process(
test_path!(the_pidfd_is_moved_above_stdio_before_the_status_channel_is_read),
crate::test_spawn::spawn,
) else {
return;
};
let program = Program::new(&[OsStr::new(MISSING)], &[OsStr::new("missing")], std::iter::empty()).expect("no NUL");
assert_unmovable_pidfd_ends_the_child(start_with_an_unmovable_pidfd(&done, &program, None));
}
fn assert_unmovable_pidfd_ends_the_child(failure: Result<Started, SpawnFailure>) {
let (cause, _fate) = match failure {
Ok(started) => {
unsafe { libc::kill(started.pid as libc::pid_t, libc::SIGKILL) };
panic!("the spawn kept a pidfd in a stdio slot (child {})", started.pid)
}
Err(failure) => failure.expect_may_have_started_with(),
};
assert!(
crate::error::Report(&cause)
.to_string()
.contains("moving the child's pidfd above stdio"),
"{cause:?}"
);
let pid = CLONED.get().expect("the clone ran");
let waited = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
std::ptr::null_mut(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
assert_eq!(
(waited, std::io::Error::last_os_error().raw_os_error()),
(-1, Some(libc::ECHILD)),
"the teardown through the unmoved pidfd ended and reaped the child"
);
}
#[skuld::test]
fn a_refused_clone_is_unsupported_and_any_other_is_the_clones_own_io() {
let refusals: [(ForkFn, &str); 2] = [
(|_| fails_with(libc::ENOSYS), "ENOSYS"),
(|_| fails_with(libc::EPERM), "EPERM"),
];
for (fork, name) in refusals {
let failure = match start_over(fork, None) {
Ok(_) => panic!("a refused clone made a child"),
Err(failure) => failure,
};
match failure.expect_not_started() {
Error::Unsupported { op, detail, .. } => {
assert_eq!(op, "spawn", "{name}");
let release = std::fs::read_to_string("/proc/sys/kernel/osrelease").expect("the kernel release");
assert!(
detail.ends_with(&format!("clone answered {name} (kernel {})", release.trim_end())),
"{name}: {detail}"
);
}
other => panic!("{name}: expected Unsupported, got {other:?}"),
}
}
let failure = match start_over(|_| fails_with(libc::EAGAIN), None) {
Ok(_) => panic!("a failed clone made a child"),
Err(failure) => failure,
};
match failure.expect_not_started() {
Error::Io(e) => assert_eq!(e.raw_os_error(), Some(libc::EAGAIN), "{e:?}"),
other => panic!("expected Io, got {other:?}"),
}
}
#[skuld::test]
fn a_failing_step_is_the_spawns_error_and_the_program_never_runs() {
let dir = tempfile::tempdir().expect("tempdir");
let ran = dir.path().join("ran");
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args(["/bin/sh".into(), "-c".into(), format!("touch {}", ran.display())])
.current_dir(dir.path().join("missing"));
assert_not_found(cmd.spawn(), "a child that cannot enter its directory");
assert!(!ran.exists(), "the program ran although its step failed");
}
#[skuld::test]
fn an_exec_that_fails_is_the_spawns_error_with_its_errno() {
let dir = tempfile::tempdir().expect("tempdir");
let denied = dir.path().join("denied");
std::fs::write(&denied, "#!/bin/sh\n").expect("write");
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args([denied.as_os_str()]);
match cmd.spawn() {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{e:?}"),
other => panic!(
"a file that is not executable: expected EACCES, got {:?}",
other.map(|c| c.pid())
),
}
}
#[skuld::test]
fn a_nul_in_an_argument_or_the_environment_is_invalid_input() {
let mut in_argument = crate::test_child::command(crate::test_child::Console::Hidden);
in_argument.args(["/bin/true", "a\0b"]);
let mut in_environment = crate::test_child::command(crate::test_child::Console::Hidden);
in_environment.args(["/bin/true"]).env("COSCA_NUL", "a\0b");
for (mut cmd, what) in [(in_argument, "argument"), (in_environment, "environment")] {
match cmd.spawn() {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput, "{what}: {e:?}"),
other => panic!("{what}: expected InvalidInput, got {:?}", other.map(|c| c.pid())),
}
}
}
fn child_env(ops: &[crate::command::EnvOp], marker: bool) -> Vec<(OsString, OsString)> {
child_env_over(std::env::vars_os(), ops, marker)
}
#[skuld::test]
fn the_childs_environment_is_the_ops_applied_in_order_and_then_the_marker() {
use crate::command::EnvOp;
let marker = OsString::from(crate::containment::NESTED_ENV);
let ops = [
EnvOp::Set("B".into(), "1".into()),
EnvOp::Clear,
EnvOp::Set("Z".into(), "2".into()),
EnvOp::Set("A".into(), "3".into()),
EnvOp::Remove("Z".into()),
];
assert_eq!(
child_env(&ops, true),
[
(OsString::from("A"), OsString::from("3")),
(marker.clone(), OsString::from("1"))
]
);
assert_eq!(child_env(&ops, false), [(OsString::from("A"), OsString::from("3"))]);
let inherited = child_env(&[EnvOp::Set("COSCA_FORK_SPAWN_TESTS".into(), "x".into())], false);
assert!(inherited.contains(&(OsString::from("COSCA_FORK_SPAWN_TESTS"), OsString::from("x"))));
assert!(inherited.len() > 1, "this process's own environment is inherited");
}
#[skuld::test]
fn an_environment_no_op_changes_is_passed_through_as_it_is() {
use crate::command::EnvOp;
let pair = |key: &str, value: &str| (OsString::from(key), OsString::from(value));
let inherited = || [pair("Z", "1"), pair("A", "2"), pair("Z", "3"), pair("M", "4")].into_iter();
assert_eq!(
child_env_over(inherited(), &[], false),
[pair("Z", "1"), pair("A", "2"), pair("Z", "3"), pair("M", "4")]
);
assert_eq!(
child_env_over(inherited(), &[EnvOp::Remove("M".into())], false),
[pair("A", "2"), pair("Z", "3")]
);
let sorted = std::collections::BTreeMap::from([
pair("A", "2"),
pair("M", "4"),
pair(crate::containment::NESTED_ENV, "1"),
pair("Z", "3"),
]);
assert_eq!(
child_env_over(inherited(), &[], true),
sorted.into_iter().collect::<Vec<_>>()
);
}
#[skuld::test]
fn a_childs_environment_is_the_one_std_gives_for_the_same_ops() {
let marker = format!("{}=", crate::containment::NESTED_ENV);
let environ_of_cosca = |ops: &dyn Fn(&mut crate::Command)| {
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args(["/bin/cat", "/proc/self/environ"]);
ops(&mut cmd);
cmd.stdout(Stdio::pipe()).expect("stdout");
let out = cmd.spawn().expect("spawn").communicate(None).expect("communicate");
let entries: Vec<Vec<u8>> = out
.stdout
.split(|&b| b == 0)
.filter(|entry| !entry.is_empty() && !entry.starts_with(marker.as_bytes()))
.map(<[u8]>::to_vec)
.collect();
entries
};
let environ_of_std = |ops: &dyn Fn(&mut std::process::Command)| {
let mut cmd = std::process::Command::new("/bin/cat");
cmd.arg("/proc/self/environ");
ops(&mut cmd);
let out = crate::test_spawn::output_captured(&mut cmd).expect("run cat");
let entries: Vec<Vec<u8>> = out
.stdout
.split(|&b| b == 0)
.filter(|entry| !entry.is_empty())
.map(<[u8]>::to_vec)
.collect();
entries
};
let ours = environ_of_cosca(&|_| {});
assert!(ours.len() > 1, "this process's own environment is inherited: {ours:?}");
assert_eq!(ours, environ_of_std(&|_| {}), "no op");
assert!(
ours.iter().any(|entry| entry.starts_with(b"PATH=")),
"the test removes a variable that is set"
);
assert_eq!(
environ_of_cosca(&|cmd| {
cmd.env_remove("PATH");
}),
environ_of_std(&|cmd| {
cmd.env_remove("PATH");
}),
"a removal"
);
assert_eq!(
environ_of_cosca(&|cmd| {
cmd.env_clear().env("B", "2").env("A", "1");
}),
environ_of_std(&|cmd| {
cmd.env_clear().env("B", "2").env("A", "1");
}),
"a clear and two variables"
);
}
#[skuld::test]
fn the_childs_signal_mask_is_the_spawning_threads() {
let blocked = |signal: i32| 1u64 << (signal - 1);
let previous = unsafe {
let mut set: libc::sigset_t = std::mem::zeroed();
let mut previous: libc::sigset_t = std::mem::zeroed();
libc::sigemptyset(&mut set);
libc::sigaddset(&mut set, libc::SIGINT);
libc::sigaddset(&mut set, libc::SIGTERM);
assert_eq!(libc::pthread_sigmask(libc::SIG_BLOCK, &set, &mut previous), 0);
previous
};
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args(["/bin/grep", "^SigBlk", "/proc/self/status"]);
cmd.stdout(Stdio::pipe()).expect("stdout");
let spawned = cmd.spawn();
assert_eq!(
unsafe { libc::pthread_sigmask(libc::SIG_SETMASK, &previous, std::ptr::null_mut()) },
0
);
let out = spawned.expect("spawn").communicate(None).expect("communicate");
let text = String::from_utf8_lossy(&out.stdout);
let mask = u64::from_str_radix(text.trim().rsplit(char::is_whitespace).next().expect("a mask"), 16)
.expect("a hexadecimal mask");
let wanted = blocked(libc::SIGINT) | blocked(libc::SIGTERM);
assert_eq!(mask & wanted, wanted, "the child's SigBlk {mask:#x} lacks {wanted:#x}");
}
#[skuld::test]
fn the_childs_sigpipe_is_the_default() {
let mut ours = unsafe { std::mem::zeroed::<libc::sigaction>() };
assert_eq!(
unsafe { libc::sigaction(libc::SIGPIPE, std::ptr::null(), &mut ours) },
0
);
assert_eq!(
ours.sa_sigaction,
libc::SIG_IGN,
"this process ignores SIGPIPE, as a Rust program's runtime does"
);
let mut cmd = crate::test_child::command(crate::test_child::Console::Hidden);
cmd.args(["/bin/sh", "-c", r#"grep '^SigIgn' /proc/$$/status"#]);
cmd.stdout(Stdio::pipe()).expect("stdout");
let out = cmd.spawn().expect("spawn").communicate(None).expect("communicate");
let ignored = String::from_utf8_lossy(&out.stdout);
let mask = u64::from_str_radix(ignored.trim().rsplit(char::is_whitespace).next().expect("a mask"), 16)
.expect("a hexadecimal mask");
assert_eq!(
mask & (1 << (libc::SIGPIPE - 1)),
0,
"the child ignores SIGPIPE: SigIgn {mask:#x}"
);
}