use std::cell::Cell;
use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
use crate::child::spawn::{spawn_lock, SpawnLockGuard};
use crate::containment::cgroup::test_support::{close_range_except, fork_running_locked, KillOnDrop};
use crate::identity::ProcessId;
use crate::os_process::linux::fork::{fork_with_pidfd, Fork};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ChildStep {
CloseRange,
SetPgid,
ReportReady,
AwaitRelease,
ForkM,
MCloseRange,
ReportMPid,
}
impl ChildStep {
pub(super) const ALL: [ChildStep; 7] = [
ChildStep::CloseRange,
ChildStep::SetPgid,
ChildStep::ReportReady,
ChildStep::AwaitRelease,
ChildStep::ForkM,
ChildStep::MCloseRange,
ChildStep::ReportMPid,
];
pub(super) const fn exit_code(self) -> i32 {
120 + self as i32
}
pub(super) fn from_exit_code(code: i32) -> Option<ChildStep> {
ChildStep::ALL.into_iter().find(|step| step.exit_code() == code)
}
pub(super) const fn cause(self) -> &'static str {
match self {
ChildStep::CloseRange | ChildStep::MCloseRange => {
"close_range(2) failed (close_range unavailable: kernel < 5.9)"
}
ChildStep::SetPgid => "setpgid(0, 0) failed",
ChildStep::ReportReady => "writing the ready byte to the rendezvous socket failed",
ChildStep::AwaitRelease => "the rendezvous socket closed before the release byte arrived",
ChildStep::ForkM => "fork of M failed",
ChildStep::ReportMPid => "writing M's pid to the m_ready pipe failed",
}
}
}
#[derive(Debug)]
pub(super) enum FixtureError {
LExited { status: i32 },
MExited,
}
impl FixtureError {
pub(super) fn l_step(&self) -> Option<ChildStep> {
match self {
FixtureError::LExited { status } if libc::WIFEXITED(*status) => {
ChildStep::from_exit_code(libc::WEXITSTATUS(*status))
}
_ => None,
}
}
}
impl std::fmt::Display for FixtureError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match (self, self.l_step()) {
(FixtureError::LExited { .. }, Some(step)) => write!(f, "L exited at {step:?}: {}", step.cause()),
(FixtureError::LExited { status }, None) => {
write!(f, "L exited unexpectedly (raw wait status {status:#x})")
}
(FixtureError::MExited, _) => write!(
f,
"M exited before reporting its pid: {} or {}",
ChildStep::MCloseRange.cause(),
ChildStep::ReportMPid.cause()
),
}
}
}
thread_local! {
static FORCE_PANIC: Cell<PanicSeam> = const { Cell::new(PanicSeam::Off) };
static FORCE_L_CLOSE_RANGE_FAILURE: Cell<bool> = const { Cell::new(false) };
}
#[derive(Clone, Copy)]
enum PanicSeam {
Off,
Armed,
Fired { l_pid: libc::pid_t },
}
#[must_use = "dropping this immediately disarms the forced panic; bind it for the probe's duration"]
pub(super) struct ForcedPanic(());
pub(super) fn force_panic_after_fixture() -> ForcedPanic {
FORCE_PANIC.with(|f| f.set(PanicSeam::Armed));
ForcedPanic(())
}
impl ForcedPanic {
pub(super) fn fired_l_pid(&self) -> Option<libc::pid_t> {
match FORCE_PANIC.with(Cell::get) {
PanicSeam::Fired { l_pid } => Some(l_pid),
_ => None,
}
}
}
impl Drop for ForcedPanic {
fn drop(&mut self) {
FORCE_PANIC.with(|f| f.set(PanicSeam::Off));
}
}
#[must_use = "dropping this immediately disarms the forced failure; bind it for the probe's duration"]
pub(super) struct ForcedLCloseRangeFailure(());
pub(super) fn force_l_close_range_failure() -> ForcedLCloseRangeFailure {
FORCE_L_CLOSE_RANGE_FAILURE.with(|f| f.set(true));
ForcedLCloseRangeFailure(())
}
impl Drop for ForcedLCloseRangeFailure {
fn drop(&mut self) {
FORCE_L_CLOSE_RANGE_FAILURE.with(|f| f.set(false));
}
}
fn raw_pipe() -> (RawFd, RawFd) {
let (r, w) = std::io::pipe().expect("pipe");
(r.into_raw_fd(), w.into_raw_fd())
}
fn raw_close(fd: RawFd) {
unsafe { libc::close(fd) };
}
fn exit_child(code: i32) -> ! {
unsafe { libc::_exit(code) }
}
fn write_all_or_exit(fd: RawFd, mut bytes: &[u8], exit_code_on_failure: i32) {
while !bytes.is_empty() {
let n = unsafe { libc::write(fd, bytes.as_ptr().cast(), bytes.len()) };
if n > 0 {
bytes = &bytes[n as usize..];
} else if n == -1 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
} else {
exit_child(exit_code_on_failure);
}
}
}
fn read_byte_or_exit(fd: RawFd, exit_code_on_failure: i32) {
let mut byte = 0u8;
loop {
let n = unsafe { libc::read(fd, (&raw mut byte).cast(), 1) };
if n == 1 {
return;
}
if n == -1 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
continue;
}
exit_child(exit_code_on_failure);
}
}
fn write_decimal(mut n: u32, buf: &mut [u8; 10]) -> &[u8] {
if n == 0 {
buf[9] = b'0';
return &buf[9..];
}
let mut i = buf.len();
while n > 0 {
i -= 1;
buf[i] = b'0' + (n % 10) as u8;
n /= 10;
}
&buf[i..]
}
fn close_range_except_or_exit(keep: &[RawFd], exit_code_on_failure: i32, force_failure: bool) {
if force_failure || !close_range_except(keep) {
exit_child(exit_code_on_failure);
}
}
fn wait_status(pid: libc::pid_t) -> i32 {
let mut status = 0;
loop {
let r = unsafe { libc::waitpid(pid, &mut status, 0) };
if r == pid {
return status;
}
assert!(
r == -1 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted,
"waitpid({pid}): {r} {}",
std::io::Error::last_os_error()
);
}
}
fn read_some(fd: RawFd, buf: &mut [u8]) -> isize {
loop {
let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) };
if n != -1 || std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
return n;
}
}
}
pub(super) struct ReapedLeaderFixture {
#[allow(dead_code, reason = "held only for its Drop; the fd close is the point")]
rendezvous_test: OwnedFd,
block_w: OwnedFd,
m_ready_r: OwnedFd,
#[allow(dead_code, reason = "held only for its Drop; the kill and reap are the point")]
l: Option<KillOnDrop>,
pub(super) m_pid: libc::pid_t,
#[allow(dead_code, reason = "held only for its Drop; the unlock is the point")]
lock: SpawnLockGuard,
}
impl ReapedLeaderFixture {
pub(super) fn release_and_confirm_m_exited(self) {
let m_ready_r_fd = self.m_ready_r.as_raw_fd();
drop(self.block_w);
let mut buf = [0u8; 1];
let n = read_some(m_ready_r_fd, &mut buf);
assert_eq!(n, 0, "expected EOF on m_ready (M's exit) after releasing M, got n={n}");
}
}
pub(super) fn build_reaped_pgid_leader() -> (ProcessId, ReapedLeaderFixture) {
try_build_reaped_pgid_leader().unwrap_or_else(|e| panic!("reaped-leader fixture: {e}"))
}
pub(super) fn try_build_reaped_pgid_leader() -> Result<(ProcessId, ReapedLeaderFixture), FixtureError> {
let lock = spawn_lock();
let mut rendezvous = [-1 as RawFd; 2];
assert_eq!(
unsafe {
libc::socketpair(
libc::AF_UNIX,
libc::SOCK_STREAM | libc::SOCK_CLOEXEC,
0,
rendezvous.as_mut_ptr(),
)
},
0,
"socketpair: {}",
std::io::Error::last_os_error()
);
let (rendezvous_test, rendezvous_l) = (rendezvous[0], rendezvous[1]);
let (m_ready_r, m_ready_w) = raw_pipe();
let (block_r, block_w) = raw_pipe();
let force_close_range_failure = FORCE_L_CLOSE_RANGE_FAILURE.with(|f| f.replace(false));
let l = fork_running_locked(&lock, || {
let mut keep = [rendezvous_l, block_r, block_w, m_ready_w];
keep.sort_unstable();
close_range_except_or_exit(&keep, ChildStep::CloseRange.exit_code(), force_close_range_failure);
if unsafe { libc::setpgid(0, 0) } != 0 {
exit_child(ChildStep::SetPgid.exit_code());
}
write_all_or_exit(rendezvous_l, b"R", ChildStep::ReportReady.exit_code());
read_byte_or_exit(rendezvous_l, ChildStep::AwaitRelease.exit_code());
let m = unsafe { fork_with_pidfd() };
let Ok(m) = m else {
exit_child(ChildStep::ForkM.exit_code());
};
if matches!(m, Fork::Child) {
let mut keep = [block_r, m_ready_w];
keep.sort_unstable();
close_range_except_or_exit(&keep, ChildStep::MCloseRange.exit_code(), false);
let pid = unsafe { libc::getpid() } as u32;
let mut digits = [0u8; 10];
write_all_or_exit(
m_ready_w,
write_decimal(pid, &mut digits),
ChildStep::ReportMPid.exit_code(),
);
write_all_or_exit(m_ready_w, b"\n", ChildStep::ReportMPid.exit_code());
let mut sink = 0u8;
loop {
let n = unsafe { libc::read(block_r, (&raw mut sink).cast(), 1) };
if n != -1 || std::io::Error::last_os_error().kind() != std::io::ErrorKind::Interrupted {
break;
}
}
exit_child(0);
}
});
let l_pid = l.pid() as libc::pid_t;
raw_close(rendezvous_l);
raw_close(m_ready_w);
raw_close(block_r);
let mut fixture = unsafe {
ReapedLeaderFixture {
rendezvous_test: OwnedFd::from_raw_fd(rendezvous_test),
block_w: OwnedFd::from_raw_fd(block_w),
m_ready_r: OwnedFd::from_raw_fd(m_ready_r),
l: Some(l),
m_pid: 0,
lock,
}
};
if matches!(FORCE_PANIC.with(Cell::get), PanicSeam::Armed) {
FORCE_PANIC.with(|f| f.set(PanicSeam::Fired { l_pid }));
panic!("forced panic mid-handshake (test seam)");
}
let mut ready = 0u8;
match read_some(fixture.rendezvous_test.as_raw_fd(), std::slice::from_mut(&mut ready)) {
1 => {}
0 => {
let status = wait_status(fixture.l.take().expect("L is still guarded").defuse() as libc::pid_t);
return Err(FixtureError::LExited { status });
}
n => panic!("read L's ready byte: n={n} err={}", std::io::Error::last_os_error()),
}
let l_id = ProcessId::of(l_pid as u32)
.found()
.expect("L's identity resolves while L is alive and blocked on the rendezvous socket");
let wrote = unsafe { libc::write(fixture.rendezvous_test.as_raw_fd(), b"R".as_ptr().cast(), 1) };
assert_eq!(wrote, 1, "release L: {}", std::io::Error::last_os_error());
let status = wait_status(fixture.l.take().expect("L is still guarded").defuse() as libc::pid_t);
if !(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0) {
return Err(FixtureError::LExited { status });
}
let mut line = Vec::new();
let mut byte = [0u8; 1];
loop {
match read_some(fixture.m_ready_r.as_raw_fd(), &mut byte) {
1 if byte[0] == b'\n' => break,
1 => line.push(byte[0]),
0 => return Err(FixtureError::MExited),
n => panic!("read M's ready line: n={n} err={}", std::io::Error::last_os_error()),
}
}
fixture.m_pid = std::str::from_utf8(&line)
.expect("M's pid is ASCII")
.parse()
.expect("M's pid is a plain decimal number");
Ok((l_id, fixture))
}