blob: 226b5ecccc1f65291df95df3e2a5b854a93758a2 [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Waiting on a supervised child, enforcing its timeout, and reaping its
//! whole process group.
use super::*;
#[cfg(unix)]
pub(super) fn supervise_child(
mut child: Child,
timeout: Duration,
log_dir: &Path,
) -> TestResult<Termination> {
let pgid = child.id() as libc::pid_t;
let deadline = Instant::now() + timeout;
let mut poll_sleep = Duration::from_millis(1);
loop {
match child.try_wait() {
Ok(Some(status)) => {
// Reap reparented grandchildren already terminated in `pgid`,
// and terminate any orphaned live descendant holding workspace
// locks before returning. `PR_SET_CHILD_SUBREAPER` keeps
// reparented descendants attached until we `waitpid` them, so
// `waitpid(-pgid, WNOHANG) == 0` guarantees `pgid` is pinned by
// our own live descendant (zero PID-reuse race).
reap_or_kill_pgid_after_exit(pgid, log_dir)?;
return Ok(Termination::Exited(status));
}
Ok(None) => {
let now = Instant::now();
if now >= deadline {
// Send SIGKILL to `-pgid` BEFORE reaping `child`, so `pgid`
// cannot be recycled before `kill(-pgid)` runs.
// SAFETY: `pgid` is positive (`child.id()`) and pinned
// until `child.wait()` reaps the group leader below.
let kill_rc = unsafe { libc::kill(-pgid, libc::SIGKILL) };
let kill_err = (kill_rc != 0).then(std::io::Error::last_os_error);
let status = child.wait().map_err(|error| {
format!(
"reap timed-out child (kill={kill_err:?}) in {}",
log_dir.display()
)
+ &format!(": {error}")
})?;
reap_pgid_blocking(pgid)?;
if let Some(err) = kill_err
&& err.raw_os_error() != Some(libc::ESRCH)
{
return Err(format!(
"kill(-{pgid}, SIGKILL) failed after deadline: {err}; logs={}",
log_dir.display()
));
}
return Ok(Termination::TimedOut(status));
}
let remaining = deadline.saturating_duration_since(now);
std::thread::sleep(poll_sleep.min(remaining));
poll_sleep = (poll_sleep * 2).min(Duration::from_millis(10));
}
Err(error) => {
// SAFETY: `pgid` is pinned by the still-unreaped `child`.
let _ = unsafe { libc::kill(-pgid, libc::SIGKILL) };
let reap = child.wait();
let _ = reap_pgid_blocking(pgid);
return Err(format!(
"wait failed: {error}; reap={reap:?}; logs={}",
log_dir.display()
));
}
}
}
}
#[cfg(unix)]
fn reap_pgid_blocking(pgid: libc::pid_t) -> TestResult {
loop {
let mut status: libc::c_int = 0;
// SAFETY: `status` points to valid stack storage; `waitpid` only
// reaps children of the current process in process group `pgid`.
let rc = unsafe { libc::waitpid(-pgid, &mut status, 0) };
if rc > 0 {
continue;
}
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::ECHILD) => return Ok(()),
_ => return Err(format!("waitpid(-{pgid}) failed: {err}")),
}
}
}
#[cfg(unix)]
fn reap_or_kill_pgid_after_exit(pgid: libc::pid_t, log_dir: &Path) -> TestResult {
loop {
let mut status: libc::c_int = 0;
// SAFETY: `status` points to valid stack storage.
let rc = unsafe { libc::waitpid(-pgid, &mut status, libc::WNOHANG) };
if rc > 0 {
continue;
}
if rc == 0 {
// A live reparented descendant still belongs to us inside `pgid`.
// Terminate the orphaned group cleanly and reap until `ECHILD`.
// SAFETY: our own live child holds `pgid` pinned until reaped.
let kill_rc = unsafe { libc::kill(-pgid, libc::SIGKILL) };
if kill_rc != 0 {
let err = std::io::Error::last_os_error();
if err.raw_os_error() != Some(libc::ESRCH) {
return Err(format!(
"kill orphaned group -{pgid} failed ({err}); logs={}",
log_dir.display()
));
}
}
return reap_pgid_blocking(pgid);
}
let err = std::io::Error::last_os_error();
match err.raw_os_error() {
Some(libc::EINTR) => continue,
Some(libc::ECHILD) => return Ok(()),
_ => {
return Err(format!(
"waitpid(-{pgid}, WNOHANG) failed: {err}; logs={}",
log_dir.display()
));
}
}
}
}
#[cfg(not(unix))]
pub(super) fn supervise_child(
mut child: Child,
timeout: Duration,
log_dir: &Path,
) -> TestResult<Termination> {
let deadline = Instant::now() + timeout;
loop {
match child.try_wait() {
Ok(Some(status)) => return Ok(Termination::Exited(status)),
Ok(None) if Instant::now() >= deadline => {
let _ = child.kill();
let status = child
.wait()
.map_err(|e| format!("reap timed-out child in {}: {e}", log_dir.display()))?;
return Ok(Termination::TimedOut(status));
}
Ok(None) => std::thread::sleep(Duration::from_millis(5)),
Err(error) => {
let _ = child.kill();
let _ = child.wait();
return Err(format!("wait failed: {error}; logs={}", log_dir.display()));
}
}
}
}