use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::time::Duration;
use windows::core::HRESULT;
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, HANDLE};
use windows::Win32::System::Threading::{
OpenProcess, TerminateProcess, CREATE_SUSPENDED, EXTENDED_STARTUPINFO_PRESENT, PROCESS_QUERY_LIMITED_INFORMATION,
PROCESS_SYNCHRONIZE, STARTUPINFOEXW,
};
use super::proc::create_process;
use crate::child::lifecycle::Wording;
use crate::child::owned::owned_tests::teardown_lines::{HANDED_BACK, LEFT};
use crate::child::owned::teardown::{Disposition, Kill, Past};
use crate::child::owned::{ChildWaitOutcome, OwnedChild};
use crate::child::spawn::held_teardown::tear_down_failed_spawn;
use crate::child::spawn::Diagnosis;
use crate::error::ChildFate;
use crate::identity::ProcessId;
use crate::os_process::child::{ExitRecord, KillRefusal, OsChild};
use crate::os_process::fake::{FakeProcess, ReapAnswer};
use crate::os_process::windows::{uac_access, WindowsProcess};
use crate::test_spawn::console_flags::NO_WINDOW;
use crate::wait::teardown_warn::Due;
const KIND: std::io::ErrorKind = std::io::ErrorKind::Other;
struct Suspended {
owned: OwnedChild,
pid: u32,
}
impl Suspended {
fn spawn() -> Suspended {
let mut cmdline: Vec<u16> = "cmd /C exit 0\0".encode_utf16().collect();
let mut si = STARTUPINFOEXW::default();
let (proc, pid) = create_process(
None,
&mut cmdline,
&mut si,
None,
&None,
EXTENDED_STARTUPINFO_PRESENT.0 | CREATE_SUSPENDED.0 | NO_WINDOW,
)
.expect("spawn suspended");
Suspended {
owned: OwnedChild::new(Box::new(WindowsProcess::for_child(proc, pid))),
pid,
}
}
fn handle(&self) -> HANDLE {
HANDLE(self.owned.os_handle().as_raw_handle())
}
fn id(&self) -> ProcessId {
ProcessId::of(self.pid).found().expect("identity")
}
fn duplicate(&self) -> OwnedHandle {
self.owned
.os_handle()
.try_clone_to_owned()
.expect("duplicate the process handle")
}
fn without_terminate_right(&self) -> OwnedHandle {
let h = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, self.pid) }
.expect("open without PROCESS_TERMINATE");
unsafe { OwnedHandle::from_raw_handle(h.0) }
}
fn end_with_code_zero(&self) -> impl FnOnce() + 'static {
let handle = self.handle();
move || {
match unsafe { TerminateProcess(handle, 0) } {
Ok(()) => {}
Err(e) if e.code() == HRESULT::from_win32(ERROR_ACCESS_DENIED.0) => {}
Err(e) => panic!("TerminateProcess(handle, 0) failed: {e:?}"),
}
}
}
fn wait_for_exit(&self) -> std::process::ExitStatus {
match self.owned.wait(None) {
Ok(crate::child::owned::ChildWaitOutcome::Exited(crate::os_process::child::ExitRecord::Status(s))) => s,
other => panic!("expected an exit status, got {other:?}"),
}
}
}
impl Drop for Suspended {
fn drop(&mut self) {
_ = unsafe { TerminateProcess(self.handle(), 1) };
_ = self.owned.wait(None);
}
}
fn real(handle: OwnedHandle, pid: u32) -> FakeProcess {
FakeProcess::over(Box::new(WindowsProcess::for_child(handle, pid)))
}
fn uac_process(handle: OwnedHandle, pid: u32) -> WindowsProcess {
let granted = uac_access(HANDLE(handle.as_raw_handle()));
WindowsProcess::for_uac(handle, pid, granted)
}
fn uac(handle: OwnedHandle, pid: u32) -> FakeProcess {
FakeProcess::over(Box::new(uac_process(handle, pid)))
}
fn owned(fake: FakeProcess) -> (OwnedChild, FakeProcess) {
(OwnedChild::new(Box::new(fake.clone())), fake)
}
const DISPOSITIONS: [Disposition; 2] = [Disposition::Leave, Disposition::HandBack];
fn after_a_failed_spawn(
child: OwnedChild,
id: Option<ProcessId>,
past: Past,
disposition: Disposition,
warn_after: Option<Duration>,
) -> (ChildFate, Option<crate::Unreaped>) {
tear_down_failed_spawn(
child,
id,
past,
disposition,
Due::in_(warn_after),
&mut Diagnosis::default(),
)
}
#[skuld::test]
fn a_failed_spawn_teardown_of_an_exited_child_with_warnings_on_does_not_warn() {
for disposition in DISPOSITIONS {
let owner = Suspended::spawn();
let id = owner.id();
let (child, _fake) = owned(uac(owner.without_terminate_right(), owner.pid));
owner.end_with_code_zero()();
owner.wait_for_exit();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (fate, unreaped) =
after_a_failed_spawn(child, Some(id), Past::Clean, disposition, Some(Duration::from_secs(1)));
assert_eq!(fate, ChildFate::Reaped, "{disposition:?}");
assert!(
unreaped.is_none(),
"a collected child is handed back by none: {disposition:?}"
);
let warns = crate::log_capture::records_since_on_current_thread(mark, "still waiting");
assert!(warns.is_empty(), "{disposition:?}: {warns:?}");
}
}
#[skuld::test]
fn a_failed_spawn_teardown_of_a_running_child_with_warnings_on_warns_once_naming_it() {
for disposition in DISPOSITIONS {
let owner = Suspended::spawn();
let (child, _fake) = owned(real(owner.duplicate(), owner.pid));
let refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
let (fate, unreaped) = after_a_failed_spawn(child, None, Past::Clean, disposition, Some(Duration::ZERO));
refusal.assert_fired();
assert_eq!(
fate,
ChildFate::Reaped,
"the wait goes on past the warn: {disposition:?}"
);
assert!(
unreaped.is_none(),
"a collected child is handed back by none: {disposition:?}"
);
let warns = crate::log_capture::records_since_on_current_thread(mark, "still waiting");
assert_eq!(warns.len(), 1, "one warn: {disposition:?}: {warns:?}");
assert!(
warns[0].1.contains(&format!("child {} ", owner.pid)),
"the warn names the child: {warns:?}"
);
}
}
#[skuld::test]
fn a_failed_spawn_teardown_with_a_denied_terminate_is_running_and_does_not_wait() {
let owner = Suspended::spawn();
let id = owner.id();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (child, fake) = owned(uac(owner.without_terminate_right(), owner.pid));
crate::wait::block_probe::take();
let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
let (fate, unreaped) = after_a_failed_spawn(child, Some(id), Past::Clean, Disposition::Leave, None);
assert!(unreaped.is_none(), "a teardown that leaves its child hands none back");
assert_eq!(fate, ChildFate::Running { id: Some(id) });
assert_eq!(fake.looks(), 1, "one look, and no wait");
assert_eq!(
crate::wait::block_probe::take(),
[],
"a failed kill is never followed by a wait"
);
let warned = crate::log_capture::warns_since(mark, "");
assert_eq!(warned.len(), 1, "one warn for one refusal: {warned:?}");
assert!(
warned[0].starts_with(&format!(
"teardown after a failed spawn: child {} could not be terminated",
owner.pid
)),
"{warned:?}"
);
}
#[skuld::test]
fn a_failed_spawn_teardown_with_a_failed_terminate_of_an_exited_child_is_reaped_silently() {
for disposition in DISPOSITIONS {
let owner = Suspended::spawn();
let id = owner.id();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let fake = FakeProcess::new([])
.with_kill_refusal(KillRefusal::Permission)
.reaps([ReapAnswer::Reaped(ExitRecord::Status(
std::process::ExitStatus::default(),
))])
.signals([Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))]);
let (child, fake) = owned(fake);
let (fate, unreaped) = after_a_failed_spawn(child, Some(id), Past::Clean, disposition, None);
assert_eq!(fate, ChildFate::Reaped, "{disposition:?}");
assert!(
unreaped.is_none(),
"a collected child is handed back by none: {disposition:?}"
);
assert_eq!(fake.looks(), 1);
let warned = crate::log_capture::warns_since(mark, "");
assert_eq!(warned, Vec::<String>::new(), "nothing is left running: {disposition:?}");
}
}
#[skuld::test]
fn a_failed_spawn_teardown_with_a_delivered_terminate_and_a_failed_wait_is_killed() {
for disposition in DISPOSITIONS {
let owner = Suspended::spawn();
let (child, fake) = owned(real(owner.duplicate(), owner.pid).reaps([ReapAnswer::Err(KIND)]));
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (fate, unreaped) = after_a_failed_spawn(child, None, Past::WaitMayFail, disposition, None);
assert_eq!(fate, ChildFate::Killed, "{disposition:?}");
assert_eq!(
unreaped.is_some(),
disposition == Disposition::HandBack,
"an uncollected child is handed back by HandBack alone: {disposition:?}"
);
assert_eq!(fake.looks(), 1, "the teardown made the wait that failed");
assert_eq!(
owner.wait_for_exit().code(),
Some(1),
"the teardown's kill must have ended it"
);
let warns = crate::log_capture::records_since_on_current_thread(mark, "");
let where_it_went = match disposition {
Disposition::Leave => LEFT,
Disposition::HandBack => HANDED_BACK,
};
assert_eq!(
warns,
[(
log::Level::Warn,
format!(
"teardown after a failed spawn: teardown of child {}: the wait failed: {}{where_it_went}",
owner.pid,
crate::child::owned::owned_tests::teardown_lines::wait_error(),
)
)],
"{disposition:?}"
);
}
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "a wait on a child's own handle failed")]
fn a_failed_wait_on_a_handle_the_spawn_expected_to_wait_on_breaks_the_contract() {
let owner = Suspended::spawn();
let (child, _fake) = owned(real(owner.duplicate(), owner.pid).reaps([ReapAnswer::Err(KIND)]));
crate::log_capture::install();
after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}
#[skuld::test]
fn each_windows_handle_kind_states_what_its_kill_may_be_refused_for() {
let owner = Suspended::spawn();
let kind = |process: WindowsProcess| process.kill_refusal();
assert_eq!(
kind(WindowsProcess::for_child(owner.duplicate(), owner.pid)),
KillRefusal::Never
);
assert_eq!(
kind(uac_process(owner.duplicate(), owner.pid)),
KillRefusal::Never,
"a UAC handle granted PROCESS_TERMINATE"
);
assert_eq!(
kind(uac_process(owner.without_terminate_right(), owner.pid)),
KillRefusal::Permission,
"a UAC handle that was not"
);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never refused")]
fn a_kill_of_a_createprocess_handle_refused_for_permission_breaks_the_contract() {
let owner = Suspended::spawn();
let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
let (child, _fake) = owned(real(owner.duplicate(), owner.pid).signals([Err(denied)]));
crate::log_capture::install();
after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never refused")]
fn a_kill_of_a_uac_handle_granted_terminate_refused_for_permission_breaks_the_contract() {
let owner = Suspended::spawn();
let denied = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
let (child, _fake) = owned(uac(owner.duplicate(), owner.pid).signals([Err(denied)]));
crate::log_capture::install();
after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "refused for a reason other than permission")]
fn a_kill_refused_for_another_reason_than_permission_breaks_the_contract() {
crate::log_capture::install();
let fake = FakeProcess::new([])
.with_kill_refusal(KillRefusal::Permission)
.reaps([ReapAnswer::Reaped(ExitRecord::Status(
std::process::ExitStatus::default(),
))])
.signals([Err(std::io::Error::from(std::io::ErrorKind::Other))]);
let (child, _fake) = owned(fake);
after_a_failed_spawn(child, None, Past::Clean, Disposition::Leave, None);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "never refused")]
fn a_failed_look_does_not_excuse_a_refusal_of_a_handle_that_is_never_refused() {
crate::log_capture::install();
let fake = FakeProcess::new([])
.with_kill_refusal(KillRefusal::Never)
.reaps([ReapAnswer::Reaped(ExitRecord::Status(
std::process::ExitStatus::default(),
))])
.signals([Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied))]);
let (child, _fake) = owned(fake);
after_a_failed_spawn(child, None, Past::WaitMayFail, Disposition::Leave, None);
}
#[cfg(debug_assertions)]
#[skuld::test]
#[should_panic(expected = "refused for a reason other than permission")]
fn a_failed_look_does_not_excuse_a_refusal_for_another_reason_than_permission() {
crate::log_capture::install();
let fake = FakeProcess::new([])
.with_kill_refusal(KillRefusal::Permission)
.reaps([ReapAnswer::Reaped(ExitRecord::Status(
std::process::ExitStatus::default(),
))])
.signals([Err(std::io::Error::from(std::io::ErrorKind::Other))]);
let (child, _fake) = owned(fake);
after_a_failed_spawn(child, None, Past::WaitMayFail, Disposition::Leave, None);
}
#[skuld::test]
fn a_failed_spawn_teardown_with_a_denied_terminate_hands_the_child_back() {
let owner = Suspended::spawn();
let id = owner.id();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let child = OwnedChild::new(Box::new(uac_process(owner.without_terminate_right(), owner.pid)));
let (fate, unreaped) = after_a_failed_spawn(child, Some(id), Past::Clean, Disposition::HandBack, None);
assert_eq!(fate, ChildFate::Running { id: Some(id) });
let unreaped = unreaped.expect("a refused kill under HandBack hands the child back");
assert_eq!((unreaped.pid(), unreaped.id()), (Some(owner.pid), Some(id)));
let warns = crate::log_capture::records_since_on_current_thread(mark, "handed back to the caller");
assert_eq!(warns.len(), 1, "{warns:?}");
owner.end_with_code_zero()();
let status = unreaped.wait().expect("wait for the handed-back child");
assert_eq!(status.code(), Some(0), "nothing was sent to the child: {status:?}");
}
fn handle_over(owner: &Suspended, script: impl FnOnce(FakeProcess) -> FakeProcess) -> (OwnedChild, FakeProcess) {
owned(script(real(owner.duplicate(), owner.pid)))
}
#[skuld::test]
fn a_kill_teardown_of_a_child_waits_for_the_exit_it_started() {
let owner = Suspended::spawn();
let (handle, _fake) = handle_over(&owner, |fake| fake);
let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
let torn = handle.tear_down(
Some(owner.id()),
Kill {
disposition: Disposition::Leave,
tree: None,
},
None,
);
assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
assert!(
matches!(torn.said(), Some(Wording::Collected(log::Level::Debug, _))),
"{torn:?}"
);
assert!(handle.is_reaped(), "teardown must wait for the exit it started");
let outcome = handle.wait(None).expect("wait after teardown");
let ChildWaitOutcome::Exited(ExitRecord::Status(status)) = outcome else {
panic!("the reaped child answers its status: {outcome:?}");
};
assert_eq!(
status.code(),
Some(1),
"teardown must end it with TerminateProcess(1): {status:?}"
);
}
#[skuld::test]
fn a_kill_teardown_never_blocks_on_a_handle_without_terminate() {
let owner = Suspended::spawn();
let id = owner.id();
crate::log_capture::install();
let mark = crate::log_capture::mark();
let (child, fake) = owned(uac(owner.without_terminate_right(), owner.pid));
let handle = child;
let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
let torn = handle.tear_down(
Some(id),
Kill {
disposition: Disposition::Leave,
tree: None,
},
None,
);
assert_eq!(torn.fate(), ChildFate::Running { id: Some(id) }, "{torn:?}");
assert!(
matches!(torn.said(), Some(Wording::Uncollected(text)) if text.contains(&owner.pid.to_string())),
"{torn:?}"
);
assert_eq!(fake.looks(), 1, "teardown looked once and did not wait");
let warned = crate::log_capture::warns_since(mark, "");
assert_eq!(
warned,
Vec::<String>::new(),
"the teardown leaves the one warn to its caller"
);
assert!(
matches!(
handle.wait(Some(crate::wait::now())),
Ok(ChildWaitOutcome::DeadlinePassed)
),
"nothing ended the child"
);
}
#[skuld::test]
fn teardown_of_a_handle_without_terminate_to_an_exited_child_reaps_it() {
let owner = Suspended::spawn();
let (child, _fake) = owned(uac(owner.without_terminate_right(), owner.pid));
let handle = child;
owner.end_with_code_zero()();
owner.wait_for_exit();
let torn = handle.tear_down(
Some(owner.id()),
Kill {
disposition: Disposition::Leave,
tree: None,
},
None,
);
assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
assert!(
matches!(torn.said(), Some(Wording::Collected(log::Level::Debug, _))),
"{torn:?}"
);
}
#[skuld::test]
fn teardown_of_an_exiting_unsignalled_child_reaps_it() {
let owner = Suspended::spawn();
let (handle, _fake) = handle_over(&owner, |fake| fake);
let _end = crate::wait::block_probe::on_blocking(owner.end_with_code_zero());
let _refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
let torn = handle.tear_down(
Some(owner.id()),
Kill {
disposition: Disposition::Leave,
tree: None,
},
None,
);
assert_eq!(torn.fate(), ChildFate::Reaped, "{torn:?}");
assert!(
matches!(torn.said(), Some(Wording::Collected(log::Level::Debug, _))),
"{torn:?}"
);
}
#[skuld::test]
fn teardown_of_an_exiting_child_with_a_failed_wait_is_unknown() {
let owner = Suspended::spawn();
let (handle, fake) = handle_over(&owner, |fake| fake.reaps([ReapAnswer::Err(KIND)]));
let _refusal = crate::identity::windows_fault::refuse_next_terminate_as_exiting();
let torn = handle.tear_down(
Some(owner.id()),
Kill {
disposition: Disposition::Leave,
tree: None,
},
None,
);
assert_eq!(torn.fate(), ChildFate::Unknown, "{torn:?}");
assert_eq!(fake.looks(), 1, "the teardown made the wait that failed");
}