use crate::child::spawn::policy::SpawnPolicy;
use crate::child::spawn::{spawn_uncommitted, SpawnFailure};
use crate::child::{Child, SuspendedChild};
use crate::command::Command;
use crate::containment::windows::{resume_initial_threads, SuspendCount};
use crate::error::Error;
impl SuspendedChild {
#[doc(hidden)]
pub fn test_job_handle_contains_self(&self) -> bool {
self.child.test_job_handle_contains_self()
}
#[doc(hidden)]
pub fn test_job_kills_on_close(&self) -> bool {
self.child.tree.job_kills_on_close_for_test()
}
#[doc(hidden)]
pub fn test_containment(&self) -> crate::Containment {
self.child.containment()
}
}
struct Borrowed<'a> {
cmd: &'a mut Command,
kill_on_drop: bool,
suspended: bool,
}
impl<'a> Borrowed<'a> {
fn new(cmd: &'a mut Command) -> Borrowed<'a> {
let kill_on_drop = cmd.kill_on_drop_flag();
cmd.kill_on_drop(true);
let suspended = cmd.set_suspended(true);
Borrowed {
cmd,
kill_on_drop,
suspended,
}
}
}
impl Drop for Borrowed<'_> {
fn drop(&mut self) {
self.cmd.kill_on_drop(self.kill_on_drop);
self.cmd.set_suspended(self.suspended);
}
}
pub(crate) fn refusal(cmd: &Command) -> Option<Error> {
cmd.elevation_request().enabled.then(|| Error::Unsupported {
op: "spawn_suspended() with elevate()".into(),
platform: "windows",
detail: "an elevated spawn goes through ShellExecuteEx, which cannot create a process \
suspended; drop one of the two"
.into(),
source: None,
})
}
pub(crate) fn spawn_frozen<T>(
cmd: &mut Command,
spawn: impl FnOnce(&mut Command) -> Result<T, SpawnFailure>,
) -> Result<(T, bool), SpawnFailure> {
debug_assert!(refusal(cmd).is_none(), "a refused command is not spawned frozen");
let wanted_kill_on_drop = cmd.kill_on_drop_flag();
let borrowed = Borrowed::new(cmd);
let spawned = spawn(&mut *borrowed.cmd);
drop(borrowed);
Ok((spawned?, wanted_kill_on_drop))
}
pub(super) fn spawn(cmd: &mut Command) -> Result<SuspendedChild, Error> {
if let Some(refusal) = refusal(cmd) {
return Err(refusal);
}
let (child, wanted_kill_on_drop) = spawn_frozen(cmd, |cmd| {
spawn_uncommitted(cmd, SpawnPolicy::SYNC, crate::identity::HostKernel)
})?;
Ok(SuspendedChild {
child,
wanted_kill_on_drop,
})
}
pub(super) fn release(child: &Child) -> std::io::Result<()> {
resume_initial_threads(child.process_handle(), SuspendCount::ExactlyOne)
}