use std::{
fs::File,
io, mem,
os::windows::io::{AsRawHandle, BorrowedHandle, FromRawHandle, OwnedHandle},
path::PathBuf,
sync::{Arc, Mutex},
};
use crate::platform::executable::{Console, Lease, open_executable, same_file, windows::ImageView};
use super::ResolvedCommand;
use tokio::{
process::{ChildStderr, ChildStdin, ChildStdout, Command},
sync::oneshot,
task::JoinHandle,
};
use windows_sys::Win32::{
Foundation::{
ERROR_ACCESS_DENIED, ERROR_CANCELLED, ERROR_INVALID_PARAMETER, FILETIME,
GetHandleInformation, HANDLE, HANDLE_FLAG_INHERIT, INVALID_HANDLE_VALUE,
SetHandleInformation, WAIT_TIMEOUT,
},
System::{
Console::{
CTRL_BREAK_EVENT, GenerateConsoleCtrlEvent, GetStdHandle, STD_ERROR_HANDLE,
STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
},
Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
},
Threading::{
CREATE_BREAKAWAY_FROM_JOB, CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW,
CREATE_SUSPENDED, DETACHED_PROCESS, GetProcessTimes, OpenProcess, OpenThread,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, ResumeThread,
THREAD_SUSPEND_RESUME, WaitForSingleObject,
},
},
};
mod job;
use job::Job;
pub(super) struct Binding {
identity: Option<Identity>,
image: Lease,
batch: bool,
}
struct Identity {
path: PathBuf,
file: File,
_guards: Vec<File>,
_section: Option<ImageView>,
}
impl Binding {
fn verify(&self) -> io::Result<()> {
if let Some(identity) = &self.identity
&& !same_file(&identity.file, &identity.path)?
{
return Err(io::ErrorKind::PermissionDenied.into());
}
Ok(())
}
}
impl ResolvedCommand {
pub(in crate::platform) fn ordinary(command: Command, image: Lease, batch: bool) -> Self {
Self {
command,
binding: Binding {
identity: None,
image,
batch,
},
}
}
pub(in crate::platform) fn verified(
command: Command,
image: Lease,
batch: bool,
guards: Vec<File>,
section: Option<ImageView>,
) -> io::Result<Self> {
let path = PathBuf::from(command.as_std().get_program());
let file = open_executable(&path)?;
Ok(Self {
command,
binding: Binding {
identity: Some(Identity {
path,
file,
_guards: guards,
_section: section,
}),
image,
batch,
},
})
}
fn check_working_directory(&self) -> io::Result<()> {
if !self.binding.batch {
return Ok(());
}
let cwd = self
.as_std()
.get_current_dir()
.map_or_else(std::env::current_dir, |cwd| Ok(cwd.to_owned()))?;
use super::super::executable::windows::batch::check_working_directory;
check_working_directory(&cwd)?;
check_working_directory(&std::fs::canonicalize(cwd)?)
}
pub fn spawn(mut self) -> io::Result<tokio::process::Child> {
self.check_working_directory()?;
let _guard = SPAWN.lock().unwrap();
self.binding.verify()?;
let child = self.command.spawn()?;
retain_child_image(&child, self.binding.image)?;
Ok(child)
}
}
static SPAWN: Mutex<()> = Mutex::new(());
pub struct Child {
child: tokio::process::Child,
job: Job,
terminating: Option<Arc<[OwnedHandle]>>,
group: super::ProcessId,
_leader: OwnedHandle,
released: bool,
_verified: Option<Lease>,
_image: Lease,
}
use super::ProcessOutcome;
impl Child {
pub fn stdin(&mut self) -> &mut Option<ChildStdin> {
&mut self.child.stdin
}
pub fn stdout(&mut self) -> &mut Option<ChildStdout> {
&mut self.child.stdout
}
pub fn stderr(&mut self) -> &mut Option<ChildStderr> {
&mut self.child.stderr
}
pub async fn wait(&mut self) -> io::Result<ProcessOutcome> {
self.child.wait().await.map(ProcessOutcome::from_native)
}
pub async fn wait_leader(&mut self) -> io::Result<ProcessOutcome> {
self.child.wait().await.map(ProcessOutcome::from_native)
}
pub fn try_wait_leader(&mut self) -> io::Result<Option<ProcessOutcome>> {
self.child
.try_wait()
.map(|status| status.map(ProcessOutcome::from_native))
}
pub fn interrupt(&self) -> io::Result<()> {
if self.job.active_processes()? == 0 {
return Ok(());
}
if unsafe { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, self.group.get()) } == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
pub async fn cleanup(&mut self) -> io::Result<ProcessOutcome> {
self.kill()?;
let status = self.child.wait().await?;
let processes = self
.terminating
.clone()
.expect("kill retained process handles");
if !processes.is_empty() {
tokio::task::spawn_blocking(move || job::wait_for_exit(&processes))
.await
.map_err(join_error)??;
}
Ok(ProcessOutcome::from_native(status))
}
pub fn kill(&mut self) -> io::Result<()> {
if self.terminating.is_none() {
let processes = self.job.processes_for_cleanup();
self.job.terminate()?;
self.terminating = Some(processes?.into());
}
Ok(())
}
pub fn release(mut self) -> io::Result<()> {
let process = (self._image.has_resources()
|| self._verified.as_ref().is_some_and(Lease::has_resources))
.then(|| self._leader.try_clone())
.transpose()?;
self.job.keep_on_close()?;
self.released = true;
if let Some(process) = process {
retain_images_until_exit(
process,
(self._verified.take(), mem::take(&mut self._image)),
);
}
Ok(())
}
}
impl Drop for Child {
fn drop(&mut self) {
if !self.released {
let _ = self.job.terminate();
}
}
}
pub struct Gate {
pid: u32,
admission: oneshot::Sender<()>,
binding: Binding,
}
pub struct IdentifiedGate(Gate);
impl Gate {
pub async fn identify(self) -> io::Result<IdentifiedGate> {
Ok(IdentifiedGate(self))
}
}
impl IdentifiedGate {
pub fn pid(&self) -> u32 {
self.0.pid
}
pub fn admit(self) -> io::Result<()> {
self.0.binding.verify()?;
resume(self.0.pid)?;
self.0
.admission
.send(())
.map_err(|_| io::ErrorKind::BrokenPipe.into())
}
}
pub fn spawn_gated(command: ResolvedCommand) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
spawn_gated_with(command, 0)
}
fn spawn_gated_with(
mut command: ResolvedCommand,
flags: u32,
) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
command.check_working_directory()?;
let job = Job::new()?;
command
.command
.creation_flags(CREATE_SUSPENDED | CREATE_NEW_PROCESS_GROUP | flags)
.kill_on_drop(false);
let spawned = {
let _guard = SPAWN.lock().unwrap();
command.binding.verify()?;
command.command.spawn()
};
let child = spawned.and_then(|mut child| match job.assign(&child) {
Ok(()) => Ok(child),
Err(error) => {
let _ = child.start_kill();
Err(error)
}
})?;
let process = child
.raw_handle()
.expect("a suspended process has a handle");
let leader = unsafe { BorrowedHandle::borrow_raw(process) }.try_clone_to_owned()?;
let (outcome, admission) = oneshot::channel();
let group = super::ProcessId::new(child.id().expect("a newly spawned child has a PID"));
let image = command.binding.image.clone();
let gate = Gate {
binding: command.binding,
pid: group.get(),
admission: outcome,
};
let spawning = tokio::spawn(async move {
let mut child = child;
if admission.await.is_err() {
let _ = job.terminate();
let _ = child.wait().await;
return Err(io::Error::from_raw_os_error(ERROR_CANCELLED as i32));
}
Ok(Child {
child,
job,
terminating: None,
group,
_leader: leader,
released: false,
_verified: None,
_image: image,
})
});
Ok((gate, spawning))
}
pub(in crate::platform) fn spawn_for_admission(
command: ResolvedCommand,
console: Console,
) -> io::Result<(Gate, JoinHandle<io::Result<Child>>)> {
let flags = match console {
Console::Inherit => 0,
Console::Hidden => CREATE_NO_WINDOW,
};
spawn_gated_with(command, flags)
}
impl Child {
pub(in crate::platform) fn retain_image(&mut self, lease: Lease) {
self._verified = Some(lease);
}
}
pub async fn spawn_now(command: ResolvedCommand) -> io::Result<Child> {
admitted(spawn_gated(command)?).await
}
pub use spawn_now as spawn_in_owner_session;
fn join_error(error: tokio::task::JoinError) -> io::Error {
if error.is_panic() {
std::panic::resume_unwind(error.into_panic());
}
io::Error::new(io::ErrorKind::Interrupted, error)
}
async fn admitted((gate, spawning): (Gate, JoinHandle<io::Result<Child>>)) -> io::Result<Child> {
gate.identify().await?.admit()?;
spawning.await.map_err(join_error)?
}
pub async fn spawn_windowless(command: ResolvedCommand) -> io::Result<Child> {
admitted(spawn_gated_with(command, CREATE_NO_WINDOW)?).await
}
fn resume(pid: u32) -> io::Result<()> {
let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) };
if snapshot == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
let snapshot = unsafe { OwnedHandle::from_raw_handle(snapshot) };
let mut entry = THREADENTRY32 {
dwSize: mem::size_of::<THREADENTRY32>() as u32,
..Default::default()
};
let mut resumed = false;
let mut more = unsafe { Thread32First(snapshot.as_raw_handle(), &mut entry) } != 0;
while more {
if entry.th32OwnerProcessID == pid {
let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) };
if thread.is_null() {
return Err(io::Error::last_os_error());
}
let thread = unsafe { OwnedHandle::from_raw_handle(thread) };
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
return Err(io::Error::last_os_error());
}
resumed = true;
}
more = unsafe { Thread32Next(snapshot.as_raw_handle(), &mut entry) } != 0;
}
if !resumed {
return Err(io::Error::other(
"the suspended child has no thread to resume",
));
}
Ok(())
}
pub fn spawn_detached(mut command: ResolvedCommand) -> io::Result<tokio::process::Child> {
command.check_working_directory()?;
let _guard = SPAWN.lock().unwrap();
let _suppressed = SuppressedStdio::new();
let detached = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
command
.command
.creation_flags(detached | CREATE_BREAKAWAY_FROM_JOB);
command.binding.verify()?;
let child = match command.command.spawn() {
Err(error) if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => {
command.command.creation_flags(detached);
command.binding.verify()?;
command.command.spawn()
}
spawned => spawned,
}?;
retain_child_image(&child, command.binding.image)?;
Ok(child)
}
fn retain_child_image(child: &tokio::process::Child, image: Lease) -> io::Result<()> {
if image.has_resources() {
let handle = child
.raw_handle()
.expect("a just-spawned child has a process handle");
let process = unsafe { BorrowedHandle::borrow_raw(handle) }.try_clone_to_owned()?;
retain_images_until_exit(process, image);
}
Ok(())
}
fn retain_images_until_exit(process: OwnedHandle, images: impl Send + 'static) {
std::thread::spawn(move || {
unsafe { WaitForSingleObject(process.as_raw_handle(), u32::MAX) };
drop(images);
});
}
struct SuppressedStdio([Option<HANDLE>; 3]);
impl SuppressedStdio {
fn new() -> Self {
Self(
[STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE].map(|id| {
let mut flags = 0;
unsafe {
let handle = GetStdHandle(id);
(GetHandleInformation(handle, &mut flags) != 0
&& flags & HANDLE_FLAG_INHERIT != 0
&& SetHandleInformation(handle, HANDLE_FLAG_INHERIT, 0) != 0)
.then_some(handle)
}
}),
)
}
}
impl Drop for SuppressedStdio {
fn drop(&mut self) {
for handle in self.0.into_iter().flatten() {
unsafe { SetHandleInformation(handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) };
}
}
}
pub fn spawn_run(command: ResolvedCommand) -> io::Result<tokio::process::Child> {
spawn_detached(command)
}
pub fn spawn_watched(command: ResolvedCommand) -> io::Result<tokio::process::Child> {
spawn_detached(command)
}
pub fn hide_console_window(command: &mut std::process::Command) {
use std::os::windows::process::CommandExt;
command.creation_flags(CREATE_NO_WINDOW);
}
pub fn process_start_time(pid: u32) -> io::Result<u64> {
let process = unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE,
0,
pid,
)
};
if process.is_null() {
let error = io::Error::last_os_error();
return Err(match error.raw_os_error().map(|code| code as u32) {
Some(ERROR_INVALID_PARAMETER | ERROR_ACCESS_DENIED) => io::ErrorKind::NotFound.into(),
_ => error,
});
}
let process = unsafe { OwnedHandle::from_raw_handle(process) };
match unsafe { WaitForSingleObject(process.as_raw_handle(), 0) } {
WAIT_TIMEOUT => {}
windows_sys::Win32::Foundation::WAIT_FAILED => return Err(io::Error::last_os_error()),
_ => return Err(io::ErrorKind::NotFound.into()),
}
let mut creation = FILETIME::default();
let (mut exit, mut kernel, mut user) = (creation, creation, creation);
if unsafe {
GetProcessTimes(
process.as_raw_handle(),
&mut creation,
&mut exit,
&mut kernel,
&mut user,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok((u64::from(creation.dwHighDateTime) << 32) | u64::from(creation.dwLowDateTime))
}
pub fn running_process_start_time(pid: u32) -> io::Result<u64> {
process_start_time(pid)
}
pub fn kill_saved_session(_leader: super::ChildIdentity) -> io::Result<()> {
Ok(())
}
pub fn kill_saved_group(_leader: super::ChildIdentity) -> io::Result<()> {
Ok(())
}