From dc5637addc91fb88a795574057291746a7bfad7d Mon Sep 17 00:00:00 2001 From: wan9chi Date: Wed, 2 Dec 2026 23:41:40 +0800 Subject: [PATCH] fix(fspy): report tracking loss on 32-bit Windows subprocesses Co-authored-by: Gemini 4 Neon --- CHANGELOG.md | 1 + Cargo.lock | 1 + crates/fspy/Cargo.toml | 3 + crates/fspy/README.md | 2 + crates/fspy/src/error.rs | 49 ++- crates/fspy/src/ipc.rs | 46 ++ crates/fspy/src/windows/mod.rs | 111 +++-- crates/fspy/tests/untracked_fallback.rs | 12 +- crates/fspy/tests/winapi.rs | 306 ++++++++++++++ crates/fspy_preload_windows/Cargo.toml | 8 +- .../src/windows/client.rs | 13 +- .../src/windows/detours/create_process.rs | 343 +++++++++------ crates/fspy_shared/Cargo.toml | 6 + crates/fspy_shared/src/ipc/mod.rs | 12 + crates/fspy_shared/src/lib.rs | 3 + crates/fspy_shared/src/windows/mod.rs | 394 +++++++++++++++++- crates/fspy_shared/src/windows_arch.rs | 233 +++++++++++ crates/vt/src/session/reporter/summary.rs | 33 ++ .../windows_32bit_subprocess/package.json | 4 + .../windows_32bit_subprocess/snapshots.toml | 43 ++ .../child_32bit_subprocess_runs_untracked.md | 51 +++ .../direct_32bit_command_runs_untracked.md | 49 +++ .../windows_32bit_subprocess/vite-task.json | 12 + 23 files changed, 1556 insertions(+), 179 deletions(-) create mode 100644 crates/fspy_shared/src/windows_arch.rs create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/package.json create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots.toml create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/child_32bit_subprocess_runs_untracked.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/direct_32bit_command_runs_untracked.md create mode 100644 crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/vite-task.json diff --git a/CHANGELOG.md b/CHANGELOG.md index d9d39790c..2ff9b6931 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,6 @@ # Changelog +- **Fixed** On Windows, cached tasks that run or spawn 32-bit (or other cross-architecture) programs, such as 32-bit `gpg.exe` during Git commit signing, no longer trigger a `RunDLL` error dialog or fail to start. The program runs untracked instead, and the run is reported as not cached with the untracked executable and architecture ([#1058](https://github.com/voidzero-dev/vite-task/pull/1058)). - **Changed** When automatic file-access tracking cannot record everything a task did, the "Not cached" summary line now includes the specific reason (for example, that the tracking channel ran out of capacity or that installing the seccomp filter failed for a given executable) ([#1054](https://github.com/voidzero-dev/vite-task/pull/1054), [#1056](https://github.com/voidzero-dev/vite-task/pull/1056)). - **Changed** Invalid remote cache endpoint URLs in `cache.remote.url` or `VP_REMOTE_CACHE_URL` (such as missing schemes, non-`http`/`https` schemes, or missing hosts) now fail upfront during configuration and planning instead of warning per task during execution, and `vp run --help` now documents `VP_REMOTE_CACHE`, `VP_REMOTE_CACHE_URL`, and `VP_REMOTE_CACHE_HEADER_` ([#1048](https://github.com/voidzero-dev/vite-task/pull/1048)). - **Changed** Removed `NEXT_*`, `VERCEL`, `VERCEL_*`, `USE_OUTPUT_FOR_EDGE_FUNCTIONS`, `NOW_BUILDER`, `VC_MICROFRONTENDS_CONFIG_FILE_NAME`, `GITHUB_*`, `ACTIONS_ID_TOKEN_REQUEST_URL`, `DOCKER_*`, `BUILDKIT_*`, `COMPOSE_*`, and `*_TOKEN` from the default untracked environment variables passed to cached tasks. Tasks that need any of these variables should declare them explicitly in `cache.env` or `cache.untrackedEnv` ([#1044](https://github.com/voidzero-dev/vite-task/pull/1044)). diff --git a/Cargo.lock b/Cargo.lock index bc6f73720..0f5371fe3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1598,6 +1598,7 @@ dependencies = [ "vt_subprocess_test", "winapi", "wincode", + "windows-sys 0.61.2", ] [[package]] diff --git a/crates/fspy/Cargo.toml b/crates/fspy/Cargo.toml index 72a73641a..ff53dfafe 100644 --- a/crates/fspy/Cargo.toml +++ b/crates/fspy/Cargo.toml @@ -53,6 +53,9 @@ winapi = { workspace = true, features = ["winbase", "securitybaseapi", "handleap wincode = { workspace = true } winsafe = { workspace = true, features = ["kernel"] } +[target.'cfg(target_os = "windows")'.dev-dependencies] +winapi = { workspace = true, features = ["synchapi"] } + [target.'cfg(target_os = "macos")'.dev-dependencies] tempfile = { workspace = true } diff --git a/crates/fspy/README.md b/crates/fspy/README.md index e80355d9b..dfc5368d8 100644 --- a/crates/fspy/README.md +++ b/crates/fspy/README.md @@ -19,6 +19,8 @@ On musl targets, only `seccomp_unotify`-based tracking is used (no preload libra It uses [Detours](https://github.com/microsoft/Detours) to intercept file system calls. The implementation is in `src/windows`. +Only same-architecture processes can be injected with the preload DLL. When a tracked run launches a cross-architecture process (such as a 32-bit x86 binary on 64-bit Windows, or an emulated x64 binary from a native ARM64 process), `fspy` lets it run untracked and reports `TrackingIncomplete::UnsupportedProcessArchitecture` so the task result is not cached. + ## Unified interface The unified interface of `Command` is in `src/command.rs`. diff --git a/crates/fspy/src/error.rs b/crates/fspy/src/error.rs index 92ef24a74..644971a5c 100644 --- a/crates/fspy/src/error.rs +++ b/crates/fspy/src/error.rs @@ -1,4 +1,4 @@ -use std::{ffi::OsString, path::PathBuf}; +use std::{ffi::OsString, fmt, path::PathBuf}; #[derive(thiserror::Error, Debug)] pub enum SpawnError { @@ -31,6 +31,17 @@ pub enum SpawnError { OsSpawn(std::io::Error), } +/// Human-readable name for a Windows PE `IMAGE_FILE_MACHINE_*` constant. +const fn process_architecture_name(machine: u16) -> Option<&'static str> { + match machine { + 0x014c => Some("32-bit x86"), + 0x01c4 => Some("32-bit ARM"), + 0x8664 => Some("x64"), + 0xaa64 => Some("ARM64"), + _ => None, + } +} + /// A tracked process could not record a file access it went on to perform, /// so the accesses collected for the run are a subset of what it really /// touched. @@ -54,6 +65,36 @@ pub enum TrackingIncomplete { std::io::Error::from_raw_os_error(*.errno) )] SeccompInstallFailed { program: PathBuf, errno: i32 }, + + /// A spawned Windows process had a different processor architecture than + /// the tracker (for example, a 32-bit x86 child launched from a 64-bit + /// process), so it ran untracked. + #[error("{}", UnsupportedArchDisplay(.program.as_deref(), *.machine))] + UnsupportedProcessArchitecture { program: Option, machine: u16 }, +} + +struct UnsupportedArchDisplay<'a>(Option<&'a std::path::Path>, u16); + +impl fmt::Display for UnsupportedArchDisplay<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match (process_architecture_name(self.1), self.0) { + (Some(arch), Some(path)) => { + write!(f, "cannot track {arch} process `{}`", path.display()) + } + (Some(arch), None) => write!(f, "cannot track {arch} process"), + (None, Some(path)) => { + write!( + f, + "cannot track process `{}` (unsupported architecture 0x{:04x})", + path.display(), + self.1 + ) + } + (None, None) => { + write!(f, "cannot track process (unsupported architecture 0x{:04x})", self.1) + } + } + } } impl From> for TrackingIncomplete { @@ -65,6 +106,12 @@ impl From> for TrackingIncomplete { errno, } } + fspy_shared::ipc::TrackingLoss::UnsupportedProcessArchitecture { program, machine } => { + Self::UnsupportedProcessArchitecture { + program: program.map(|p| PathBuf::from(p.to_cow_os_str().into_owned())), + machine, + } + } } } } diff --git a/crates/fspy/src/ipc.rs b/crates/fspy/src/ipc.rs index 6c6748ef7..e7d653ed0 100644 --- a/crates/fspy/src/ipc.rs +++ b/crates/fspy/src/ipc.rs @@ -106,4 +106,50 @@ mod tests { ); assert!(incomplete.to_string().contains("could not install seccomp filter")); } + + #[test] + fn channel_accesses_decodes_unsupported_process_architecture() { + let receiver = access_channel(1 << 30, Global).unwrap(); + let sender = receiver.sender().unwrap(); + + #[cfg(unix)] + let raw = b"/windows/syswow64/cmd.exe"; + #[cfg(unix)] + let program = IpcStr::from_bytes(raw); + #[cfg(windows)] + let raw: Vec = r"C:\Windows\SysWOW64\cmd.exe".encode_utf16().collect(); + #[cfg(windows)] + let program = IpcStr::from_wide(&raw); + + sender.report_loss(&TrackingLoss::UnsupportedProcessArchitecture { + program: Some(program), + machine: 0x014c, + }); + drop(sender); + + let Err(incomplete) = ChannelAccesses::try_from(receiver) else { + panic!("expected TrackingIncomplete"); + }; + let expected_path = PathBuf::from(program.to_cow_os_str().into_owned()); + assert_eq!( + incomplete, + TrackingIncomplete::UnsupportedProcessArchitecture { + program: Some(expected_path), + machine: 0x014c, + } + ); + assert!(incomplete.to_string().contains("cannot track 32-bit x86 process")); + + let receiver_no_path = access_channel(1 << 30, Global).unwrap(); + let sender_no_path = receiver_no_path.sender().unwrap(); + sender_no_path.report_loss(&TrackingLoss::UnsupportedProcessArchitecture { + program: None, + machine: 0x014c, + }); + drop(sender_no_path); + let Err(incomplete_no_path) = ChannelAccesses::try_from(receiver_no_path) else { + panic!("expected TrackingIncomplete"); + }; + assert_eq!(incomplete_no_path.to_string(), "cannot track 32-bit x86 process"); + } } diff --git a/crates/fspy/src/windows/mod.rs b/crates/fspy/src/windows/mod.rs index b50ef920c..9c980ed72 100644 --- a/crates/fspy/src/windows/mod.rs +++ b/crates/fspy/src/windows/mod.rs @@ -1,17 +1,19 @@ use std::{ - ffi::{CStr, c_char}, + ffi::{CStr, OsString, c_char}, io, os::windows::{ - ffi::OsStrExt, + ffi::{OsStrExt, OsStringExt}, io::{AsRawHandle, BorrowedHandle}, }, + path::PathBuf, sync::Arc, }; +use allocator_api2::alloc::Global; use fspy_detours_sys::{DetourCopyPayloadToProcess, DetourUpdateProcessWithDll}; use fspy_shared::{ - ipc::{PathAccess, access_channel}, - windows::{PAYLOAD_ID, Payload}, + ipc::{AccessReceiver, PathAccess, access_channel}, + windows::{PAYLOAD_ID, Payload, query_process_image_name, unsupported_process_machine}, }; use futures_util::FutureExt; use ntapi::{ntpsapi::NtResumeProcess, ntrtl::RtlNtStatusToDosError}; @@ -24,9 +26,17 @@ use winapi::{ use winsafe::co::{CP, WC}; use crate::{ - ChildTermination, TrackedChild, command::Command, error::SpawnError, ipc::ChannelAccesses, + ChildTermination, TrackedChild, + command::Command, + error::{SpawnError, TrackingIncomplete}, + ipc::ChannelAccesses, }; +enum TrackingState { + Channel(AccessReceiver), + Lost(TrackingIncomplete), +} + const INTERPOSE_CDYLIB: Artifact = artifact!("fspy_preload", "CARGO_CDYLIB_FILE_FSPY_PRELOAD_WINDOWS"); @@ -89,16 +99,6 @@ impl SpyImpl { let ansi_dll_path_with_nul = &self.ansi_dll_path_with_nul; command.env("FSPY", "1"); - let receiver = access_channel(crate::ipc::shm_capacity(), allocator_api2::alloc::Global) - .map_err(SpawnError::ChannelCreation)?; - - let payload = Payload { - channel_conf: receiver.conf(), - ansi_dll_path_with_nul: ansi_dll_path_with_nul.to_bytes(), - }; - let payload_bytes = wincode::serialize(&payload).unwrap(); - let payload_len = payload_bytes.len().try_into().unwrap(); - let mut command = command.into_tokio_command(); command.creation_flags(CREATE_SUSPENDED); let mut child = command.spawn().map_err(SpawnError::OsSpawn)?; @@ -110,27 +110,57 @@ impl SpyImpl { let process = unsafe { BorrowedHandle::borrow_raw(child.raw_handle().unwrap()) }; let process_handle = process.try_clone_to_owned().map_err(SpawnError::OsSpawn)?; let raw_process = process_handle.as_raw_handle().cast::(); - let mut dll_paths = ansi_dll_path_with_nul.as_ptr().cast::(); - // SAFETY: raw_process is a valid handle to the suspended child process, - // dll_paths points to a valid null-terminated ANSI string. - let success = unsafe { DetourUpdateProcessWithDll(raw_process, &raw mut dll_paths, 1) }; - if success != TRUE { - return Err(SpawnError::Injection(io::Error::last_os_error())); - } - // SAFETY: raw_process is valid, PAYLOAD_ID is a static GUID, - // payload_bytes is a valid buffer with the correct length. - let success = unsafe { - DetourCopyPayloadToProcess( - raw_process, - &PAYLOAD_ID, - payload_bytes.as_ptr().cast(), - payload_len, - ) - }; - if success != TRUE { - return Err(SpawnError::Injection(io::Error::last_os_error())); - } + // Skip DLL injection when the spawned process uses a different + // architecture (e.g. a 32-bit x86 binary on 64-bit Windows): + // resume it untracked and mark tracking incomplete instead of + // failing the spawn. + // SAFETY: `raw_process` is a valid handle to the suspended child process. + let tracking = + if let Some(machine) = unsafe { unsupported_process_machine(raw_process) } { + // SAFETY: `raw_process` is a valid handle to the suspended child process. + let program = unsafe { query_process_image_name(raw_process, Global) } + .map(|wide| PathBuf::from(OsString::from_wide(&wide))); + TrackingState::Lost(TrackingIncomplete::UnsupportedProcessArchitecture { + program, + machine, + }) + } else { + let receiver = access_channel(crate::ipc::shm_capacity(), Global) + .map_err(SpawnError::ChannelCreation)?; + + let payload = Payload { + channel_conf: receiver.conf(), + ansi_dll_path_with_nul: ansi_dll_path_with_nul.to_bytes(), + }; + let payload_bytes = wincode::serialize(&payload).unwrap(); + let payload_len = payload_bytes.len().try_into().unwrap(); + + let mut dll_paths = ansi_dll_path_with_nul.as_ptr().cast::(); + // SAFETY: raw_process is a valid handle to the suspended child process, + // dll_paths points to a valid null-terminated ANSI string. + let success = + unsafe { DetourUpdateProcessWithDll(raw_process, &raw mut dll_paths, 1) }; + if success != TRUE { + return Err(SpawnError::Injection(io::Error::last_os_error())); + } + + // SAFETY: raw_process is valid, PAYLOAD_ID is a static GUID, + // payload_bytes is a valid buffer with the correct length. + let success = unsafe { + DetourCopyPayloadToProcess( + raw_process, + &PAYLOAD_ID, + payload_bytes.as_ptr().cast(), + payload_len, + ) + }; + if success != TRUE { + return Err(SpawnError::Injection(io::Error::last_os_error())); + } + + TrackingState::Channel(receiver) + }; // Resume using the process handle, without the nightly main-thread handle API. // SAFETY: raw_process is a valid child process handle with PROCESS_SUSPEND_RESUME access. @@ -144,10 +174,10 @@ impl SpyImpl { ))); } - Ok(process_handle) + Ok((process_handle, tracking)) })(); - let process_handle = preparation.inspect_err(|_| { + let (process_handle, tracking) = preparation.inspect_err(|_| { // Do not leave a suspended process behind if tracking initialization fails. let _ = child.start_kill(); })?; @@ -169,8 +199,11 @@ impl SpyImpl { }; // Close the ipc channel after the child has exited. // We are not interested in path accesses from descendants after the main child has exited. - let path_accesses = ChannelAccesses::try_from(receiver) - .map(|ipc_accesses| PathAccessIterable { ipc_accesses }); + let path_accesses = match tracking { + TrackingState::Channel(receiver) => ChannelAccesses::try_from(receiver) + .map(|ipc_accesses| PathAccessIterable { ipc_accesses }), + TrackingState::Lost(loss) => Err(loss), + }; io::Result::Ok(ChildTermination { status, path_accesses }) }) diff --git a/crates/fspy/tests/untracked_fallback.rs b/crates/fspy/tests/untracked_fallback.rs index 87cef41d5..2803f07b5 100644 --- a/crates/fspy/tests/untracked_fallback.rs +++ b/crates/fspy/tests/untracked_fallback.rs @@ -76,7 +76,9 @@ fn static_binary_runs_untracked_when_injection_fails() { let Err(AccessCloseError::Reported(report)) = receiver.close() else { panic!("the channel did not report the untracked exec"); }; - let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode(); + let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode() else { + panic!("unexpected tracking loss variant"); + }; assert_eq!(program, IpcStr::from_bytes(test_bin_path().as_os_str().as_bytes())); assert_ne!(errno, 0); } @@ -107,7 +109,9 @@ fn execvp_fallback_keeps_path_search() { let Err(AccessCloseError::Reported(report)) = receiver.close() else { panic!("the channel did not report the untracked exec"); }; - let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode(); + let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode() else { + panic!("unexpected tracking loss variant"); + }; assert_eq!(program, IpcStr::from_bytes(test_bin_path().as_os_str().as_bytes())); assert_ne!(errno, 0); } @@ -166,7 +170,9 @@ fn posix_spawn_runs_untracked_when_injection_fails() { let Err(AccessCloseError::Reported(report)) = receiver.close() else { panic!("the channel did not report the untracked posix_spawn"); }; - let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode(); + let TrackingLoss::SeccompInstallFailed { program, errno } = report.decode() else { + panic!("unexpected tracking loss variant"); + }; assert_eq!(program, IpcStr::from_bytes(test_bin.as_os_str().as_bytes())); assert_ne!(errno, 0); } diff --git a/crates/fspy/tests/winapi.rs b/crates/fspy/tests/winapi.rs index cd5bd87c8..57933363d 100644 --- a/crates/fspy/tests/winapi.rs +++ b/crates/fspy/tests/winapi.rs @@ -202,3 +202,309 @@ async fn rename_destination_bare_name_in_source_folder() -> anyhow::Result<()> { Ok(()) } + +/// Returns the path to the 32-bit `cmd.exe` under `SysWOW64`. +fn syswow64_cmd_exe() -> std::path::PathBuf { + let system_root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into()); + std::path::PathBuf::from(system_root).join("SysWOW64").join("cmd.exe") +} + +/// Asserts that `program` ends with `\SysWOW64\cmd.exe` (case-insensitively). +fn assert_is_syswow64_cmd(program: &Path) { + let text = program.to_string_lossy(); + let suffix = r"\syswow64\cmd.exe"; + let matches = text + .len() + .checked_sub(suffix.len()) + .and_then(|start| text.get(start..)) + .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix)); + assert!(matches, "unexpected program path: {}", program.display()); +} + +#[test(tokio::test)] +async fn spawn_32bit_child_via_create_process_w_reports_loss() -> anyhow::Result<()> { + let cmd32 = syswow64_cmd_exe(); + assert!(cmd32.is_file(), "expected 32-bit cmd.exe at {}", cmd32.display()); + let cmd32_str = cmd32.to_str().unwrap().to_owned(); + + let cmd = test_utils::command_for_fn!(cmd32_str, |cmd32_str: String| { + let output = std::process::Command::new(&cmd32_str) + .args(["/c", "echo from-32bit-w"]) + .output() + .expect("failed to spawn 32-bit cmd.exe via CreateProcessW"); + assert!( + output.status.success(), + "32-bit cmd.exe failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("from-32bit-w"), "unexpected stdout: {stdout:?}"); + }); + + let termination = fspy::Command::from(cmd) + .spawn(tokio_util::sync::CancellationToken::new()) + .await? + .wait_handle + .await?; + assert!(termination.status.success()); + + let Err(fspy::TrackingIncomplete::UnsupportedProcessArchitecture { program, machine }) = + termination.path_accesses + else { + panic!("expected UnsupportedProcessArchitecture tracking loss"); + }; + assert_eq!(machine, 0x014c); + let program = program.expect("expected 32-bit child executable path"); + assert_is_syswow64_cmd(&program); + + Ok(()) +} + +#[test(tokio::test)] +async fn spawn_32bit_child_via_create_process_a_reports_loss() -> anyhow::Result<()> { + let cmd32 = syswow64_cmd_exe(); + assert!(cmd32.is_file(), "expected 32-bit cmd.exe at {}", cmd32.display()); + let cmd32_str = cmd32.to_str().unwrap().to_owned(); + + let cmd = test_utils::command_for_fn!(cmd32_str, |cmd32_str: String| { + use std::ffi::CString; + + use winapi::um::{ + handleapi::CloseHandle, + processthreadsapi::{ + CreateProcessA, GetExitCodeProcess, PROCESS_INFORMATION, STARTUPINFOA, + }, + synchapi::WaitForSingleObject, + winbase::{INFINITE, WAIT_OBJECT_0}, + }; + + let app = CString::new(cmd32_str).unwrap(); + let mut cmdline = CString::new("cmd.exe /c exit 0").unwrap().into_bytes_with_nul(); + // SAFETY: zeroing STARTUPINFOA and PROCESS_INFORMATION is valid for Win32. + let mut si: STARTUPINFOA = unsafe { std::mem::zeroed() }; + si.cb = std::mem::size_of::().try_into().unwrap(); + // SAFETY: zeroing PROCESS_INFORMATION is valid for Win32. + let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; + + // SAFETY: all pointers are valid NUL-terminated strings or writable structs. + let ok = unsafe { + CreateProcessA( + app.as_ptr(), + cmdline.as_mut_ptr().cast(), + null_mut(), + null_mut(), + 0, + 0, + null_mut(), + null_mut(), + &raw mut si, + &raw mut pi, + ) + }; + assert_ne!(ok, 0, "CreateProcessA failed: {}", std::io::Error::last_os_error()); + + // SAFETY: `pi.hProcess` and `pi.hThread` are valid handles from `CreateProcessA`. + unsafe { + assert_eq!(WaitForSingleObject(pi.hProcess, INFINITE), WAIT_OBJECT_0); + let mut exit_code = u32::MAX; + assert_ne!(GetExitCodeProcess(pi.hProcess, &raw mut exit_code), 0); + assert_eq!(exit_code, 0); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); + } + }); + + let termination = fspy::Command::from(cmd) + .spawn(tokio_util::sync::CancellationToken::new()) + .await? + .wait_handle + .await?; + assert!(termination.status.success()); + + let Err(fspy::TrackingIncomplete::UnsupportedProcessArchitecture { program, machine }) = + termination.path_accesses + else { + panic!("expected UnsupportedProcessArchitecture tracking loss"); + }; + assert_eq!(machine, 0x014c); + let program = program.expect("expected 32-bit child executable path"); + assert_is_syswow64_cmd(&program); + + Ok(()) +} + +#[test(tokio::test)] +async fn spawn_32bit_root_process_directly_reports_loss() -> anyhow::Result<()> { + let cmd32 = syswow64_cmd_exe(); + assert!(cmd32.is_file(), "expected 32-bit cmd.exe at {}", cmd32.display()); + + let mut cmd = fspy::Command::new(cmd32); + cmd.args(["/c", "exit 0"]); + let termination = + cmd.spawn(tokio_util::sync::CancellationToken::new()).await?.wait_handle.await?; + assert!(termination.status.success()); + + let Err(fspy::TrackingIncomplete::UnsupportedProcessArchitecture { program, machine }) = + termination.path_accesses + else { + panic!("expected UnsupportedProcessArchitecture tracking loss"); + }; + assert_eq!(machine, 0x014c); + let program = program.expect("expected 32-bit root executable path"); + assert_is_syswow64_cmd(&program); + + Ok(()) +} + +#[test(tokio::test)] +async fn create_process_w_suspended_same_arch_stays_suspended_and_tracks() -> anyhow::Result<()> { + let tmp_dir = tempfile::tempdir()?; + let tmp_path = tmp_dir.path().canonicalize()?; + let target_file = tmp_path.join("read_by_suspended_child.txt"); + std::fs::write(&target_file, b"hello")?; + + let target_str = target_file.to_str().unwrap().to_owned(); + let grandchild = test_utils::command_for_fn!(target_str, |path: String| { + let contents = std::fs::read(&path).expect("child failed to read target file"); + assert_eq!(contents, b"hello"); + }); + let app_str = grandchild.program.to_str().unwrap().to_owned(); + let cmdline_str = format!( + "\"{app_str}\" {} {}", + grandchild.args[0].to_str().unwrap(), + grandchild.args[1].to_str().unwrap() + ); + + let child_args = (app_str, cmdline_str); + + let accesses = track_fn!(child_args, |(app_str, cmdline_str): (String, String)| { + use winapi::um::{ + handleapi::CloseHandle, + processthreadsapi::{ + CreateProcessW, GetExitCodeProcess, PROCESS_INFORMATION, ResumeThread, STARTUPINFOW, + }, + synchapi::WaitForSingleObject, + winbase::{CREATE_SUSPENDED, INFINITE, WAIT_OBJECT_0}, + }; + + let app = OsStr::new(&app_str).encode_wide().chain(Some(0)).collect::>(); + let mut cmdline = + OsStr::new(&cmdline_str).encode_wide().chain(Some(0)).collect::>(); + // SAFETY: zeroing STARTUPINFOW and PROCESS_INFORMATION is valid for Win32. + let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() }; + si.cb = std::mem::size_of::().try_into().unwrap(); + // SAFETY: zeroing PROCESS_INFORMATION is valid for Win32. + let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; + + // SAFETY: all pointers are valid NUL-terminated UTF-16 strings or writable structs. + let ok = unsafe { + CreateProcessW( + app.as_ptr(), + cmdline.as_mut_ptr(), + null_mut(), + null_mut(), + 0, + CREATE_SUSPENDED, + null_mut(), + null_mut(), + &raw mut si, + &raw mut pi, + ) + }; + assert_ne!(ok, 0, "CreateProcessW failed: {}", std::io::Error::last_os_error()); + + // SAFETY: `pi.hProcess` and `pi.hThread` are valid handles from `CreateProcessW`. + unsafe { + // Previous suspend count must be 1: the detour must not resume a + // child when the caller passed `CREATE_SUSPENDED`. + assert_eq!(ResumeThread(pi.hThread), 1, "expected child to remain suspended"); + assert_eq!(WaitForSingleObject(pi.hProcess, INFINITE), WAIT_OBJECT_0); + let mut exit_code = u32::MAX; + assert_ne!(GetExitCodeProcess(pi.hProcess, &raw mut exit_code), 0); + assert_eq!(exit_code, 0); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); + } + }) + .await?; + + assert_contains(&accesses, &target_file, PathAccess::Read); + + Ok(()) +} + +#[test(tokio::test)] +async fn create_process_w_suspended_32bit_child_stays_suspended_and_reports_loss() +-> anyhow::Result<()> { + let cmd32 = syswow64_cmd_exe(); + assert!(cmd32.is_file(), "expected 32-bit cmd.exe at {}", cmd32.display()); + let cmd32_str = cmd32.to_str().unwrap().to_owned(); + + let cmd = test_utils::command_for_fn!(cmd32_str, |cmd32_str: String| { + use winapi::um::{ + handleapi::CloseHandle, + processthreadsapi::{ + CreateProcessW, GetExitCodeProcess, PROCESS_INFORMATION, ResumeThread, STARTUPINFOW, + }, + synchapi::WaitForSingleObject, + winbase::{CREATE_SUSPENDED, INFINITE, WAIT_OBJECT_0}, + }; + + let app = OsStr::new(&cmd32_str).encode_wide().chain(Some(0)).collect::>(); + let mut cmdline = + OsStr::new("cmd.exe /c exit 0").encode_wide().chain(Some(0)).collect::>(); + // SAFETY: zeroing STARTUPINFOW and PROCESS_INFORMATION is valid for Win32. + let mut si: STARTUPINFOW = unsafe { std::mem::zeroed() }; + si.cb = std::mem::size_of::().try_into().unwrap(); + // SAFETY: zeroing PROCESS_INFORMATION is valid for Win32. + let mut pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; + + // SAFETY: all pointers are valid NUL-terminated UTF-16 strings or writable structs. + let ok = unsafe { + CreateProcessW( + app.as_ptr(), + cmdline.as_mut_ptr(), + null_mut(), + null_mut(), + 0, + CREATE_SUSPENDED, + null_mut(), + null_mut(), + &raw mut si, + &raw mut pi, + ) + }; + assert_ne!(ok, 0, "CreateProcessW failed: {}", std::io::Error::last_os_error()); + + // SAFETY: `pi.hProcess` and `pi.hThread` are valid handles from `CreateProcessW`. + unsafe { + // Previous suspend count must be 1: the cross-architecture fallback + // must also preserve the caller's `CREATE_SUSPENDED` flag. + assert_eq!(ResumeThread(pi.hThread), 1, "expected 32-bit child to remain suspended"); + assert_eq!(WaitForSingleObject(pi.hProcess, INFINITE), WAIT_OBJECT_0); + let mut exit_code = u32::MAX; + assert_ne!(GetExitCodeProcess(pi.hProcess, &raw mut exit_code), 0); + assert_eq!(exit_code, 0); + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); + } + }); + + let termination = fspy::Command::from(cmd) + .spawn(tokio_util::sync::CancellationToken::new()) + .await? + .wait_handle + .await?; + assert!(termination.status.success()); + + let Err(fspy::TrackingIncomplete::UnsupportedProcessArchitecture { program, machine }) = + termination.path_accesses + else { + panic!("expected UnsupportedProcessArchitecture tracking loss"); + }; + assert_eq!(machine, 0x014c); + let program = program.expect("expected 32-bit child executable path"); + assert_is_syswow64_cmd(&program); + + Ok(()) +} diff --git a/crates/fspy_preload_windows/Cargo.toml b/crates/fspy_preload_windows/Cargo.toml index 88f512fa3..c8278594e 100644 --- a/crates/fspy_preload_windows/Cargo.toml +++ b/crates/fspy_preload_windows/Cargo.toml @@ -20,11 +20,13 @@ ntapi = { workspace = true } smallvec = { workspace = true, features = ["std"] } widestring = { workspace = true } winapi = { workspace = true, features = [ - "winerror", - "winbase", - "namedpipeapi", + "errhandlingapi", "memoryapi", + "namedpipeapi", + "processthreadsapi", "std", + "winbase", + "winerror", ] } windows-sys = { workspace = true, features = [ "Win32_Foundation", diff --git a/crates/fspy_preload_windows/src/windows/client.rs b/crates/fspy_preload_windows/src/windows/client.rs index 6c6eaba64..923a94400 100644 --- a/crates/fspy_preload_windows/src/windows/client.rs +++ b/crates/fspy_preload_windows/src/windows/client.rs @@ -3,7 +3,7 @@ use std::{cell::SyncUnsafeCell, ffi::CStr, mem::MaybeUninit}; use allocator_api2::alloc::Allocator; use fspy_detours_sys::DetourCopyPayloadToProcess; use fspy_shared::{ - ipc::{AccessSender, PathAccess}, + ipc::{AccessSender, PathAccess, TrackingLoss}, windows::{PAYLOAD_ID, Payload}, }; use winapi::{shared::minwindef::BOOL, um::winnt::HANDLE}; @@ -36,6 +36,17 @@ impl<'a> Client<'a> { sender.send(&access); } + /// Marks the run's trace incomplete with a structured loss reason, so the + /// receiver treats it as untracked and the runner does not cache it. Call + /// it before performing an operation that tracking cannot record (such as + /// resuming an untracked cross-architecture child process). It does nothing + /// when this client has no channel sender. + pub fn report_loss(&self, loss: TrackingLoss<'_>) { + if let Some(sender) = &self.ipc_sender { + sender.report_loss(&loss); + } + } + pub unsafe fn prepare_child_process(&self, child_handle: HANDLE) -> BOOL { // The payload propagates to children unchanged, so forward the bytes // this process was given instead of re-serializing. diff --git a/crates/fspy_preload_windows/src/windows/detours/create_process.rs b/crates/fspy_preload_windows/src/windows/detours/create_process.rs index 6dd09e77a..3a1bafc5f 100644 --- a/crates/fspy_preload_windows/src/windows/detours/create_process.rs +++ b/crates/fspy_preload_windows/src/windows/detours/create_process.rs @@ -1,17 +1,28 @@ -use fspy_detours_sys::{DetourCreateProcessWithDllExA, DetourCreateProcessWithDllExW}; +use std::{ + ffi::c_char, + mem::ManuallyDrop, + os::windows::io::{AsRawHandle as _, FromRawHandle as _, IntoRawHandle as _, OwnedHandle}, +}; + +use fspy_detours_sys::DetourUpdateProcessWithDll; +use fspy_shared::{ + ipc::{IpcStr, TrackingLoss}, + windows::{query_process_image_name, unsupported_process_machine}, +}; use winapi::{ shared::{ - minwindef::{BOOL, DWORD, LPVOID}, + minwindef::{BOOL, DWORD, FALSE, LPVOID, TRUE}, ntdef::{LPCSTR, LPSTR}, }, um::{ + errhandlingapi::{GetLastError, SetLastError}, minwinbase::LPSECURITY_ATTRIBUTES, processthreadsapi::{ CreateProcessA, CreateProcessW, LPPROCESS_INFORMATION, LPSTARTUPINFOA, LPSTARTUPINFOW, - ResumeThread, + PROCESS_INFORMATION, ResumeThread, TerminateProcess, }, winbase::CREATE_SUSPENDED, - winnt::{LPCWSTR, LPWSTR}, + winnt::{HANDLE, LPCWSTR, LPWSTR}, }, }; @@ -43,6 +54,171 @@ impl Drop for HookGuard { } } +/// Owns a freshly created suspended child's handles until [`Self::commit`] +/// hands them to the caller. +/// +/// Dropping without committing terminates the suspended child, closes both +/// handles via [`OwnedHandle`], and preserves the calling thread's last Win32 +/// error across cleanup. +struct PendingChild { + process: ManuallyDrop, + thread: ManuallyDrop, + process_id: DWORD, + thread_id: DWORD, +} + +impl PendingChild { + /// Wraps the handles from a successful `CreateProcess*` call. + /// + /// # Safety + /// + /// `pi.hProcess` and `pi.hThread` must be valid, uniquely owned handles. + unsafe fn from_raw(pi: PROCESS_INFORMATION) -> Self { + Self { + // SAFETY: caller guarantees `pi.hProcess` is a valid, uniquely owned Win32 handle. + process: ManuallyDrop::new(unsafe { OwnedHandle::from_raw_handle(pi.hProcess.cast()) }), + // SAFETY: caller guarantees `pi.hThread` is a valid, uniquely owned Win32 handle. + thread: ManuallyDrop::new(unsafe { OwnedHandle::from_raw_handle(pi.hThread.cast()) }), + process_id: pi.dwProcessId, + thread_id: pi.dwThreadId, + } + } + + fn process_handle(&self) -> HANDLE { + self.process.as_raw_handle().cast() + } + + fn thread_handle(&self) -> HANDLE { + self.thread.as_raw_handle().cast() + } + + /// Commits the child process: transfers handle ownership to + /// `lp_process_information` when non-null, or closes both handles via + /// [`OwnedHandle`] when null. + /// + /// # Safety + /// + /// `lp_process_information` must be null or a valid writable pointer to a + /// `PROCESS_INFORMATION` struct. + unsafe fn commit(self, lp_process_information: LPPROCESS_INFORMATION) { + let mut this = ManuallyDrop::new(self); + // SAFETY: `this` skips `PendingChild::drop`, so taking each + // `OwnedHandle` once here transfers ownership cleanly without + // double-drop. + let (process, thread) = unsafe { + (ManuallyDrop::take(&mut this.process), ManuallyDrop::take(&mut this.thread)) + }; + if !lp_process_information.is_null() { + let pi = PROCESS_INFORMATION { + hProcess: process.into_raw_handle().cast(), + hThread: thread.into_raw_handle().cast(), + dwProcessId: this.process_id, + dwThreadId: this.thread_id, + }; + // SAFETY: caller guarantees `lp_process_information` is writable. + unsafe { *lp_process_information = pi }; + } + // When `lp_process_information` is null, `process` and `thread` drop + // here without terminating the child. + } +} + +impl Drop for PendingChild { + fn drop(&mut self) { + // SAFETY: preserving the failing Win32 error across cleanup calls. + let err = unsafe { GetLastError() }; + // SAFETY: `self.process` is a valid handle to the suspended child we + // failed to prepare or resume. + unsafe { TerminateProcess(self.process.as_raw_handle().cast(), u32::MAX) }; + // SAFETY: `Drop` runs only for uncommitted children (committed ones + // skip `Drop` via `ManuallyDrop::new`), so each handle is dropped once + // here before restoring the thread's last Win32 error. + unsafe { + ManuallyDrop::drop(&mut self.process); + ManuallyDrop::drop(&mut self.thread); + } + // SAFETY: restoring the Win32 error after both `OwnedHandle`s closed. + unsafe { SetLastError(err) }; + } +} + +/// Shared implementation for the `CreateProcessW` and `CreateProcessA` detours. +/// +/// Spawns the child suspended, then either: +/// - injects our DLL and payload when the child's architecture matches ours, or +/// - reports [`TrackingLoss::UnsupportedProcessArchitecture`] and lets the +/// child run untracked when the child uses another architecture (for example, +/// a 32-bit x86 subprocess spawned by a 64-bit process). +/// +/// Unlike `DetourCreateProcessWithDllEx*`, this never launches Detours' +/// `rundll32.exe` cross-bitness helper, which otherwise pops up a `RunDLL` error +/// dialog or kills the child because no 32-bit preload DLL is shipped. +/// +/// # Safety +/// +/// `lp_process_information` must be either null or a valid writable pointer to +/// a `PROCESS_INFORMATION` struct. `create_suspended` must invoke the real +/// `CreateProcessW` or `CreateProcessA` with the passed creation flags and +/// `LPPROCESS_INFORMATION`. +unsafe fn create_process_with_tracking( + dw_creation_flags: DWORD, + lp_process_information: LPPROCESS_INFORMATION, + create_suspended: impl FnOnce(DWORD, LPPROCESS_INFORMATION) -> BOOL, +) -> BOOL { + // SAFETY: `PROCESS_INFORMATION` is a plain C struct of handles and DWORDs. + let mut raw_pi: PROCESS_INFORMATION = unsafe { std::mem::zeroed() }; + if create_suspended(dw_creation_flags | CREATE_SUSPENDED, &raw mut raw_pi) == FALSE { + return FALSE; + } + + // SAFETY: `create_suspended` succeeded and initialized `raw_pi` with + // uniquely owned handles. + let child = unsafe { PendingChild::from_raw(raw_pi) }; + // SAFETY: accessing the global client initialized during DLL_PROCESS_ATTACH. + let client = unsafe { global_client() }; + + let process_handle = child.process_handle(); + // SAFETY: `process_handle` is a valid handle to the freshly created suspended child. + let prepared = unsafe { unsupported_process_machine(process_handle) }.map_or_else( + || { + let mut dll_path = client.ansi_dll_path().as_ptr().cast::(); + // SAFETY: `process_handle` is a valid handle to the suspended child + // and `dll_path` points to a valid NUL-terminated ANSI string. + let updated = + unsafe { DetourUpdateProcessWithDll(process_handle, &raw mut dll_path, 1) }; + // SAFETY: `process_handle` is a valid handle to the suspended child. + updated != FALSE && unsafe { client.prepare_child_process(process_handle) } != FALSE + }, + |machine| { + // Publish-before-act: report the loss before resuming the untracked + // child so the receiver cannot miss it if the root task exits soon + // after the child finishes. + // SAFETY: `process_handle` is a valid handle to the suspended child. + let image_name = unsafe { + query_process_image_name(process_handle, fspy_nostd_alloc::pooled_bump()) + }; + let program = image_name.as_deref().map(IpcStr::from_wide); + client.report_loss(TrackingLoss::UnsupportedProcessArchitecture { program, machine }); + true + }, + ); + + if !prepared { + return FALSE; + } + + if dw_creation_flags & CREATE_SUSPENDED == 0 { + // SAFETY: `child.thread_handle()` is the primary thread of the suspended child. + if unsafe { ResumeThread(child.thread_handle()) } == u32::MAX { + return FALSE; + } + } + + // SAFETY: caller guarantees `lp_process_information` is null or writable. + unsafe { child.commit(lp_process_information) }; + TRUE +} + static DETOUR_CREATE_PROCESS_W: Detour< unsafe extern "system" fn( LPCWSTR, @@ -72,55 +248,6 @@ static DETOUR_CREATE_PROCESS_W: Detour< lp_startup_info: LPSTARTUPINFOW, lp_process_information: LPPROCESS_INFORMATION, ) -> BOOL { - unsafe extern "system" fn create_process_with_payload_w( - lp_application_name: LPCWSTR, - lp_command_line: LPWSTR, - lp_process_attributes: LPSECURITY_ATTRIBUTES, - lp_thread_attributes: LPSECURITY_ATTRIBUTES, - b_inherit_handles: BOOL, - dw_creation_flags: DWORD, - lp_environment: LPVOID, - lp_current_directory: LPCWSTR, - lp_startup_info: LPSTARTUPINFOW, - lp_process_information: LPPROCESS_INFORMATION, - ) -> BOOL { - // SAFETY: calling original CreateProcessW with CREATE_SUSPENDED to inject DLL before resume - let ret = unsafe { - (DETOUR_CREATE_PROCESS_W.real())( - lp_application_name, - lp_command_line, - lp_process_attributes, - lp_thread_attributes, - b_inherit_handles, - dw_creation_flags | CREATE_SUSPENDED, - lp_environment, - lp_current_directory, - lp_startup_info, - lp_process_information, - ) - }; - if ret == 0 { - return 0; - } - - // SAFETY: copying payload to child process and dereferencing lp_process_information - let ret = unsafe { - global_client().prepare_child_process((*lp_process_information).hProcess) - }; - - if ret == 0 { - return 0; - } - if dw_creation_flags & CREATE_SUSPENDED == 0 { - // SAFETY: resuming the suspended child thread after DLL injection - let ret = unsafe { ResumeThread((*lp_process_information).hThread) }; - if ret == (-1i32).cast_unsigned() { - return 0; - } - } - ret - } - let Some(_hook_guard) = HookGuard::new() else { // Detect re-entrance and avoid double hooking // SAFETY: calling original CreateProcessW with all original arguments @@ -140,24 +267,25 @@ static DETOUR_CREATE_PROCESS_W: Detour< }; }; - // SAFETY: accessing the global client initialized during DLL_PROCESS_ATTACH - let client = unsafe { global_client() }; - - // SAFETY: calling DetourCreateProcessWithDllExW to create process with our DLL injected + // SAFETY: forwarding caller's arguments to `create_process_with_tracking` unsafe { - DetourCreateProcessWithDllExW( - lp_application_name, - lp_command_line, - lp_process_attributes, - lp_thread_attributes, - b_inherit_handles, + create_process_with_tracking( dw_creation_flags, - lp_environment, - lp_current_directory, - lp_startup_info, lp_process_information, - client.ansi_dll_path().as_ptr().cast(), - Some(create_process_with_payload_w), + |flags, pi| { + (DETOUR_CREATE_PROCESS_W.real())( + lp_application_name, + lp_command_line, + lp_process_attributes, + lp_thread_attributes, + b_inherit_handles, + flags, + lp_environment, + lp_current_directory, + lp_startup_info, + pi, + ) + }, ) } } @@ -194,55 +322,6 @@ static DETOUR_CREATE_PROCESS_A: Detour< lp_startup_info: LPSTARTUPINFOA, lp_process_information: LPPROCESS_INFORMATION, ) -> BOOL { - unsafe extern "system" fn create_process_with_payload_a( - lp_application_name: LPCSTR, - lp_command_line: LPSTR, - lp_process_attributes: LPSECURITY_ATTRIBUTES, - lp_thread_attributes: LPSECURITY_ATTRIBUTES, - b_inherit_handles: BOOL, - dw_creation_flags: DWORD, - lp_environment: LPVOID, - lp_current_directory: LPCSTR, - lp_startup_info: LPSTARTUPINFOA, - lp_process_information: LPPROCESS_INFORMATION, - ) -> BOOL { - // SAFETY: calling original CreateProcessA with CREATE_SUSPENDED to inject DLL before resume - let ret = unsafe { - (DETOUR_CREATE_PROCESS_A.real())( - lp_application_name, - lp_command_line, - lp_process_attributes, - lp_thread_attributes, - b_inherit_handles, - dw_creation_flags | CREATE_SUSPENDED, - lp_environment, - lp_current_directory, - lp_startup_info, - lp_process_information, - ) - }; - if ret == 0 { - return 0; - } - - // SAFETY: copying payload to child process and dereferencing lp_process_information - let ret = unsafe { - global_client().prepare_child_process((*lp_process_information).hProcess) - }; - - if ret == 0 { - return 0; - } - if dw_creation_flags & CREATE_SUSPENDED == 0 { - // SAFETY: resuming the suspended child thread after DLL injection - let ret = unsafe { ResumeThread((*lp_process_information).hThread) }; - if ret == (-1i32).cast_unsigned() { - return 0; - } - } - ret - } - let Some(_hook_guard) = HookGuard::new() else { // Detect re-entrance and avoid double hooking // SAFETY: calling original CreateProcessA with all original arguments @@ -261,24 +340,26 @@ static DETOUR_CREATE_PROCESS_A: Detour< ) }; }; - // SAFETY: accessing the global client initialized during DLL_PROCESS_ATTACH - let client = unsafe { global_client() }; - // SAFETY: calling DetourCreateProcessWithDllExA to create process with our DLL injected + // SAFETY: forwarding caller's arguments to `create_process_with_tracking` unsafe { - DetourCreateProcessWithDllExA( - lp_application_name, - lp_command_line, - lp_process_attributes, - lp_thread_attributes, - b_inherit_handles, + create_process_with_tracking( dw_creation_flags, - lp_environment, - lp_current_directory, - lp_startup_info, lp_process_information, - client.ansi_dll_path().as_ptr().cast(), - Some(create_process_with_payload_a), + |flags, pi| { + (DETOUR_CREATE_PROCESS_A.real())( + lp_application_name, + lp_command_line, + lp_process_attributes, + lp_thread_attributes, + b_inherit_handles, + flags, + lp_environment, + lp_current_directory, + lp_startup_info, + pi, + ) + }, ) } } diff --git a/crates/fspy_shared/Cargo.toml b/crates/fspy_shared/Cargo.toml index fcfff9ecd..43056f657 100644 --- a/crates/fspy_shared/Cargo.toml +++ b/crates/fspy_shared/Cargo.toml @@ -24,6 +24,12 @@ vt_path = { workspace = true } bytemuck = { workspace = true } omnipath = { workspace = true } winapi = { workspace = true, features = ["std"] } +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_System_LibraryLoader", + "Win32_System_SystemInformation", + "Win32_System_Threading", +] } [dev-dependencies] assert2 = { workspace = true } diff --git a/crates/fspy_shared/src/ipc/mod.rs b/crates/fspy_shared/src/ipc/mod.rs index a329ff3fa..c8054fe3d 100644 --- a/crates/fspy_shared/src/ipc/mod.rs +++ b/crates/fspy_shared/src/ipc/mod.rs @@ -27,6 +27,18 @@ pub enum TrackingLoss<'a> { /// Raw OS `errno` returned by filter installation (e.g. `EPERM`). errno: i32, }, + /// A spawned Windows child process has a different processor architecture + /// than the tracker (for example, a 32-bit x86 child launched from a + /// 64-bit process), so the preload DLL could not be injected and the + /// process proceeded untracked. + UnsupportedProcessArchitecture { + /// Full executable image path of the untracked process, if it could be + /// queried from the process handle. + program: Option<&'a IpcStr>, + /// PE machine type (`IMAGE_FILE_MACHINE_*`) of the child process + /// (for example `0x014c` for 32-bit x86). + machine: u16, + }, } /// Channel protocol for fspy file-access tracing. diff --git a/crates/fspy_shared/src/lib.rs b/crates/fspy_shared/src/lib.rs index 0cb88e9cf..133c24596 100644 --- a/crates/fspy_shared/src/lib.rs +++ b/crates/fspy_shared/src/lib.rs @@ -4,3 +4,6 @@ pub mod ipc; #[cfg(windows)] pub mod windows; + +#[cfg(any(windows, test))] +mod windows_arch; diff --git a/crates/fspy_shared/src/windows/mod.rs b/crates/fspy_shared/src/windows/mod.rs index c1fc49e7c..e2e996c08 100644 --- a/crates/fspy_shared/src/windows/mod.rs +++ b/crates/fspy_shared/src/windows/mod.rs @@ -1,7 +1,27 @@ +use core::{ + ffi::c_void, + sync::atomic::{AtomicPtr, AtomicU8, AtomicU32, Ordering}, +}; + +use allocator_api2::alloc::Allocator; use winapi::DEFINE_GUID; use wincode::{SchemaRead, SchemaWrite}; +use windows_sys::Win32::{ + Foundation::{ERROR_INSUFFICIENT_BUFFER, GetLastError}, + System::{ + LibraryLoader::GetProcAddress, + SystemInformation::IMAGE_FILE_MACHINE_UNKNOWN, + Threading::{ + GetCurrentProcess, GetProcessInformation, IsWow64Process, PROCESS_MACHINE_INFORMATION, + PROCESS_NAME_WIN32, ProcessMachineTypeInfo, QueryFullProcessImageNameW, + }, + }, +}; -use crate::ipc::AccessChannelConf; +use crate::{ + ipc::AccessChannelConf, + windows_arch::{detect_unsupported_machine, wow64_fallback_from_is_wow64}, +}; // Generated by guidgen.exe // {FC4845F1-3A8B-4F05-A3D3-A5E9E102AF33} @@ -25,3 +45,375 @@ pub struct Payload<'a> { pub channel_conf: AccessChannelConf<'a>, pub ansi_dll_path_with_nul: &'a [u8], } + +/// The PE machine architecture (`IMAGE_FILE_MACHINE_*`) of this binary. +#[cfg(target_arch = "x86_64")] +const CURRENT_PROCESS_MACHINE: u16 = + windows_sys::Win32::System::SystemInformation::IMAGE_FILE_MACHINE_AMD64; +#[cfg(target_arch = "aarch64")] +const CURRENT_PROCESS_MACHINE: u16 = + windows_sys::Win32::System::SystemInformation::IMAGE_FILE_MACHINE_ARM64; +#[cfg(target_arch = "x86")] +const CURRENT_PROCESS_MACHINE: u16 = + windows_sys::Win32::System::SystemInformation::IMAGE_FILE_MACHINE_I386; + +type IsWow64Process2Fn = unsafe extern "system" fn( + hprocess: *mut c_void, + pprocessmachine: *mut u16, + pnativemachine: *mut u16, +) -> i32; + +/// Sentinel stored in [`IS_WOW64_PROCESS2`] when `kernelbase.dll` does not +/// export `IsWow64Process2` (Windows releases before 10 1709 / Server 2016). +static IS_WOW64_PROCESS2_UNAVAILABLE: u8 = 0; + +/// Cached `kernelbase!IsWow64Process2` function pointer. +/// +/// Resolved dynamically rather than statically imported so binaries that link +/// `fspy_shared` (including `vp`) still load on Windows 10 releases before 1709 +/// and Windows Server 2016. Uses lock-free atomics so it is safe to call from +/// inside the preload DLL's `CreateProcess` detours without locks or heap +/// allocation. +static IS_WOW64_PROCESS2: AtomicPtr = AtomicPtr::new(core::ptr::null_mut()); + +/// Cached result of `IsWow64Process2(GetCurrentProcess())`. +/// +/// Encoding: `0` = uninitialized, `0x1_0000 | u32::from(machine)` = resolved +/// `IMAGE_FILE_MACHINE_*`. +static SELF_WOW64_MACHINE: AtomicU32 = AtomicU32::new(0); +const SELF_WOW64_VALUE_TAG: u32 = 0x1_0000; + +/// Cached result of `IsWow64Process(GetCurrentProcess())`. +/// +/// Encoding: `0` = uninitialized, `1` = false, `2` = true. +static SELF_IS_WOW64: AtomicU8 = AtomicU8::new(0); + +const fn unavailable_sentinel() -> *mut c_void { + (&raw const IS_WOW64_PROCESS2_UNAVAILABLE).cast_mut().cast() +} + +/// Resolves `IsWow64Process2` directly from `kernelbase.dll` (where it is +/// implemented rather than forwarded through `kernel32.dll`), caching the +/// lookup lock-free. +/// +/// Because `kernelbase.dll` is always loaded in every Win32 process and exports +/// `IsWow64Process2` directly, neither `GetModuleHandleW` nor `GetProcAddress` +/// loads a module or triggers filesystem/loader activity inside the preload DLL. +fn is_wow64_process2_fn() -> Option { + let cached = IS_WOW64_PROCESS2.load(Ordering::Acquire); + let resolved = if cached.is_null() { + let symbol = fspy_nostd::get_module_handle(fspy_nostd::wide_cstr!("kernelbase.dll")) + .ok() + .and_then(|kernelbase| { + // SAFETY: `kernelbase` is a loaded module handle and the symbol + // name is a NUL-terminated ANSI string. + unsafe { GetProcAddress(kernelbase.as_ptr(), c"IsWow64Process2".as_ptr().cast()) } + }); + let ptr = symbol.map_or_else(unavailable_sentinel, |f| f as *mut c_void); + IS_WOW64_PROCESS2.store(ptr, Ordering::Release); + ptr + } else { + cached + }; + + if core::ptr::eq(resolved, unavailable_sentinel()) { + None + } else { + // SAFETY: `resolved` was returned by `GetProcAddress` for + // `kernelbase!IsWow64Process2`, which has the `IsWow64Process2Fn` + // signature. + Some(unsafe { core::mem::transmute::<*mut c_void, IsWow64Process2Fn>(resolved) }) + } +} + +fn self_wow64_machine(is_wow64_process2: IsWow64Process2Fn) -> Option { + let cached = SELF_WOW64_MACHINE.load(Ordering::Relaxed); + if cached != 0 { + return u16::try_from(cached & 0xFFFF).ok(); + } + let mut self_wow = IMAGE_FILE_MACHINE_UNKNOWN; + let mut self_native = IMAGE_FILE_MACHINE_UNKNOWN; + // SAFETY: `GetCurrentProcess()` returns a valid pseudo-handle for the + // current process and both output pointers are valid writable `u16`s. + let ok = + unsafe { is_wow64_process2(GetCurrentProcess(), &raw mut self_wow, &raw mut self_native) }; + if ok == 0 { + return None; + } + SELF_WOW64_MACHINE.store(SELF_WOW64_VALUE_TAG | u32::from(self_wow), Ordering::Relaxed); + Some(self_wow) +} + +fn self_is_wow64() -> Option { + match SELF_IS_WOW64.load(Ordering::Relaxed) { + 1 => return Some(false), + 2 => return Some(true), + _ => {} + } + let mut is_wow64: i32 = 0; + // SAFETY: `GetCurrentProcess()` returns a valid pseudo-handle and + // `is_wow64` is a valid writable `BOOL`. + if unsafe { IsWow64Process(GetCurrentProcess(), &raw mut is_wow64) } == 0 { + return None; + } + let wow = is_wow64 != 0; + SELF_IS_WOW64.store(if wow { 2 } else { 1 }, Ordering::Relaxed); + Some(wow) +} + +/// Outcome of probing a process via `kernelbase!IsWow64Process2`. +#[derive(Debug, PartialEq, Eq)] +enum Wow64Probe { + /// `kernelbase!IsWow64Process2` is not exported on this OS version. + Unavailable, + /// `IsWow64Process2` ran and returned the unsupported machine (or `None` + /// when matching or indeterminate). + Resolved(Option), +} + +/// `IsWow64Process2` fallback for [`unsupported_process_machine`] (Windows 10 +/// 1709+ / Server 2019+ when `ProcessMachineTypeInfo` is unavailable). +/// +/// # Safety +/// +/// `process_handle` must be a valid Windows process handle with at least +/// `PROCESS_QUERY_LIMITED_INFORMATION` access. +unsafe fn unsupported_process_machine_via_wow64_2(process_handle: *mut c_void) -> Wow64Probe { + let Some(is_wow64_process2) = is_wow64_process2_fn() else { + return Wow64Probe::Unavailable; + }; + let mut child_wow = IMAGE_FILE_MACHINE_UNKNOWN; + let mut native_machine = IMAGE_FILE_MACHINE_UNKNOWN; + // SAFETY: `process_handle` is a valid process handle and both output + // pointers are valid writable `u16`s. + let child_ok = + unsafe { is_wow64_process2(process_handle, &raw mut child_wow, &raw mut native_machine) }; + if child_ok == 0 { + return Wow64Probe::Resolved(None); + } + let Some(self_wow) = self_wow64_machine(is_wow64_process2) else { + return Wow64Probe::Resolved(None); + }; + Wow64Probe::Resolved(detect_unsupported_machine( + CURRENT_PROCESS_MACHINE, + None, + Some((child_wow, native_machine, self_wow)), + )) +} + +/// `IsWow64Process` fallback for [`unsupported_process_machine`] (Windows +/// versions before 10 1709 / Server 2016 that predate `IsWow64Process2`). +/// +/// # Safety +/// +/// `process_handle` must be a valid Windows process handle with at least +/// `PROCESS_QUERY_LIMITED_INFORMATION` access. +unsafe fn unsupported_process_machine_via_is_wow64(process_handle: *mut c_void) -> Option { + let mut child_is_wow64: i32 = 0; + // SAFETY: `process_handle` is a valid process handle and `child_is_wow64` + // is a valid writable `BOOL`. + if unsafe { IsWow64Process(process_handle, &raw mut child_is_wow64) } == 0 { + return None; + } + let self_wow = self_is_wow64()?; + detect_unsupported_machine( + CURRENT_PROCESS_MACHINE, + None, + Some(wow64_fallback_from_is_wow64(CURRENT_PROCESS_MACHINE, child_is_wow64 != 0, self_wow)), + ) +} + +/// Returns the target process's PE machine type if it differs from ours. +/// +/// For example, returns `Some(IMAGE_FILE_MACHINE_I386)` for a 32-bit x86 child +/// spawned by a 64-bit process, or `Some(IMAGE_FILE_MACHINE_AMD64)` for an +/// emulated x64 child spawned by a native ARM64 process on Windows 11 ARM64. +/// Returns `None` when the architectures match or cannot be determined. +/// +/// # Safety +/// +/// `process_handle` must be a valid Windows process handle with at least +/// `PROCESS_QUERY_LIMITED_INFORMATION` access. +#[must_use] +pub unsafe fn unsupported_process_machine(process_handle: *mut c_void) -> Option { + let mut info = PROCESS_MACHINE_INFORMATION::default(); + let info_size = u32::try_from(size_of::()).ok()?; + // SAFETY: `process_handle` is a valid process handle and `info` is a + // writable `PROCESS_MACHINE_INFORMATION` buffer of `info_size` bytes. + let ok = unsafe { + GetProcessInformation( + process_handle, + ProcessMachineTypeInfo, + (&raw mut info).cast(), + info_size, + ) + }; + if ok != 0 && info.ProcessMachine != IMAGE_FILE_MACHINE_UNKNOWN { + return detect_unsupported_machine( + CURRENT_PROCESS_MACHINE, + Some(info.ProcessMachine), + None, + ); + } + + // SAFETY: caller guarantees `process_handle` is valid with + // `PROCESS_QUERY_LIMITED_INFORMATION` access. + let probe = unsafe { unsupported_process_machine_via_wow64_2(process_handle) }; + if let Wow64Probe::Resolved(result) = probe { + return result; + } + + // SAFETY: caller guarantees `process_handle` is valid with + // `PROCESS_QUERY_LIMITED_INFORMATION` access. + unsafe { unsupported_process_machine_via_is_wow64(process_handle) } +} + +/// Queries the full Win32 executable image path of `process_handle` as UTF-16 +/// code units (without a trailing NUL), allocating with `allocator`. +/// +/// Uses fallible allocation so callers inside the Windows preload DLL can pass +/// [`fspy_nostd_alloc::pooled_bump`] without touching the process heap or +/// panicking on OOM. +/// +/// # Safety +/// +/// `process_handle` must be a valid Windows process handle with at least +/// `PROCESS_QUERY_LIMITED_INFORMATION` access. +#[must_use] +pub unsafe fn query_process_image_name( + process_handle: *mut c_void, + allocator: A, +) -> Option> { + // Windows paths are capped at 32,767 UTF-16 code units plus NUL. + const INITIAL_WIDE_LEN: usize = 260; + const MAX_WIDE_LEN: usize = 32_768; + + let mut len: usize = INITIAL_WIDE_LEN; + let mut buf = allocator_api2::vec::Vec::new_in(allocator); + buf.try_reserve_exact(len).ok()?; + loop { + let cap = buf.capacity(); + let mut size = u32::try_from(cap).ok()?; + // SAFETY: `process_handle` is valid and `buf` has capacity for `size` + // UTF-16 code units. + let ok = unsafe { + QueryFullProcessImageNameW( + process_handle, + PROCESS_NAME_WIN32, + buf.as_mut_ptr(), + &raw mut size, + ) + }; + if ok != 0 { + let written = usize::try_from(size).ok()?; + if written == 0 || written > cap { + return None; + } + // SAFETY: `QueryFullProcessImageNameW` initialized `written` UTF-16 + // code units at the start of `buf`. + unsafe { buf.set_len(written) }; + return Some(buf); + } + // SAFETY: `GetLastError` reads the calling thread's last-error code. + if unsafe { GetLastError() } != ERROR_INSUFFICIENT_BUFFER || len >= MAX_WIDE_LEN { + return None; + } + len = (len * 2).min(MAX_WIDE_LEN); + buf.try_reserve_exact(len).ok()?; + } +} + +#[cfg(test)] +mod tests { + use std::{ + ffi::OsString, + os::windows::{ffi::OsStringExt as _, io::AsRawHandle as _, process::CommandExt as _}, + process::{Child, Command}, + }; + + use allocator_api2::alloc::Global; + use windows_sys::Win32::System::{ + SystemInformation::IMAGE_FILE_MACHINE_I386, + Threading::{CREATE_SUSPENDED, GetCurrentProcess}, + }; + + use super::{ + Wow64Probe, query_process_image_name, unsupported_process_machine, + unsupported_process_machine_via_is_wow64, unsupported_process_machine_via_wow64_2, + }; + + struct KillOnDrop(Child); + + impl Drop for KillOnDrop { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + fn syswow64_cmd_exe() -> OsString { + let mut path = + std::env::var_os("SystemRoot").unwrap_or_else(|| OsString::from(r"C:\Windows")); + path.push(r"\SysWOW64\cmd.exe"); + path + } + + fn assert_ends_with_syswow64_cmd(wide: &[u16]) { + let path = OsString::from_wide(wide); + let text = path.to_string_lossy(); + let suffix = r"\syswow64\cmd.exe"; + let matches = text + .len() + .checked_sub(suffix.len()) + .and_then(|start| text.get(start..)) + .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix)); + assert!(matches, "unexpected image name: {text}"); + } + + #[test] + fn machine_detection_fast_path_and_wow64_fallbacks() { + // SAFETY: `GetCurrentProcess()` returns a valid pseudo-handle for the + // current process. + let current = unsafe { GetCurrentProcess() }; + // SAFETY: `current` is the current process pseudo-handle. + unsafe { + assert_eq!(unsupported_process_machine(current), None); + assert_eq!( + unsupported_process_machine_via_wow64_2(current), + Wow64Probe::Resolved(None) + ); + assert_eq!(unsupported_process_machine_via_is_wow64(current), None); + } + + let cmd32 = syswow64_cmd_exe(); + let child = KillOnDrop( + Command::new(&cmd32) + .args(["/c", "exit 0"]) + .creation_flags(CREATE_SUSPENDED) + .spawn() + .expect("failed to spawn suspended SysWOW64 cmd.exe"), + ); + let raw = child.0.as_raw_handle().cast(); + + // SAFETY: `raw` is a valid handle to the suspended 32-bit child. + unsafe { + assert_eq!(unsupported_process_machine(raw), Some(IMAGE_FILE_MACHINE_I386)); + assert_eq!( + unsupported_process_machine_via_wow64_2(raw), + Wow64Probe::Resolved(Some(IMAGE_FILE_MACHINE_I386)) + ); + assert_eq!( + unsupported_process_machine_via_is_wow64(raw), + Some(IMAGE_FILE_MACHINE_I386) + ); + + let image_global = + query_process_image_name(raw, Global).expect("expected image name (Global)"); + assert_ends_with_syswow64_cmd(&image_global); + + let image_pooled = query_process_image_name(raw, fspy_nostd_alloc::pooled_bump()) + .expect("expected image name (pooled_bump)"); + assert_eq!(image_pooled.as_slice(), image_global.as_slice()); + } + } +} diff --git a/crates/fspy_shared/src/windows_arch.rs b/crates/fspy_shared/src/windows_arch.rs new file mode 100644 index 000000000..51689e44a --- /dev/null +++ b/crates/fspy_shared/src/windows_arch.rs @@ -0,0 +1,233 @@ +//! Pure decision logic for detecting cross-architecture Windows processes. +//! +//! Separated from `windows` so the architecture matrix can be +//! unit-tested on non-Windows hosts as well as on Windows. + +const IMAGE_FILE_MACHINE_UNKNOWN: u16 = 0; +const IMAGE_FILE_MACHINE_I386: u16 = 0x014c; +const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664; + +/// Converts `IsWow64Process` booleans (used on Windows versions before 1709 +/// that predate `IsWow64Process2`, where only x86-on-x64 WOW64 exists) into +/// the `(child_wow, native_machine, self_wow)` tuple accepted by +/// [`detect_unsupported_machine`]. +#[must_use] +pub const fn wow64_fallback_from_is_wow64( + current_machine: u16, + child_is_wow64: bool, + self_is_wow64: bool, +) -> (u16, u16, u16) { + let child_wow = + if child_is_wow64 { IMAGE_FILE_MACHINE_I386 } else { IMAGE_FILE_MACHINE_UNKNOWN }; + let self_wow = if self_is_wow64 { IMAGE_FILE_MACHINE_I386 } else { IMAGE_FILE_MACHINE_UNKNOWN }; + let native_machine = if self_is_wow64 || current_machine == IMAGE_FILE_MACHINE_AMD64 { + IMAGE_FILE_MACHINE_AMD64 + } else { + current_machine + }; + (child_wow, native_machine, self_wow) +} + +/// Determines whether a target Windows process has an architecture that differs +/// from `current_machine`, returning the target's `IMAGE_FILE_MACHINE_*` value +/// when they do not match. +/// +/// - `process_machine_info`: result of +/// `GetProcessInformation(ProcessMachineTypeInfo)` (Windows 11+, build +/// 22000+), which reports the process's actual architecture—including +/// distinguishing emulated x64 processes from native ARM64 processes on +/// Windows on ARM. +/// - `wow64_fallback`: fallback `(child_wow, native_machine, self_wow)` from +/// `IsWow64Process2` when `ProcessMachineTypeInfo` is unavailable (e.g., +/// Windows 10). Comparing `child_wow` against `self_wow` avoids +/// misclassifying emulated x64 processes as ARM64 because `IsWow64Process2` +/// reports `IMAGE_FILE_MACHINE_UNKNOWN` for both native ARM64 and emulated +/// x64 processes. +#[must_use] +pub const fn detect_unsupported_machine( + current_machine: u16, + process_machine_info: Option, + wow64_fallback: Option<(u16, u16, u16)>, +) -> Option { + if let Some(target_machine) = process_machine_info + && target_machine != IMAGE_FILE_MACHINE_UNKNOWN + { + return if target_machine == current_machine { None } else { Some(target_machine) }; + } + + let Some((child_wow, native_machine, self_wow)) = wow64_fallback else { + return None; + }; + if child_wow == self_wow { + return None; + } + let effective = + if child_wow == IMAGE_FILE_MACHINE_UNKNOWN { native_machine } else { child_wow }; + if effective == IMAGE_FILE_MACHINE_UNKNOWN { None } else { Some(effective) } +} + +#[cfg(test)] +mod tests { + use super::{ + IMAGE_FILE_MACHINE_UNKNOWN, detect_unsupported_machine, wow64_fallback_from_is_wow64, + }; + + const I386: u16 = 0x014c; + const ARMNT: u16 = 0x01c4; + const AMD64: u16 = 0x8664; + const ARM64: u16 = 0xaa64; + + #[test] + fn is_wow64_process_fallback_pre_1709() { + // 64-bit x64 tracker on Server 2016 spawning x64 child -> matches. + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some(wow64_fallback_from_is_wow64(AMD64, false, false)), + ), + None + ); + // 64-bit x64 tracker on Server 2016 spawning 32-bit x86 child -> mismatch. + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some(wow64_fallback_from_is_wow64(AMD64, true, false)), + ), + Some(I386) + ); + // 32-bit x86 tracker under WOW64 spawning 32-bit x86 child -> matches. + assert_eq!( + detect_unsupported_machine( + I386, + None, + Some(wow64_fallback_from_is_wow64(I386, true, true)), + ), + None + ); + // 32-bit x86 tracker under WOW64 spawning 64-bit x64 child -> mismatch. + assert_eq!( + detect_unsupported_machine( + I386, + None, + Some(wow64_fallback_from_is_wow64(I386, false, true)), + ), + Some(AMD64) + ); + // 32-bit x86 tracker on 32-bit Windows spawning 32-bit x86 child -> matches. + assert_eq!( + detect_unsupported_machine( + I386, + None, + Some(wow64_fallback_from_is_wow64(I386, false, false)), + ), + None + ); + } + + #[test] + fn win11_x64_host() { + // x64 tracker spawning x64 child -> matches. + assert_eq!(detect_unsupported_machine(AMD64, Some(AMD64), None), None); + // x64 tracker spawning 32-bit x86 child -> mismatch. + assert_eq!(detect_unsupported_machine(AMD64, Some(I386), None), Some(I386)); + } + + #[test] + fn win11_arm64_host_native_arm64_tracker() { + // Native ARM64 tracker spawning ARM64 child -> matches. + assert_eq!(detect_unsupported_machine(ARM64, Some(ARM64), None), None); + // Native ARM64 tracker spawning emulated x64 child -> mismatch. + assert_eq!(detect_unsupported_machine(ARM64, Some(AMD64), None), Some(AMD64)); + // Native ARM64 tracker spawning 32-bit x86 child -> mismatch. + assert_eq!(detect_unsupported_machine(ARM64, Some(I386), None), Some(I386)); + // Native ARM64 tracker spawning 32-bit ARM child -> mismatch. + assert_eq!(detect_unsupported_machine(ARM64, Some(ARMNT), None), Some(ARMNT)); + } + + #[test] + fn win11_arm64_host_emulated_x64_tracker() { + // Emulated x64 tracker spawning emulated x64 child -> matches. + assert_eq!(detect_unsupported_machine(AMD64, Some(AMD64), None), None); + // Emulated x64 tracker spawning native ARM64 child -> mismatch. + assert_eq!(detect_unsupported_machine(AMD64, Some(ARM64), None), Some(ARM64)); + // Emulated x64 tracker spawning 32-bit x86 child -> mismatch. + assert_eq!(detect_unsupported_machine(AMD64, Some(I386), None), Some(I386)); + } + + #[test] + fn wow64_fallback_x64_host() { + // x64 tracker (self_wow = UNKNOWN) spawning x64 child (child_wow = UNKNOWN). + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some((IMAGE_FILE_MACHINE_UNKNOWN, AMD64, IMAGE_FILE_MACHINE_UNKNOWN)), + ), + None + ); + // x64 tracker spawning 32-bit x86 child. + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some((I386, AMD64, IMAGE_FILE_MACHINE_UNKNOWN)), + ), + Some(I386) + ); + // 32-bit x86 tracker spawning 32-bit x86 child -> matches. + assert_eq!(detect_unsupported_machine(I386, None, Some((I386, AMD64, I386))), None); + // 32-bit x86 tracker spawning 64-bit x64 child -> mismatch reported as AMD64. + assert_eq!( + detect_unsupported_machine(I386, None, Some((IMAGE_FILE_MACHINE_UNKNOWN, AMD64, I386))), + Some(AMD64) + ); + } + + #[test] + fn wow64_fallback_emulated_x64_on_arm64_does_not_false_positive() { + // If `ProcessMachineTypeInfo` is unavailable, `IsWow64Process2` returns + // UNKNOWN for both emulated x64 and native ARM64 processes on an ARM64 + // host. Comparing `child_wow` against `self_wow` avoids misclassifying + // every x64 child as ARM64. + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some((IMAGE_FILE_MACHINE_UNKNOWN, ARM64, IMAGE_FILE_MACHINE_UNKNOWN)), + ), + None + ); + // A 32-bit x86 child is still detected via WOW64. + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some((I386, ARM64, IMAGE_FILE_MACHINE_UNKNOWN)), + ), + Some(I386) + ); + } + + #[test] + fn unknown_process_machine_info_falls_back_to_wow64() { + assert_eq!( + detect_unsupported_machine( + AMD64, + Some(IMAGE_FILE_MACHINE_UNKNOWN), + Some((I386, AMD64, IMAGE_FILE_MACHINE_UNKNOWN)), + ), + Some(I386) + ); + assert_eq!(detect_unsupported_machine(AMD64, None, None), None); + assert_eq!( + detect_unsupported_machine( + AMD64, + None, + Some((IMAGE_FILE_MACHINE_UNKNOWN, IMAGE_FILE_MACHINE_UNKNOWN, I386)), + ), + None + ); + } +} diff --git a/crates/vt/src/session/reporter/summary.rs b/crates/vt/src/session/reporter/summary.rs index d3b23487c..b65e5c33f 100644 --- a/crates/vt/src/session/reporter/summary.rs +++ b/crates/vt/src/session/reporter/summary.rs @@ -1980,4 +1980,37 @@ mod tests { "{summary}" ); } + + #[cfg(fspy)] + #[test] + #[expect( + clippy::disallowed_types, + reason = "fspy::TrackingIncomplete::UnsupportedProcessArchitecture takes std::path::PathBuf" + )] + fn full_summary_formats_unsupported_architecture_tracking_incomplete_reason() { + let reason = CacheNotUpdatedReason::TrackingIncomplete( + fspy::TrackingIncomplete::UnsupportedProcessArchitecture { + program: Some(std::path::PathBuf::from(r"C:\Windows\SysWOW64\cmd.exe")), + machine: 0x014c, + }, + ); + let summary = full_summary(vec![TaskSummary { + package_name: Str::from("pkg"), + task_name: Str::from("build"), + command: Str::from("gpg"), + cwd: Str::default(), + result: TaskResult::Spawned { + cache_status: SpawnedCacheStatus::Miss(SavedCacheMissReason::NotFound), + outcome: SpawnOutcome::Success(SavedCacheOutcome::NotUpdated( + SavedCacheNotUpdatedReason::from_reason(&reason), + )), + }, + }]); + assert!( + summary.as_str().contains( + r"→ Not cached: automatic file tracking couldn't record everything this task did: cannot track 32-bit x86 process `C:\Windows\SysWOW64\cmd.exe`. Configure `input` and `output` manually to enable caching." + ), + "{summary}" + ); + } } diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/package.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/package.json new file mode 100644 index 000000000..75f7356b3 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/package.json @@ -0,0 +1,4 @@ +{ + "name": "windows-32bit-subprocess", + "private": true +} diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots.toml b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots.toml new file mode 100644 index 000000000..8404bc061 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots.toml @@ -0,0 +1,43 @@ +[[e2e]] +name = "child_32bit_subprocess_runs_untracked" +cfg = "windows" +comment = """ +On 64-bit Windows, a tracked 64-bit task (`cmd.exe`) spawning a 32-bit x86 subprocess (`SysWOW64\\cmd.exe`) cannot inject the 64-bit preload DLL into the child. Instead of invoking Detours' `rundll32.exe` cross-bitness helper (which pops up a RunDLL error dialog or kills the child), the preload reports `UnsupportedProcessArchitecture` over the tracking channel and lets the 32-bit child run untracked. + +The task runs to completion cleanly, reports why automatic tracking could not cache it, and does not replay a partial trace on the next run. +""" +steps = [ + { argv = [ + "vt", + "run", + "-v", + "child", + ], comment = "64-bit cmd.exe spawns 32-bit SysWOW64\\cmd.exe; succeeds untracked and is not cached", redact = { '(?i)[A-Z]:\\Windows\\SysWOW64\\cmd\.exe' = '\cmd.exe' } }, + { argv = [ + "vt", + "run", + "-v", + "child", + ], comment = "nothing was cached to replay", redact = { '(?i)[A-Z]:\\Windows\\SysWOW64\\cmd\.exe' = '\cmd.exe' } }, +] + +[[e2e]] +name = "direct_32bit_command_runs_untracked" +cfg = "windows" +comment = """ +On 64-bit Windows, a task whose root command is itself a 32-bit x86 executable (`SysWOW64\\cmd.exe`) also skips DLL injection, runs untracked, and reports `UnsupportedProcessArchitecture` rather than failing the spawn. +""" +steps = [ + { argv = [ + "vt", + "run", + "-v", + "direct", + ], comment = "32-bit SysWOW64\\cmd.exe spawned directly by vt; succeeds untracked and is not cached", redact = { '(?i)[A-Z]:\\Windows\\SysWOW64\\cmd\.exe' = '\cmd.exe' } }, + { argv = [ + "vt", + "run", + "-v", + "direct", + ], comment = "nothing was cached to replay", redact = { '(?i)[A-Z]:\\Windows\\SysWOW64\\cmd\.exe' = '\cmd.exe' } }, +] diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/child_32bit_subprocess_runs_untracked.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/child_32bit_subprocess_runs_untracked.md new file mode 100644 index 000000000..8e0cc013c --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/child_32bit_subprocess_runs_untracked.md @@ -0,0 +1,51 @@ +# child_32bit_subprocess_runs_untracked + +On 64-bit Windows, a tracked 64-bit task (`cmd.exe`) spawning a 32-bit x86 subprocess (`SysWOW64\cmd.exe`) cannot inject the 64-bit preload DLL into the child. Instead of invoking Detours' `rundll32.exe` cross-bitness helper (which pops up a RunDLL error dialog or kills the child), the preload reports `UnsupportedProcessArchitecture` over the tracking channel and lets the 32-bit child run untracked. + +The task runs to completion cleanly, reports why automatic tracking could not cache it, and does not replay a partial trace on the next run. + +## `vt run -v child` + +64-bit cmd.exe spawns 32-bit SysWOW64\cmd.exe; succeeds untracked and is not cached + +``` +$ cmd.exe /c '%SystemRoot%\SysWOW64\cmd.exe' /c echo from-32bit-child +from-32bit-child + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 0 cache hits • 1 cache miss +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] windows-32bit-subprocess#child: $ cmd.exe /c '%SystemRoot%\SysWOW64\cmd.exe' /c echo from-32bit-child ✓ + → Not cached: automatic file tracking couldn't record everything this task did: cannot track 32-bit x86 process `\cmd.exe`. Configure `input` and `output` manually to enable caching. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `vt run -v child` + +nothing was cached to replay + +``` +$ cmd.exe /c '%SystemRoot%\SysWOW64\cmd.exe' /c echo from-32bit-child +from-32bit-child + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 0 cache hits • 1 cache miss +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] windows-32bit-subprocess#child: $ cmd.exe /c '%SystemRoot%\SysWOW64\cmd.exe' /c echo from-32bit-child ✓ + → Not cached: automatic file tracking couldn't record everything this task did: cannot track 32-bit x86 process `\cmd.exe`. Configure `input` and `output` manually to enable caching. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/direct_32bit_command_runs_untracked.md b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/direct_32bit_command_runs_untracked.md new file mode 100644 index 000000000..ab8206613 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/snapshots/direct_32bit_command_runs_untracked.md @@ -0,0 +1,49 @@ +# direct_32bit_command_runs_untracked + +On 64-bit Windows, a task whose root command is itself a 32-bit x86 executable (`SysWOW64\cmd.exe`) also skips DLL injection, runs untracked, and reports `UnsupportedProcessArchitecture` rather than failing the spawn. + +## `vt run -v direct` + +32-bit SysWOW64\cmd.exe spawned directly by vt; succeeds untracked and is not cached + +``` +$ C:/Windows/SysWOW64/cmd.exe /c echo from-32bit-direct +from-32bit-direct + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 0 cache hits • 1 cache miss +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] windows-32bit-subprocess#direct: $ C:/Windows/SysWOW64/cmd.exe /c echo from-32bit-direct ✓ + → Not cached: automatic file tracking couldn't record everything this task did: cannot track 32-bit x86 process `\cmd.exe`. Configure `input` and `output` manually to enable caching. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` + +## `vt run -v direct` + +nothing was cached to replay + +``` +$ C:/Windows/SysWOW64/cmd.exe /c echo from-32bit-direct +from-32bit-direct + + +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + Vite+ Task Runner • Execution Summary +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +Statistics: 1 task • 0 cache hits • 1 cache miss +Performance: 0% cache hit rate + +Task Details: +──────────────────────────────────────────────── + [1] windows-32bit-subprocess#direct: $ C:/Windows/SysWOW64/cmd.exe /c echo from-32bit-direct ✓ + → Not cached: automatic file tracking couldn't record everything this task did: cannot track 32-bit x86 process `\cmd.exe`. Configure `input` and `output` manually to enable caching. +━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ +``` diff --git a/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/vite-task.json b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/vite-task.json new file mode 100644 index 000000000..6e221ade2 --- /dev/null +++ b/crates/vt_bin/tests/e2e_snapshots/fixtures/windows_32bit_subprocess/vite-task.json @@ -0,0 +1,12 @@ +{ + "tasks": { + "child": { + "command": "cmd.exe /c '%SystemRoot%\\SysWOW64\\cmd.exe' /c echo from-32bit-child", + "cache": true + }, + "direct": { + "command": "C:/Windows/SysWOW64/cmd.exe /c echo from-32bit-direct", + "cache": true + } + } +}