use crate::test_child::Console;
#[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(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, 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(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, 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(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(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(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 ERROR_INVALID_HANDLE: i32 = 6;
const ERROR_ACCESS_DENIED: i32 = 5;
fn io_err(code: i32) -> std::io::Error {
std::io::Error::from_raw_os_error(code)
}
#[skuld::test]
fn invalid_handle_with_no_console_is_typed_no_console() {
let e = super::classify_ctrl_event_failure(4242, io_err(ERROR_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(ERROR_INVALID_HANDLE), Ok(true));
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
#[skuld::test]
fn duplicate_job_failure_carries_the_win32_code() {
let err = super::duplicate_job(windows::Win32::Foundation::HANDLE::default())
.expect_err("duplicating a null handle must fail");
let crate::error::Error::Io(err) = err else {
panic!("expected Error::Io, got {err:?}");
};
assert_eq!(err.raw_os_error(), Some(ERROR_INVALID_HANDLE), "{err:?}");
}
fn no_console_failure() -> windows::core::Error {
unsafe {
windows::Win32::Foundation::SetLastError(windows::Win32::Foundation::ERROR_INVALID_HANDLE);
}
windows::core::Error::from_thread()
}
#[skuld::test]
fn terminate_classifies_a_real_no_console_failure() {
let e = super::terminate_with(4242, || Err(no_console_failure()), || Ok(false)).expect_err("the send failed");
assert!(matches!(e, crate::error::Error::NoConsole { .. }), "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(ERROR_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(ERROR_ACCESS_DENIED), console);
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
let e = super::classify_ctrl_event_failure(1, io_err(ERROR_ACCESS_DENIED), Err(io_err(87)));
assert!(matches!(e, crate::error::Error::Io(_)), "got {e:?}");
}
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::test_child::command(Console::Hidden);
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}"
);
}
fn source_os_code(e: &std::io::Error) -> Option<i32> {
std::error::Error::source(e.get_ref()?)
.and_then(|s| s.downcast_ref::<std::io::Error>())
.and_then(std::io::Error::raw_os_error)
}
#[skuld::test]
fn fail_win32_keeps_the_win32_code_and_kind() {
use super::{walk_verdict, Walk};
use windows::core::{Error, HRESULT};
let mut walk = Walk::default();
let cause = Error::from_hresult(HRESULT::from_win32(ERROR_ACCESS_DENIED as u32));
walk.fail_win32("ResumeThread", 1, 9, cause);
let err = walk_verdict(9, walk).expect_err("a failure");
assert_eq!(err.kind(), std::io::ErrorKind::PermissionDenied, "{err:?}");
assert_eq!(source_os_code(&err), Some(ERROR_ACCESS_DENIED), "{err:?}");
assert!(
err.to_string()
.starts_with("ResumeThread failed for thread 1 of pid 9: "),
"{err}"
);
}
#[skuld::test]
fn fail_unidentified_has_no_os_code() {
use super::{walk_verdict, Walk};
let mut walk = Walk::default();
walk.fail_unidentified(7, 12, 34);
let err = walk_verdict(7, walk).expect_err("a failure");
assert_eq!(err.raw_os_error(), None, "{err:?}");
assert_eq!(source_os_code(&err), None, "{err:?}");
}
#[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 fail_unidentified_reports_the_whole_sentence() {
use super::{walk_verdict, Walk};
let mut walk = Walk::default();
walk.fail_unidentified(7, 12, 34);
let text = walk_verdict(7, walk).expect_err("a failure").to_string();
assert_eq!(
text,
"the initial thread of pid 7 cannot be identified: threads 12 and 34 have the same creation time"
);
}
#[skuld::test]
fn initial_thread_id_records_a_skip_for_each_stale_thread() {
use super::{initial_thread_id, walk_verdict, Walk};
let mut walk = Walk::default();
let found = initial_thread_id(7, &[0xFFFF_FFFF, 0xFFFF_FFFD], &mut walk);
assert_eq!(
found, None,
"no listed thread is readable, so none is the initial thread"
);
let text = walk_verdict(7, walk).expect_err("nothing was resumed").to_string();
assert!(
text.contains("every thread the snapshot listed for pid 7 was stale")
&& text.contains("thread 4294967293")
&& !text.contains("listed no threads"),
"the error must say the listed threads were stale: {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}"
);
}
#[skuld::test]
fn process_pid_of_failure_carries_the_win32_code() {
let err = super::process_pid_of(windows::Win32::Foundation::HANDLE::default()).expect_err("a null handle");
assert_eq!(source_os_code(&err), Some(ERROR_INVALID_HANDLE), "{err:?}");
assert_eq!(
err.kind(),
std::io::Error::from_raw_os_error(ERROR_INVALID_HANDLE).kind(),
"{err:?}"
);
assert!(
err.to_string()
.starts_with("GetProcessId failed on the child's handle: "),
"{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(), super::SuspendCount::Any);
}
#[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(), super::SuspendCount::Any)
.expect_err("a null handle names no process");
assert!(err.to_string().contains("GetProcessId"), "{err}");
}
fn dispose(mut child: std::process::Child) {
child.kill().expect("kill the test child");
child.wait().expect("reap the test child");
}
#[skuld::test]
fn resume_initial_threads_leaves_no_thread_suspended() {
let mut child = crate::test_frozen::spawn_suspended_blocker();
let thread = crate::test_frozen::InitialThread::of(child.id());
assert_eq!(thread.suspend_count(), 1, "the child is created suspended");
super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect("resume a frozen child");
assert_eq!(thread.suspend_count(), 0, "the resumed child's initial thread must run");
drop(child.stdin.take());
child.wait().expect("the resumed blocker exits on stdin EOF");
}
#[skuld::test]
fn resume_initial_threads_fails_when_the_initial_thread_was_suspended_twice() {
let child = crate::test_frozen::spawn_suspended_blocker();
let thread = crate::test_frozen::InitialThread::of(child.id());
thread.suspend_once();
let err = super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect_err("the thread is still suspended");
let text = err.to_string();
assert!(
text.contains("previous suspend count was 2"),
"the error must name the count it found: {text}"
);
assert_eq!(
thread.suspend_count(),
1,
"the walk resumed once; the foreign suspend is still held, and the failure says so"
);
dispose(child);
}
#[skuld::test]
fn resume_initial_threads_fails_when_the_initial_thread_was_already_running() {
let child = crate::test_frozen::spawn_suspended_blocker();
let thread = crate::test_frozen::InitialThread::of(child.id());
assert_eq!(thread.release_one(), 1);
let err = super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect_err("the child already ran");
let text = err.to_string();
assert!(
text.contains("previous suspend count was 0"),
"the error must name the count it found: {text}"
);
dispose(child);
}
#[skuld::test]
fn resume_initial_threads_accepts_a_running_thread_someone_else_started() {
let mut child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let _injected = crate::test_frozen::inject_running_thread_into_std_child(&child);
super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect("a running second thread must not fail the release of a child whose initial thread is frozen");
assert_eq!(initial.suspend_count(), 0, "the initial thread must run");
drop(child.stdin.take());
child.wait().expect("the resumed blocker exits on stdin EOF");
}
#[skuld::test]
fn resume_initial_threads_leaves_a_thread_someone_else_suspended_suspended() {
let mut child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let held = crate::test_frozen::inject_suspended_thread_into_std_child(&child);
super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect("the initial thread is frozen exactly once");
assert_eq!(initial.suspend_count(), 0, "the initial thread must run");
assert_eq!(
held.suspend_count(),
1,
"the other party's suspension must still be held after the release"
);
drop(child.stdin.take());
child.wait().expect("the resumed blocker exits on stdin EOF");
}
#[skuld::test]
fn resume_initial_threads_visits_only_the_initial_thread() {
use crate::containment::windows::fault::{force_next_for_thread, forced_is_armed, Step};
const ERROR_NOT_ENOUGH_MEMORY: u32 = 8;
let mut child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let other = crate::test_frozen::inject_running_thread_into_std_child(&child);
let _forced = force_next_for_thread(Step::QueryOpen, ERROR_NOT_ENOUGH_MEMORY, other.tid());
super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect("the resume walk's open_query must not be made for a thread that is not the initial one");
assert!(forced_is_armed(), "the walk opened the other thread");
assert_eq!(initial.suspend_count(), 0, "the initial thread must run");
drop(child.stdin.take());
child.wait().expect("the resumed blocker exits on stdin EOF");
}
#[skuld::test]
fn resume_initial_threads_resumes_nothing_when_a_childs_creation_time_cannot_be_read() {
use crate::containment::windows::fault::{force_next_for_thread, Step};
const ERROR_NOT_ENOUGH_MEMORY: u32 = 8;
let child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let other = crate::test_frozen::inject_running_thread_into_std_child(&child);
let _forced = force_next_for_thread(Step::CreationTime, ERROR_NOT_ENOUGH_MEMORY, other.tid());
let err = super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect_err("the initial thread cannot be identified");
let text = err.to_string();
assert!(
text.contains("GetThreadTimes failed") && text.contains(&format!("thread {} of pid", other.tid())),
"the error must name the call and the unreadable thread: {text}"
);
assert_eq!(
initial.suspend_count(),
1,
"nothing may be resumed when the initial thread is unknown"
);
dispose(child);
}
#[skuld::test]
fn resume_initial_threads_resumes_nothing_when_the_earliest_creation_times_are_equal() {
let child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let other = crate::test_frozen::inject_running_thread_into_std_child(&child);
let _equal = crate::containment::windows::fault::equal_creation_times();
let err = super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect_err("the initial thread cannot be identified");
let (a, b) = (initial.tid(), other.tid());
let sentence = |first: u32, second: u32| {
format!(
"the initial thread of pid {} cannot be identified: threads {first} and {second} have the same creation time",
child.id()
)
};
let text = err.to_string();
assert!(
text == sentence(a, b) || text == sentence(b, a),
"the error must say why the initial thread is unknown, in single-spaced words: {text}"
);
assert_eq!(
initial.suspend_count(),
1,
"nothing may be resumed when the initial thread is unknown"
);
dispose(child);
}
#[skuld::test]
fn earliest_created_answers_the_unique_earliest_and_reports_a_tie_for_it() {
use super::Earliest;
assert_eq!(super::earliest_created([]), Earliest::NoThread);
assert_eq!(super::earliest_created([(7, 1)]), Earliest::Unique(1));
assert_eq!(super::earliest_created([(9, 1), (7, 2), (8, 3)]), Earliest::Unique(2));
assert_eq!(super::earliest_created([(7, 5), (7, 2), (8, 3)]), Earliest::Tie(5, 2));
assert_eq!(super::earliest_created([(8, 5), (8, 2), (7, 3)]), Earliest::Unique(3));
}
#[skuld::test]
fn resume_initial_threads_with_any_count_resumes_every_thread() {
let mut child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let second = crate::test_frozen::inject_suspended_thread_into_std_child(&child);
super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::Any)
.expect("resume every thread");
assert_eq!(initial.suspend_count(), 0, "the initial thread must run");
assert_eq!(second.suspend_count(), 0, "`Any` resumes the second thread too");
drop(child.stdin.take());
child.wait().expect("the resumed blocker exits on stdin EOF");
}
#[skuld::test]
fn resume_initial_threads_names_the_initial_thread_when_it_was_already_running() {
let child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
assert_eq!(initial.release_one(), 1);
let _injected = crate::test_frozen::inject_running_thread_into_std_child(&child);
let err = super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect_err("the initial thread already ran");
let text = err.to_string();
assert!(
text.contains(&format!("thread {} of pid", initial.tid())) && text.contains("previous suspend count was 0"),
"the error must name the initial thread and its count: {text}"
);
dispose(child);
}
#[skuld::test]
fn resume_initial_threads_names_the_initial_thread_when_it_was_suspended_twice() {
let child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
initial.suspend_once();
let _injected = crate::test_frozen::inject_running_thread_into_std_child(&child);
let err = super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::ExactlyOne)
.expect_err("the initial thread is still suspended");
let text = err.to_string();
assert!(
text.contains(&format!("thread {} of pid", initial.tid())) && text.contains("previous suspend count was 2"),
"the error must name the initial thread and its count: {text}"
);
dispose(child);
}
#[skuld::test]
fn initial_thread_id_picks_the_earliest_created_thread_whatever_the_list_order() {
let child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let injected = crate::test_frozen::inject_running_thread_into_std_child(&child);
for tids in [[initial.tid(), injected.tid()], [injected.tid(), initial.tid()]] {
let mut walk = super::Walk::default();
let picked = super::initial_thread_id(child.id(), &tids, &mut walk);
assert_eq!(picked, Some(initial.tid()), "list {tids:?}");
assert!(walk.last_err.is_none(), "{:?}", walk.last_err);
}
dispose(child);
}
#[skuld::test]
fn initial_thread_id_ignores_a_thread_that_is_not_the_childs() {
let older = crate::test_frozen::spawn_suspended_blocker();
let older_thread = crate::test_frozen::InitialThread::of(older.id());
let child = crate::test_frozen::spawn_suspended_blocker();
let initial = crate::test_frozen::InitialThread::of(child.id());
let mut walk = super::Walk::default();
let picked = super::initial_thread_id(child.id(), &[older_thread.tid(), 1, initial.tid()], &mut walk);
assert_eq!(picked, Some(initial.tid()));
assert!(
walk.last_err.is_none(),
"a foreign or vanished thread is a skip: {:?}",
walk.last_err
);
dispose(older);
dispose(child);
}
#[skuld::test]
fn resume_initial_threads_with_any_count_accepts_a_thread_that_was_already_running() {
let child = crate::test_frozen::spawn_suspended_blocker();
let thread = crate::test_frozen::InitialThread::of(child.id());
assert_eq!(thread.release_one(), 1);
super::resume_initial_threads(crate::test_frozen::raw(&child), super::SuspendCount::Any)
.expect("the ordinary resume accepts a running thread");
dispose(child);
}
#[skuld::test]
fn death_watch_attach_job_succeeds_when_the_initial_thread_was_already_running() {
let mut child = crate::test_frozen::spawn_suspended_releasable();
let thread = crate::test_frozen::InitialThread::of(child.id());
assert_eq!(thread.release_one(), 1);
let job = super::attach_job(crate::test_frozen::raw(&child))
.expect("an ordinary attach must not fail on a running thread")
.expect("the job was assigned");
drop(job);
crate::test_frozen::assert_not_released("the child", child.wait().expect("reap the child"));
}
#[skuld::test]
fn death_watch_assign_held_assigns_the_job_without_resuming() {
let mut child = crate::test_frozen::spawn_suspended_releasable();
let thread = crate::test_frozen::InitialThread::of(child.id());
let job = super::assign_held(crate::test_frozen::raw(&child)).expect("assign the held child");
assert_eq!(thread.suspend_count(), 1, "assign_held must not resume");
assert_ne!(
crate::test_frozen::limit_flags(&job).0
& windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0,
0
);
drop(job); crate::test_frozen::release(&mut child, &thread);
crate::test_frozen::assert_not_released("the frozen child", child.wait().expect("reap the frozen child"));
}
fn event_handle() -> windows::Win32::Foundation::HANDLE {
unsafe { windows::Win32::System::Threading::CreateEventW(None, true, false, None) }.expect("create an event handle")
}
#[skuld::test]
fn hard_kill_failure_carries_the_win32_code() {
let h = super::JobHandle::new(event_handle());
let err = h.hard_kill().expect_err("an event is not a job");
assert_eq!(err.raw_os_error(), Some(ERROR_INVALID_HANDLE), "{err:?}");
}
#[skuld::test]
fn owned_job_failure_carries_the_win32_code() {
use windows::core::HRESULT;
use windows::Win32::Foundation::ERROR_NOT_ENOUGH_MEMORY;
let failed = windows::core::Error::from_hresult(HRESULT::from_win32(ERROR_NOT_ENOUGH_MEMORY.0));
let err = super::owned_job(Err(failed)).expect_err("the creation failed");
assert_eq!(err.raw_os_error(), Some(ERROR_NOT_ENOUGH_MEMORY.0 as i32), "{err:?}");
}
#[skuld::test]
fn set_kill_on_close_failure_carries_the_win32_code() {
let err = super::set_kill_on_close_or_close(event_handle()).expect_err("an event is not a job");
assert_eq!(err.raw_os_error(), Some(ERROR_INVALID_HANDLE), "{err:?}");
}
#[skuld::test]
fn assign_failure_carries_the_win32_code() {
let me = unsafe { windows::Win32::System::Threading::GetCurrentProcess() };
let err = super::assign_or_close(event_handle(), me).expect_err("an event is not a job");
assert_eq!(err.raw_os_error(), Some(ERROR_INVALID_HANDLE), "{err:?}");
}
#[skuld::test]
fn member_check_failure_carries_the_win32_code() {
use windows::Win32::System::Threading::{
GetCurrentProcessId, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
};
let opened = unsafe {
OpenProcess(
PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
false,
GetCurrentProcessId(),
)
};
let err = super::member_to_watch(opened, event_handle()).expect_err("an event is not a job");
assert_eq!(err.raw_os_error(), Some(ERROR_INVALID_HANDLE), "{err:?}");
}
#[skuld::test]
fn denied_open_carries_the_win32_code() {
use windows::core::HRESULT;
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED as DENIED, ERROR_INVALID_PARAMETER, HANDLE};
let refused = |code| Err(windows::core::Error::from_hresult(HRESULT::from_win32(code)));
let err = super::member_to_watch(refused(DENIED.0), HANDLE::default()).expect_err("denied");
assert_eq!(err.raw_os_error(), Some(ERROR_ACCESS_DENIED), "{err:?}");
let gone = super::member_to_watch(refused(ERROR_INVALID_PARAMETER.0), HANDLE::default());
assert!(matches!(gone, Ok(None)), "an exited pid is not a failure: {gone:?}");
}
#[skuld::test]
fn thread_walk_failure_carries_the_win32_code() {
let err = super::thread_entries_closing(event_handle()).expect_err("an event is not a snapshot");
let code = err.raw_os_error();
assert_eq!(code, Some(ERROR_INVALID_HANDLE), "ERROR_INVALID_HANDLE expected");
}
#[skuld::test]
fn thread_snapshot_failure_carries_the_win32_code() {
use windows::core::HRESULT;
use windows::Win32::Foundation::ERROR_NOT_ENOUGH_MEMORY;
let failed = windows::core::Error::from_hresult(HRESULT::from_win32(ERROR_NOT_ENOUGH_MEMORY.0));
let err = super::thread_snapshot(Err(failed)).expect_err("the snapshot failed");
assert_eq!(err.raw_os_error(), Some(ERROR_NOT_ENOUGH_MEMORY.0 as i32), "{err:?}");
}
#[skuld::test]
fn a_refused_disarm_is_returned_with_the_win32_code() {
use super::JobHandle;
use windows::Win32::Foundation::ERROR_ACCESS_DENIED;
let job = JobHandle::create_without_set_access_for_test();
let err = job
.disarm()
.expect_err("the OS refuses SetInformationJobObject on this handle");
assert_eq!(err.raw_os_error(), Some(ERROR_ACCESS_DENIED.0 as i32), "{err:?}");
}
#[skuld::test]
fn disarm_of_an_empty_job_is_ok() {
super::JobHandle::create_empty_for_test()
.disarm()
.expect("a job made by the crate can be disarmed");
}
#[skuld::test]
fn disarm_of_a_consumed_job_is_ok() {
let job = super::JobHandle::create_empty_for_test();
job.hard_kill().expect("hard_kill on a live job");
job.disarm().expect("a consumed handle has nothing to disarm");
}