#[skuld::test]
fn job_handle_debug_does_not_panic() {
use super::JobHandle;
let h = JobHandle::create_empty_for_test();
h.hard_kill().expect("hard_kill on a live job");
let s = format!("{h:?}");
assert!(s.contains("JobHandle"), "debug output: {s}");
}
#[skuld::test]
fn wait_drained_on_a_consumed_handle_is_unassessable() {
use super::JobHandle;
let h = JobHandle::create_empty_for_test();
h.hard_kill().expect("hard_kill on a live job");
let err = h
.wait_drained(Some(None), None)
.expect_err("a consumed job handle must not report a live drain verdict");
let crate::error::Error::Unassessable { source, .. } = err else {
panic!("expected Unassessable, got {err:?}");
};
assert!(
source.is_none(),
"nothing was asked of the OS on this path — no source is expected"
);
}
#[skuld::test]
fn query_job_pid_list_is_empty_for_an_unpopulated_job() {
use super::JobHandle;
let job = JobHandle::create_empty_for_test();
let job_handle = job.as_handle().expect("freshly created job handle must be live");
let pids = super::query_job_pid_list(job_handle).expect("query pid list");
assert!(pids.is_empty(), "an empty job must report no members: {pids:?}");
}
#[skuld::test]
fn wait_drained_raw_reports_drained_for_an_empty_job() {
use super::JobHandle;
let job = JobHandle::create_empty_for_test();
let job_handle = job.as_handle().expect("freshly created job handle must be live");
let verdict = super::wait_drained_raw(job_handle, Some(None), None).expect("wait_drained_raw");
assert_eq!(verdict, crate::containment::TreeDrain::AllMembersExited);
}
#[skuld::test]
fn wait_drained_raw_tracks_a_real_member_through_exit() {
use std::os::windows::io::AsRawHandle;
let mut child = crate::test_spawn::spawn(
std::process::Command::new("cmd")
.args(["/C", "more"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()),
)
.expect("spawn cmd /C more");
let raw = child.as_raw_handle();
let job = super::assign_to_kill_on_close_job(raw).expect("assign to job");
let job_handle = job.as_handle().expect("freshly created job handle must be live");
let pids = super::query_job_pid_list(job_handle).expect("query pid list");
assert_eq!(
pids,
vec![child.id()],
"the job must report exactly the member just assigned"
);
let past = std::time::Instant::now() - std::time::Duration::from_secs(1);
let verdict = super::wait_drained_raw(job_handle, Some(Some(past)), None).expect("wait_drained_raw");
assert_eq!(verdict, crate::containment::TreeDrain::MembersRemain);
drop(child.stdin.take());
child.wait().expect("wait for cmd /C more to exit");
let verdict = super::wait_drained_raw(job_handle, Some(None), None).expect("wait_drained_raw");
assert_eq!(verdict, crate::containment::TreeDrain::AllMembersExited);
}
fn spawn_job_member() -> (std::process::Child, super::JobHandle) {
use std::os::windows::io::AsRawHandle;
let child = crate::test_spawn::spawn(
std::process::Command::new("cmd")
.args(["/C", "more"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null()),
)
.expect("spawn cmd /C more");
let raw = child.as_raw_handle();
let job = super::assign_to_kill_on_close_job(raw).expect("assign to job");
(child, job)
}
fn let_member_exit(mut child: std::process::Child) {
drop(child.stdin.take());
child.wait().expect("wait for cmd /C more to exit");
}
#[skuld::test]
fn wait_drained_raw_arms_the_ceiling_of_the_remaining_duration() {
use std::time::{Duration, Instant};
let (child, job) = spawn_job_member();
let job_handle = job.as_handle().expect("freshly created job handle must be live");
let (_clock, at) = crate::wait::test_clock::FrozenClockGuard::install();
crate::wait::wait_ms_probe::take();
let _override = crate::wait::remaining_override_seam::set(Duration::from_micros(500));
let deadline = at + Duration::from_millis(5);
let verdict = super::wait_drained_raw(job_handle, Some(Some(deadline)), None);
let reached = Instant::now() >= deadline;
let arms = crate::wait::wait_ms_probe::take();
let_member_exit(child);
assert_eq!(
verdict.expect("a live never-exiting member must not report a wait failure"),
crate::containment::TreeDrain::MembersRemain
);
assert!(reached, "the call returned before the real deadline");
let first = arms.first().expect("at least one armed wait");
assert_eq!(first.remaining, Duration::from_micros(500));
assert_eq!(first.ms, 1);
assert_eq!(
first.requested,
Duration::from_millis(5),
"the site must pass the time left to its own deadline (clock frozen at the deadline's origin)"
);
}
#[skuld::test]
fn wait_drained_raw_never_reports_members_remain_before_the_deadline() {
use std::time::{Duration, Instant};
let (mut child, job) = spawn_job_member();
let stdin = child.stdin.take().expect("piped stdin");
let job_handle = job.as_handle().expect("freshly created job handle must be live");
crate::wait::wait_ms_probe::take();
let _override = crate::wait::remaining_override_seam::set(Duration::from_micros(500));
crate::wait::wait_ms_probe::on_second_arm(move || drop(stdin)); let deadline = Instant::now() + Duration::from_secs(3600);
let verdict = super::wait_drained_raw(job_handle, Some(Some(deadline)), None);
let arms = crate::wait::wait_ms_probe::take();
child.wait().expect("reap the member after it exits");
assert_eq!(
verdict.expect("a genuinely-drained job must not report a wait failure"),
crate::containment::TreeDrain::AllMembersExited
);
assert!(arms.len() >= 2, "expected a re-arm, got {} arm(s)", arms.len());
}
#[skuld::test]
fn wait_drained_raw_re_arms_past_a_clamped_timeout() {
use std::time::{Duration, Instant};
let (mut child, job) = spawn_job_member();
let stdin = child.stdin.take().expect("piped stdin");
let job_handle = job.as_handle().expect("freshly created job handle must be live");
crate::wait::wait_ms_probe::take();
let _clamp = crate::wait::wait_clamp_seam::set(5);
crate::wait::wait_ms_probe::on_second_arm(move || drop(stdin));
let deadline = Instant::now() + Duration::from_secs(3600);
let verdict = super::wait_drained_raw(job_handle, Some(Some(deadline)), None);
let arms = crate::wait::wait_ms_probe::take();
child.wait().expect("reap the member after it exits");
assert_eq!(
verdict.expect("a genuinely-drained job must not report a wait failure"),
crate::containment::TreeDrain::AllMembersExited
);
crate::wait::wait_ms_probe::assert_rearmed_with_fresh_remaining(&arms, 5);
}
#[skuld::test]
fn caller_has_console_is_true_under_cargo_test() {
assert!(
matches!(super::caller_has_console(), Ok(true)),
"the test runner is expected to run with a console attached"
);
}
#[skuld::test]
fn console_probe_error_surfaces() {
super::fault::set_force_console_probe_error(true);
assert!(super::caller_has_console().is_err());
assert!(!super::fault::armed(), "the seam must be consumed by one call");
assert!(matches!(super::caller_has_console(), Ok(true)));
}
const E_INVALID_HANDLE: i32 = 0x8007_0006u32 as i32;
const E_ACCESS_DENIED: i32 = 0x8007_0005u32 as i32;
fn io_err(hresult: i32) -> std::io::Error {
std::io::Error::from_raw_os_error(hresult)
}
#[skuld::test]
fn invalid_handle_with_no_console_is_typed_no_console() {
let e = super::classify_ctrl_event_failure(4242, io_err(E_INVALID_HANDLE), Ok(false));
let crate::error::Error::NoConsole { detail } = e else {
panic!("expected NoConsole, got {e:?}");
};
assert!(detail.contains("4242"), "the detail must name the group: {detail}");
assert!(
detail.contains("kill_tree()"),
"the detail must name the way out: {detail}"
);
}
#[skuld::test]
fn invalid_handle_with_a_console_attached_stays_io() {
let e = super::classify_ctrl_event_failure(1, io_err(E_INVALID_HANDLE), Ok(true));
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
#[skuld::test]
fn invalid_handle_with_a_failed_probe_stays_io() {
let probe = Err(std::io::Error::from_raw_os_error(87)); let e = super::classify_ctrl_event_failure(1, io_err(E_INVALID_HANDLE), probe);
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
#[skuld::test]
fn a_different_failure_code_stays_io_whatever_the_probe_says() {
for console in [Ok(true), Ok(false)] {
let e = super::classify_ctrl_event_failure(1, io_err(E_ACCESS_DENIED), console);
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
let e = super::classify_ctrl_event_failure(1, io_err(E_ACCESS_DENIED), Err(io_err(87)));
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
#[skuld::test]
fn the_no_console_signature_matches_the_real_win32_mapping() {
use windows::Win32::Foundation::ERROR_INVALID_HANDLE;
let hr = windows::core::HRESULT::from_win32(ERROR_INVALID_HANDLE.0);
assert_eq!(hr.0, E_INVALID_HANDLE);
assert_eq!(
std::io::Error::from(windows::core::Error::from_hresult(hr)).raw_os_error(),
Some(E_INVALID_HANDLE)
);
}
mod mechanism_from_flags_tests {
use crate::containment::windows::{group_flags, mechanism_from_flags, root_flags};
use crate::graceful::GracefulMechanism;
use windows::Win32::System::Threading::{CREATE_NEW_CONSOLE, CREATE_NO_WINDOW, DETACHED_PROCESS};
#[skuld::test]
fn mechanism_from_flags_reports_none_for_no_flags() {
assert_eq!(mechanism_from_flags(0), GracefulMechanism::None);
}
#[skuld::test]
fn mechanism_from_flags_reports_console_group_for_group_flags() {
assert_eq!(mechanism_from_flags(group_flags()), GracefulMechanism::ConsoleGroup);
}
#[skuld::test]
fn mechanism_from_flags_reports_console_group_for_root_flags() {
assert_eq!(mechanism_from_flags(root_flags()), GracefulMechanism::ConsoleGroup);
}
#[skuld::test]
fn mechanism_from_flags_reports_other_console_group_for_group_plus_detached() {
assert_eq!(
mechanism_from_flags(group_flags() | DETACHED_PROCESS.0),
GracefulMechanism::OtherConsoleGroup
);
}
#[skuld::test]
fn mechanism_from_flags_reports_other_console_group_for_group_plus_new_console() {
assert_eq!(
mechanism_from_flags(group_flags() | CREATE_NEW_CONSOLE.0),
GracefulMechanism::OtherConsoleGroup
);
}
#[skuld::test]
fn mechanism_from_flags_reports_other_console_group_for_group_plus_no_window() {
assert_eq!(
mechanism_from_flags(group_flags() | CREATE_NO_WINDOW.0),
GracefulMechanism::OtherConsoleGroup
);
}
#[skuld::test]
fn mechanism_from_flags_reports_none_for_detached_without_a_group() {
assert_eq!(mechanism_from_flags(DETACHED_PROCESS.0), GracefulMechanism::None);
}
#[skuld::test]
fn mechanism_from_flags_reports_none_for_a_new_console_without_a_group() {
assert_eq!(mechanism_from_flags(CREATE_NEW_CONSOLE.0), GracefulMechanism::None);
}
#[skuld::test]
fn mechanism_from_flags_reports_none_for_no_window_without_a_group() {
assert_eq!(mechanism_from_flags(CREATE_NO_WINDOW.0), GracefulMechanism::None);
}
}
#[skuld::test]
fn probe_reports_unknown_when_the_query_fails() {
use crate::containment::windows::{fault, probe_job_breakaway, JobBreakaway};
assert_ne!(
probe_job_breakaway(),
JobBreakaway::Unknown,
"unarmed, the probe must reach a real verdict"
);
fault::set_force_job_probe_error(true);
assert_eq!(probe_job_breakaway(), JobBreakaway::Unknown);
assert_ne!(
probe_job_breakaway(),
JobBreakaway::Unknown,
"take semantics: the fault applies to exactly one call"
);
}
const JOB_BREAKAWAY_PROBE_FIXTURE_MARKER: &str = "COSCA_FIXTURE_JOB_BREAKAWAY_PROBE";
#[skuld::test]
fn probe_agrees_with_an_independent_is_process_in_job_measurement() {
let exe = std::env::current_exe().expect("current_exe");
let fixture = crate::test_child::fixture_path!(fixture_reports_job_breakaway_probe);
let child = crate::test_spawn::spawn(
crate::test_reexec::with_json_events(
crate::test_reexec::command(&exe).args(crate::test_reexec::fixture_args(fixture)),
)
.env(JOB_BREAKAWAY_PROBE_FIXTURE_MARKER, "1")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped()),
)
.expect("spawn the job-breakaway probe fixture");
let output = child.wait_with_output().expect("wait for the fixture child");
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if let Err(why) = crate::test_reexec::suite_passed_exactly_one(&output) {
panic!(
"job-breakaway probe fixture did not run and pass exactly one test: {why}\n--- stdout ---\n{stdout}\n\
--- stderr ---\n{stderr}"
);
}
}
#[skuld::test]
fn fixture_reports_job_breakaway_probe() {
if std::env::var_os(JOB_BREAKAWAY_PROBE_FIXTURE_MARKER).is_none() {
return; }
use crate::containment::windows::{probe_job_breakaway, JobBreakaway};
use windows::Win32::System::JobObjects::IsProcessInJob;
use windows::Win32::System::Threading::GetCurrentProcess;
let mut in_job = windows::core::BOOL(0);
unsafe { IsProcessInJob(GetCurrentProcess(), None, &mut in_job) }.expect("IsProcessInJob");
let verdict = probe_job_breakaway();
if in_job.as_bool() {
assert_ne!(
verdict,
JobBreakaway::NotInJob,
"this process IS in a job, so the probe must not report otherwise"
);
} else {
assert_eq!(
verdict,
JobBreakaway::NotInJob,
"this process is in no job, so the probe must say so"
);
}
}
struct SuspendedHelper {
process: windows::Win32::Foundation::HANDLE,
thread: windows::Win32::Foundation::HANDLE,
tid: u32,
pid: u32,
_job: super::JobHandle,
}
impl SuspendedHelper {
fn new() -> Self {
use windows::core::PWSTR;
use windows::Win32::System::Threading::{
CreateProcessW, CREATE_NO_WINDOW, CREATE_SUSPENDED, PROCESS_INFORMATION, STARTUPINFOW,
};
let mut cmdline: Vec<u16> = "cmd /C more".encode_utf16().chain(std::iter::once(0)).collect();
let si = STARTUPINFOW {
cb: std::mem::size_of::<STARTUPINFOW>() as u32,
..Default::default()
};
let mut pi = PROCESS_INFORMATION::default();
unsafe {
CreateProcessW(
None,
Some(PWSTR(cmdline.as_mut_ptr())),
None,
None,
false,
CREATE_NO_WINDOW | CREATE_SUSPENDED,
None,
None,
&si,
&mut pi,
)
}
.expect("CreateProcessW for the suspended helper");
let job = super::assign_to_kill_on_close_job(pi.hProcess.0).expect("assign the helper to a job");
Self {
process: pi.hProcess,
thread: pi.hThread,
tid: pi.dwThreadId,
pid: pi.dwProcessId,
_job: job,
}
}
}
impl Drop for SuspendedHelper {
fn drop(&mut self) {
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::System::Threading::TerminateProcess;
unsafe {
_ = TerminateProcess(self.process, 1);
_ = CloseHandle(self.thread);
_ = CloseHandle(self.process);
}
}
}
fn spawn_contained_blocker() -> Result<crate::Child, crate::error::Error> {
let mut cmd = crate::Command::new();
cmd.args(crate::test_child::BLOCKER_ARGV.iter().copied());
cmd.stdin(crate::Stdio::pipe()).expect("set stdin pipe");
cmd.stdout(crate::Stdio::null()).expect("set stdout");
cmd.contain();
cmd.spawn()
}
fn spawn_with_injected_tid(
tid: u32,
owner: Option<u32>,
) -> (
Result<crate::Child, crate::error::Error>,
Option<Option<crate::containment::windows::Visit>>,
) {
let injected = crate::containment::windows::fault::inject_snapshot_tid(tid, owner);
let spawned = spawn_contained_blocker();
let visit = crate::containment::windows::fault::take_injected_visit();
drop(injected);
(spawned, visit)
}
fn finish_child(spawned: Result<crate::Child, crate::error::Error>) {
let mut child = spawned.expect("a stale snapshot entry must not fail the spawn");
assert_eq!(
child.containment(),
crate::Containment::JobObject,
"the walk under test only runs for a Job Object spawn"
);
drop(child.stdin().expect("piped stdin"));
child.wait().expect("wait for the contained child");
}
#[skuld::test]
fn windows_resume_initial_threads_never_resumes_a_foreign_thread() {
use crate::containment::windows::Visit;
use windows::Win32::System::Threading::{ResumeThread, SuspendThread};
let helper = SuspendedHelper::new();
let (spawned, visit) = spawn_with_injected_tid(helper.tid, None);
assert!(
spawned.is_ok(),
"a snapshot entry for another process's thread must not fail the spawn: {:?}",
spawned.as_ref().err()
);
assert_eq!(
visit,
Some(Some(Visit::Foreign { owner: helper.pid })),
"the injected entry must be walked and identified as the helper's"
);
let previous = unsafe { SuspendThread(helper.thread) };
assert_eq!(
previous, 1,
"the helper's thread is another process's: the spawn must not have resumed it"
);
unsafe { ResumeThread(helper.thread) };
finish_child(spawned);
}
#[skuld::test]
fn windows_resume_initial_threads_drops_an_entry_owned_by_another_pid() {
use windows::Win32::System::Threading::{ResumeThread, SuspendThread};
let helper = SuspendedHelper::new();
let (spawned, visit) = spawn_with_injected_tid(helper.tid, Some(helper.pid));
assert_eq!(visit, Some(None), "an entry owned by another pid must be filtered out");
let previous = unsafe { SuspendThread(helper.thread) };
assert_eq!(previous, 1, "a filtered entry must not be touched");
unsafe { ResumeThread(helper.thread) };
finish_child(spawned);
}
#[skuld::test]
fn windows_resume_initial_threads_skips_a_thread_id_that_no_longer_exists() {
use crate::containment::windows::Visit;
let (spawned, visit) = spawn_with_injected_tid(1, None);
assert!(
spawned.is_ok(),
"a snapshot entry for a nonexistent thread must not fail the spawn: {:?}",
spawned.as_ref().err()
);
assert_eq!(
visit,
Some(Some(Visit::Gone)),
"the entry must be walked and found gone"
);
finish_child(spawned);
}
#[skuld::test]
fn windows_resume_initial_threads_treats_a_denied_query_open_as_stale() {
use crate::containment::windows::fault::{force_next, Step};
const ERROR_ACCESS_DENIED: u32 = 5;
let _forced = force_next(Step::QueryOpen, ERROR_ACCESS_DENIED);
let spawned = spawn_contained_blocker();
assert!(spawned.is_err(), "no thread was resumed, so the spawn must fail");
let text = format!("{:?}", spawned.err());
assert!(
text.contains("was stale") && text.contains("access denied"),
"a denied query open must be reported as a stale skip: {text}"
);
}
fn assert_forced_failure_fails_the_spawn(step: crate::containment::windows::fault::Step, code: u32, call: &str) {
let _forced = crate::containment::windows::fault::force_next(step, code);
let spawned = spawn_contained_blocker();
assert!(
spawned.is_err(),
"a failure on the child's own thread must fail the spawn"
);
let text = format!("{:?}", spawned.err());
assert!(
text.contains(&format!("{call} failed for thread")) && text.contains("of pid"),
"the error must name the call, thread and pid ({call}): {text}"
);
assert!(!text.contains("was stale"), "a failure is not a stale skip: {text}");
}
#[skuld::test]
fn windows_resume_initial_threads_fails_the_spawn_when_the_query_open_fails() {
use crate::containment::windows::fault::Step;
const ERROR_NOT_ENOUGH_MEMORY: u32 = 8;
assert_forced_failure_fails_the_spawn(Step::QueryOpen, ERROR_NOT_ENOUGH_MEMORY, "OpenThread(query)");
}
#[skuld::test]
fn windows_resume_initial_threads_fails_the_spawn_when_the_resume_open_is_denied() {
use crate::containment::windows::fault::Step;
const ERROR_ACCESS_DENIED: u32 = 5;
assert_forced_failure_fails_the_spawn(Step::ResumeOpen, ERROR_ACCESS_DENIED, "OpenThread(suspend/resume)");
}
#[skuld::test]
fn windows_resume_initial_threads_fails_the_spawn_when_the_owner_is_unreadable() {
use crate::containment::windows::fault::Step;
const ERROR_INVALID_HANDLE: u32 = 6;
assert_forced_failure_fails_the_spawn(Step::Owner, ERROR_INVALID_HANDLE, "GetProcessIdOfThread");
}
#[skuld::test]
fn windows_resume_initial_threads_fails_the_spawn_when_resume_thread_fails() {
use crate::containment::windows::fault::Step;
const ERROR_INVALID_HANDLE: u32 = 6;
assert_forced_failure_fails_the_spawn(Step::Resume, ERROR_INVALID_HANDLE, "ResumeThread");
}
#[skuld::test]
fn walk_verdict_returns_the_first_failure() {
use super::{walk_verdict, Walk};
let mut walk = Walk::default();
walk.fail("ResumeThread", 1, 9, "first cause");
walk.fail("ResumeThread", 2, 9, "second cause");
let text = walk_verdict(9, walk).expect_err("a failure").to_string();
assert!(text.contains("thread 1") && text.contains("first cause"), "{text}");
assert!(
!text.contains("second cause"),
"the later failure replaced the first: {text}"
);
}
#[skuld::test]
fn walk_verdict_with_only_skips_names_the_last_skip() {
use super::{walk_verdict, Walk};
let mut walk = Walk::default();
walk.skip("thread 7 no longer exists".to_owned());
let text = walk_verdict(4321, walk).expect_err("nothing was resumed").to_string();
assert!(
text.contains("4321") && text.contains("thread 7 no longer exists"),
"{text}"
);
let text = walk_verdict(4321, Walk::default())
.expect_err("nothing listed")
.to_string();
assert!(text.contains("listed no threads"), "{text}");
}
#[skuld::test]
fn walk_verdict_accepts_a_walk_that_resumed_a_thread() {
use super::{walk_verdict, Walk};
let mut walk = Walk {
resumed: 1,
..Walk::default()
};
walk.skip("thread 7 no longer exists".to_owned());
walk_verdict(4321, walk).expect("a resumed thread with stale siblings is a success");
}
#[skuld::test]
fn process_pid_of_rejects_a_handle_that_names_no_process() {
let result = super::process_pid_of(windows::Win32::Foundation::HANDLE::default());
assert!(result.is_err(), "a null handle names no process: {result:?}");
let err = result.unwrap_err();
assert!(
err.to_string().contains("GetProcessId"),
"error must name the call: {err}"
);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "live process handle")]
fn resume_initial_threads_asserts_its_handle_contract_in_debug() {
_ = super::resume_initial_threads(std::ptr::null_mut());
}
#[cfg(not(debug_assertions))]
#[skuld::test]
fn resume_initial_threads_reports_a_broken_handle_contract_in_release() {
let err = super::resume_initial_threads(std::ptr::null_mut()).expect_err("a null handle names no process");
assert!(err.to_string().contains("GetProcessId"), "{err}");
}