use std::io;
use std::os::fd::{AsRawFd, OwnedFd};
use std::sync::Arc;
use super::fd_channel::{self, publish_ends, Shared};
use super::SpawnLockGuard;
use crate::error::Error;
const REPORT_ID: u32 = 1;
const REPORT_ERRNO: u32 = 2;
const REPORT_LEN: usize = 12;
#[derive(Debug)]
pub(crate) enum Report {
Id(u64),
ChildRefused(i32),
Missing,
Unwritten,
ReadFailed(io::Error),
BadTag(u32),
}
pub(crate) struct Pending {
shared: Arc<Shared>,
}
pub(crate) struct Channel {
read_end: OwnedFd,
write_end: OwnedFd,
shared: Arc<Shared>,
}
pub(crate) fn register(cmd: &mut std::process::Command) -> Pending {
#[cfg(test)]
let seam = seams::armed();
let shared = unsafe {
fd_channel::register(cmd, move |shared| {
report(
shared,
#[cfg(test)]
seam,
)
})
};
Pending { shared }
}
impl Pending {
pub(crate) fn open(self, _lock: &SpawnLockGuard) -> Result<Channel, Error> {
let (read_end, write_end) = std::io::pipe().map_err(|e| Error::Io(crate::error::io_context("pipe", e)))?;
let (write_end, read_end) = publish_ends(&self.shared, OwnedFd::from(write_end), OwnedFd::from(read_end))?;
set_nonblocking(&read_end)?;
Ok(Channel {
read_end,
write_end,
shared: self.shared,
})
}
}
fn set_nonblocking(fd: &OwnedFd) -> Result<(), Error> {
let flags = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_GETFL) };
if flags < 0 || unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) } < 0 {
return Err(Error::Io(crate::error::io_context("fcntl", io::Error::last_os_error())));
}
Ok(())
}
impl Channel {
pub(crate) fn run<T, E>(self, spawn: impl FnOnce() -> Result<T, E>) -> (Result<T, E>, Report) {
let Channel {
read_end,
write_end,
shared,
} = self;
let spawned = spawn();
shared.withdraw();
drop(write_end);
(spawned, read_report(&read_end))
}
}
fn read_report(read_end: &OwnedFd) -> Report {
#[cfg(test)]
if let Some(errno) = seams::parent_read_fails() {
return Report::ReadFailed(io::Error::from_raw_os_error(errno));
}
#[cfg(test)]
if seams::parent_read_finds_nothing() {
return Report::Unwritten;
}
let mut buf = [0u8; REPORT_LEN];
let mut got = 0;
while got < REPORT_LEN {
let n = unsafe { libc::read(read_end.as_raw_fd(), buf[got..].as_mut_ptr().cast(), REPORT_LEN - got) };
if n > 0 {
got += n as usize;
} else if n == 0 {
return Report::Missing;
} else {
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::EINTR) => {}
Some(libc::EAGAIN) => return Report::Unwritten,
_ => return Report::ReadFailed(e),
}
}
}
let tag = u32::from_ne_bytes(buf[..4].try_into().expect("four bytes"));
let value = u64::from_ne_bytes(buf[4..].try_into().expect("eight bytes"));
match tag {
REPORT_ID => Report::Id(value),
REPORT_ERRNO => Report::ChildRefused(value as i32),
other => Report::BadTag(other),
}
}
#[derive(Debug)]
pub(crate) struct NotAdopted {
pub(crate) error: Error,
pub(crate) why: Unadoptable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Unadoptable {
DiedBeforeExec,
Unreported,
Unverified,
}
pub(crate) fn adopted_id(report: Report, pid: u32) -> Result<u64, NotAdopted> {
let not = |why, error| Err(NotAdopted { error, why });
match report {
Report::Id(id) => Ok(id),
Report::ChildRefused(errno) => not(Unadoptable::DiedBeforeExec, refused_error(errno)),
Report::Missing => not(
Unadoptable::DiedBeforeExec,
Error::Io(io::Error::other(format!(
"the spawned child {pid} died before exec; the program did not start"
))),
),
Report::Unwritten => not(
Unadoptable::Unreported,
Error::Io(io::Error::other(format!(
"the spawned child {pid} had not reported its unique id when its spawn returned; the child was \
not adopted"
))),
),
Report::ReadFailed(e) => not(
Unadoptable::Unverified,
Error::Unassessable {
detail: format!("pid {pid}: its unique-id report could not be read ({e}); the child was not adopted"),
source: Some(e),
},
),
Report::BadTag(tag) => {
debug_assert!(false, "a unique-id report with tag {tag}");
not(
Unadoptable::Unverified,
Error::Unassessable {
detail: format!(
"pid {pid}: its unique-id report is malformed (tag {tag}); the child was not adopted"
),
source: None,
},
)
}
}
}
#[cfg(any(test, feature = "tokio"))]
pub(crate) fn proves_no_exec(report: &Report) -> bool {
match report {
Report::ChildRefused(_) | Report::Missing => true,
Report::Id(_) | Report::Unwritten | Report::ReadFailed(_) | Report::BadTag(_) => false,
}
}
pub(crate) fn failed_spawn_error(error: Error, report: &Report) -> Error {
match report {
Report::ChildRefused(errno) => refused_error(*errno),
other => {
debug_assert!(
!matches!(other, Report::BadTag(_)),
"a unique-id report is malformed: {other:?}"
);
log::debug!("the spawn failed ({error}); the child's unique-id report was {other:?}");
error
}
}
}
pub(crate) fn refused_error(errno: i32) -> Error {
Error::Unassessable {
detail: format!(
"the spawned child could not read its own unique id (errno {errno}); it was stopped before exec, so the program did not start"
),
source: Some(io::Error::from_raw_os_error(errno)),
}
}
fn report(shared: &Shared, #[cfg(test)] seam: seams::Armed) -> io::Result<()> {
#[cfg(test)]
if let Some(errno) = seam.fail_before_report() {
return Err(io::Error::from_raw_os_error(errno));
}
#[cfg(test)]
let read = seam.read(shared.child_end());
#[cfg(not(test))]
let read = crate::identity::own_unique_id();
let (tag, value) = match read {
Ok(id) => (REPORT_ID, id),
Err(errno) => (REPORT_ERRNO, errno as u64),
};
let mut buf = [0u8; REPORT_LEN];
buf[..4].copy_from_slice(&tag.to_ne_bytes());
buf[4..].copy_from_slice(&value.to_ne_bytes());
loop {
let n = unsafe { libc::write(shared.child_end(), buf.as_ptr().cast(), REPORT_LEN) };
if n == REPORT_LEN as isize {
return match tag {
REPORT_ERRNO => Err(io::Error::from_raw_os_error(value as i32)),
_ => Ok(()),
};
}
if n < 0 {
let e = io::Error::last_os_error();
if e.raw_os_error() == Some(libc::EINTR) {
continue;
}
return Err(e);
}
return Err(io::Error::from_raw_os_error(libc::EIO));
}
}
#[cfg(test)]
pub(crate) mod seams {
use std::cell::Cell;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Force {
None,
Errno(i32),
KillSelf,
FailBeforeReport(i32),
}
thread_local! {
static FORCE: Cell<Force> = const { Cell::new(Force::None) };
static PARENT_READ_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
static PARENT_READ_UNWRITTEN: Cell<bool> = const { Cell::new(false) };
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Armed(Force);
impl Armed {
pub(super) fn fail_before_report(self) -> Option<i32> {
match self.0 {
Force::FailBeforeReport(errno) => Some(errno),
_ => None,
}
}
pub(super) fn read(self, child_end: std::os::fd::RawFd) -> Result<u64, i32> {
match self.0 {
Force::None | Force::FailBeforeReport(_) => crate::identity::own_unique_id(),
Force::Errno(errno) => Err(errno),
Force::KillSelf => {
unsafe {
libc::close(child_end);
libc::kill(libc::getpid(), libc::SIGKILL);
}
Err(libc::EINTR)
}
}
}
}
pub(super) fn armed() -> Armed {
Armed(FORCE.with(Cell::get))
}
#[must_use = "dropping this immediately disarms the force; bind it for the probe's duration"]
pub(crate) struct Forced(());
impl Drop for Forced {
fn drop(&mut self) {
FORCE.with(|f| f.set(Force::None));
}
}
pub(crate) fn force_child_read_errno(errno: i32) -> Forced {
FORCE.with(|f| f.set(Force::Errno(errno)));
Forced(())
}
pub(crate) fn force_hook_failure_before_report(errno: i32) -> Forced {
FORCE.with(|f| f.set(Force::FailBeforeReport(errno)));
Forced(())
}
pub(crate) fn fail_parent_read(errno: i32) -> FailedParentRead {
PARENT_READ_ERRNO.with(|f| f.set(Some(errno)));
FailedParentRead(())
}
#[must_use = "the read succeeds again as soon as the guard is dropped"]
pub(crate) struct FailedParentRead(());
impl Drop for FailedParentRead {
fn drop(&mut self) {
PARENT_READ_ERRNO.with(|f| f.set(None));
}
}
pub(super) fn parent_read_fails() -> Option<i32> {
PARENT_READ_ERRNO.with(Cell::get)
}
pub(crate) fn find_the_report_unwritten() -> UnwrittenRead {
PARENT_READ_UNWRITTEN.with(|f| f.set(true));
UnwrittenRead(())
}
#[must_use = "the read finds the report again as soon as the guard is dropped"]
pub(crate) struct UnwrittenRead(());
impl Drop for UnwrittenRead {
fn drop(&mut self) {
PARENT_READ_UNWRITTEN.with(|f| f.set(false));
}
}
pub(super) fn parent_read_finds_nothing() -> bool {
PARENT_READ_UNWRITTEN.with(Cell::get)
}
pub(crate) fn force_child_killed_before_report() -> Forced {
FORCE.with(|f| f.set(Force::KillSelf));
Forced(())
}
}
#[cfg(test)]
#[path = "unique_report_tests.rs"]
mod unique_report_tests;