From d7df925b6545f75bcf86cc63ec55ef82463e0dc9 Mon Sep 17 00:00:00 2001 From: Luka Tsabadze Date: Fri, 20 Nov 2026 19:34:56 +0200 Subject: [PATCH] fix(windows): resume wxc-exec without scanning every thread MxcWindowsSandbox::launch() creates wxc-exec.exe suspended, assigns it to the limited Job Object, and then resumes it. resume_process found the executor's suspended thread with CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD), which lists every thread on the system. On a Windows 11 laptop running CrowdStrike that took a median of 61 ms per launch (spawn.resume span, 40-87 ms across runs), and more when the host was busy. Resume through the process handle that std's Child already holds, with NtResumeProcess. Like the old loop, it resumes every thread of the process once, but in one system call. Keeping the main thread handle instead would mean calling CreateProcessW ourselves, because Command does not expose it. NtResumeProcess is not documented by Microsoft, but ntdll has exported it since Windows XP and the Windows SDK's ntdll.lib provides it. The suspended, assign, resume order is unchanged, and so is the failure path: if the resume fails, for example because the executor is already exiting, launch() kills it and returns an error before any user code runs. A new test covers both the resume and the refusal for an exited process. The windows crate's ToolHelp feature is no longer used and is dropped. Co-authored-by: Cursor --- crates/axis-sandbox/Cargo.toml | 1 - crates/axis-sandbox/src/windows/job_object.rs | 90 +++++++++++-------- crates/axis-sandbox/src/windows/mxc.rs | 9 +- 3 files changed, 62 insertions(+), 38 deletions(-) diff --git a/crates/axis-sandbox/Cargo.toml b/crates/axis-sandbox/Cargo.toml index e820e404..e34c64ad 100644 --- a/crates/axis-sandbox/Cargo.toml +++ b/crates/axis-sandbox/Cargo.toml @@ -26,7 +26,6 @@ windows = { version = "0.62", features = [ "Win32_Globalization", "Win32_Security", "Win32_Security_Authorization", - "Win32_System_Diagnostics_ToolHelp", "Win32_System_IO", "Win32_System_JobObjects", "Win32_System_Threading", diff --git a/crates/axis-sandbox/src/windows/job_object.rs b/crates/axis-sandbox/src/windows/job_object.rs index 9b4264f5..5b9ee3b4 100644 --- a/crates/axis-sandbox/src/windows/job_object.rs +++ b/crates/axis-sandbox/src/windows/job_object.rs @@ -7,7 +7,8 @@ //! CPU rate caps, and KILL_ON_JOB_CLOSE (if AXIS crashes, all sandbox //! processes die automatically). No admin required. -use windows::Win32::Foundation::{CloseHandle, HANDLE}; +use std::os::windows::io::{AsRawHandle, BorrowedHandle}; +use windows::Win32::Foundation::{CloseHandle, HANDLE, NTSTATUS}; use windows::Win32::System::JobObjects::*; use windows::Win32::System::Threading::{ ALL_PROCESSOR_GROUPS, GetActiveProcessorCount, OpenProcess, @@ -87,42 +88,18 @@ pub fn create_limited_kill_on_close_job( Ok(job) } -/// Resume every thread of a process created with CREATE_SUSPENDED. -pub fn resume_process(pid: u32) -> Result<(), String> { - use windows::Win32::System::Diagnostics::ToolHelp::{ - CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, - }; - use windows::Win32::System::Threading::{OpenThread, ResumeThread, THREAD_SUSPEND_RESUME}; - - let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) } - .map_err(|e| format!("CreateToolhelp32Snapshot failed: {e}"))?; - let mut entry = THREADENTRY32 { - dwSize: std::mem::size_of::() as u32, - ..Default::default() - }; - let mut resumed = 0; - let mut more = unsafe { Thread32First(snapshot, &mut entry) }.is_ok(); - while more { - if entry.th32OwnerProcessID == pid - && let Ok(thread) = - unsafe { OpenThread(THREAD_SUSPEND_RESUME, false, entry.th32ThreadID) } - { - if unsafe { ResumeThread(thread) } != u32::MAX { - resumed += 1; - } - unsafe { - let _ = CloseHandle(thread); - } - } - more = unsafe { Thread32Next(snapshot, &mut entry) }.is_ok(); - } - unsafe { - let _ = CloseHandle(snapshot); - } - if resumed == 0 { - return Err(format!("no suspended thread resumed for pid {pid}")); +/// Resume every thread of a process created with CREATE_SUSPENDED, through a +/// process handle with PROCESS_SUSPEND_RESUME access. Fails once the process +/// is exiting. +pub fn resume_process(process: BorrowedHandle<'_>) -> Result<(), String> { + #[link(name = "ntdll")] + unsafe extern "system" { + fn NtResumeProcess(process: HANDLE) -> NTSTATUS; } - Ok(()) + + unsafe { NtResumeProcess(HANDLE(process.as_raw_handle())) } + .ok() + .map_err(|e| format!("NtResumeProcess failed: {e}")) } /// Assign a process to a Job Object by PID. @@ -138,3 +115,44 @@ pub fn assign_process_to_job(job: &JobHandle, pid: u32) -> Result<(), String> { result.map_err(|e| format!("AssignProcessToJobObject failed: {e}")) } + +#[cfg(test)] +mod tests { + use super::*; + use std::os::windows::io::AsHandle; + use std::os::windows::process::CommandExt; + use std::process::{Command, Stdio}; + use std::time::{Duration, Instant}; + + #[test] + fn resume_process_runs_a_suspended_child_and_refuses_an_exited_one() { + const CREATE_SUSPENDED: u32 = 0x0000_0004; + let mut child = Command::new("cmd.exe") + .args(["/d", "/c", "exit 7"]) + .creation_flags(CREATE_SUSPENDED) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .expect("spawn suspended cmd.exe"); + let job = create_limited_kill_on_close_job(0, 0, 0).expect("create job"); + assign_process_to_job(&job, child.id()).expect("assign child to job"); + std::thread::sleep(Duration::from_millis(100)); + assert!( + child.try_wait().unwrap().is_none(), + "child ran before resume" + ); + + resume_process(child.as_handle()).expect("resume suspended child"); + let deadline = Instant::now() + Duration::from_secs(30); + let status = loop { + if let Some(status) = child.try_wait().unwrap() { + break status; + } + assert!(Instant::now() < deadline, "resumed child did not exit"); + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!(status.code(), Some(7)); + assert!(resume_process(child.as_handle()).is_err()); + } +} diff --git a/crates/axis-sandbox/src/windows/mxc.rs b/crates/axis-sandbox/src/windows/mxc.rs index 23e824bf..85edb898 100644 --- a/crates/axis-sandbox/src/windows/mxc.rs +++ b/crates/axis-sandbox/src/windows/mxc.rs @@ -22,6 +22,7 @@ use std::ffi::{OsStr, OsString}; use std::fs::{self, File}; use std::io::{Read, Seek, SeekFrom, Write}; use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::{AsHandle, BorrowedHandle}; use std::path::{Component, Path, PathBuf}; use std::process::{Child, Command, ExitStatus, Stdio}; use std::time::{Duration, Instant}; @@ -243,6 +244,12 @@ impl MxcExecutorChild { } } + fn handle(&self) -> BorrowedHandle<'_> { + match self { + Self::Standard(child) => child.as_handle(), + } + } + fn try_wait(&mut self) -> std::io::Result> { match self { Self::Standard(child) => { @@ -491,7 +498,7 @@ impl MxcWindowsSandbox { "MXC Job Object assignment: {err}" ))); } - if let Err(err) = super::job_object::resume_process(pid) { + if let Err(err) = super::job_object::resume_process(child.handle()) { let _ = child.kill(); let _ = child.wait(); return Err(SandboxError::IsolationFailed(format!(