From 58d0d5a0884d8175b35ed55b2e413af35eb94576 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:12:35 -0500 Subject: [PATCH 01/82] Expand guest timing and thread handle services Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 5 + crates/import-gen/src/classify.rs | 39 +++--- crates/import-gen/src/metadata.rs | 45 +++++++ crates/import-gen/tests/pipeline.rs | 14 +- crates/loader/src/services.rs | 163 ++++++++++++++++++++-- crates/loader/tests/runtime_x15.rs | 202 +++++++++++++++++++++++++++- docs/interfaces.md | 29 +++- 7 files changed, 457 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fac0705..5beb90e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ remains unsupported. ### Added +- Added same-process duplication of synthetic thread handles with independent closure. +- Added a rights-checked `GetThreadId` query for handles to the synthetic guest thread. +- Added 32-bit and 64-bit millisecond uptime queries for synthetic Windows guests. +- Added high-resolution elapsed-time queries for synthetic Windows guests through `QueryPerformanceCounter` and `QueryPerformanceFrequency`. + - Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and verifies the value lands in guest memory. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 97dc99ac..67bb1286 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -33,6 +33,8 @@ pub enum Classification { /// Brief description for the stub comment. note: &'static str, }, + /// Service supplied by the loader standard registry. + StandardService, /// Compiler intrinsic or SEH helper; stub that traps gracefully. RuntimeHelper { note: &'static str }, /// Proprietary, platform-only, or requires significant manual engineering. @@ -47,6 +49,7 @@ impl Classification { Self::CrtNative { .. } => "crt-native", Self::CrtWrapper { .. } => "crt-wrapper", Self::Win32Stub { .. } => "win32-stub", + Self::StandardService => "standard-service", Self::RuntimeHelper { .. } => "runtime-helper", Self::Manual { .. } => "manual", Self::Unsupported { .. } => "unsupported", @@ -54,7 +57,10 @@ impl Classification { } pub fn is_generatable(&self) -> bool { - !matches!(self, Self::Manual { .. } | Self::Unsupported { .. }) + !matches!( + self, + Self::StandardService | Self::Manual { .. } | Self::Unsupported { .. } + ) } } @@ -675,6 +681,12 @@ impl SymbolDb { fn populate_win32_kernel(&mut self) { let p1 = "api-ms-win-core-processthreads-l1-1-0.dll"; let p2 = "api-ms-win-core-processthreads-l1-1-2.dll"; + for module in [p1, "kernel32.dll"] { + self.ins(module, "GetThreadId", Classification::StandardService); + } + for module in ["kernel32.dll", "api-ms-win-core-handle-l1-1-0.dll"] { + self.ins(module, "DuplicateHandle", Classification::StandardService); + } for m in &[p1, p2, "kernel32.dll"] { self.win32_stub( m, @@ -916,19 +928,11 @@ impl SymbolDb { // ---- Win32 performance ------------------------------------------------- fn populate_win32_profile(&mut self) { - let m = "api-ms-win-core-profile-l1-1-0.dll"; - self.win32_stub( - m, - "QueryPerformanceCounter", - false, - "QPC — returns host mach_absolute_time", - ); - self.win32_stub( - m, - "QueryPerformanceFrequency", - false, - "QPF — returns 10 MHz", - ); + for module in ["kernel32.dll", "api-ms-win-core-profile-l1-1-0.dll"] { + for symbol in ["QueryPerformanceCounter", "QueryPerformanceFrequency"] { + self.ins(module, symbol, Classification::StandardService); + } + } } // ---- Win32 system info ------------------------------------------------- @@ -941,8 +945,11 @@ impl SymbolDb { false, "returns current UTC as FILETIME", ); - self.win32_stub(m, "GetTickCount64", false, "returns uptime in ms as u64"); - self.win32_stub(m, "GetTickCount", false, "returns uptime in ms as u32"); + for module in [m, "kernel32.dll"] { + for symbol in ["GetTickCount", "GetTickCount64"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub( m, "GetSystemInfo", diff --git a/crates/import-gen/src/metadata.rs b/crates/import-gen/src/metadata.rs index 02d5d5f2..8d6be1c2 100644 --- a/crates/import-gen/src/metadata.rs +++ b/crates/import-gen/src/metadata.rs @@ -30,6 +30,8 @@ pub enum AbiType { U64, F32, F64, + /// Opaque Win64 object handle. + Handle, /// Raw guest pointer (virtual address). Pointer { is_const: bool, @@ -319,6 +321,49 @@ impl MetadataCatalog { "", "Sets the last-error code for the calling thread", ); + self.add( + "kernel32.dll", + "GetThreadId", + AbiType::U32, + vec![("Thread", AbiType::Handle)], + "", + "Retrieves the identifier of the specified thread", + ); + self.add( + "kernel32.dll", + "DuplicateHandle", + AbiType::Bool, + vec![ + ("hSourceProcessHandle", AbiType::Handle), + ("hSourceHandle", AbiType::Handle), + ("hTargetProcessHandle", AbiType::Handle), + ( + "lpTargetHandle", + AbiType::Pointer { + is_const: false, + pointee: "HANDLE".into(), + }, + ), + ("dwDesiredAccess", AbiType::U32), + ("bInheritHandle", AbiType::Bool), + ("dwOptions", AbiType::U32), + ], + "", + "Creates another handle to the same object", + ); + for (name, return_type) in [ + ("GetTickCount", AbiType::U32), + ("GetTickCount64", AbiType::U64), + ] { + self.add( + "kernel32.dll", + name, + return_type, + vec![], + "", + "Returns elapsed system uptime in milliseconds", + ); + } self.add( "kernel32.dll", "QueryPerformanceCounter", diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index c5c603e1..92c4bfa3 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -40,6 +40,11 @@ fn test_manifest_and_codegen_pipeline() { "api-ms-win-crt-string-l1-1-0.dll","strlen",0x1008 "api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010 "custom.dll","UnknownCustomFunc",0x1018 +"kernel32.dll","QueryPerformanceCounter",0x1020 +"api-ms-win-core-profile-l1-1-0.dll","QueryPerformanceFrequency",0x1028 +"api-ms-win-core-processthreads-l1-1-0.dll","GetThreadId",0x1030 +"api-ms-win-core-handle-l1-1-0.dll","DuplicateHandle",0x1038 +"api-ms-win-core-sysinfo-l1-1-0.dll","GetTickCount64",0x1040 "#; let tmp_dir = std::env::temp_dir().join("xenora_test_pipeline"); @@ -48,7 +53,7 @@ fn test_manifest_and_codegen_pipeline() { std::fs::write(&csv_file, csv_content).unwrap(); let records = parse_csv(csv_file.to_str().unwrap()).unwrap(); - assert_eq!(records.len(), 4); + assert_eq!(records.len(), 9); let db = SymbolDb::builtin(); let manifest = Manifest::build(&records, &db); @@ -58,10 +63,17 @@ fn test_manifest_and_codegen_pipeline() { assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1); assert_eq!(*summary.get("manual").unwrap_or(&0), 1); + assert_eq!(summary.get("standard-service"), Some(&5)); + assert_eq!(manifest.generatable().count(), 3); + let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); assert!(files.crt_rs.contains("strlen")); assert!(files.stubs_rs.contains("CreateThread")); + assert!(!files.stubs_rs.contains("QueryPerformance")); + assert!(!files.stubs_rs.contains("GetThreadId")); + assert!(!files.stubs_rs.contains("DuplicateHandle")); + assert!(!files.stubs_rs.contains("GetTickCount64")); assert!(files.tests_rs.contains("generated_test_strlen")); let out_dir = tmp_dir.join("out"); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 2d27294a..32266b8d 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -3,7 +3,7 @@ //! Standard Windows and Xbox Scarlett Host Services Implementation for Xenora X15. //! //! Provides verifiable guest implementations of Windows NT and Xbox Scarlett APIs: -//! - Time: `GetSystemTimeAsFileTime` (injected deterministic clock or real UTC) +//! - Time: UTC file time and a monotonic performance counter //! - Process and thread identity and guest process priority boost policy //! - Error slots: `GetLastError`, `SetLastError` //! - Virtual memory: `VirtualAlloc`, `VirtualFree` @@ -14,7 +14,8 @@ use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions}; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::Instant; const CURRENT_PROCESS: u64 = u64::MAX; const CURRENT_THREAD: u64 = u64::MAX - 1; @@ -29,34 +30,54 @@ const THREAD_SET_RIGHTS: u32 = 0x0020 | 0x0400; const THREAD_SUPPORTED_RIGHTS: u32 = THREAD_QUERY_RIGHTS | THREAD_SET_RIGHTS | 0x0010_0000; const THREAD_PRIORITY_ERROR_RETURN: u64 = 0x7fff_ffff; const MAX_THREAD_HANDLES: usize = 1024; +const DUPLICATE_SAME_ACCESS: u32 = 2; +const HANDLE_API: &str = "api-ms-win-core-handle-l1-1-0.dll"; const PAGE_SIZE: u64 = 4096; const MEM_COMMIT_RESERVE: u32 = 0x3000; const MEM_RELEASE: u32 = 0x8000; const ERROR_NOACCESS: u32 = 998; const KERNEL32: &str = "kernel32.dll"; +const SYSINFO_API: &str = "api-ms-win-core-sysinfo-l1-1-0.dll"; const PROCESS_THREADS_V1: &str = "api-ms-win-core-processthreads-l1-1-0.dll"; const PROCESS_THREADS_V2: &str = "api-ms-win-core-processthreads-l1-1-2.dll"; +const PERFORMANCE_FREQUENCY: u64 = 10_000_000; +const MAX_PERFORMANCE_COUNT: u64 = i64::MAX as u64; + /// Clock trait for injecting deterministic time in tests or host time in production. pub trait Clock: Send + Sync { /// Return Windows 100-nanosecond intervals since January 1, 1601 (UTC). fn now_filetime(&self) -> u64; + + /// Return elapsed monotonic time in 100-nanosecond ticks, capped at `i64::MAX`. + fn performance_count(&self) -> u64 { + static ORIGIN: OnceLock = OnceLock::new(); + let ticks = ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() / 100; + ticks.min(u128::from(MAX_PERFORMANCE_COUNT)) as u64 + } } /// Deterministic test clock. pub struct MockClock { current: AtomicU64, + performance_count: AtomicU64, } impl MockClock { pub fn new(initial_filetime: u64) -> Self { Self { current: AtomicU64::new(initial_filetime), + performance_count: AtomicU64::new(0), } } pub fn advance(&self, intervals: u64) { self.current.fetch_add(intervals, Ordering::SeqCst); + self.performance_count + .try_update(Ordering::SeqCst, Ordering::SeqCst, |count| { + Some(count.saturating_add(intervals).min(MAX_PERFORMANCE_COUNT)) + }) + .expect("clock update always returns a value"); } } @@ -64,6 +85,10 @@ impl Clock for MockClock { fn now_filetime(&self) -> u64 { self.current.load(Ordering::SeqCst) } + + fn performance_count(&self) -> u64 { + self.performance_count.load(Ordering::SeqCst) + } } /// Host system UTC clock. @@ -94,6 +119,17 @@ struct ThreadState { } impl ThreadState { + fn next_handle(&self) -> Option { + self.last_handle + .checked_add(4) + .filter(|_| self.handles.len() < MAX_THREAD_HANDLES) + } + + fn insert_handle(&mut self, handle: u64, access: u32) { + self.handles.insert(handle, access); + self.last_handle = handle; + } + fn check_access(&self, handle: u64, required: u32) -> Result<(), u32> { if handle == CURRENT_THREAD { return Ok(()); @@ -109,6 +145,7 @@ impl ThreadState { /// State container for runtime services. pub struct ServicesState { pub clock: Arc, + clock_origin: u64, pub process_id: u32, priority_boost_disabled: AtomicBool, pub thread_id: u32, @@ -121,6 +158,7 @@ pub struct ServicesState { impl ServicesState { pub fn new(clock: Arc) -> Self { Self { + clock_origin: clock.performance_count(), clock, priority_boost_disabled: AtomicBool::new(false), process_id: 0x4100, // Synthetic process ID @@ -131,6 +169,14 @@ impl ServicesState { graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), } } + fn uptime_millis(&self) -> u64 { + let ticks = self + .clock + .performance_count() + .saturating_sub(self.clock_origin); + ticks / (PERFORMANCE_FREQUENCY / 1_000) + } + /// The scheduling policy recorded for the synthetic process. pub fn priority_boost_disabled(&self) -> bool { self.priority_boost_disabled.load(Ordering::SeqCst) @@ -213,15 +259,10 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc DWORD let s = state.clone(); let handler = move |_args: &crate::imports::Win64Args, diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 13f3e3af..755c2636 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -628,22 +628,36 @@ fn call_identity_fixture( module: &str, symbol: &str, args: [u64; 3], +) -> xenora_loader::startup::StartupResult { + call_service_fixture(state, module, symbol, &args) +} + +fn call_service_fixture( + state: &Arc, + module: &str, + symbol: &str, + args: &[u64], ) -> xenora_loader::startup::StartupResult { let image_base = 0x140000000; - let mut code = vec![0x48, 0x83, 0xec, 0x28]; // Win64 home space and alignment - for (register, value) in [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8]] - .into_iter() - .zip(args) - { - code.extend_from_slice(®ister); // mov rcx/rdx/r8, imm64 + assert!(args.len() <= 7); + let mut code = vec![0x48, 0x83, 0xec, 0x48]; // home space, stack arguments and alignment + let registers = [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8], [0x49, 0xb9]]; + for (register, value) in registers.into_iter().zip(args) { + code.extend_from_slice(®ister); code.extend_from_slice(&value.to_le_bytes()); } + for (index, value) in args.iter().skip(registers.len()).enumerate() { + code.extend_from_slice(&[0x48, 0xb8]); // mov rax, imm64 + code.extend_from_slice(&value.to_le_bytes()); + // mov [rsp + 32 + index * 8], rax (before the call pushes its return address) + code.extend_from_slice(&[0x48, 0x89, 0x44, 0x24, 0x20 + index as u8 * 8]); + } code.extend_from_slice(&[0x48, 0xb8]); // mov rax, address of output slot code.extend_from_slice(&PROCESS_FIXTURE_OUTPUT.to_le_bytes()); // mov qword ptr [rax], -1, seeding the BOOL and adjacent bytes code.extend_from_slice(&[0x48, 0xc7, 0x00, 0xff, 0xff, 0xff, 0xff]); append_import_call(&mut code, 0x2060); - code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); // release frame and halt + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]); // release frame and halt let bytes = TestPeBuilder::new(image_base, 0x1000) .code(&code) @@ -768,6 +782,104 @@ fn test_process_priority_boost_query_through_iat() { } } +#[test] +fn test_guest_performance_counter_through_iat() { + let clock = Arc::new(MockClock::new(133_000_000_000_000_000)); + let state = Arc::new(ServicesState::new(clock.clone())); + let query = |module, symbol| { + let result = call_process_fixture(&state, module, symbol, PROCESS_FIXTURE_OUTPUT, 0); + assert_eq!(result.execution.final_state.get(Register::Rax), 1); + result + .image + .memory + .read_u64(PROCESS_FIXTURE_OUTPUT) + .unwrap() + }; + let kernel = "kernel32.dll"; + let profile = "api-ms-win-core-profile-l1-1-0.dll"; + assert_eq!(query(kernel, "QueryPerformanceCounter"), 0); + assert_eq!(query(profile, "QueryPerformanceFrequency"), 10_000_000); + clock.advance(2_500_000); + assert_eq!(query(profile, "QueryPerformanceCounter"), 2_500_000); + assert_eq!(query(kernel, "QueryPerformanceFrequency"), 10_000_000); + + for symbol in ["QueryPerformanceCounter", "QueryPerformanceFrequency"] { + for ptr in [0, 0x140001000, PROCESS_FIXTURE_STACK_TOP - 2] { + let result = call_process_fixture(&state, profile, symbol, ptr, 0); + assert_eq!(result.execution.final_state.get(Register::Rax), 0); + assert_eq!( + result + .image + .memory + .read_u64(PROCESS_FIXTURE_OUTPUT) + .unwrap(), + u64::MAX + ); + let error = call_process_fixture(&state, kernel, "GetLastError", 0, 0); + assert_eq!(error.execution.final_state.get(Register::Rax), 998); + } + } + clock.advance(u64::MAX); + assert_eq!(query(kernel, "QueryPerformanceCounter"), i64::MAX as u64); + let error = call_process_fixture(&state, kernel, "GetLastError", 0, 0); + assert_eq!(error.execution.final_state.get(Register::Rax), 998); +} + +#[test] +fn test_guest_performance_counter_with_host_clock() { + let state = Arc::new(ServicesState::new(Arc::new( + xenora_loader::services::SystemClock, + ))); + let read_counter = || { + let result = call_process_fixture( + &state, + "kernel32.dll", + "QueryPerformanceCounter", + PROCESS_FIXTURE_OUTPUT, + 0, + ); + assert_eq!(result.execution.final_state.get(Register::Rax), 1); + result + .image + .memory + .read_u64(PROCESS_FIXTURE_OUTPUT) + .unwrap() + }; + + let first = read_counter(); + std::thread::sleep(std::time::Duration::from_millis(1)); + assert!(read_counter() > first); +} + +#[test] +fn test_guest_uptime_wraps_only_at_32_bits() { + let clock = Arc::new(MockClock::new(133_000_000_000_000_000)); + clock.advance(5_000_000); + let state = Arc::new(ServicesState::new(clock.clone())); + let query = |module, symbol| { + call_service_fixture(&state, module, symbol, &[]) + .execution + .final_state + .get(Register::Rax) + }; + let kernel = "kernel32.dll"; + let sysinfo = "api-ms-win-core-sysinfo-l1-1-0.dll"; + assert_eq!(query(kernel, "GetTickCount"), 0); + assert_eq!(query(sysinfo, "GetTickCount64"), 0); + clock.advance(9_999); + assert_eq!(query(kernel, "GetTickCount"), 0); + clock.advance(1); + assert_eq!(query(sysinfo, "GetTickCount64"), 1); + + let max = u64::from(u32::MAX); + clock.advance((max - 1) * 10_000); + assert_eq!(query(sysinfo, "GetTickCount"), max); + assert_eq!(query(kernel, "GetTickCount64"), max); + clock.advance(10_000); + assert_eq!(query(sysinfo, "GetTickCount"), 0); + assert_eq!(query(kernel, "GetTickCount64"), max + 1); +} + fn append_import_call(code: &mut Vec, slot_rva: i32) { // call qword ptr [rip + disp32], through the fixture's import slot. let next_rva = 0x1000 + code.len() as i32 + 6; @@ -789,6 +901,7 @@ fn test_guest_thread_handle_lifecycle_through_iat() { let last_error = || call("kernel32.dll", "GetLastError", [0; 3]); let id = call(api, "GetCurrentThreadId", [0; 3]); let pseudo = call(api, "GetCurrentThread", [0; 3]); + let thread_id = |handle| call(api, "GetThreadId", [handle, 0, 0]); assert_eq!(pseudo, u64::MAX - 1); const QUERY_LIMITED: u64 = 0x0800; @@ -809,6 +922,12 @@ fn test_guest_thread_handle_lifecycle_through_iat() { assert_ne!(query_only, 0); assert_ne!(set_only, 0); assert_ne!(query_only, set_only); + assert_eq!(thread_id(pseudo), id); + assert_eq!(thread_id(query_only), id); + assert_eq!(thread_id(set_only), 0); + assert_eq!(last_error(), 5); + assert_eq!(thread_id(u64::MAX), 0); + assert_eq!(last_error(), 6); assert_eq!(query(query_only), 0); assert_eq!(set(query_only, 1), 0); assert_eq!(last_error(), 5); @@ -824,16 +943,85 @@ fn test_guest_thread_handle_lifecycle_through_iat() { assert_eq!(query(pseudo), u64::from(u32::MAX)); assert_eq!(close(pseudo), 1); assert_eq!(close(query_only), 1); + assert_eq!(thread_id(query_only), 0); + assert_eq!(last_error(), 6); assert_eq!(query(query_only), 0x7fff_ffff); assert_eq!(last_error(), 6); assert_eq!(close(query_only), 0); assert_eq!(last_error(), 6); let reopened = open(QUERY_LIMITED, 0, id); assert_ne!(reopened, query_only); + assert_eq!(thread_id(reopened), id); + assert_eq!(thread_id(query_only), 0); assert_eq!(query(reopened), u64::from(u32::MAX)); assert_eq!(last_error(), 6); } +#[test] +fn test_guest_duplicates_thread_handle_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |symbol, arg| { + call_process_fixture(&state, "kernel32.dll", symbol, arg, 0) + .execution + .final_state + .get(Register::Rax) + }; + let duplicate = |source, output, rights, inherit, options| { + let result = call_service_fixture( + &state, + "api-ms-win-core-handle-l1-1-0.dll", + "DuplicateHandle", + &[u64::MAX, source, u64::MAX, output, rights, inherit, options], + ); + let success = result.execution.final_state.get(Register::Rax); + let handle = result + .image + .memory + .read_u64(PROCESS_FIXTURE_OUTPUT) + .unwrap(); + (success, handle) + }; + + let id = call("GetCurrentThreadId", 0); + let pseudo = call("GetCurrentThread", 0); + let (success, source) = duplicate(pseudo, PROCESS_FIXTURE_OUTPUT, 0x0800, 0, 0); + assert_eq!(success, 1); + assert_ne!(source, pseudo); + assert_eq!(call("GetThreadId", source), id); + + assert_eq!( + duplicate(source, PROCESS_FIXTURE_OUTPUT, 0x0400, 0, 0), + (0, u64::MAX) + ); + assert_eq!(call("GetLastError", 0), 5); + assert_eq!(duplicate(source, 0, 0, 0, 2), (0, u64::MAX)); + assert_eq!(call("GetLastError", 0), 998); + assert_eq!( + duplicate(source, PROCESS_FIXTURE_OUTPUT, 0, 1, 2), + (0, u64::MAX) + ); + assert_eq!(call("GetLastError", 0), 50); + assert_eq!( + duplicate(source, PROCESS_FIXTURE_OUTPUT, 0, 0, 1), + (0, u64::MAX) + ); + assert_eq!(call("GetLastError", 0), 50); + assert_eq!(call("GetThreadId", source), id); + + let (success, copy) = duplicate(source, PROCESS_FIXTURE_OUTPUT, u64::MAX, 0, 2); + assert_eq!(success, 1); + assert_ne!(source, copy); + assert_eq!(call("CloseHandle", source), 1); + assert_eq!(call("GetThreadId", copy), id); + assert_eq!( + duplicate(source, PROCESS_FIXTURE_OUTPUT, 0, 0, 2), + (0, u64::MAX) + ); + assert_eq!(call("GetLastError", 0), 6); + assert_eq!(call("CloseHandle", copy), 1); + assert_eq!(call("GetThreadId", copy), 0); +} + #[test] fn test_virtual_allocation_release_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index 903b2ca6..eef05929 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -93,14 +93,37 @@ Win32 references include Microsoft's documentation for [SetProcessPriorityBoost](https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-setprocesspriorityboost), and [GetProcessPriorityBoost](https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getprocesspriorityboost). +### Performance timing + +The guest can import `QueryPerformanceCounter` and `QueryPerformanceFrequency` +from Kernel32 or the profile API set. The counter measures monotonic elapsed +time at a fixed 10 MHz, independently of wall-clock time. Synthetic fixtures +can advance it deterministically. A failed guest output write returns false +and records `ERROR_NOACCESS`. `GetTickCount` and `GetTickCount64` return +whole milliseconds since the synthetic runtime was created. The 32-bit value +wraps at 2³² milliseconds. Both use the monotonic clock and are available +through Kernel32 and the system-information API set. + +See Microsoft's documentation for +[QueryPerformanceCounter](https://learn.microsoft.com/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter) +[QueryPerformanceFrequency](https://learn.microsoft.com/windows/win32/api/profileapi/nf-profileapi-queryperformancefrequency), +[GetTickCount](https://learn.microsoft.com/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount), +and [GetTickCount64](https://learn.microsoft.com/windows/win32/api/sysinfoapi/nf-sysinfoapi-gettickcount64). + ### Thread handles and virtual memory The thread object model exposes one guest thread with a stable synthetic ID. `OpenThread` issues rights-checked handles to that thread, and `CloseHandle` invalidates real handles. A thread pseudo handle refers to the current synthetic -thread. The priority APIs store and query the thread's base-priority setting. +thread. `GetThreadId` accepts the pseudo handle and live thread handles with +query rights. The priority APIs store and query the thread's base-priority setting. Thread creation, inheritance, debugger exceptions, and scheduling remain outside -this model. +this model. Within the synthetic process, `DuplicateHandle` can convert the +thread pseudo handle to a real handle or copy a live thread handle. The new +handle can keep or reduce the source's rights. The original and duplicate can +be closed independently. Cross-process duplication, inheritable handles, +process-handle duplication, and closing the source during duplication are +outside this subset. A failed output write leaves the handle table unchanged. `VirtualAlloc` supports combined reserve and commit for data-only pages. `VirtualFree` supports `MEM_RELEASE` with the exact allocation base and a @@ -110,7 +133,9 @@ allocation lifecycle remain unsupported. References include Microsoft's [thread handle](https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthread), +[thread ID](https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadid), [thread priority](https://learn.microsoft.com/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadpriority), +[handle duplication](https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-duplicatehandle), [handle close](https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-closehandle), [virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc), and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts. From 86467c2f6c2746e19b9551f7865beab3cbe8e9b6 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:17:00 -0500 Subject: [PATCH 02/82] Add guest events with shared duplicate handles Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 31 +++---- crates/loader/src/services.rs | 76 +++++++++++------- crates/loader/src/services/events.rs | 116 +++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 71 ++++++++++++++++ docs/interfaces.md | 15 ++++ 6 files changed, 262 insertions(+), 49 deletions(-) create mode 100644 crates/loader/src/services/events.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5beb90e0..4036396f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication. + - Added same-process duplication of synthetic thread handles with independent closure. - Added a rights-checked `GetThreadId` query for handles to the synthetic guest thread. - Added 32-bit and 64-bit millisecond uptime queries for synthetic Windows guests. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 67bb1286..eb9f3b83 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -765,32 +765,23 @@ impl SymbolDb { fn populate_win32_synch(&mut self) { let m = "api-ms-win-core-synch-l1-1-0.dll"; - self.win32_stub( - m, - "WaitForSingleObject", - false, - "WaitForSingleObject — stub returning WAIT_OBJECT_0", - ); + for module in [m, "kernel32.dll"] { + for symbol in [ + "CreateEventA", + "CreateEventW", + "SetEvent", + "ResetEvent", + "WaitForSingleObject", + ] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub( m, "WaitForSingleObjectEx", false, "WaitForSingleObjectEx — stub", ); - self.win32_stub( - m, - "CreateEventA", - true, - "CreateEvent — stub returning fake handle", - ); - self.win32_stub( - m, - "CreateEventW", - true, - "CreateEvent wide — stub returning fake handle", - ); - self.win32_stub(m, "SetEvent", false, "SetEvent — no-op stub"); - self.win32_stub(m, "ResetEvent", false, "ResetEvent — no-op stub"); self.win32_stub(m, "CreateMutexA", true, "CreateMutex — stub"); self.win32_stub(m, "CreateMutexW", true, "CreateMutex wide — stub"); self.win32_stub(m, "ReleaseMutex", false, "ReleaseMutex — stub"); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 32266b8d..89680512 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -9,6 +9,8 @@ //! - Virtual memory: `VirtualAlloc`, `VirtualFree` //! - Xbox physical memory: `XMemAlloc`, `XMemFree` +mod events; + use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions}; @@ -29,7 +31,7 @@ const THREAD_QUERY_RIGHTS: u32 = 0x0040 | 0x0800; const THREAD_SET_RIGHTS: u32 = 0x0020 | 0x0400; const THREAD_SUPPORTED_RIGHTS: u32 = THREAD_QUERY_RIGHTS | THREAD_SET_RIGHTS | 0x0010_0000; const THREAD_PRIORITY_ERROR_RETURN: u64 = 0x7fff_ffff; -const MAX_THREAD_HANDLES: usize = 1024; +const MAX_OBJECT_HANDLES: usize = 1024; const DUPLICATE_SAME_ACCESS: u32 = 2; const HANDLE_API: &str = "api-ms-win-core-handle-l1-1-0.dll"; const PAGE_SIZE: u64 = 4096; @@ -111,22 +113,30 @@ impl Clock for SystemClock { } } -#[derive(Default)] -struct ThreadState { - priority: i32, - last_handle: u64, - handles: BTreeMap, +enum GuestObject { + Thread(u32), + Event { + state: Arc>, + access: u32, + }, } -impl ThreadState { +#[derive(Default)] +struct ObjectState { + priority: i32, + last_handle: u64, + handles: BTreeMap, +} + +impl ObjectState { fn next_handle(&self) -> Option { self.last_handle .checked_add(4) - .filter(|_| self.handles.len() < MAX_THREAD_HANDLES) + .filter(|_| self.handles.len() < MAX_OBJECT_HANDLES) } - fn insert_handle(&mut self, handle: u64, access: u32) { - self.handles.insert(handle, access); + fn insert_handle(&mut self, handle: u64, object: GuestObject) { + self.handles.insert(handle, object); self.last_handle = handle; } @@ -135,9 +145,9 @@ impl ThreadState { return Ok(()); } match self.handles.get(&handle) { - Some(access) if access & required != 0 => Ok(()), - Some(_) => Err(ERROR_ACCESS_DENIED), - None => Err(ERROR_INVALID_HANDLE), + Some(GuestObject::Thread(access)) if access & required != 0 => Ok(()), + Some(GuestObject::Thread(_)) => Err(ERROR_ACCESS_DENIED), + _ => Err(ERROR_INVALID_HANDLE), } } } @@ -149,7 +159,7 @@ pub struct ServicesState { pub process_id: u32, priority_boost_disabled: AtomicBool, pub thread_id: u32, - thread: Mutex, + objects: Mutex, pub last_error: AtomicU32, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, @@ -163,7 +173,7 @@ impl ServicesState { priority_boost_disabled: AtomicBool::new(false), process_id: 0x4100, // Synthetic process ID thread_id: 0x4104, // Synthetic main thread ID - thread: Mutex::new(ThreadState::default()), + objects: Mutex::new(ObjectState::default()), last_error: AtomicU32::new(0), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), @@ -258,18 +268,18 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc (*rights, None), + Some(GuestObject::Event { state, access }) => (*access, Some(Arc::clone(state))), + None => return s.fail(ERROR_INVALID_HANDLE, 0), + } }; let access = if options & DUPLICATE_SAME_ACCESS != 0 { granted @@ -369,12 +381,18 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc GuestObject::Event { state, access }, + None => GuestObject::Thread(access), + }; + thread.insert_handle(handle, object); Ok(1) }); registry.alias(HANDLE_API, KERNEL32, "DuplicateHandle"); registry.set_status(KERNEL32, "DuplicateHandle", ServiceStatus::Partial); + events::register(registry, &state); + // 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME) let s = state.clone(); let handler = move |args: &crate::imports::Win64Args, diff --git a/crates/loader/src/services/events.rs b/crates/loader/src/services/events.rs new file mode 100644 index 00000000..aa8085eb --- /dev/null +++ b/crates/loader/src/services/events.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Unnamed event objects and waits that can resolve without a guest scheduler. + +use super::{ + ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, + GuestObject, KERNEL32, ServicesState, +}; +use crate::cpu::ExitReason; +use crate::imports::{ImportRegistry, ServiceStatus}; +use std::sync::{Arc, Mutex}; + +const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll"; +const EVENT_MODIFY_STATE: u32 = 0x0002; +const SYNCHRONIZE: u32 = 0x0010_0000; +const EVENT_ALL_ACCESS: u32 = 0x001f_0003; +const WAIT_OBJECT_0: u64 = 0; +const WAIT_TIMEOUT: u64 = 258; +const WAIT_FAILED: u64 = u32::MAX as u64; + +pub(super) struct Event { + manual_reset: bool, + signaled: bool, +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + for symbol in ["CreateEventA", "CreateEventW"] { + let state = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let manual_reset = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; + let signaled = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; + let name = args.get(3, mem).map_err(ExitReason::MemoryFault)?; + if attributes != 0 || name != 0 { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + let mut objects = state.objects.lock().expect("guest object state"); + let Some(handle) = objects.next_handle() else { + return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + }; + objects.insert_handle( + handle, + GuestObject::Event { + state: Arc::new(Mutex::new(Event { + manual_reset, + signaled, + })), + access: EVENT_ALL_ACCESS, + }, + ); + Ok(handle) + }); + } + + for (symbol, signaled) in [("SetEvent", true), ("ResetEvent", false)] { + let state = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let objects = state.objects.lock().expect("guest object state"); + let Some(GuestObject::Event { + state: event, + access, + }) = objects.handles.get(&handle) + else { + return state.fail(ERROR_INVALID_HANDLE, 0); + }; + if access & EVENT_MODIFY_STATE == 0 { + return state.fail(ERROR_ACCESS_DENIED, 0); + } + event.lock().expect("guest event state").signaled = signaled; + Ok(1) + }); + } + + let state = Arc::clone(state); + registry.register(KERNEL32, "WaitForSingleObject", move |args, _, mem| { + let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; + let objects = state.objects.lock().expect("guest object state"); + let Some(GuestObject::Event { + state: event, + access, + }) = objects.handles.get(&handle) + else { + if objects.handles.contains_key(&handle) + || matches!(handle, super::CURRENT_THREAD | super::CURRENT_PROCESS) + { + return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + } + return state.fail(ERROR_INVALID_HANDLE, WAIT_FAILED); + }; + if access & SYNCHRONIZE == 0 { + return state.fail(ERROR_ACCESS_DENIED, WAIT_FAILED); + } + let mut event = event.lock().expect("guest event state"); + if event.signaled { + event.signaled = event.manual_reset; + return Ok(WAIT_OBJECT_0); + } + if timeout == 0 { + return Ok(WAIT_TIMEOUT); + } + state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED) + }); + + for symbol in [ + "CreateEventA", + "CreateEventW", + "SetEvent", + "ResetEvent", + "WaitForSingleObject", + ] { + registry.alias(SYNCH_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 755c2636..a9e0be06 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1022,6 +1022,77 @@ fn test_guest_duplicates_thread_handle_through_iat() { assert_eq!(call("GetThreadId", copy), 0); } +#[test] +fn test_guest_event_signaling_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |module, symbol, args: &[u64]| { + call_service_fixture(&state, module, symbol, args) + .execution + .final_state + .get(Register::Rax) + }; + let kernel = "kernel32.dll"; + let synch = "api-ms-win-core-synch-l1-1-0.dll"; + let wait = |handle, timeout| call(synch, "WaitForSingleObject", &[handle, timeout]); + let error = || call(kernel, "GetLastError", &[]); + + let manual = call(synch, "CreateEventW", &[0, 1, 0, 0]); + let auto = call(kernel, "CreateEventA", &[0, 0, 1, 0]); + assert_ne!(manual, 0); + assert_ne!(auto, 0); + assert_ne!(manual, auto); + assert_eq!(wait(manual, 0), 258); + assert_eq!(wait(manual, 1), u32::MAX as u64); + assert_eq!(error(), 50); + assert_eq!(call(synch, "SetEvent", &[manual]), 1); + assert_eq!(wait(manual, u32::MAX as u64), 0); + assert_eq!(wait(manual, 0), 0); + assert_eq!(call(synch, "ResetEvent", &[manual]), 1); + assert_eq!(wait(manual, 0), 258); + assert_eq!(wait(auto, 0), 0); + assert_eq!(wait(auto, 0), 258); + assert_eq!(call(synch, "SetEvent", &[auto]), 1); + assert_eq!(call(synch, "SetEvent", &[auto]), 1); + assert_eq!(wait(auto, 0), 0); + assert_eq!(wait(auto, 0), 258); + + assert_eq!(call(kernel, "GetThreadId", &[auto]), 0); + assert_eq!(error(), 6); + let thread = call(kernel, "GetCurrentThread", &[]); + assert_eq!(call(synch, "SetEvent", &[thread]), 0); + assert_eq!(error(), 6); + assert_eq!(call(kernel, "CloseHandle", &[manual]), 1); + assert_eq!(wait(manual, 0), u32::MAX as u64); + assert_eq!(error(), 6); + assert_eq!(call(kernel, "CreateEventW", &[0, 0, 0, 1]), 0); + assert_eq!(error(), 50); + let copy = call_service_fixture( + &state, + kernel, + "DuplicateHandle", + &[ + u64::MAX, + auto, + u64::MAX, + PROCESS_FIXTURE_OUTPUT, + 0x10_0000, + 0, + 0, + ], + ); + assert_eq!(copy.execution.final_state.get(Register::Rax), 1); + let copy = copy.image.memory.read_u64(PROCESS_FIXTURE_OUTPUT).unwrap(); + assert_eq!(call(synch, "SetEvent", &[copy]), 0); + assert_eq!(error(), 5); + assert_eq!(call(synch, "SetEvent", &[auto]), 1); + assert_eq!(wait(copy, 0), 0); + assert_eq!(wait(auto, 0), 258); + assert_eq!(call(synch, "SetEvent", &[auto]), 1); + assert_eq!(call(kernel, "CloseHandle", &[auto]), 1); + assert_eq!(wait(copy, 0), 0); + assert_eq!(call(kernel, "CloseHandle", &[copy]), 1); +} + #[test] fn test_virtual_allocation_release_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index eef05929..9d4b8d54 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -140,6 +140,21 @@ References include Microsoft's [virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc), and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts. +### Event signaling + +The synthetic runtime supports unnamed manual-reset and auto-reset events +created with default security attributes. `SetEvent` signals an event, +`ResetEvent` clears it, and `CloseHandle` invalidates the handle. +`WaitForSingleObject` consumes an auto-reset signal once, leaves a manual-reset +signal set, and reports `WAIT_TIMEOUT` when a zero-timeout poll finds no signal. +A wait that would block returns `WAIT_FAILED` with `ERROR_NOT_SUPPORTED`. +Thread and event handles are distinct types in the same bounded table. +Event duplicates share signal state and keep the event alive independently. +A duplicate can retain or reduce its rights. Waiting requires synchronize +access, and setting or resetting requires modify-state access. + +See Microsoft's [event object documentation](https://learn.microsoft.com/windows/win32/sync/event-objects). + ## Synthetic tiled textures The texture crate reads original fixtures in an array-layer-major layout. Each From 7599de0e01fd370138db2be6fdd5bb9901b76d0f Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:17:52 -0500 Subject: [PATCH 03/82] Check Win64 service stack argument offsets Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/loader/src/imports.rs | 54 +++++++++++++++++++++++++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4036396f..7b39f602 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ remains unsupported. ### Fixed +- Win64 service argument decoding reports a guest memory error when a stack argument offset overflows. + - Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20], rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent execution test above), so the probe reports no blocker for this program. diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index f0d47b7a..3eb15c77 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -83,7 +83,10 @@ impl Win64Args { 2 => Ok(self.r8), 3 => Ok(self.r9), n => { - let stack_offset = 40 + ((n - 4) as u64) * 8; + let stack_offset = ((n - 4) as u64) + .checked_mul(8) + .and_then(|offset| offset.checked_add(40)) + .ok_or(MemoryError::Overflow)?; let addr = self .rsp .checked_add(stack_offset) @@ -430,3 +433,52 @@ fn find_import_directory(bytes: &[u8]) -> Result, ImportError Ok(Some((import_rva, import_size))) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::memory::MemoryPermissions; + + #[test] + fn win64_arguments_follow_register_and_stack_layout() { + let args = Win64Args { + rcx: 11, + rdx: 12, + r8: 13, + r9: 14, + rsp: 0x1000, + }; + let mut memory = GuestMemory::new(); + memory + .map_region(0x1000, 56, MemoryPermissions::READ_WRITE) + .unwrap(); + memory.write_u64(0x1028, 15).unwrap(); + memory.write_u64(0x1030, 16).unwrap(); + for (index, expected) in (11..=16).enumerate() { + assert_eq!(args.get(index, &memory), Ok(expected)); + } + assert_eq!( + args.get(6, &memory), + Err(MemoryError::UnmappedAddress(0x1038)) + ); + } + + #[test] + fn win64_stack_arguments_reject_overflow_in_offsets_and_addresses() { + let mut args = Win64Args { + rcx: 0, + rdx: 0, + r8: 0, + r9: 0, + rsp: 0x1000, + }; + let memory = GuestMemory::new(); + assert_eq!(args.get(usize::MAX, &memory), Err(MemoryError::Overflow)); + assert_eq!( + args.get(usize::MAX / 8 + 4, &memory), + Err(MemoryError::Overflow) + ); + args.rsp = u64::MAX - 39; + assert_eq!(args.get(4, &memory), Err(MemoryError::Overflow)); + } +} From 7130da2635987f78451f15f15c93697edb490e5c Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:18:57 -0500 Subject: [PATCH 04/82] Reject generated CRT calls without a guest ABI adapter Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/codegen.rs | 105 +++++----------------------- crates/import-gen/tests/pipeline.rs | 5 ++ 3 files changed, 26 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7b39f602..36b69d11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,8 @@ remains unsupported. ### Fixed +- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing. + - Win64 service argument decoding reports a guest memory error when a stack argument offset overflows. - Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20], diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index be5a3d0d..7cd8ebb8 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -119,9 +119,15 @@ pub fn register_generated_crt_services(registry: &mut ImportRegistry) { /// Generate a registration block for a CrtNative symbol. /// These use a simple `Win64Args` → libc dispatch pattern. -fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note: &str) -> String { +fn gen_crt_native_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String { // Determine the calling pattern based on symbol name - let dispatch = crt_dispatch_expr(symbol, libc_sym); + let (status, dispatch) = match crt_dispatch_expr(symbol) { + Some(dispatch) => ("Partial", dispatch), + None => ( + "Stub", + "Err(ExitReason::IllegalInstruction(0xFE))".to_owned(), + ), + }; format!( r#" @@ -129,7 +135,7 @@ fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note: // Source: ISO C / POSIX public specification. registry.register_with_status( "{module}", "{symbol}", - ServiceStatus::Partial, // upgraded to Implemented when conformance test passes + ServiceStatus::{status}, |args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result {{ {dispatch} }}, @@ -151,9 +157,7 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not "{module}", "{symbol}", ServiceStatus::Stub, |args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result {{ - // Safe-CRT wrapper: delegates to underlying function, ignores size argument. - // Guest memory is already bounds-checked by the caller's service dispatch. - Ok(0) // success + Err(ExitReason::IllegalInstruction(0xFE)) }}, ); "#, @@ -162,14 +166,14 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not /// Generate a registration for a runtime helper (EH frame handlers, etc.). fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String { - // Most runtime helpers either call abort or return 0 + // Termination helpers halt. Other unimplemented helpers fail explicitly. let body = if symbol.contains("Throw") || symbol.contains("terminate") || symbol.contains("purecall") { "// C++ exception/terminate: halt guest execution.\n Err(ExitReason::Halted)" } else { - "Ok(0)" + "Err(ExitReason::IllegalInstruction(0xFE))" }; format!( r#" @@ -276,6 +280,7 @@ fn fresh_state() -> (CpuState, GuestMemory) { // Generate a test per CrtNative entry that has a testable canonical case for entry in manifest.entries.iter() { if let Classification::CrtNative { libc_sym, .. } = &entry.classification + && crt_dispatch_expr(&entry.symbol).is_some() && let Some(test) = canonical_test(&entry.symbol, libc_sym) { out.push_str(&format!( @@ -339,74 +344,9 @@ fn symbol_to_ident_lower(sym: &str) -> String { symbol_to_ident(sym).to_ascii_lowercase() } -/// Returns the Rust dispatch expression body for a CRT native call. -/// We call libc via `unsafe` FFI. Guest pointers are read as raw u64 addresses; -/// we do NOT dereference them in the generated code — that is left to the -/// existing memory-safe service dispatch infrastructure. -fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String { - // Categorise by calling pattern - match symbol { - // Math f64 → f64, single arg - "acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2" - | "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => { - format!( - r#"let x = f64::from_bits(args.rcx); - extern "C" {{ fn {libc_sym}(x: f64) -> f64; }} - let r = unsafe {{ {libc_sym}(x) }}; - Ok(r.to_bits())"#, - libc_sym = libc_sym, - ) - } - // Math f32 → f32, single arg - "acosf" | "asinf" | "atanf" | "cosf" | "sinf" | "tanf" | "expf" | "logf" | "log10f" - | "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf" - | "erff" | "exp2f" => { - format!( - r#"let x = f32::from_bits(args.rcx as u32); - extern "C" {{ fn {libc_sym}(x: f32) -> f32; }} - let r = unsafe {{ {libc_sym}(x) }}; - Ok(r.to_bits() as u64)"#, - libc_sym = libc_sym, - ) - } - // Math f64 × f64 → f64, two args - "atan2" | "pow" | "fmod" | "hypot" | "fmax" | "fmin" | "copysign" => { - format!( - r#"let x = f64::from_bits(args.rcx); - let y = f64::from_bits(args.rdx); - extern "C" {{ fn {libc_sym}(x: f64, y: f64) -> f64; }} - let r = unsafe {{ {libc_sym}(x, y) }}; - Ok(r.to_bits())"#, - libc_sym = libc_sym, - ) - } - // Math f32 × f32 → f32 - "atan2f" | "powf" | "fmodf" | "hypotf" | "fmaxf" | "fminf" | "copysignf" => { - format!( - r#"let x = f32::from_bits(args.rcx as u32); - let y = f32::from_bits(args.rdx as u32); - extern "C" {{ fn {libc_sym}(x: f32, y: f32) -> f32; }} - let r = unsafe {{ {libc_sym}(x, y) }}; - Ok(r.to_bits() as u64)"#, - libc_sym = libc_sym, - ) - } - // Math f64 × f64 × f64 → f64 (fma) - "fma" => r#"let x = f64::from_bits(args.rcx); - let y = f64::from_bits(args.rdx); - let z = f64::from_bits(args.r8); - extern "C" { fn fma(x: f64, y: f64, z: f64) -> f64; } - let r = unsafe { fma(x, y, z) }; - Ok(r.to_bits())"# - .to_string(), - "fmaf" => r#"let x = f32::from_bits(args.rcx as u32); - let y = f32::from_bits(args.rdx as u32); - let z = f32::from_bits(args.r8 as u32); - extern "C" { fn fmaf(x: f32, y: f32, z: f32) -> f32; } - let r = unsafe { fmaf(x, y, z) }; - Ok(r.to_bits() as u64)"# - .to_string(), - // strlen(ptr) -> size_t +/// Returns a dispatch body for CRT calls with a compatible guest ABI adapter. +fn crt_dispatch_expr(symbol: &str) -> Option { + Some(match symbol { "strlen" => r#"// strlen: RCX = guest pointer to null-terminated string let ptr = args.rcx; if ptr == 0 { return Ok(0); } @@ -513,16 +453,9 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String { "toupper" => r#"let c = (args.rcx & 0xFF) as u8; Ok(c.to_ascii_uppercase() as u64)"# .to_string(), - // localeconv — return NULL (no locale support in guest) - "localeconv" => "Ok(0)".to_string(), - // strftime — stub returning 0 - "strftime" => "Ok(0)".to_string(), - // Generic: return 0 as a safe default - _ => format!( - "// No specific dispatch for '{symbol}' — safe default\n Ok(0)", - symbol = symbol, - ), - } + // Floating-point CRT calls also land here until XMM state is available. + _ => return None, + }) } /// Returns a Rust test body for symbols where we can derive a known-good expected value. diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 92c4bfa3..a0301068 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -69,6 +69,11 @@ fn test_manifest_and_codegen_pipeline() { let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); assert!(files.crt_rs.contains("strlen")); + let acos = files.crt_rs.split_once("\"acos\"").unwrap().1; + let (acos, _) = acos.split_once("registry.register_with_status").unwrap(); + assert!(acos.contains("ServiceStatus::Stub")); + assert!(acos.contains("Err(ExitReason::IllegalInstruction(0xFE))")); + assert!(!files.tests_rs.contains("generated_test_acos")); assert!(files.stubs_rs.contains("CreateThread")); assert!(!files.stubs_rs.contains("QueryPerformance")); assert!(!files.stubs_rs.contains("GetThreadId")); From e4b1898b0081dc5cc2136f1b44e3ee601a8f7606 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:20:22 -0500 Subject: [PATCH 05/82] Serve bounded CRT byte string lengths through the guest registry Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/import-gen/src/classify.rs | 6 +++- crates/import-gen/src/codegen.rs | 12 -------- crates/import-gen/src/metadata.rs | 8 ++++++ crates/import-gen/tests/pipeline.rs | 8 +++--- crates/loader/src/services.rs | 2 ++ crates/loader/src/services/crt.rs | 43 +++++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 18 ++++++++++++ docs/interfaces.md | 8 ++++++ 9 files changed, 90 insertions(+), 17 deletions(-) create mode 100644 crates/loader/src/services/crt.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 36b69d11..8e7f1b5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest CRT string length services for UCRT and its string API set. + - Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication. - Added same-process duplication of synthetic thread handles with independent closure. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index eb9f3b83..838a8b3d 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -204,6 +204,11 @@ impl SymbolDb { fn populate_crt_string(&mut self) { let m = "api-ms-win-crt-string-l1-1-0.dll"; + for module in [m, "ucrtbase.dll"] { + for symbol in ["strlen", "strnlen"] { + self.ins(module, symbol, Classification::StandardService); + } + } for (sym, libc) in &[ ("isalnum", "isalnum"), ("isalpha", "isalpha"), @@ -226,7 +231,6 @@ impl SymbolDb { ("strcmp", "strcmp"), ("strcpy", "strcpy"), ("strcspn", "strcspn"), - ("strlen", "strlen"), ("strncat", "strncat"), ("strncmp", "strncmp"), ("strncpy", "strncpy"), diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 7cd8ebb8..d56b2379 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -347,18 +347,6 @@ fn symbol_to_ident_lower(sym: &str) -> String { /// Returns a dispatch body for CRT calls with a compatible guest ABI adapter. fn crt_dispatch_expr(symbol: &str) -> Option { Some(match symbol { - "strlen" => r#"// strlen: RCX = guest pointer to null-terminated string - let ptr = args.rcx; - if ptr == 0 { return Ok(0); } - let mut len: u64 = 0; - loop { - let b = mem.read_u8(ptr + len).map_err(ExitReason::MemoryFault)?; - if b == 0 { break; } - len += 1; - if len > 1_048_576 { break; } // safety cap 1 MiB - } - Ok(len)"# - .to_string(), // memset(dst, val, count) -> dst "memset" => r#"let dst = args.rcx; let val = (args.rdx & 0xFF) as u8; diff --git a/crates/import-gen/src/metadata.rs b/crates/import-gen/src/metadata.rs index 8d6be1c2..42e60a72 100644 --- a/crates/import-gen/src/metadata.rs +++ b/crates/import-gen/src/metadata.rs @@ -193,6 +193,14 @@ impl MetadataCatalog { "", "Calculates the length of a string in guest memory", ); + self.add( + "ucrtbase.dll", + "strnlen", + AbiType::U64, + vec![("str", AbiType::StringAnsi), ("count", AbiType::U64)], + "", + "Calculates a byte string length up to the supplied bound", + ); self.add( "ucrtbase.dll", "strcmp", diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index a0301068..179c6960 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -16,7 +16,7 @@ fn test_builtin_db_classifies_crt_math() { fn test_builtin_db_classifies_crt_string() { let db = SymbolDb::builtin(); let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen"); - assert!(matches!(strlen_cls, Some(Classification::CrtNative { .. }))); + assert!(matches!(strlen_cls, Some(Classification::StandardService))); let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s"); assert!(matches!( @@ -37,7 +37,7 @@ fn test_builtin_db_case_insensitive() { fn test_manifest_and_codegen_pipeline() { let csv_content = r#""module","symbol_or_ordinal","iat_rva" "api-ms-win-crt-math-l1-1-0.dll","acos",0x1000 -"api-ms-win-crt-string-l1-1-0.dll","strlen",0x1008 +"api-ms-win-crt-string-l1-1-0.dll","memset",0x1008 "api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010 "custom.dll","UnknownCustomFunc",0x1018 "kernel32.dll","QueryPerformanceCounter",0x1020 @@ -68,7 +68,7 @@ fn test_manifest_and_codegen_pipeline() { let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); - assert!(files.crt_rs.contains("strlen")); + assert!(files.crt_rs.contains("memset")); let acos = files.crt_rs.split_once("\"acos\"").unwrap().1; let (acos, _) = acos.split_once("registry.register_with_status").unwrap(); assert!(acos.contains("ServiceStatus::Stub")); @@ -79,7 +79,7 @@ fn test_manifest_and_codegen_pipeline() { assert!(!files.stubs_rs.contains("GetThreadId")); assert!(!files.stubs_rs.contains("DuplicateHandle")); assert!(!files.stubs_rs.contains("GetTickCount64")); - assert!(files.tests_rs.contains("generated_test_strlen")); + assert!(files.tests_rs.contains("generated_test_memset")); let out_dir = tmp_dir.join("out"); files.write_all(out_dir.to_str().unwrap()).unwrap(); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 89680512..e8ff9055 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -9,6 +9,7 @@ //! - Virtual memory: `VirtualAlloc`, `VirtualFree` //! - Xbox physical memory: `XMemAlloc`, `XMemFree` +mod crt; mod events; use crate::cpu::ExitReason; @@ -392,6 +393,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result { + if limit != 0 && address == 0 { + return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0))); + } + for offset in 0..limit.min(SCAN_BUDGET) { + let address = address + .checked_add(offset) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + if memory.read_u8(address).map_err(ExitReason::MemoryFault)? == 0 { + return Ok(offset); + } + } + if limit <= SCAN_BUDGET { + return Ok(limit); + } + Err(ExitReason::IllegalInstruction(0xFE)) +} + +pub(super) fn register(registry: &mut ImportRegistry) { + registry.register(UCRT, "strlen", |args, _, memory| { + string_length(memory, args.rcx, u64::MAX) + }); + registry.register(UCRT, "strnlen", |args, _, memory| { + string_length(memory, args.rcx, args.rdx) + }); + + for symbol in ["strlen", "strnlen"] { + registry.alias(CRT_STRING_API, UCRT, symbol); + registry.set_status(UCRT, symbol, ServiceStatus::Partial); + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index a9e0be06..3c114612 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1022,6 +1022,24 @@ fn test_guest_duplicates_thread_handle_through_iat() { assert_eq!(call("GetThreadId", copy), 0); } +#[test] +fn test_guest_crt_string_length_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + for module in ["ucrtbase.dll", "api-ms-win-crt-string-l1-1-0.dll"] { + // The fixture seeds the output slot with eight 0xff bytes followed by zeroed stack bytes. + for (symbol, address, bound, expected) in [ + ("strlen", PROCESS_FIXTURE_OUTPUT, 0, 8), + ("strlen", PROCESS_FIXTURE_OUTPUT + 8, 0, 0), + ("strnlen", PROCESS_FIXTURE_OUTPUT, 3, 3), + ("strnlen", PROCESS_FIXTURE_OUTPUT, 12, 8), + ("strnlen", PROCESS_FIXTURE_STACK_TOP, 0, 0), + ] { + let result = call_service_fixture(&state, module, symbol, &[address, bound]); + assert_eq!(result.execution.final_state.get(Register::Rax), expected); + } + } +} + #[test] fn test_guest_event_signaling_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index 9d4b8d54..44cd378f 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -140,6 +140,14 @@ References include Microsoft's [virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc), and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts. +### CRT byte strings + +The standard registry provides `strlen` and `strnlen` under UCRT and the CRT +string API set. They count bytes using checked guest memory. The scan stops at +a null byte or the requested bound for `strnlen`. A scan that would continue +past 1 MiB reports an unsupported-service fault. See the +[Microsoft CRT string-length contract](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strnlen-strnlen-s). + ### Event signaling The synthetic runtime supports unnamed manual-reset and auto-reset events From 7134523a08d474a2be6089d8cd8e831f50ffc227 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:21:38 -0500 Subject: [PATCH 06/82] Run CRT byte memory operations through checked guest spans Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 6 +-- crates/import-gen/src/codegen.rs | 35 ----------------- crates/import-gen/tests/pipeline.rs | 6 +-- crates/loader/src/services/crt.rs | 60 ++++++++++++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 39 +++++++++++++++++++ docs/interfaces.md | 5 +++ 7 files changed, 109 insertions(+), 44 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e7f1b5a..7d616a2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added bounded guest CRT byte fill, copy, move, and comparison services. + - Added guest CRT string length services for UCRT and its string API set. - Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 838a8b3d..bf5e65ce 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -205,7 +205,7 @@ impl SymbolDb { fn populate_crt_string(&mut self) { let m = "api-ms-win-crt-string-l1-1-0.dll"; for module in [m, "ucrtbase.dll"] { - for symbol in ["strlen", "strnlen"] { + for symbol in ["strlen", "strnlen", "memset", "memcpy", "memmove", "memcmp"] { self.ins(module, symbol, Classification::StandardService); } } @@ -223,10 +223,6 @@ impl SymbolDb { ("tolower", "tolower"), ("toupper", "toupper"), ("memchr", "memchr"), - ("memcmp", "memcmp"), - ("memcpy", "memcpy"), - ("memmove", "memmove"), - ("memset", "memset"), ("strcat", "strcat"), ("strcmp", "strcmp"), ("strcpy", "strcpy"), diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index d56b2379..155b4e65 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -347,41 +347,6 @@ fn symbol_to_ident_lower(sym: &str) -> String { /// Returns a dispatch body for CRT calls with a compatible guest ABI adapter. fn crt_dispatch_expr(symbol: &str) -> Option { Some(match symbol { - // memset(dst, val, count) -> dst - "memset" => r#"let dst = args.rcx; - let val = (args.rdx & 0xFF) as u8; - let count = args.r8 as usize; - for i in 0..count as u64 { - mem.write_u8(dst + i, val).map_err(ExitReason::MemoryFault)?; - } - Ok(dst)"# - .to_string(), - // memcpy(dst, src, n) -> dst - "memcpy" | "memmove" => r#"let dst = args.rcx; - let src = args.rdx; - let n = args.r8 as usize; - let mut buf = vec![0u8; n]; - for (i, slot) in buf.iter_mut().enumerate() { - *slot = mem.read_u8(src + i as u64).map_err(ExitReason::MemoryFault)?; - } - for (i, &b) in buf.iter().enumerate() { - mem.write_u8(dst + i as u64, b).map_err(ExitReason::MemoryFault)?; - } - Ok(dst)"# - .to_string(), - // memcmp(a, b, n) -> int - "memcmp" => r#"let a = args.rcx; - let b = args.rdx; - let n = args.r8 as usize; - for i in 0..n as u64 { - let ba = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?; - let bb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?; - if ba != bb { - return Ok((ba as i64 - bb as i64) as u64); - } - } - Ok(0)"# - .to_string(), // strcmp(a, b) -> int "strcmp" => r#"let a = args.rcx; let b = args.rdx; diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 179c6960..4f17a308 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -37,7 +37,7 @@ fn test_builtin_db_case_insensitive() { fn test_manifest_and_codegen_pipeline() { let csv_content = r#""module","symbol_or_ordinal","iat_rva" "api-ms-win-crt-math-l1-1-0.dll","acos",0x1000 -"api-ms-win-crt-string-l1-1-0.dll","memset",0x1008 +"api-ms-win-crt-string-l1-1-0.dll","strcmp",0x1008 "api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010 "custom.dll","UnknownCustomFunc",0x1018 "kernel32.dll","QueryPerformanceCounter",0x1020 @@ -68,7 +68,7 @@ fn test_manifest_and_codegen_pipeline() { let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); - assert!(files.crt_rs.contains("memset")); + assert!(files.crt_rs.contains("strcmp")); let acos = files.crt_rs.split_once("\"acos\"").unwrap().1; let (acos, _) = acos.split_once("registry.register_with_status").unwrap(); assert!(acos.contains("ServiceStatus::Stub")); @@ -79,7 +79,7 @@ fn test_manifest_and_codegen_pipeline() { assert!(!files.stubs_rs.contains("GetThreadId")); assert!(!files.stubs_rs.contains("DuplicateHandle")); assert!(!files.stubs_rs.contains("GetTickCount64")); - assert!(files.tests_rs.contains("generated_test_memset")); + assert!(files.tests_rs.contains("generated_test_strcmp")); let out_dir = tmp_dir.join("out"); files.write_all(out_dir.to_str().unwrap()).unwrap(); diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index 5f5440ed..2a66385f 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -28,6 +28,19 @@ fn string_length(memory: &GuestMemory, address: u64, limit: u64) -> Result Result, ExitReason> { + if count > SCAN_BUDGET { + return Err(ExitReason::IllegalInstruction(0xFE)); + } + let count = count as usize; + let mut buffer = Vec::new(); + buffer + .try_reserve_exact(count) + .map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?; + buffer.resize(count, fill); + Ok(buffer) +} + pub(super) fn register(registry: &mut ImportRegistry) { registry.register(UCRT, "strlen", |args, _, memory| { string_length(memory, args.rcx, u64::MAX) @@ -36,7 +49,52 @@ pub(super) fn register(registry: &mut ImportRegistry) { string_length(memory, args.rcx, args.rdx) }); - for symbol in ["strlen", "strnlen"] { + registry.register(UCRT, "memset", |args, _, memory| { + if args.r8 != 0 { + let buffer = transfer_buffer(args.r8, args.rdx as u8)?; + memory + .write_bytes(args.rcx, &buffer) + .map_err(ExitReason::MemoryFault)?; + } + Ok(args.rcx) + }); + + for symbol in ["memcpy", "memmove"] { + registry.register(UCRT, symbol, |args, _, memory| { + if args.r8 != 0 { + let mut buffer = transfer_buffer(args.r8, 0)?; + memory + .read_bytes(args.rdx, &mut buffer) + .map_err(ExitReason::MemoryFault)?; + memory + .write_bytes(args.rcx, &buffer) + .map_err(ExitReason::MemoryFault)?; + } + Ok(args.rcx) + }); + } + + registry.register(UCRT, "memcmp", |args, _, memory| { + if args.r8 == 0 { + return Ok(0); + } + let mut left = transfer_buffer(args.r8, 0)?; + let mut right = transfer_buffer(args.r8, 0)?; + memory + .read_bytes(args.rcx, &mut left) + .map_err(ExitReason::MemoryFault)?; + memory + .read_bytes(args.rdx, &mut right) + .map_err(ExitReason::MemoryFault)?; + let result = left + .iter() + .zip(right) + .find_map(|(&a, b)| (a != b).then_some(i32::from(a) - i32::from(b))) + .unwrap_or(0); + Ok(u64::from(result as u32)) + }); + + for symbol in ["strlen", "strnlen", "memset", "memcpy", "memmove", "memcmp"] { registry.alias(CRT_STRING_API, UCRT, symbol); registry.set_status(UCRT, symbol, ServiceStatus::Partial); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 3c114612..a4b39f7d 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1022,6 +1022,45 @@ fn test_guest_duplicates_thread_handle_through_iat() { assert_eq!(call("GetThreadId", copy), 0); } +#[test] +fn test_guest_crt_memory_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let slot = PROCESS_FIXTURE_OUTPUT; + let call = |symbol, args: &[u64]| { + call_service_fixture(&state, "api-ms-win-crt-string-l1-1-0.dll", symbol, args) + }; + let fill = call("memset", &[slot + 2, 0x141, 3]); + assert_eq!(fill.execution.final_state.get(Register::Rax), slot + 2); + assert_eq!( + fill.image.memory.read_u64(slot).unwrap().to_le_bytes(), + [255, 255, 65, 65, 65, 255, 255, 255] + ); + + let copy = call("memcpy", &[slot + 8, slot, 8]); + assert_eq!(copy.execution.final_state.get(Register::Rax), slot + 8); + assert_eq!(copy.image.memory.read_u64(slot + 8).unwrap(), u64::MAX); + + let shifted = call("memmove", &[slot + 1, slot, 8]); + assert_eq!(shifted.image.memory.read_u64(slot + 1).unwrap(), u64::MAX); + let shifted = call("memmove", &[slot, slot + 1, 8]); + assert_eq!( + shifted.image.memory.read_u64(slot).unwrap().to_le_bytes(), + [255, 255, 255, 255, 255, 255, 255, 0] + ); + + for (a, b, expected) in [ + (slot, slot + 8, 255), + (slot + 8, slot, -255), + (slot, slot, 0), + ] { + let result = call("memcmp", &[a, b, 8]); + assert_eq!( + result.execution.final_state.get(Register::Rax) as i32, + expected + ); + } +} + #[test] fn test_guest_crt_string_length_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index 44cd378f..82b225d8 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -148,6 +148,11 @@ a null byte or the requested bound for `strnlen`. A scan that would continue past 1 MiB reports an unsupported-service fault. See the [Microsoft CRT string-length contract](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strnlen-strnlen-s). +The same modules expose `memset`, `memcpy`, `memmove`, and `memcmp` for spans +up to 1 MiB. Each nonempty span must fit in one mapped guest region with the +required permissions. Writes validate the full destination before changing +bytes, and moves preserve the original source bytes when ranges overlap. + ### Event signaling The synthetic runtime supports unnamed manual-reset and auto-reset events From d76c7d061c8076ffc6b2dcf9f94737cb7d566c08 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:22:38 -0500 Subject: [PATCH 07/82] Compare CRT byte strings through checked guest reads Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/import-gen/src/classify.rs | 6 ++--- crates/import-gen/src/codegen.rs | 24 ------------------ crates/import-gen/tests/pipeline.rs | 6 ++--- crates/loader/src/services/crt.rs | 39 ++++++++++++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 20 +++++++++++++++ docs/interfaces.md | 4 +++ 7 files changed, 70 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d616a2a..57899573 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added checked guest CRT byte string comparison with `strcmp` and `strncmp`. + - Added bounded guest CRT byte fill, copy, move, and comparison services. - Added guest CRT string length services for UCRT and its string API set. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index bf5e65ce..08d6a053 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -205,7 +205,9 @@ impl SymbolDb { fn populate_crt_string(&mut self) { let m = "api-ms-win-crt-string-l1-1-0.dll"; for module in [m, "ucrtbase.dll"] { - for symbol in ["strlen", "strnlen", "memset", "memcpy", "memmove", "memcmp"] { + for symbol in [ + "strlen", "strnlen", "strcmp", "strncmp", "memset", "memcpy", "memmove", "memcmp", + ] { self.ins(module, symbol, Classification::StandardService); } } @@ -224,11 +226,9 @@ impl SymbolDb { ("toupper", "toupper"), ("memchr", "memchr"), ("strcat", "strcat"), - ("strcmp", "strcmp"), ("strcpy", "strcpy"), ("strcspn", "strcspn"), ("strncat", "strncat"), - ("strncmp", "strncmp"), ("strncpy", "strncpy"), ("strpbrk", "strpbrk"), ("strspn", "strspn"), diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 155b4e65..78965653 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -347,30 +347,6 @@ fn symbol_to_ident_lower(sym: &str) -> String { /// Returns a dispatch body for CRT calls with a compatible guest ABI adapter. fn crt_dispatch_expr(symbol: &str) -> Option { Some(match symbol { - // strcmp(a, b) -> int - "strcmp" => r#"let a = args.rcx; - let b = args.rdx; - let mut i = 0u64; - loop { - let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?; - let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?; - if ca != cb { return Ok((ca as i64 - cb as i64) as u64); } - if ca == 0 { return Ok(0); } - i += 1; - }"# - .to_string(), - // strncmp(a, b, n) -> int - "strncmp" => r#"let a = args.rcx; - let b = args.rdx; - let n = args.r8 as usize; - for i in 0..n as u64 { - let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?; - let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?; - if ca != cb { return Ok((ca as i64 - cb as i64) as u64); } - if ca == 0 { return Ok(0); } - } - Ok(0)"# - .to_string(), // abs(int) -> int "abs" | "labs" => r#"let x = args.rcx as i32; Ok(x.abs() as u64)"# diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 4f17a308..39da5ac5 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -37,7 +37,7 @@ fn test_builtin_db_case_insensitive() { fn test_manifest_and_codegen_pipeline() { let csv_content = r#""module","symbol_or_ordinal","iat_rva" "api-ms-win-crt-math-l1-1-0.dll","acos",0x1000 -"api-ms-win-crt-string-l1-1-0.dll","strcmp",0x1008 +"api-ms-win-crt-string-l1-1-0.dll","tolower",0x1008 "api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010 "custom.dll","UnknownCustomFunc",0x1018 "kernel32.dll","QueryPerformanceCounter",0x1020 @@ -68,7 +68,7 @@ fn test_manifest_and_codegen_pipeline() { let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); - assert!(files.crt_rs.contains("strcmp")); + assert!(files.crt_rs.contains("tolower")); let acos = files.crt_rs.split_once("\"acos\"").unwrap().1; let (acos, _) = acos.split_once("registry.register_with_status").unwrap(); assert!(acos.contains("ServiceStatus::Stub")); @@ -79,7 +79,7 @@ fn test_manifest_and_codegen_pipeline() { assert!(!files.stubs_rs.contains("GetThreadId")); assert!(!files.stubs_rs.contains("DuplicateHandle")); assert!(!files.stubs_rs.contains("GetTickCount64")); - assert!(files.tests_rs.contains("generated_test_strcmp")); + assert!(files.tests_rs.contains("generated_test_tolower")); let out_dir = tmp_dir.join("out"); files.write_all(out_dir.to_str().unwrap()).unwrap(); diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index 2a66385f..0aaa600e 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -28,6 +28,34 @@ fn string_length(memory: &GuestMemory, address: u64, limit: u64) -> Result Result { + for offset in 0..limit.min(SCAN_BUDGET) { + let read = |base: u64| { + if base == 0 { + return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0))); + } + let address = base + .checked_add(offset) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + memory.read_u8(address).map_err(ExitReason::MemoryFault) + }; + let a = read(left)?; + let b = read(right)?; + if a != b || a == 0 { + return Ok(u64::from((i32::from(a) - i32::from(b)) as u32)); + } + } + if limit <= SCAN_BUDGET { + return Ok(0); + } + Err(ExitReason::IllegalInstruction(0xFE)) +} + fn transfer_buffer(count: u64, fill: u8) -> Result, ExitReason> { if count > SCAN_BUDGET { return Err(ExitReason::IllegalInstruction(0xFE)); @@ -49,6 +77,13 @@ pub(super) fn register(registry: &mut ImportRegistry) { string_length(memory, args.rcx, args.rdx) }); + registry.register(UCRT, "strcmp", |args, _, memory| { + compare_strings(memory, args.rcx, args.rdx, u64::MAX) + }); + registry.register(UCRT, "strncmp", |args, _, memory| { + compare_strings(memory, args.rcx, args.rdx, args.r8) + }); + registry.register(UCRT, "memset", |args, _, memory| { if args.r8 != 0 { let buffer = transfer_buffer(args.r8, args.rdx as u8)?; @@ -94,7 +129,9 @@ pub(super) fn register(registry: &mut ImportRegistry) { Ok(u64::from(result as u32)) }); - for symbol in ["strlen", "strnlen", "memset", "memcpy", "memmove", "memcmp"] { + for symbol in [ + "strlen", "strnlen", "strcmp", "strncmp", "memset", "memcpy", "memmove", "memcmp", + ] { registry.alias(CRT_STRING_API, UCRT, symbol); registry.set_status(UCRT, symbol, ServiceStatus::Partial); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index a4b39f7d..74b85530 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1061,6 +1061,26 @@ fn test_guest_crt_memory_through_iat() { } } +#[test] +fn test_guest_crt_string_comparison_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let slot = PROCESS_FIXTURE_OUTPUT; + for (symbol, a, b, limit, expected) in [ + ("strcmp", slot, slot + 8, 0, 255), + ("strcmp", slot + 8, slot, 0, -255), + ("strcmp", slot, slot, 0, 0), + ("strncmp", slot, slot + 1, 7, 0), + ("strncmp", slot, slot + 1, 8, 255), + ("strncmp", u64::MAX, u64::MAX, 0, 0), + ] { + let result = call_service_fixture(&state, "ucrtbase.dll", symbol, &[a, b, limit]); + assert_eq!( + result.execution.final_state.get(Register::Rax) as i32, + expected + ); + } +} + #[test] fn test_guest_crt_string_length_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index 82b225d8..ed61b7c0 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -148,6 +148,10 @@ a null byte or the requested bound for `strnlen`. A scan that would continue past 1 MiB reports an unsupported-service fault. See the [Microsoft CRT string-length contract](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strnlen-strnlen-s). +The same modules expose `strcmp` and `strncmp`. These compare unsigned bytes +and stop at the first difference, null byte, or supplied comparison bound. +They share the 1 MiB scan budget. + The same modules expose `memset`, `memcpy`, `memmove`, and `memcmp` for spans up to 1 MiB. Each nonempty span must fit in one mapped guest region with the required permissions. Writes validate the full destination before changing From 4c1ac39c7e6b049dd24ea1187b159feee5a09108 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:23:47 -0500 Subject: [PATCH 08/82] Support Win64 wide string length and comparison Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 6 +- crates/loader/src/services/crt.rs | 102 ++++++++++++++++++----------- crates/loader/tests/runtime_x15.rs | 22 +++++++ docs/interfaces.md | 6 +- 5 files changed, 95 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57899573..13188b41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest CRT wide-string length and comparison using Windows 16-bit code units. + - Added checked guest CRT byte string comparison with `strcmp` and `strncmp`. - Added bounded guest CRT byte fill, copy, move, and comparison services. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 08d6a053..53e2cec7 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -206,7 +206,8 @@ impl SymbolDb { let m = "api-ms-win-crt-string-l1-1-0.dll"; for module in [m, "ucrtbase.dll"] { for symbol in [ - "strlen", "strnlen", "strcmp", "strncmp", "memset", "memcpy", "memmove", "memcmp", + "strlen", "strnlen", "strcmp", "strncmp", "wcslen", "wcsnlen", "wcscmp", "wcsncmp", + "memset", "memcpy", "memmove", "memcmp", ] { self.ins(module, symbol, Classification::StandardService); } @@ -234,11 +235,8 @@ impl SymbolDb { ("strspn", "strspn"), ("strstr", "strstr"), ("strtok", "strtok"), - ("wcslen", "wcslen"), ("wcscat", "wcscat"), - ("wcscmp", "wcscmp"), ("wcscpy", "wcscpy"), - ("wcsncmp", "wcsncmp"), ("wcsncpy", "wcsncpy"), ("wcsstr", "wcsstr"), ("wcstok", "wcstok"), diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index 0aaa600e..2e596ad3 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -10,19 +10,48 @@ const SCAN_BUDGET: u64 = 1_048_576; const UCRT: &str = "ucrtbase.dll"; const CRT_STRING_API: &str = "api-ms-win-crt-string-l1-1-0.dll"; -fn string_length(memory: &GuestMemory, address: u64, limit: u64) -> Result { - if limit != 0 && address == 0 { - return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0))); +#[derive(Clone, Copy)] +enum StringUnit { + Byte, + Wide, +} + +impl StringUnit { + fn width(self) -> u64 { + match self { + Self::Byte => 1, + Self::Wide => 2, + } } - for offset in 0..limit.min(SCAN_BUDGET) { - let address = address - .checked_add(offset) + + fn read(self, memory: &GuestMemory, base: u64, offset: u64) -> Result { + if base == 0 { + return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0))); + } + let address = base + .checked_add(offset * self.width()) .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; - if memory.read_u8(address).map_err(ExitReason::MemoryFault)? == 0 { + match self { + Self::Byte => memory.read_u8(address).map(u16::from), + Self::Wide => memory.read_u16(address), + } + .map_err(ExitReason::MemoryFault) + } +} + +fn string_length( + memory: &GuestMemory, + address: u64, + limit: u64, + unit: StringUnit, +) -> Result { + let budget = SCAN_BUDGET / unit.width(); + for offset in 0..limit.min(budget) { + if unit.read(memory, address, offset)? == 0 { return Ok(offset); } } - if limit <= SCAN_BUDGET { + if limit <= budget { return Ok(limit); } Err(ExitReason::IllegalInstruction(0xFE)) @@ -33,24 +62,17 @@ fn compare_strings( left: u64, right: u64, limit: u64, + unit: StringUnit, ) -> Result { - for offset in 0..limit.min(SCAN_BUDGET) { - let read = |base: u64| { - if base == 0 { - return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0))); - } - let address = base - .checked_add(offset) - .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; - memory.read_u8(address).map_err(ExitReason::MemoryFault) - }; - let a = read(left)?; - let b = read(right)?; + let budget = SCAN_BUDGET / unit.width(); + for offset in 0..limit.min(budget) { + let a = unit.read(memory, left, offset)?; + let b = unit.read(memory, right, offset)?; if a != b || a == 0 { return Ok(u64::from((i32::from(a) - i32::from(b)) as u32)); } } - if limit <= SCAN_BUDGET { + if limit <= budget { return Ok(0); } Err(ExitReason::IllegalInstruction(0xFE)) @@ -70,19 +92,27 @@ fn transfer_buffer(count: u64, fill: u8) -> Result, ExitReason> { } pub(super) fn register(registry: &mut ImportRegistry) { - registry.register(UCRT, "strlen", |args, _, memory| { - string_length(memory, args.rcx, u64::MAX) - }); - registry.register(UCRT, "strnlen", |args, _, memory| { - string_length(memory, args.rcx, args.rdx) - }); - - registry.register(UCRT, "strcmp", |args, _, memory| { - compare_strings(memory, args.rcx, args.rdx, u64::MAX) - }); - registry.register(UCRT, "strncmp", |args, _, memory| { - compare_strings(memory, args.rcx, args.rdx, args.r8) - }); + for (length, bounded_length, compare, bounded_compare, unit) in [ + ("strlen", "strnlen", "strcmp", "strncmp", StringUnit::Byte), + ("wcslen", "wcsnlen", "wcscmp", "wcsncmp", StringUnit::Wide), + ] { + registry.register(UCRT, length, move |args, _, memory| { + string_length(memory, args.rcx, u64::MAX, unit) + }); + registry.register(UCRT, bounded_length, move |args, _, memory| { + string_length(memory, args.rcx, args.rdx, unit) + }); + registry.register(UCRT, compare, move |args, _, memory| { + compare_strings(memory, args.rcx, args.rdx, u64::MAX, unit) + }); + registry.register(UCRT, bounded_compare, move |args, _, memory| { + compare_strings(memory, args.rcx, args.rdx, args.r8, unit) + }); + for symbol in [length, bounded_length, compare, bounded_compare] { + registry.alias(CRT_STRING_API, UCRT, symbol); + registry.set_status(UCRT, symbol, ServiceStatus::Partial); + } + } registry.register(UCRT, "memset", |args, _, memory| { if args.r8 != 0 { @@ -129,9 +159,7 @@ pub(super) fn register(registry: &mut ImportRegistry) { Ok(u64::from(result as u32)) }); - for symbol in [ - "strlen", "strnlen", "strcmp", "strncmp", "memset", "memcpy", "memmove", "memcmp", - ] { + for symbol in ["memset", "memcpy", "memmove", "memcmp"] { registry.alias(CRT_STRING_API, UCRT, symbol); registry.set_status(UCRT, symbol, ServiceStatus::Partial); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 74b85530..68b97cf7 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1081,6 +1081,28 @@ fn test_guest_crt_string_comparison_through_iat() { } } +#[test] +fn test_guest_crt_wide_strings_use_16_bit_units() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let slot = PROCESS_FIXTURE_OUTPUT; + for module in ["ucrtbase.dll", "api-ms-win-crt-string-l1-1-0.dll"] { + for (symbol, args, expected) in [ + ("wcslen", [slot, 0, 0], 4), + ("wcsnlen", [slot, 3, 0], 3), + ("wcsnlen", [slot, 7, 0], 4), + ("wcscmp", [slot + 8, slot, 0], -65535), + ("wcsncmp", [slot, slot + 2, 3], 0), + ("wcsncmp", [slot, slot + 2, 4], 65535), + ] { + let result = call_service_fixture(&state, module, symbol, &args); + assert_eq!( + result.execution.final_state.get(Register::Rax) as i32, + expected + ); + } + } +} + #[test] fn test_guest_crt_string_length_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index ed61b7c0..9e38e10a 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -140,7 +140,7 @@ References include Microsoft's [virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc), and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts. -### CRT byte strings +### CRT strings and byte memory The standard registry provides `strlen` and `strnlen` under UCRT and the CRT string API set. They count bytes using checked guest memory. The scan stops at @@ -150,7 +150,9 @@ past 1 MiB reports an unsupported-service fault. See the The same modules expose `strcmp` and `strncmp`. These compare unsigned bytes and stop at the first difference, null byte, or supplied comparison bound. -They share the 1 MiB scan budget. +They share the 1 MiB scan budget. `wcslen`, `wcsnlen`, `wcscmp`, and +`wcsncmp` apply the same rules to unsigned 16-bit Windows code units. +Counts and bounds for the wide variants are in code units. The same modules expose `memset`, `memcpy`, `memmove`, and `memcmp` for spans up to 1 MiB. Each nonempty span must fit in one mapped guest region with the From fa6a52ab93ef4fd8b43c928912b4ab919ddd3b8f Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:24:40 -0500 Subject: [PATCH 09/82] Catalog Win64 wide string and byte move signatures Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/metadata.rs | 63 +++++++++++++++++++++++++++++ crates/import-gen/tests/pipeline.rs | 33 +++++++++++++++ 3 files changed, 98 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13188b41..4f34e94e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog. + - Added guest CRT wide-string length and comparison using Windows 16-bit code units. - Added checked guest CRT byte string comparison with `strcmp` and `strncmp`. diff --git a/crates/import-gen/src/metadata.rs b/crates/import-gen/src/metadata.rs index 42e60a72..d5ee2f3e 100644 --- a/crates/import-gen/src/metadata.rs +++ b/crates/import-gen/src/metadata.rs @@ -221,6 +221,42 @@ impl MetadataCatalog { "", "Compares up to count characters of two strings", ); + self.add( + "ucrtbase.dll", + "wcslen", + AbiType::U64, + vec![("str", AbiType::StringWide)], + "", + "Counts 16-bit Windows code units before the terminator", + ); + self.add( + "ucrtbase.dll", + "wcsnlen", + AbiType::U64, + vec![("str", AbiType::StringWide), ("count", AbiType::U64)], + "", + "Counts 16-bit Windows code units up to the supplied bound", + ); + self.add( + "ucrtbase.dll", + "wcscmp", + AbiType::I32, + vec![("str1", AbiType::StringWide), ("str2", AbiType::StringWide)], + "", + "Compares two strings of 16-bit Windows code units", + ); + self.add( + "ucrtbase.dll", + "wcsncmp", + AbiType::I32, + vec![ + ("str1", AbiType::StringWide), + ("str2", AbiType::StringWide), + ("count", AbiType::U64), + ], + "", + "Compares up to count 16-bit Windows code units of two strings", + ); self.add( "ucrtbase.dll", "memset", @@ -269,6 +305,33 @@ impl MetadataCatalog { "", "Copies memory between non-overlapping guest regions", ); + self.add( + "ucrtbase.dll", + "memmove", + AbiType::Pointer { + is_const: false, + pointee: "void".into(), + }, + vec![ + ( + "dest", + AbiType::Pointer { + is_const: false, + pointee: "void".into(), + }, + ), + ( + "src", + AbiType::Pointer { + is_const: true, + pointee: "void".into(), + }, + ), + ("count", AbiType::U64), + ], + "", + "Copies memory between guest ranges that may overlap", + ); self.add( "ucrtbase.dll", "memcmp", diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 39da5ac5..84e0fc47 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -88,3 +88,36 @@ fn test_manifest_and_codegen_pipeline() { assert!(out_dir.join("generated_tests.rs").exists()); assert!(out_dir.join("generated_manifest.md").exists()); } + +#[test] +fn test_catalog_describes_windows_wide_string_signatures() { + use xenora_import_gen::{AbiType, MetadataCatalog}; + + let catalog = MetadataCatalog::builtin(); + let wide = AbiType::StringWide; + for (symbol, return_type, parameters) in [ + ("wcslen", AbiType::U64, vec![wide.clone()]), + ("wcsnlen", AbiType::U64, vec![wide.clone(), AbiType::U64]), + ("wcscmp", AbiType::I32, vec![wide.clone(), wide.clone()]), + ( + "wcsncmp", + AbiType::I32, + vec![wide.clone(), wide, AbiType::U64], + ), + ] { + let signature = catalog.lookup("ucrtbase.dll", symbol).unwrap(); + assert_eq!(signature.return_type, return_type); + assert_eq!( + signature + .params + .iter() + .map(|p| p.abi_type.clone()) + .collect::>(), + parameters + ); + } + let copy = catalog.lookup("ucrtbase.dll", "memcpy").unwrap(); + let move_ = catalog.lookup("ucrtbase.dll", "memmove").unwrap(); + assert_eq!(move_.params, copy.params); + assert_eq!(move_.return_type, copy.return_type); +} From 6b068a225d235d732709a4f444d17b87fb93916c Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:26:23 -0500 Subject: [PATCH 10/82] Expose a bounded default process heap to Win64 guests Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 5 ++ crates/loader/src/memory.rs | 68 +++++++++++++++++++++---- crates/loader/src/services.rs | 2 + crates/loader/src/services/heap.rs | 64 +++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 82 ++++++++++++++++++++++++++++++ docs/interfaces.md | 9 ++++ 7 files changed, 223 insertions(+), 9 deletions(-) create mode 100644 crates/loader/src/services/heap.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f34e94e..e2a8fa8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added the synthetic default process heap with allocation, size queries, and release. + - Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog. - Added guest CRT wide-string length and comparison using Windows 16-bit code units. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 53e2cec7..d07b6e7a 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -677,6 +677,11 @@ impl SymbolDb { // ---- Win32 kernel / process -------------------------------------------- fn populate_win32_kernel(&mut self) { + for module in ["kernel32.dll", "api-ms-win-core-heap-l1-1-0.dll"] { + for symbol in ["GetProcessHeap", "HeapAlloc", "HeapSize", "HeapFree"] { + self.ins(module, symbol, Classification::StandardService); + } + } let p1 = "api-ms-win-core-processthreads-l1-1-0.dll"; let p2 = "api-ms-win-core-processthreads-l1-1-2.dll"; for module in [p1, "kernel32.dll"] { diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index fa8aabc9..702532c3 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -85,12 +85,19 @@ impl fmt::Display for MemoryError { impl std::error::Error for MemoryError {} +#[derive(Clone, Copy, PartialEq, Eq)] +enum AllocationKind { + ImageOrStatic, + Virtual, + Heap, +} + #[derive(Clone)] struct MappedRegion { base: u64, data: Vec, permissions: MemoryPermissions, - virtual_allocation: bool, + allocation: AllocationKind, } impl MappedRegion { @@ -136,7 +143,13 @@ impl GuestMemory { permissions: MemoryPermissions, initial_data: &[u8], ) -> Result<(), MemoryError> { - self.insert_region(base, size, permissions, initial_data, false) + self.insert_region( + base, + size, + permissions, + initial_data, + AllocationKind::ImageOrStatic, + ) } fn insert_region( @@ -145,7 +158,7 @@ impl GuestMemory { size: usize, permissions: MemoryPermissions, initial_data: &[u8], - virtual_allocation: bool, + allocation: AllocationKind, ) -> Result<(), MemoryError> { let size_u64 = size as u64; let end = base.checked_add(size_u64).ok_or(MemoryError::Overflow)?; @@ -170,7 +183,7 @@ impl GuestMemory { base, data, permissions, - virtual_allocation, + allocation, }); self.regions.sort_by_key(|r| r.base); Ok(()) @@ -182,15 +195,37 @@ impl GuestMemory { size: usize, permissions: MemoryPermissions, ) -> Result { - // Bound the host storage retained by the synthetic VirtualAlloc service. + self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual) + } + + pub(crate) fn map_heap_allocation(&mut self, size: usize) -> Result { + self.map_dynamic_allocation(0, size, MemoryPermissions::READ_WRITE, AllocationKind::Heap) + } + + fn map_dynamic_allocation( + &mut self, + requested_base: u64, + size: usize, + permissions: MemoryPermissions, + allocation: AllocationKind, + ) -> Result { + // Bound retained host storage independently for each allocation kind. const MAX_VIRTUAL_BYTES: usize = 64 * 1024 * 1024; let allocated: usize = self .regions .iter() - .filter(|region| region.virtual_allocation) + .filter(|region| region.allocation == allocation) .map(|region| region.data.len()) .sum(); - if size > MAX_VIRTUAL_BYTES - allocated { + if size > MAX_VIRTUAL_BYTES - allocated + || (allocation == AllocationKind::Heap + && self + .regions + .iter() + .filter(|r| r.allocation == allocation) + .count() + >= 4096) + { return Err(MemoryError::AllocationFailed); } @@ -210,15 +245,30 @@ impl GuestMemory { } } } - self.insert_region(base, size, permissions, &[], true)?; + self.insert_region(base, size, permissions, &[], allocation)?; Ok(base) } pub(crate) fn release_virtual_allocation(&mut self, base: u64) -> bool { + self.release_dynamic_allocation(base, AllocationKind::Virtual) + } + + pub(crate) fn release_heap_allocation(&mut self, base: u64) -> bool { + self.release_dynamic_allocation(base, AllocationKind::Heap) + } + + pub(crate) fn heap_allocation_size(&self, base: u64) -> Option { + self.regions + .iter() + .find(|region| region.base == base && region.allocation == AllocationKind::Heap) + .map(|region| region.data.len()) + } + + fn release_dynamic_allocation(&mut self, base: u64, allocation: AllocationKind) -> bool { let Some(index) = self .regions .iter() - .position(|region| region.base == base && region.virtual_allocation) + .position(|region| region.base == base && region.allocation == allocation) else { return false; }; diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index e8ff9055..621e8564 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -11,6 +11,7 @@ mod crt; mod events; +mod heap; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; @@ -394,6 +395,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc) { + registry.register(KERNEL32, "GetProcessHeap", |_, _, _| Ok(PROCESS_HEAP)); + + registry.register(KERNEL32, "HeapAlloc", |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + let size = args.get(2, memory).map_err(ExitReason::MemoryFault)?; + if handle != PROCESS_HEAP || flags & !HEAP_ZERO_MEMORY != 0 { + return Ok(0); + } + Ok(memory + .map_heap_allocation(size.max(1) as usize) + .unwrap_or(0)) + }); + + registry.register(KERNEL32, "HeapSize", |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; + if handle != PROCESS_HEAP || flags != 0 { + return Ok(u64::MAX); + } + Ok(memory + .heap_allocation_size(address) + .map_or(u64::MAX, |size| size as u64)) + }); + + let state = Arc::clone(state); + registry.register(KERNEL32, "HeapFree", move |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; + if handle != PROCESS_HEAP { + return state.fail(ERROR_INVALID_HANDLE, 0); + } + if flags != 0 { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + if address != 0 && !memory.release_heap_allocation(address) { + return state.fail(ERROR_INVALID_ADDRESS, 0); + } + Ok(1) + }); + + for symbol in ["GetProcessHeap", "HeapAlloc", "HeapSize", "HeapFree"] { + registry.alias(HEAP_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 68b97cf7..0e4053b4 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1192,6 +1192,88 @@ fn test_guest_event_signaling_through_iat() { assert_eq!(call(kernel, "CloseHandle", &[copy]), 1); } +#[test] +fn test_guest_process_heap_through_iat() { + const IMAGE: u64 = 0x140000000; + const MODULE: &str = "api-ms-win-core-heap-l1-1-0.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let heap = call_service_fixture(&state, MODULE, "GetProcessHeap", &[]) + .execution + .final_state + .get(Register::Rax); + assert_ne!(heap, 0); + + let allocate = |size, followup| { + let mut code = vec![0x48, 0x83, 0xec, 0x28]; + for (register, value) in [ + ([0x48, 0xb9], heap), + ([0x48, 0xba], 8), + ([0x49, 0xb8], size), + ] { + code.extend_from_slice(®ister); + code.extend_from_slice(&value.to_le_bytes()); + } + append_import_call(&mut code, 0x2060); + // Preserve the address in RBX for inspection and pass it in R8. + code.extend_from_slice(&[0x48, 0x89, 0xc3, 0x49, 0x89, 0xc0]); + code.extend_from_slice(&[0x48, 0xb9]); // Reload the heap handle. + code.extend_from_slice(&heap.to_le_bytes()); + code.extend_from_slice(&[0x48, 0xba]); // dwFlags = 0 + code.extend_from_slice(&0u64.to_le_bytes()); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import(MODULE, "HeapAlloc") + .add_import(MODULE, followup) + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 2); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result + }; + + let allocated = allocate(19, "HeapSize"); + let address = allocated.execution.final_state.get(Register::Rbx); + assert_ne!(address, 0); + assert_eq!(address % 16, 0); + assert_eq!(allocated.execution.final_state.get(Register::Rax), 19); + let mut bytes = [1; 19]; + allocated + .image + .memory + .read_bytes(address, &mut bytes) + .unwrap(); + assert_eq!(bytes, [0; 19]); + + let freed = allocate(19, "HeapFree"); + assert_eq!(freed.execution.final_state.get(Register::Rax), 1); + assert!( + freed + .image + .memory + .read_u8(freed.execution.final_state.get(Register::Rbx)) + .is_err() + ); + + let oversized = allocate(64 * 1024 * 1024 + 1, "HeapSize"); + assert_eq!(oversized.execution.final_state.get(Register::Rbx), 0); + assert_eq!(oversized.execution.final_state.get(Register::Rax), u64::MAX); +} + #[test] fn test_virtual_allocation_release_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index 9e38e10a..6855c1c9 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -159,6 +159,15 @@ up to 1 MiB. Each nonempty span must fit in one mapped guest region with the required permissions. Writes validate the full destination before changing bytes, and moves preserve the original source bytes when ranges overlap. +### Default process heap + +`GetProcessHeap`, `HeapAlloc`, `HeapSize`, and `HeapFree` expose a single +synthetic heap. Allocations are at least 16-byte aligned and zero initialized. +A zero-size request allocates one byte. The heap is bounded to 64 MiB and +4096 live allocations. Heap and virtual allocations have distinct ownership. +Private heaps, reallocation, and flags other than `HEAP_ZERO_MEMORY` on +allocation remain unsupported. See the [Windows heap API reference](https://learn.microsoft.com/windows/win32/api/heapapi/). + ### Event signaling The synthetic runtime supports unnamed manual-reset and auto-reset events From cd01d04a96a11194804466b6c43431750a536fbb Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:27:52 -0500 Subject: [PATCH 11/82] Resize default guest heap blocks with transactional failure Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 8 +- crates/loader/src/memory.rs | 132 +++++++++++++++++++++++------ crates/loader/src/services/heap.rs | 23 ++++- crates/loader/tests/runtime_x15.rs | 26 +++++- docs/interfaces.md | 5 +- 6 files changed, 164 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e2a8fa8e..bee6e05b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added default guest heap reallocation with data preservation and an in-place-only option. + - Added the synthetic default process heap with allocation, size queries, and release. - Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index d07b6e7a..2958bea4 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -678,7 +678,13 @@ impl SymbolDb { fn populate_win32_kernel(&mut self) { for module in ["kernel32.dll", "api-ms-win-core-heap-l1-1-0.dll"] { - for symbol in ["GetProcessHeap", "HeapAlloc", "HeapSize", "HeapFree"] { + for symbol in [ + "GetProcessHeap", + "HeapAlloc", + "HeapReAlloc", + "HeapSize", + "HeapFree", + ] { self.ins(module, symbol, Classification::StandardService); } } diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index 702532c3..83a4f431 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -85,6 +85,8 @@ impl fmt::Display for MemoryError { impl std::error::Error for MemoryError {} +const MAX_DYNAMIC_BYTES: usize = 64 * 1024 * 1024; + #[derive(Clone, Copy, PartialEq, Eq)] enum AllocationKind { ImageOrStatic, @@ -210,14 +212,8 @@ impl GuestMemory { allocation: AllocationKind, ) -> Result { // Bound retained host storage independently for each allocation kind. - const MAX_VIRTUAL_BYTES: usize = 64 * 1024 * 1024; - let allocated: usize = self - .regions - .iter() - .filter(|region| region.allocation == allocation) - .map(|region| region.data.len()) - .sum(); - if size > MAX_VIRTUAL_BYTES - allocated + let allocated = self.dynamic_bytes(allocation); + if size > MAX_DYNAMIC_BYTES - allocated || (allocation == AllocationKind::Heap && self .regions @@ -229,26 +225,86 @@ impl GuestMemory { return Err(MemoryError::AllocationFailed); } - let mut base = requested_base; - if base == 0 { - base = 0x0000_0003_0000_0000; - for region in &self.regions { - let end = base.checked_add(size as u64).ok_or(MemoryError::Overflow)?; - if end <= region.base { - break; - } - let region_end = region.base + region.data.len() as u64; - if base < region_end { - base = region_end - .checked_next_multiple_of(ALLOCATION_GRANULARITY) - .ok_or(MemoryError::Overflow)?; - } - } - } + let base = if requested_base == 0 { + self.find_dynamic_base(size)? + } else { + requested_base + }; self.insert_region(base, size, permissions, &[], allocation)?; Ok(base) } + fn dynamic_bytes(&self, allocation: AllocationKind) -> usize { + self.regions + .iter() + .filter(|region| region.allocation == allocation) + .map(|region| region.data.len()) + .sum() + } + + fn find_dynamic_base(&self, size: usize) -> Result { + let mut base = 0x0000_0003_0000_0000u64; + for region in &self.regions { + let end = base.checked_add(size as u64).ok_or(MemoryError::Overflow)?; + if end <= region.base { + return Ok(base); + } + let region_end = region.base + region.data.len() as u64; + if base < region_end { + base = region_end + .checked_next_multiple_of(ALLOCATION_GRANULARITY) + .ok_or(MemoryError::Overflow)?; + } + } + base.checked_add(size as u64).ok_or(MemoryError::Overflow)?; + Ok(base) + } + + pub(crate) fn resize_heap_allocation( + &mut self, + base: u64, + size: usize, + in_place_only: bool, + ) -> Result { + let index = self + .regions + .iter() + .position(|region| region.base == base && region.allocation == AllocationKind::Heap) + .ok_or(MemoryError::UnmappedAddress(base))?; + let previous = self.regions[index].data.len(); + let other_bytes = self.dynamic_bytes(AllocationKind::Heap) - previous; + if size > MAX_DYNAMIC_BYTES - other_bytes { + return Err(MemoryError::AllocationFailed); + } + + let boundary = self + .regions + .get(index + 1) + .map_or(u64::MAX, |next| next.base); + let destination = if (size as u64) <= boundary - base { + base + } else if in_place_only { + return Err(MemoryError::AllocationFailed); + } else { + self.find_dynamic_base(size)? + }; + + let region = &mut self.regions[index]; + region + .data + .try_reserve_exact(size.saturating_sub(previous)) + .map_err(|_| MemoryError::AllocationFailed)?; + region.data.resize(size, 0); + if size < previous { + region.data.shrink_to_fit(); + } + if destination != base { + region.base = destination; + self.regions.sort_by_key(|region| region.base); + } + Ok(destination) + } + pub(crate) fn release_virtual_allocation(&mut self, base: u64) -> bool { self.release_dynamic_allocation(base, AllocationKind::Virtual) } @@ -415,3 +471,31 @@ impl GuestMemory { self.write_bytes(address, &value.to_le_bytes()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heap_resize_moves_only_when_allowed_and_preserves_bytes() { + let mut memory = GuestMemory::new(); + let base = memory.map_heap_allocation(19).unwrap(); + let neighbor = memory.map_heap_allocation(1).unwrap(); + memory.write_u8(base, 0xab).unwrap(); + memory.write_u8(neighbor, 0xcd).unwrap(); + let growth = (neighbor - base) as usize + 1; + assert_eq!( + memory.resize_heap_allocation(base, growth, true), + Err(MemoryError::AllocationFailed) + ); + assert_eq!(memory.heap_allocation_size(base), Some(19)); + let moved = memory.resize_heap_allocation(base, growth, false).unwrap(); + assert_ne!(moved, base); + assert_eq!(memory.read_u8(moved), Ok(0xab)); + assert_eq!(memory.read_u8(neighbor), Ok(0xcd)); + assert_eq!(memory.read_u8(moved + growth as u64 - 1), Ok(0)); + assert_eq!(memory.heap_allocation_size(base), None); + assert_eq!(memory.resize_heap_allocation(moved, 1, true), Ok(moved)); + assert_eq!(memory.heap_allocation_size(moved), Some(1)); + } +} diff --git a/crates/loader/src/services/heap.rs b/crates/loader/src/services/heap.rs index ebf2ddef..ed3539be 100644 --- a/crates/loader/src/services/heap.rs +++ b/crates/loader/src/services/heap.rs @@ -11,6 +11,7 @@ use std::sync::Arc; const PROCESS_HEAP: u64 = u64::MAX - 2; const HEAP_ZERO_MEMORY: u32 = 8; +const HEAP_REALLOC_IN_PLACE_ONLY: u32 = 16; const HEAP_API: &str = "api-ms-win-core-heap-l1-1-0.dll"; pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { @@ -28,6 +29,20 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .unwrap_or(0)) }); + registry.register(KERNEL32, "HeapReAlloc", |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; + let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; + let size = args.get(3, memory).map_err(ExitReason::MemoryFault)?; + if handle != PROCESS_HEAP || flags & !(HEAP_ZERO_MEMORY | HEAP_REALLOC_IN_PLACE_ONLY) != 0 { + return Ok(0); + } + let in_place_only = flags & HEAP_REALLOC_IN_PLACE_ONLY != 0; + Ok(memory + .resize_heap_allocation(address, size.max(1) as usize, in_place_only) + .unwrap_or(0)) + }); + registry.register(KERNEL32, "HeapSize", |args, _, memory| { let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; @@ -57,7 +72,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); - for symbol in ["GetProcessHeap", "HeapAlloc", "HeapSize", "HeapFree"] { + for symbol in [ + "GetProcessHeap", + "HeapAlloc", + "HeapReAlloc", + "HeapSize", + "HeapFree", + ] { registry.alias(HEAP_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 0e4053b4..38d4a41d 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1203,7 +1203,7 @@ fn test_guest_process_heap_through_iat() { .get(Register::Rax); assert_ne!(heap, 0); - let allocate = |size, followup| { + let allocate = |size, followup, resize: u64| { let mut code = vec![0x48, 0x83, 0xec, 0x28]; for (register, value) in [ ([0x48, 0xb9], heap), @@ -1220,6 +1220,12 @@ fn test_guest_process_heap_through_iat() { code.extend_from_slice(&heap.to_le_bytes()); code.extend_from_slice(&[0x48, 0xba]); // dwFlags = 0 code.extend_from_slice(&0u64.to_le_bytes()); + if followup == "HeapReAlloc" { + // Write a sentinel into the allocation, then pass the new size in R9. + code.extend_from_slice(&[0x48, 0xc7, 0x00, 0x78, 0x56, 0x34, 0x12]); + code.extend_from_slice(&[0x49, 0xb9]); + code.extend_from_slice(&resize.to_le_bytes()); + } append_import_call(&mut code, 0x21a0); code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); @@ -1246,7 +1252,7 @@ fn test_guest_process_heap_through_iat() { result }; - let allocated = allocate(19, "HeapSize"); + let allocated = allocate(19, "HeapSize", 0); let address = allocated.execution.final_state.get(Register::Rbx); assert_ne!(address, 0); assert_eq!(address % 16, 0); @@ -1259,7 +1265,7 @@ fn test_guest_process_heap_through_iat() { .unwrap(); assert_eq!(bytes, [0; 19]); - let freed = allocate(19, "HeapFree"); + let freed = allocate(19, "HeapFree", 0); assert_eq!(freed.execution.final_state.get(Register::Rax), 1); assert!( freed @@ -1269,9 +1275,21 @@ fn test_guest_process_heap_through_iat() { .is_err() ); - let oversized = allocate(64 * 1024 * 1024 + 1, "HeapSize"); + let oversized = allocate(64 * 1024 * 1024 + 1, "HeapSize", 0); assert_eq!(oversized.execution.final_state.get(Register::Rbx), 0); assert_eq!(oversized.execution.final_state.get(Register::Rax), u64::MAX); + + let grown = allocate(19, "HeapReAlloc", 32); + let base = grown.execution.final_state.get(Register::Rbx); + assert_eq!(grown.execution.final_state.get(Register::Rax), base); + assert_eq!(grown.image.memory.read_u64(base).unwrap(), 0x1234_5678); + assert_eq!(grown.image.memory.read_u8(base + 31).unwrap(), 0); + + let rejected = allocate(19, "HeapReAlloc", 64 * 1024 * 1024 + 1); + let base = rejected.execution.final_state.get(Register::Rbx); + assert_eq!(rejected.execution.final_state.get(Register::Rax), 0); + assert_eq!(rejected.image.memory.read_u64(base).unwrap(), 0x1234_5678); + assert!(rejected.image.memory.read_u8(base + 19).is_err()); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index 6855c1c9..a53f54aa 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -165,8 +165,9 @@ bytes, and moves preserve the original source bytes when ranges overlap. synthetic heap. Allocations are at least 16-byte aligned and zero initialized. A zero-size request allocates one byte. The heap is bounded to 64 MiB and 4096 live allocations. Heap and virtual allocations have distinct ownership. -Private heaps, reallocation, and flags other than `HEAP_ZERO_MEMORY` on -allocation remain unsupported. See the [Windows heap API reference](https://learn.microsoft.com/windows/win32/api/heapapi/). +`HeapReAlloc` preserves the retained bytes and zeroes newly added bytes. +It can move a block unless `HEAP_REALLOC_IN_PLACE_ONLY` is set. Failed +resizes preserve the original block. Private heaps remain unsupported. See the [Windows heap API reference](https://learn.microsoft.com/windows/win32/api/heapapi/). ### Event signaling From 8e29b5491989bb4d6d54281601f561e49875b7b0 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:30:00 -0500 Subject: [PATCH 12/82] Track allocations owned by private guest heaps Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 2 + crates/loader/src/memory.rs | 114 +++++++++++++++++++++++------ crates/loader/src/services/heap.rs | 49 ++++++++++--- crates/loader/tests/runtime_x15.rs | 55 ++++++++++++++ docs/interfaces.md | 13 ++-- 6 files changed, 196 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f6f2afb2..d4ecad05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added private guest heap creation and destruction with per-heap allocation ownership. + - Added default guest heap reallocation with data preservation and an in-place-only option. - Added the synthetic default process heap with allocation, size queries, and release. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 2958bea4..d0584399 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -684,6 +684,8 @@ impl SymbolDb { "HeapReAlloc", "HeapSize", "HeapFree", + "HeapCreate", + "HeapDestroy", ] { self.ins(module, symbol, Classification::StandardService); } diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index 83a4f431..d5cae5fa 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -85,13 +85,14 @@ impl fmt::Display for MemoryError { impl std::error::Error for MemoryError {} +pub(crate) const PROCESS_HEAP: u64 = u64::MAX - 2; const MAX_DYNAMIC_BYTES: usize = 64 * 1024 * 1024; #[derive(Clone, Copy, PartialEq, Eq)] enum AllocationKind { ImageOrStatic, Virtual, - Heap, + Heap(u64), } #[derive(Clone)] @@ -117,14 +118,14 @@ impl MappedRegion { #[derive(Default, Clone)] pub struct GuestMemory { regions: Vec, + private_heaps: std::collections::BTreeSet, + private_heap_serial: u64, } impl GuestMemory { /// Create a new empty guest address space. pub fn new() -> Self { - Self { - regions: Vec::new(), - } + Self::default() } /// Map a new region into guest virtual memory. @@ -200,8 +201,46 @@ impl GuestMemory { self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual) } - pub(crate) fn map_heap_allocation(&mut self, size: usize) -> Result { - self.map_dynamic_allocation(0, size, MemoryPermissions::READ_WRITE, AllocationKind::Heap) + pub(crate) fn create_private_heap(&mut self, initial: u64) -> Option { + if initial > MAX_DYNAMIC_BYTES as u64 + || self.private_heaps.len() >= 256 + || self.private_heap_serial >= i64::MAX as u64 - 3 + { + return None; + } + self.private_heap_serial += 1; + let heap = PROCESS_HEAP - self.private_heap_serial; + self.private_heaps.insert(heap); + Some(heap) + } + + pub(crate) fn has_heap(&self, heap: u64) -> bool { + heap == PROCESS_HEAP || self.private_heaps.contains(&heap) + } + + pub(crate) fn destroy_private_heap(&mut self, heap: u64) -> bool { + if !self.private_heaps.remove(&heap) { + return false; + } + self.regions + .retain(|region| region.allocation != AllocationKind::Heap(heap)); + true + } + + pub(crate) fn map_heap_allocation( + &mut self, + heap: u64, + size: usize, + ) -> Result { + if !self.has_heap(heap) { + return Err(MemoryError::AllocationFailed); + } + self.map_dynamic_allocation( + 0, + size, + MemoryPermissions::READ_WRITE, + AllocationKind::Heap(heap), + ) } fn map_dynamic_allocation( @@ -214,11 +253,11 @@ impl GuestMemory { // Bound retained host storage independently for each allocation kind. let allocated = self.dynamic_bytes(allocation); if size > MAX_DYNAMIC_BYTES - allocated - || (allocation == AllocationKind::Heap + || (matches!(allocation, AllocationKind::Heap(_)) && self .regions .iter() - .filter(|r| r.allocation == allocation) + .filter(|r| matches!(r.allocation, AllocationKind::Heap(_))) .count() >= 4096) { @@ -237,7 +276,10 @@ impl GuestMemory { fn dynamic_bytes(&self, allocation: AllocationKind) -> usize { self.regions .iter() - .filter(|region| region.allocation == allocation) + .filter(|region| match allocation { + AllocationKind::Heap(_) => matches!(region.allocation, AllocationKind::Heap(_)), + _ => region.allocation == allocation, + }) .map(|region| region.data.len()) .sum() } @@ -262,6 +304,7 @@ impl GuestMemory { pub(crate) fn resize_heap_allocation( &mut self, + heap: u64, base: u64, size: usize, in_place_only: bool, @@ -269,10 +312,12 @@ impl GuestMemory { let index = self .regions .iter() - .position(|region| region.base == base && region.allocation == AllocationKind::Heap) + .position(|region| { + region.base == base && region.allocation == AllocationKind::Heap(heap) + }) .ok_or(MemoryError::UnmappedAddress(base))?; let previous = self.regions[index].data.len(); - let other_bytes = self.dynamic_bytes(AllocationKind::Heap) - previous; + let other_bytes = self.dynamic_bytes(AllocationKind::Heap(heap)) - previous; if size > MAX_DYNAMIC_BYTES - other_bytes { return Err(MemoryError::AllocationFailed); } @@ -309,14 +354,14 @@ impl GuestMemory { self.release_dynamic_allocation(base, AllocationKind::Virtual) } - pub(crate) fn release_heap_allocation(&mut self, base: u64) -> bool { - self.release_dynamic_allocation(base, AllocationKind::Heap) + pub(crate) fn release_heap_allocation(&mut self, heap: u64, base: u64) -> bool { + self.release_dynamic_allocation(base, AllocationKind::Heap(heap)) } - pub(crate) fn heap_allocation_size(&self, base: u64) -> Option { + pub(crate) fn heap_allocation_size(&self, heap: u64, base: u64) -> Option { self.regions .iter() - .find(|region| region.base == base && region.allocation == AllocationKind::Heap) + .find(|region| region.base == base && region.allocation == AllocationKind::Heap(heap)) .map(|region| region.data.len()) } @@ -476,26 +521,49 @@ impl GuestMemory { mod tests { use super::*; + #[test] + fn private_heap_destruction_reclaims_only_owned_regions() { + let mut memory = GuestMemory::new(); + let private = memory.create_private_heap(0).unwrap(); + let peer = memory.create_private_heap(0).unwrap(); + let address = memory.map_heap_allocation(private, 16).unwrap(); + let retained = memory.map_heap_allocation(peer, 16).unwrap(); + assert!(!memory.release_heap_allocation(peer, address)); + assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, address), None); + assert!(!memory.destroy_private_heap(PROCESS_HEAP)); + assert!(memory.destroy_private_heap(private)); + assert!(!memory.destroy_private_heap(private)); + assert!(memory.map_heap_allocation(private, 16).is_err()); + assert!(memory.read_u8(address).is_err()); + assert_eq!(memory.read_u8(retained), Ok(0)); + assert_ne!(memory.create_private_heap(0).unwrap(), private); + } + #[test] fn heap_resize_moves_only_when_allowed_and_preserves_bytes() { let mut memory = GuestMemory::new(); - let base = memory.map_heap_allocation(19).unwrap(); - let neighbor = memory.map_heap_allocation(1).unwrap(); + let base = memory.map_heap_allocation(PROCESS_HEAP, 19).unwrap(); + let neighbor = memory.map_heap_allocation(PROCESS_HEAP, 1).unwrap(); memory.write_u8(base, 0xab).unwrap(); memory.write_u8(neighbor, 0xcd).unwrap(); let growth = (neighbor - base) as usize + 1; assert_eq!( - memory.resize_heap_allocation(base, growth, true), + memory.resize_heap_allocation(PROCESS_HEAP, base, growth, true), Err(MemoryError::AllocationFailed) ); - assert_eq!(memory.heap_allocation_size(base), Some(19)); - let moved = memory.resize_heap_allocation(base, growth, false).unwrap(); + assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, base), Some(19)); + let moved = memory + .resize_heap_allocation(PROCESS_HEAP, base, growth, false) + .unwrap(); assert_ne!(moved, base); assert_eq!(memory.read_u8(moved), Ok(0xab)); assert_eq!(memory.read_u8(neighbor), Ok(0xcd)); assert_eq!(memory.read_u8(moved + growth as u64 - 1), Ok(0)); - assert_eq!(memory.heap_allocation_size(base), None); - assert_eq!(memory.resize_heap_allocation(moved, 1, true), Ok(moved)); - assert_eq!(memory.heap_allocation_size(moved), Some(1)); + assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, base), None); + assert_eq!( + memory.resize_heap_allocation(PROCESS_HEAP, moved, 1, true), + Ok(moved) + ); + assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, moved), Some(1)); } } diff --git a/crates/loader/src/services/heap.rs b/crates/loader/src/services/heap.rs index ed3539be..7c056eb1 100644 --- a/crates/loader/src/services/heap.rs +++ b/crates/loader/src/services/heap.rs @@ -1,15 +1,16 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Default heap services backed by owned guest memory regions. +//! Guest heap services backed by owned guest memory regions. use super::{ - ERROR_INVALID_ADDRESS, ERROR_INVALID_HANDLE, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState, + ERROR_INVALID_ADDRESS, ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, + KERNEL32, ServicesState, }; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use std::sync::Arc; -const PROCESS_HEAP: u64 = u64::MAX - 2; +use crate::memory::PROCESS_HEAP; const HEAP_ZERO_MEMORY: u32 = 8; const HEAP_REALLOC_IN_PLACE_ONLY: u32 = 16; const HEAP_API: &str = "api-ms-win-core-heap-l1-1-0.dll"; @@ -21,11 +22,11 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; let size = args.get(2, memory).map_err(ExitReason::MemoryFault)?; - if handle != PROCESS_HEAP || flags & !HEAP_ZERO_MEMORY != 0 { + if !memory.has_heap(handle) || flags & !HEAP_ZERO_MEMORY != 0 { return Ok(0); } Ok(memory - .map_heap_allocation(size.max(1) as usize) + .map_heap_allocation(handle, size.max(1) as usize) .unwrap_or(0)) }); @@ -34,12 +35,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; let size = args.get(3, memory).map_err(ExitReason::MemoryFault)?; - if handle != PROCESS_HEAP || flags & !(HEAP_ZERO_MEMORY | HEAP_REALLOC_IN_PLACE_ONLY) != 0 { + if !memory.has_heap(handle) || flags & !(HEAP_ZERO_MEMORY | HEAP_REALLOC_IN_PLACE_ONLY) != 0 + { return Ok(0); } let in_place_only = flags & HEAP_REALLOC_IN_PLACE_ONLY != 0; Ok(memory - .resize_heap_allocation(address, size.max(1) as usize, in_place_only) + .resize_heap_allocation(handle, address, size.max(1) as usize, in_place_only) .unwrap_or(0)) }); @@ -47,26 +49,49 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; - if handle != PROCESS_HEAP || flags != 0 { + if !memory.has_heap(handle) || flags != 0 { return Ok(u64::MAX); } Ok(memory - .heap_allocation_size(address) + .heap_allocation_size(handle, address) .map_or(u64::MAX, |size| size as u64)) }); + let service_state = Arc::clone(state); + registry.register(KERNEL32, "HeapCreate", move |args, _, memory| { + let flags = args.get(0, memory).map_err(ExitReason::MemoryFault)? as u32; + let initial = args.get(1, memory).map_err(ExitReason::MemoryFault)?; + let maximum = args.get(2, memory).map_err(ExitReason::MemoryFault)?; + if flags != 0 || maximum != 0 { + return service_state.fail(ERROR_NOT_SUPPORTED, 0); + } + match memory.create_private_heap(initial) { + Some(handle) => Ok(handle), + None => service_state.fail(ERROR_NOT_ENOUGH_MEMORY, 0), + } + }); + + let service_state = Arc::clone(state); + registry.register(KERNEL32, "HeapDestroy", move |args, _, memory| { + let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; + if !memory.destroy_private_heap(handle) { + return service_state.fail(ERROR_INVALID_HANDLE, 0); + } + Ok(1) + }); + let state = Arc::clone(state); registry.register(KERNEL32, "HeapFree", move |args, _, memory| { let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; - if handle != PROCESS_HEAP { + if !memory.has_heap(handle) { return state.fail(ERROR_INVALID_HANDLE, 0); } if flags != 0 { return state.fail(ERROR_NOT_SUPPORTED, 0); } - if address != 0 && !memory.release_heap_allocation(address) { + if address != 0 && !memory.release_heap_allocation(handle, address) { return state.fail(ERROR_INVALID_ADDRESS, 0); } Ok(1) @@ -78,6 +103,8 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "HeapReAlloc", "HeapSize", "HeapFree", + "HeapCreate", + "HeapDestroy", ] { registry.alias(HEAP_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 38d4a41d..0bb96349 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1192,6 +1192,61 @@ fn test_guest_event_signaling_through_iat() { assert_eq!(call(kernel, "CloseHandle", &[copy]), 1); } +#[test] +fn test_guest_creates_and_allocates_private_heap_through_iat() { + const IMAGE: u64 = 0x140000000; + const MODULE: &str = "api-ms-win-core-heap-l1-1-0.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let mut code = vec![0x48, 0x83, 0xec, 0x28]; + for register in [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8]] { + code.extend_from_slice(®ister); + code.extend_from_slice(&0u64.to_le_bytes()); + } + append_import_call(&mut code, 0x2060); + // Preserve the new heap handle in RBX and pass it in RCX. + code.extend_from_slice(&[0x48, 0x89, 0xc3, 0x48, 0x89, 0xc1]); + code.extend_from_slice(&[0x48, 0xba]); + code.extend_from_slice(&8u64.to_le_bytes()); + code.extend_from_slice(&[0x49, 0xb8]); + code.extend_from_slice(&16u64.to_le_bytes()); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import(MODULE, "HeapCreate") + .add_import(MODULE, "HeapAlloc") + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 2); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + let heap = result.execution.final_state.get(Register::Rbx); + let address = result.execution.final_state.get(Register::Rax); + assert_ne!(heap, 0); + assert_ne!(address, 0); + assert_eq!(result.image.memory.read_u64(address).unwrap(), 0); + assert_eq!( + call_service_fixture(&state, MODULE, "HeapDestroy", &[heap]) + .execution + .final_state + .get(Register::Rax), + 0, + "a different address space cannot destroy the private heap" + ); +} + #[test] fn test_guest_process_heap_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index a53f54aa..51f416c5 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -159,15 +159,18 @@ up to 1 MiB. Each nonempty span must fit in one mapped guest region with the required permissions. Writes validate the full destination before changing bytes, and moves preserve the original source bytes when ranges overlap. -### Default process heap +### Guest heaps -`GetProcessHeap`, `HeapAlloc`, `HeapSize`, and `HeapFree` expose a single -synthetic heap. Allocations are at least 16-byte aligned and zero initialized. -A zero-size request allocates one byte. The heap is bounded to 64 MiB and +`GetProcessHeap`, `HeapAlloc`, `HeapSize`, and `HeapFree` expose the +default synthetic heap. Allocations are at least 16-byte aligned and zero initialized. +A zero-size request allocates one byte. All heaps in an address space share a 64 MiB budget and a limit of 4096 live allocations. Heap and virtual allocations have distinct ownership. `HeapReAlloc` preserves the retained bytes and zeroes newly added bytes. It can move a block unless `HEAP_REALLOC_IN_PLACE_ONLY` is set. Failed -resizes preserve the original block. Private heaps remain unsupported. See the [Windows heap API reference](https://learn.microsoft.com/windows/win32/api/heapapi/). +resizes preserve the original block. `HeapCreate` supports up to 256 growable private heaps with default flags. +The initial size is checked against the budget and backing is allocated on +demand. `HeapDestroy` frees all blocks owned by that private heap and +invalidates its handle. The default heap cannot be destroyed. See the [Windows heap API reference](https://learn.microsoft.com/windows/win32/api/heapapi/). ### Event signaling From f992721fdafb6162171a0a809a59f33daac688c5 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:31:29 -0500 Subject: [PATCH 13/82] Back CRT allocation imports with the default guest heap Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 11 ++--- crates/loader/src/services.rs | 1 + crates/loader/src/services/crt.rs | 53 +++++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 72 ++++++++++++++++++++++++++++++ docs/interfaces.md | 7 +++ 6 files changed, 138 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d4ecad05..bff7157a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest CRT allocation, zeroed array allocation, resizing, and release. + - Added private guest heap creation and destruction with per-heap allocation ownership. - Added default guest heap reallocation with data preservation and an in-place-only option. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index d0584399..01870316 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -117,10 +117,6 @@ impl SymbolDb { self.ins(module, sym, Classification::Win32Stub { return_zero, note }); } - fn manual(&mut self, module: &str, sym: &str, reason: &'static str) { - self.ins(module, sym, Classification::Manual { reason }); - } - fn runtime_helper(&mut self, module: &str, sym: &str, note: &'static str) { self.ins(module, sym, Classification::RuntimeHelper { note }); } @@ -502,9 +498,10 @@ impl SymbolDb { fn populate_crt_heap(&mut self) { let m = "api-ms-win-crt-heap-l1-1-0.dll"; - // These map to guest VirtualAlloc, not host malloc — Manual - for sym in &["malloc", "free", "calloc", "realloc"] { - self.manual(m, sym, "Must use guest VirtualAlloc, not host malloc"); + for module in [m, "ucrtbase.dll"] { + for symbol in ["malloc", "free", "calloc", "realloc"] { + self.ins(module, symbol, Classification::StandardService); + } } self.win32_stub(m, "_set_new_handler", false, "new handler — stub"); } diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 621e8564..29cd5d23 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -395,6 +395,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result<(), ExitReason> { + if address == 0 || memory.release_heap_allocation(PROCESS_HEAP, address) { + Ok(()) + } else { + Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress( + address, + ))) + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 0bb96349..32c0db94 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1192,6 +1192,78 @@ fn test_guest_event_signaling_through_iat() { assert_eq!(call(kernel, "CloseHandle", &[copy]), 1); } +#[test] +fn test_guest_crt_allocation_and_resize_through_iat() { + const IMAGE: u64 = 0x140000000; + const MODULE: &str = "api-ms-win-crt-heap-l1-1-0.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let calloc = call_service_fixture(&state, MODULE, "calloc", &[3, 8]); + let block = calloc.execution.final_state.get(Register::Rax); + assert_ne!(block, 0); + let mut bytes = [1; 24]; + calloc.image.memory.read_bytes(block, &mut bytes).unwrap(); + assert_eq!(bytes, [0; 24]); + let overflow = call_service_fixture(&state, MODULE, "calloc", &[u64::MAX, 2]); + assert_eq!(overflow.execution.final_state.get(Register::Rax), 0); + + let resize = |size: u64, function| { + let mut code = vec![0x48, 0x83, 0xec, 0x28, 0x48, 0xb9]; + code.extend_from_slice(&16u64.to_le_bytes()); + append_import_call(&mut code, 0x2060); + // Save the allocation, seed it, and pass it as the first argument. + code.extend_from_slice(&[0x48, 0x89, 0xc3, 0x48, 0xc7, 0x00, 0x78, 0x56, 0x34, 0x12]); + code.extend_from_slice(&[0x48, 0x89, 0xc1, 0x48, 0xba]); + code.extend_from_slice(&size.to_le_bytes()); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import("ucrtbase.dll", "malloc") + .add_import(MODULE, function) + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 2); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result + }; + let grown = resize(32, "realloc"); + let block = grown.execution.final_state.get(Register::Rax); + assert_ne!(block, 0); + assert_eq!(grown.image.memory.read_u64(block).unwrap(), 0x1234_5678); + assert_eq!(grown.image.memory.read_u8(block + 31).unwrap(), 0); + + let rejected = resize(u64::MAX, "realloc"); + assert_eq!(rejected.execution.final_state.get(Register::Rax), 0); + let original = rejected.execution.final_state.get(Register::Rbx); + assert_eq!( + rejected.image.memory.read_u64(original).unwrap(), + 0x1234_5678 + ); + + for function in ["realloc", "free"] { + let freed = resize(0, function); + assert!( + freed + .image + .memory + .read_u8(freed.execution.final_state.get(Register::Rbx)) + .is_err() + ); + } +} + #[test] fn test_guest_creates_and_allocates_private_heap_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index 51f416c5..d061af42 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -172,6 +172,13 @@ The initial size is checked against the budget and backing is allocated on demand. `HeapDestroy` frees all blocks owned by that private heap and invalidates its handle. The default heap cannot be destroyed. See the [Windows heap API reference](https://learn.microsoft.com/windows/win32/api/heapapi/). +UCRT and the CRT heap API set expose `malloc`, `calloc`, `realloc`, and +`free` on the bounded default guest heap. `calloc` checks for size overflow. +`realloc(NULL, size)` allocates a new block, and resizing a nonnull block to +zero frees it. Allocation failures return null and preserve existing blocks. +CRT `errno` and new-handler callbacks remain unsupported. See +[Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation). + ### Event signaling The synthetic runtime supports unnamed manual-reset and auto-reset events From edba4df430e714afba0a1ba625f51f16f3ad91b0 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:33:03 -0500 Subject: [PATCH 14/82] Expose guest CRT errno and report allocation failures Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 13 ++--- crates/loader/src/memory.rs | 11 ++++ crates/loader/src/services.rs | 1 + crates/loader/src/services/crt.rs | 80 ++++++++++++++++++++++++------ crates/loader/tests/runtime_x15.rs | 70 ++++++++++++++++++++++++++ docs/interfaces.md | 5 +- 7 files changed, 158 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bff7157a..8a54d2d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread. + - Added guest CRT allocation, zeroed array allocation, resizing, and release. - Added private guest heap creation and destruction with per-heap allocation ownership. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 01870316..6f577c95 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -380,14 +380,11 @@ impl SymbolDb { ] { self.crt_native(m, sym, libc, "ISO C runtime — identical ABI on macOS"); } - self.win32_stub( - m, - "_errno", - false, - "Windows errno accessor — returns pointer to thread errno", - ); - self.win32_stub(m, "_get_errno", false, "Windows get_errno"); - self.win32_stub(m, "_set_errno", false, "Windows set_errno"); + for module in [m, "ucrtbase.dll"] { + for symbol in ["_errno", "_get_errno", "_set_errno"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub(m, "_set_app_type", false, "CRT app-type hint — no-op"); self.win32_stub(m, "_set_fmode", false, "CRT file mode hint — no-op"); self.win32_stub(m, "_set_new_mode", false, "CRT new-mode hint — no-op"); diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index d5cae5fa..58cd0084 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -120,6 +120,7 @@ pub struct GuestMemory { regions: Vec, private_heaps: std::collections::BTreeSet, private_heap_serial: u64, + crt_errno: Option, } impl GuestMemory { @@ -201,6 +202,16 @@ impl GuestMemory { self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual) } + pub(crate) fn crt_errno_address(&mut self) -> Result { + if let Some(address) = self.crt_errno { + return Ok(address); + } + let address = self.find_dynamic_base(4)?; + self.map_region(address, 4, MemoryPermissions::READ_WRITE)?; + self.crt_errno = Some(address); + Ok(address) + } + pub(crate) fn create_private_heap(&mut self, initial: u64) -> Option { if initial > MAX_DYNAMIC_BYTES as u64 || self.private_heaps.len() >= 256 diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 29cd5d23..5347aeca 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -396,6 +396,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result<(), ExitReason> { + let address = memory + .crt_errno_address() + .map_err(ExitReason::MemoryFault)?; + memory + .write_u32(address, error) + .map_err(ExitReason::MemoryFault) +} + +fn allocation_result( + memory: &mut GuestMemory, + result: Result, +) -> Result { + match result { + Ok(address) => Ok(address), + Err(_) => { + set_errno(memory, ENOMEM)?; + Ok(0) + } + } +} + +pub(super) fn register_errno(registry: &mut ImportRegistry) { + registry.register(UCRT, "_errno", |_, _, memory| { + memory.crt_errno_address().map_err(ExitReason::MemoryFault) + }); + registry.register(UCRT, "_set_errno", |args, _, memory| { + set_errno(memory, args.rcx as u32)?; + Ok(0) + }); + registry.register(UCRT, "_get_errno", |args, _, memory| { + if args.rcx == 0 { + set_errno(memory, EINVAL)?; + return Ok(u64::from(EINVAL)); + } + let address = memory + .crt_errno_address() + .map_err(ExitReason::MemoryFault)?; + let value = memory.read_u32(address).map_err(ExitReason::MemoryFault)?; + memory + .write_u32(args.rcx, value) + .map_err(ExitReason::MemoryFault)?; + Ok(0) + }); + for symbol in ["_errno", "_set_errno", "_get_errno"] { + registry.alias("api-ms-win-crt-runtime-l1-1-0.dll", UCRT, symbol); + registry.set_status(UCRT, symbol, ServiceStatus::Partial); + } +} + pub(super) fn register_heap(registry: &mut ImportRegistry) { registry.register(UCRT, "malloc", |args, _, memory| { - Ok(memory - .map_heap_allocation(PROCESS_HEAP, args.rcx.max(1) as usize) - .unwrap_or(0)) + let result = memory.map_heap_allocation(PROCESS_HEAP, args.rcx.max(1) as usize); + allocation_result(memory, result) }); registry.register(UCRT, "calloc", |args, _, memory| { - let Some(size) = args.rcx.checked_mul(args.rdx) else { - return Ok(0); - }; - Ok(memory - .map_heap_allocation(PROCESS_HEAP, size.max(1) as usize) - .unwrap_or(0)) + let result = args + .rcx + .checked_mul(args.rdx) + .ok_or(MemoryError::AllocationFailed) + .and_then(|size| memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize)); + allocation_result(memory, result) }); registry.register(UCRT, "realloc", |args, _, memory| { let address = args.rcx; let size = args.rdx; if address == 0 { - return Ok(memory - .map_heap_allocation(PROCESS_HEAP, size.max(1) as usize) - .unwrap_or(0)); + let result = memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize); + return allocation_result(memory, result); } if size == 0 { free(memory, address)?; return Ok(0); } - Ok(memory - .resize_heap_allocation(PROCESS_HEAP, address, size as usize, false) - .unwrap_or(0)) + let result = memory.resize_heap_allocation(PROCESS_HEAP, address, size as usize, false); + allocation_result(memory, result) }); registry.register(UCRT, "free", |args, _, memory| { free(memory, args.rcx)?; diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 32c0db94..a19497b2 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1192,6 +1192,76 @@ fn test_guest_event_signaling_through_iat() { assert_eq!(call(kernel, "CloseHandle", &[copy]), 1); } +#[test] +fn test_guest_crt_errno_through_iat() { + const MODULE: &str = "api-ms-win-crt-runtime-l1-1-0.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let run = |first, argument: u64, second, output: u64| { + let mut code = vec![0x48, 0x83, 0xec, 0x28, 0x48, 0xb9]; + code.extend_from_slice(&argument.to_le_bytes()); + append_import_call(&mut code, 0x2060); + code.extend_from_slice(&[0x48, 0x89, 0xc3, 0x48, 0xb9]); + code.extend_from_slice(&output.to_le_bytes()); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + let bytes = TestPeBuilder::new(0x140000000, 0x1000) + .add_import("ucrtbase.dll", first) + .add_import(MODULE, second) + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: 0x140000000, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 2); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result + }; + + let output = PROCESS_FIXTURE_OUTPUT; + let failed = run("malloc", u64::MAX, "_get_errno", output); + assert_eq!(failed.execution.final_state.get(Register::Rbx), 0); + assert_eq!(failed.execution.final_state.get(Register::Rax), 0); + assert_eq!(failed.image.memory.read_u32(output).unwrap(), 12); + + let set = run("_set_errno", 34, "_errno", 0); + let slot = set.execution.final_state.get(Register::Rax); + assert_eq!(set.image.memory.read_u32(slot).unwrap(), 34); + let fresh = run("_errno", 0, "_errno", 0); + assert_eq!( + fresh.execution.final_state.get(Register::Rbx), + fresh.execution.final_state.get(Register::Rax) + ); + assert_eq!( + fresh + .image + .memory + .read_u32(fresh.execution.final_state.get(Register::Rax)) + .unwrap(), + 0 + ); + + let invalid = run("_get_errno", 0, "_errno", 0); + assert_eq!(invalid.execution.final_state.get(Register::Rbx), 22); + assert_eq!( + invalid + .image + .memory + .read_u32(invalid.execution.final_state.get(Register::Rax)) + .unwrap(), + 22 + ); +} + #[test] fn test_guest_crt_allocation_and_resize_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index d061af42..1e173632 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -176,7 +176,10 @@ UCRT and the CRT heap API set expose `malloc`, `calloc`, `realloc`, and `free` on the bounded default guest heap. `calloc` checks for size overflow. `realloc(NULL, size)` allocates a new block, and resizing a nonnull block to zero frees it. Allocation failures return null and preserve existing blocks. -CRT `errno` and new-handler callbacks remain unsupported. See +Allocation failures also set the synthetic main thread's CRT `errno` to +`ENOMEM`. The runtime API set and UCRT expose `_errno`, `_get_errno`, and +`_set_errno` through a stable guest memory slot. Additional guest threads +and CRT parameter or new-handler callbacks remain unsupported. See [Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation). ### Event signaling From a4a2425bcc7a887e42a1aa55191177aeb3ef5ac8 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:35:00 -0500 Subject: [PATCH 15/82] Parse Windows long integers in the guest CRT Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 9 +-- crates/loader/src/services.rs | 1 + crates/loader/src/services/crt.rs | 101 +++++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 80 +++++++++++++++++++++++ docs/interfaces.md | 8 +++ 6 files changed, 197 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a54d2d0..ebf69814 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added bounded guest CRT long-integer parsing for byte and wide strings. + - Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread. - Added guest CRT allocation, zeroed array allocation, resizing, and release. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 6f577c95..ecbc05aa 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -522,18 +522,19 @@ impl SymbolDb { fn populate_crt_convert(&mut self) { let m = "api-ms-win-crt-convert-l1-1-0.dll"; + for module in [m, "ucrtbase.dll"] { + for symbol in ["strtol", "strtoul", "wcstol", "wcstoul"] { + self.ins(module, symbol, Classification::StandardService); + } + } for (sym, libc) in &[ ("strtod", "strtod"), ("strtof", "strtof"), - ("strtol", "strtol"), - ("strtoul", "strtoul"), ("strtoll", "strtoll"), ("strtoull", "strtoull"), ("mbstowcs", "mbstowcs"), ("wcstombs", "wcstombs"), ("wcstod", "wcstod"), - ("wcstol", "wcstol"), - ("wcstoul", "wcstoul"), ("wctob", "wctob"), ("btowc", "btowc"), ] { diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 5347aeca..38163431 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -397,6 +397,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result { + if address == 0 || (radix != 0 && !(2..=36).contains(&radix)) { + if end != 0 { + memory + .write_u64(end, address) + .map_err(ExitReason::MemoryFault)?; + } + set_errno(memory, EINVAL)?; + return Ok(0); + } + + let read = |index| { + if index >= SCAN_BUDGET / unit.width() { + return Err(ExitReason::IllegalInstruction(0xFE)); + } + unit.read(memory, address, index) + .map(|value| char::from_u32(u32::from(value)).unwrap_or(char::REPLACEMENT_CHARACTER)) + }; + let mut index = 0; + let mut next = read(index)?; + while matches!(next, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c') { + index += 1; + next = read(index)?; + } + let negative = next == '-'; + if matches!(next, '+' | '-') { + index += 1; + next = read(index)?; + } + if next == '0' + && matches!(radix, 0 | 16) + && matches!(read(index + 1)?, 'x' | 'X') + && read(index + 2)?.is_ascii_hexdigit() + { + radix = 16; + index += 2; + next = read(index)?; + } + if radix == 0 { + radix = if next == '0' { 8 } else { 10 }; + } + + let limit = if signed { + i32::MAX as u32 + u32::from(negative) + } else { + u32::MAX + }; + let start = index; + let mut value = 0u32; + let mut overflow = false; + while let Some(digit) = next.to_digit(radix) { + match value.checked_mul(radix).and_then(|v| v.checked_add(digit)) { + Some(v) if v <= limit => value = v, + _ => overflow = true, + } + index += 1; + next = read(index)?; + } + let consumed = if start == index { 0 } else { index }; + if end != 0 { + let pointer = address + .checked_add(consumed * unit.width()) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + memory + .write_u64(end, pointer) + .map_err(ExitReason::MemoryFault)?; + } + if overflow { + set_errno(memory, ERANGE)?; + value = limit; + } + if negative && (!overflow || signed) { + value = value.wrapping_neg(); + } + Ok(u64::from(value)) +} + +pub(super) fn register_conversions(registry: &mut ImportRegistry) { + for (symbol, signed, unit) in [ + ("strtol", true, StringUnit::Byte), + ("strtoul", false, StringUnit::Byte), + ("wcstol", true, StringUnit::Wide), + ("wcstoul", false, StringUnit::Wide), + ] { + registry.register(UCRT, symbol, move |args, _, memory| { + parse_long(memory, args.rcx, args.rdx, args.r8 as u32, signed, unit) + }); + registry.alias("api-ms-win-crt-convert-l1-1-0.dll", UCRT, symbol); + registry.set_status(UCRT, symbol, ServiceStatus::Partial); + } +} + pub(super) fn register_errno(registry: &mut ImportRegistry) { registry.register(UCRT, "_errno", |_, _, memory| { memory.crt_errno_address().map_err(ExitReason::MemoryFault) diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index a19497b2..531272f7 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1192,6 +1192,86 @@ fn test_guest_event_signaling_through_iat() { assert_eq!(call(kernel, "CloseHandle", &[copy]), 1); } +#[test] +fn test_guest_crt_long_conversions_through_iat() { + const IMAGE: u64 = 0x140000000; + const INPUT: u64 = IMAGE + 0x1080; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let run = |symbol, input: &[u8], radix: u64| { + let mut code = vec![0x48, 0x83, 0xec, 0x28]; + for (register, value) in [ + ([0x48, 0xb9], INPUT), + ([0x48, 0xba], PROCESS_FIXTURE_OUTPUT), + ([0x49, 0xb8], radix), + ] { + code.extend_from_slice(®ister); + code.extend_from_slice(&value.to_le_bytes()); + } + append_import_call(&mut code, 0x2060); + code.extend_from_slice(&[0x48, 0x89, 0xc3, 0x48, 0xb9]); + code.extend_from_slice(&(PROCESS_FIXTURE_OUTPUT + 8).to_le_bytes()); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + code.resize(0x80, 0); + code.extend_from_slice(input); + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import("api-ms-win-crt-convert-l1-1-0.dll", symbol) + .add_import("ucrtbase.dll", "_get_errno") + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 2); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + ( + result.execution.final_state.get(Register::Rbx) as u32, + result + .image + .memory + .read_u64(PROCESS_FIXTURE_OUTPUT) + .unwrap() + - INPUT, + result + .image + .memory + .read_u32(PROCESS_FIXTURE_OUTPUT + 8) + .unwrap(), + ) + }; + assert_eq!(run("strtol", b" -0x10!\0", 0), ((-16i32) as u32, 6, 0)); + assert_eq!( + run("strtol", b"21474836480!\0", 10), + (i32::MAX as u32, 11, 34) + ); + assert_eq!( + run("strtol", b"-2147483649\0", 10), + (i32::MIN as u32, 11, 34) + ); + assert_eq!(run("strtol", b" +!\0", 10), (0, 0, 0)); + assert_eq!(run("strtol", b"17\0", 37), (0, 0, 22)); + assert_eq!(run("strtoul", b"-1\0", 10), (u32::MAX, 2, 0)); + assert_eq!(run("strtoul", b"4294967296\0", 10), (u32::MAX, 10, 34)); + assert_eq!(run("strtoul", b"078\0", 0), (7, 2, 0)); + let wide = "42!" + .encode_utf16() + .chain([0]) + .flat_map(u16::to_le_bytes) + .collect::>(); + assert_eq!(run("wcstol", &wide, 10), (42, 4, 0)); + assert_eq!(run("wcstoul", &wide, 10), (42, 4, 0)); +} + #[test] fn test_guest_crt_errno_through_iat() { const MODULE: &str = "api-ms-win-crt-runtime-l1-1-0.dll"; diff --git a/docs/interfaces.md b/docs/interfaces.md index 1e173632..dd12550b 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -182,6 +182,14 @@ Allocation failures also set the synthetic main thread's CRT `errno` to and CRT parameter or new-handler callbacks remain unsupported. See [Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation). +### CRT integer conversion + +UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and +wcstoul with 32-bit Windows long results. The parser supports C-locale +whitespace, explicit bases 2–36 and automatic base selection, and writes +the first unparsed guest address to a supplied end pointer. Overflow +clamps the result and sets ERANGE. Scans have a 1 MiB input budget. + ### Event signaling The synthetic runtime supports unnamed manual-reset and auto-reset events From b8613486672f3bbcf50028abf5847c68067fc6c5 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:36:13 -0500 Subject: [PATCH 16/82] Support 64-bit integer conversion in the guest CRT Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/import-gen/src/classify.rs | 29 ++++++++-------- crates/loader/src/services/crt.rs | 53 ++++++++++++++++++++++-------- crates/loader/tests/runtime_x15.rs | 39 ++++++++++++++++++---- docs/interfaces.md | 4 ++- 5 files changed, 91 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ebf69814..64daf2d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings. + - Added bounded guest CRT long-integer parsing for byte and wide strings. - Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index ecbc05aa..ff63c0e0 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -523,15 +523,26 @@ impl SymbolDb { fn populate_crt_convert(&mut self) { let m = "api-ms-win-crt-convert-l1-1-0.dll"; for module in [m, "ucrtbase.dll"] { - for symbol in ["strtol", "strtoul", "wcstol", "wcstoul"] { + for symbol in [ + "strtol", + "strtoul", + "wcstol", + "wcstoul", + "strtoll", + "strtoull", + "wcstoll", + "wcstoull", + "_strtoi64", + "_strtoui64", + "_wcstoi64", + "_wcstoui64", + ] { self.ins(module, symbol, Classification::StandardService); } } for (sym, libc) in &[ ("strtod", "strtod"), ("strtof", "strtof"), - ("strtoll", "strtoll"), - ("strtoull", "strtoull"), ("mbstowcs", "mbstowcs"), ("wcstombs", "wcstombs"), ("wcstod", "wcstod"), @@ -540,18 +551,6 @@ impl SymbolDb { ] { self.crt_native(m, sym, libc, "ISO C conversion — identical ABI on macOS"); } - self.win32_stub( - m, - "_strtoi64", - false, - "Windows 64-bit strtoi64 — same as strtoll", - ); - self.win32_stub( - m, - "_strtoui64", - false, - "Windows 64-bit strtoui64 — same as strtoull", - ); self.win32_stub(m, "_itoa", false, "Windows itoa — integer to ASCII"); self.win32_stub(m, "_itoa_s", false, "Windows itoa_s — safe variant"); self.win32_stub(m, "_wtoi", false, "Wide char to int"); diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index 12fa7264..a83790a0 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -192,12 +192,13 @@ fn allocation_result( const ERANGE: u32 = 34; -fn parse_long( +fn parse_integer( memory: &mut GuestMemory, address: u64, end: u64, mut radix: u32, signed: bool, + wide_result: bool, unit: StringUnit, ) -> Result { if address == 0 || (radix != 0 && !(2..=36).contains(&radix)) { @@ -241,16 +242,20 @@ fn parse_long( radix = if next == '0' { 8 } else { 10 }; } - let limit = if signed { - i32::MAX as u32 + u32::from(negative) - } else { - u32::MAX + let limit = match (wide_result, signed) { + (false, false) => u64::from(u32::MAX), + (false, true) => i32::MAX as u64 + u64::from(negative), + (true, false) => u64::MAX, + (true, true) => i64::MAX as u64 + u64::from(negative), }; let start = index; - let mut value = 0u32; + let mut value = 0u64; let mut overflow = false; while let Some(digit) = next.to_digit(radix) { - match value.checked_mul(radix).and_then(|v| v.checked_add(digit)) { + match value + .checked_mul(u64::from(radix)) + .and_then(|v| v.checked_add(u64::from(digit))) + { Some(v) if v <= limit => value = v, _ => overflow = true, } @@ -273,18 +278,38 @@ fn parse_long( if negative && (!overflow || signed) { value = value.wrapping_neg(); } - Ok(u64::from(value)) + Ok(if wide_result { + value + } else { + u64::from(value as u32) + }) } pub(super) fn register_conversions(registry: &mut ImportRegistry) { - for (symbol, signed, unit) in [ - ("strtol", true, StringUnit::Byte), - ("strtoul", false, StringUnit::Byte), - ("wcstol", true, StringUnit::Wide), - ("wcstoul", false, StringUnit::Wide), + for (symbol, signed, wide_result, unit) in [ + ("strtol", true, false, StringUnit::Byte), + ("strtoul", false, false, StringUnit::Byte), + ("wcstol", true, false, StringUnit::Wide), + ("wcstoul", false, false, StringUnit::Wide), + ("strtoll", true, true, StringUnit::Byte), + ("strtoull", false, true, StringUnit::Byte), + ("wcstoll", true, true, StringUnit::Wide), + ("wcstoull", false, true, StringUnit::Wide), + ("_strtoi64", true, true, StringUnit::Byte), + ("_strtoui64", false, true, StringUnit::Byte), + ("_wcstoi64", true, true, StringUnit::Wide), + ("_wcstoui64", false, true, StringUnit::Wide), ] { registry.register(UCRT, symbol, move |args, _, memory| { - parse_long(memory, args.rcx, args.rdx, args.r8 as u32, signed, unit) + parse_integer( + memory, + args.rcx, + args.rdx, + args.r8 as u32, + signed, + wide_result, + unit, + ) }); registry.alias("api-ms-win-crt-convert-l1-1-0.dll", UCRT, symbol); registry.set_status(UCRT, symbol, ServiceStatus::Partial); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 531272f7..81dc552b 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1235,7 +1235,7 @@ fn test_guest_crt_long_conversions_through_iat() { assert_eq!(result.bound_imports, 2); assert_eq!(result.execution.exit_reason, ExitReason::Halt); ( - result.execution.final_state.get(Register::Rbx) as u32, + result.execution.final_state.get(Register::Rbx), result .image .memory @@ -1249,19 +1249,25 @@ fn test_guest_crt_long_conversions_through_iat() { .unwrap(), ) }; - assert_eq!(run("strtol", b" -0x10!\0", 0), ((-16i32) as u32, 6, 0)); + assert_eq!( + run("strtol", b" -0x10!\0", 0), + (u64::from((-16i32) as u32), 6, 0) + ); assert_eq!( run("strtol", b"21474836480!\0", 10), - (i32::MAX as u32, 11, 34) + (i32::MAX as u64, 11, 34) ); assert_eq!( run("strtol", b"-2147483649\0", 10), - (i32::MIN as u32, 11, 34) + (u64::from(i32::MIN as u32), 11, 34) ); assert_eq!(run("strtol", b" +!\0", 10), (0, 0, 0)); assert_eq!(run("strtol", b"17\0", 37), (0, 0, 22)); - assert_eq!(run("strtoul", b"-1\0", 10), (u32::MAX, 2, 0)); - assert_eq!(run("strtoul", b"4294967296\0", 10), (u32::MAX, 10, 34)); + assert_eq!(run("strtoul", b"-1\0", 10), (u64::from(u32::MAX), 2, 0)); + assert_eq!( + run("strtoul", b"4294967296\0", 10), + (u64::from(u32::MAX), 10, 34) + ); assert_eq!(run("strtoul", b"078\0", 0), (7, 2, 0)); let wide = "42!" .encode_utf16() @@ -1270,6 +1276,27 @@ fn test_guest_crt_long_conversions_through_iat() { .collect::>(); assert_eq!(run("wcstol", &wide, 10), (42, 4, 0)); assert_eq!(run("wcstoul", &wide, 10), (42, 4, 0)); + assert_eq!( + run("strtoll", b"9223372036854775808\0", 10), + (i64::MAX as u64, 19, 34) + ); + assert_eq!( + run("_strtoi64", b"-9223372036854775808\0", 10), + (i64::MIN as u64, 20, 0) + ); + assert_eq!( + run("_strtoui64", b"18446744073709551616\0", 10), + (u64::MAX, 20, 34) + ); + assert_eq!(run("strtoull", b"-1\0", 10), (u64::MAX, 2, 0)); + let wide = "4294967296" + .encode_utf16() + .chain([0]) + .flat_map(u16::to_le_bytes) + .collect::>(); + for symbol in ["wcstoll", "wcstoull", "_wcstoi64", "_wcstoui64"] { + assert_eq!(run(symbol, &wide, 10), (4_294_967_296, 20, 0)); + } } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index dd12550b..cf7a91e3 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -188,7 +188,9 @@ UCRT and the CRT conversion API set expose strtol, strtoul, wcstol, and wcstoul with 32-bit Windows long results. The parser supports C-locale whitespace, explicit bases 2–36 and automatic base selection, and writes the first unparsed guest address to a supplied end pointer. Overflow -clamps the result and sets ERANGE. Scans have a 1 MiB input budget. +clamps the result and sets ERANGE. Scans have a 1 MiB input budget. The long-long variants and +Microsoft's _strtoi64, _strtoui64, _wcstoi64, and _wcstoui64 apply the +same rules with 64-bit results. ### Event signaling From 654e4c28b5686d415857204788ecb9952922ec03 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:38:04 -0500 Subject: [PATCH 17/82] Resolve immediate guest waits on multiple events Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 6 +- crates/loader/src/services/events.rs | 112 ++++++++++++++++++++------- crates/loader/tests/runtime_x15.rs | 70 +++++++++++++++++ docs/interfaces.md | 6 ++ 5 files changed, 167 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64daf2d2..796adaf7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added immediate wait-any and wait-all for guest event handles. + - Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings. - Added bounded guest CRT long-integer parsing for byte and wide strings. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index ff63c0e0..72be27e8 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -777,6 +777,7 @@ impl SymbolDb { "SetEvent", "ResetEvent", "WaitForSingleObject", + "WaitForMultipleObjects", ] { self.ins(module, symbol, Classification::StandardService); } @@ -856,11 +857,10 @@ impl SymbolDb { ); let m2 = "api-ms-win-core-synch-l1-2-1.dll"; - self.win32_stub( + self.ins( m2, "WaitForMultipleObjects", - false, - "WaitForMultipleObjects — stub returning 0", + Classification::StandardService, ); self.win32_stub( m2, diff --git a/crates/loader/src/services/events.rs b/crates/loader/src/services/events.rs index aa8085eb..a6d91469 100644 --- a/crates/loader/src/services/events.rs +++ b/crates/loader/src/services/events.rs @@ -3,11 +3,12 @@ //! Unnamed event objects and waits that can resolve without a guest scheduler. use super::{ - ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, - GuestObject, KERNEL32, ServicesState, + ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, + ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState, }; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; +use crate::memory::MemoryError; use std::sync::{Arc, Mutex}; const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll"; @@ -72,35 +73,31 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }); } - let state = Arc::clone(state); + let single = Arc::clone(state); registry.register(KERNEL32, "WaitForSingleObject", move |args, _, mem| { let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; - let objects = state.objects.lock().expect("guest object state"); - let Some(GuestObject::Event { - state: event, - access, - }) = objects.handles.get(&handle) - else { - if objects.handles.contains_key(&handle) - || matches!(handle, super::CURRENT_THREAD | super::CURRENT_PROCESS) - { - return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); - } - return state.fail(ERROR_INVALID_HANDLE, WAIT_FAILED); - }; - if access & SYNCHRONIZE == 0 { - return state.fail(ERROR_ACCESS_DENIED, WAIT_FAILED); + wait_for_events(&single, &[handle], false, timeout) + }); + + let multiple = Arc::clone(state); + registry.register(KERNEL32, "WaitForMultipleObjects", move |args, _, mem| { + let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; + let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?; + let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; + let timeout = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; + if !(1..=64).contains(&count) || address == 0 { + return multiple.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); } - let mut event = event.lock().expect("guest event state"); - if event.signaled { - event.signaled = event.manual_reset; - return Ok(WAIT_OBJECT_0); + let mut handles = [0; 64]; + let handles = &mut handles[..count as usize]; + for (index, handle) in handles.iter_mut().enumerate() { + let slot = address + .checked_add(index as u64 * 8) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + *handle = mem.read_u64(slot).map_err(ExitReason::MemoryFault)?; } - if timeout == 0 { - return Ok(WAIT_TIMEOUT); - } - state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED) + wait_for_events(&multiple, handles, all, timeout) }); for symbol in [ @@ -109,8 +106,71 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "SetEvent", "ResetEvent", "WaitForSingleObject", + "WaitForMultipleObjects", ] { registry.alias(SYNCH_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); } + registry.alias( + "api-ms-win-core-synch-l1-2-1.dll", + KERNEL32, + "WaitForMultipleObjects", + ); +} + +fn wait_for_events( + state: &ServicesState, + handles: &[u64], + all: bool, + timeout: u32, +) -> Result { + // The object table remains locked through validation and consumption. + let objects = state.objects.lock().expect("guest object state"); + let mut events: Vec<&Arc>> = Vec::with_capacity(handles.len()); + for (index, handle) in handles.iter().enumerate() { + if handles[..index].contains(handle) { + return state.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); + } + match objects.handles.get(handle) { + Some(GuestObject::Event { + state: event, + access, + }) => { + if access & SYNCHRONIZE == 0 { + return state.fail(ERROR_ACCESS_DENIED, WAIT_FAILED); + } + if all && events.iter().any(|existing| Arc::ptr_eq(existing, event)) { + return state.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); + } + events.push(event); + } + Some(_) => return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED), + None if matches!(*handle, super::CURRENT_THREAD | super::CURRENT_PROCESS) => { + return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + } + None => return state.fail(ERROR_INVALID_HANDLE, WAIT_FAILED), + } + } + let mut ready = Vec::with_capacity(handles.len()); + for (index, event) in events.into_iter().enumerate() { + if event.lock().expect("guest event state").signaled { + ready.push((index, event)); + if !all { + break; + } + } + } + if ready.is_empty() || (all && ready.len() != handles.len()) { + return if timeout == 0 { + Ok(WAIT_TIMEOUT) + } else { + state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED) + }; + } + let first = ready[0].0; + for (_, event) in ready { + let mut event = event.lock().expect("guest event state"); + event.signaled = event.manual_reset; + } + Ok(WAIT_OBJECT_0 + first as u64) } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 81dc552b..eb3b6d0b 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,76 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn test_guest_waits_for_multiple_events_through_iat() { + const IMAGE: u64 = 0x140000000; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |symbol, args: &[u64]| { + call_service_fixture(&state, "kernel32.dll", symbol, args) + .execution + .final_state + .get(Register::Rax) + }; + let wait = |handles: [u64; 2], all: bool| { + let mut code = vec![0x48, 0x83, 0xec, 0x28]; + for (register, value) in [ + ([0x48, 0xb9], 2u64), + ([0x48, 0xba], IMAGE + 0x1080), + ([0x49, 0xb8], u64::from(all)), + ([0x49, 0xb9], 0), + ] { + code.extend_from_slice(®ister); + code.extend_from_slice(&value.to_le_bytes()); + } + append_import_call(&mut code, 0x2060); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + code.resize(0x80, 0); + for handle in handles { + code.extend_from_slice(&handle.to_le_bytes()); + } + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import("api-ms-win-core-synch-l1-2-1.dll", "WaitForMultipleObjects") + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 1); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result.execution.final_state.get(Register::Rax) + }; + + let first = call("CreateEventW", &[0, 0, 1, 0]); + let second = call("CreateEventW", &[0, 0, 0, 0]); + assert_eq!(wait([first, second], true), 258); + assert_eq!(wait([second, first], false), 1); + assert_eq!(wait([first, second], false), 258); + + assert_eq!(call("SetEvent", &[first]), 1); + assert_eq!(call("SetEvent", &[second]), 1); + assert_eq!(wait([first, second], false), 0); + assert_eq!(call("SetEvent", &[first]), 1); + assert_eq!(wait([first, second], true), 0); + assert_eq!(wait([first, second], false), 258); + + assert_eq!(call("SetEvent", &[first]), 1); + assert_eq!(wait([first, first], true), u64::from(u32::MAX)); + assert_eq!(call("GetLastError", &[]), 87); + assert_eq!(wait([first, 0], false), u64::from(u32::MAX)); + assert_eq!(call("GetLastError", &[]), 6); + assert_eq!(wait([second, first], false), 1); +} + #[test] fn test_guest_event_signaling_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index cf7a91e3..46eaf74c 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -205,6 +205,12 @@ Event duplicates share signal state and keep the event alive independently. A duplicate can retain or reduce its rights. Waiting requires synchronize access, and setting or resetting requires modify-state access. +`WaitForMultipleObjects` supports immediate waits on up to 64 events. +Wait-any selects the first signaled handle. Wait-all consumes auto-reset +signals only when every event is ready. Repeated handles and wait-all +aliases to the same event are rejected. Waits that would block remain +unsupported. + See Microsoft's [event object documentation](https://learn.microsoft.com/windows/win32/sync/event-objects). ## Synthetic tiled textures From 9b22c664bbb516858acdae0830f72165d733f080 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:39:46 -0500 Subject: [PATCH 18/82] Handle non-alertable extended guest event waits Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 14 +---- crates/loader/src/services/events.rs | 77 +++++++++++++++++----------- crates/loader/tests/runtime_x15.rs | 49 ++++++++++++++---- docs/interfaces.md | 6 ++- 5 files changed, 92 insertions(+), 56 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 796adaf7..61402702 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added non-alertable extended event waits through both Win64 wait APIs. + - Added immediate wait-any and wait-all for guest event handles. - Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 72be27e8..58bc6b98 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -777,17 +777,13 @@ impl SymbolDb { "SetEvent", "ResetEvent", "WaitForSingleObject", + "WaitForSingleObjectEx", "WaitForMultipleObjects", + "WaitForMultipleObjectsEx", ] { self.ins(module, symbol, Classification::StandardService); } } - self.win32_stub( - m, - "WaitForSingleObjectEx", - false, - "WaitForSingleObjectEx — stub", - ); self.win32_stub(m, "CreateMutexA", true, "CreateMutex — stub"); self.win32_stub(m, "CreateMutexW", true, "CreateMutex wide — stub"); self.win32_stub(m, "ReleaseMutex", false, "ReleaseMutex — stub"); @@ -862,12 +858,6 @@ impl SymbolDb { "WaitForMultipleObjects", Classification::StandardService, ); - self.win32_stub( - m2, - "WaitForMultipleObjectsEx", - false, - "WaitForMultipleObjectsEx — stub", - ); self.win32_stub( m2, "InitOnceExecuteOnce", diff --git a/crates/loader/src/services/events.rs b/crates/loader/src/services/events.rs index a6d91469..2194b3fc 100644 --- a/crates/loader/src/services/events.rs +++ b/crates/loader/src/services/events.rs @@ -73,32 +73,47 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }); } - let single = Arc::clone(state); - registry.register(KERNEL32, "WaitForSingleObject", move |args, _, mem| { - let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; - wait_for_events(&single, &[handle], false, timeout) - }); - - let multiple = Arc::clone(state); - registry.register(KERNEL32, "WaitForMultipleObjects", move |args, _, mem| { - let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; - let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?; - let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; - let timeout = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; - if !(1..=64).contains(&count) || address == 0 { - return multiple.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); - } - let mut handles = [0; 64]; - let handles = &mut handles[..count as usize]; - for (index, handle) in handles.iter_mut().enumerate() { - let slot = address - .checked_add(index as u64 * 8) - .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; - *handle = mem.read_u64(slot).map_err(ExitReason::MemoryFault)?; - } - wait_for_events(&multiple, handles, all, timeout) - }); + for (symbol, extended) in [ + ("WaitForSingleObject", false), + ("WaitForSingleObjectEx", true), + ] { + let single = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; + if extended && args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 { + return single.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + } + wait_for_events(&single, &[handle], false, timeout) + }); + } + for (symbol, extended) in [ + ("WaitForMultipleObjects", false), + ("WaitForMultipleObjectsEx", true), + ] { + let multiple = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; + let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?; + let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; + let timeout = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; + if extended && args.get(4, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 { + return multiple.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + } + if !(1..=64).contains(&count) || address == 0 { + return multiple.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); + } + let mut handles = [0; 64]; + let handles = &mut handles[..count as usize]; + for (index, handle) in handles.iter_mut().enumerate() { + let slot = address + .checked_add(index as u64 * 8) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + *handle = mem.read_u64(slot).map_err(ExitReason::MemoryFault)?; + } + wait_for_events(&multiple, handles, all, timeout) + }); + } for symbol in [ "CreateEventA", @@ -106,16 +121,16 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "SetEvent", "ResetEvent", "WaitForSingleObject", + "WaitForSingleObjectEx", "WaitForMultipleObjects", + "WaitForMultipleObjectsEx", ] { registry.alias(SYNCH_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); } - registry.alias( - "api-ms-win-core-synch-l1-2-1.dll", - KERNEL32, - "WaitForMultipleObjects", - ); + for symbol in ["WaitForMultipleObjects", "WaitForMultipleObjectsEx"] { + registry.alias("api-ms-win-core-synch-l1-2-1.dll", KERNEL32, symbol); + } } fn wait_for_events( diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index eb3b6d0b..d051da02 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1131,7 +1131,7 @@ fn test_guest_waits_for_multiple_events_through_iat() { .final_state .get(Register::Rax) }; - let wait = |handles: [u64; 2], all: bool| { + let wait = |handles: [u64; 2], all: bool, alertable: Option| { let mut code = vec![0x48, 0x83, 0xec, 0x28]; for (register, value) in [ ([0x48, 0xb9], 2u64), @@ -1142,6 +1142,12 @@ fn test_guest_waits_for_multiple_events_through_iat() { code.extend_from_slice(®ister); code.extend_from_slice(&value.to_le_bytes()); } + if let Some(alertable) = alertable { + // Fifth argument, at the first stack slot past the home area. + code.extend_from_slice(&[0x48, 0xb8]); + code.extend_from_slice(&u64::from(alertable).to_le_bytes()); + code.extend_from_slice(&[0x48, 0x89, 0x44, 0x24, 0x20]); + } append_import_call(&mut code, 0x2060); code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); code.resize(0x80, 0); @@ -1149,7 +1155,14 @@ fn test_guest_waits_for_multiple_events_through_iat() { code.extend_from_slice(&handle.to_le_bytes()); } let bytes = TestPeBuilder::new(IMAGE, 0x1000) - .add_import("api-ms-win-core-synch-l1-2-1.dll", "WaitForMultipleObjects") + .add_import( + "api-ms-win-core-synch-l1-2-1.dll", + if alertable.is_some() { + "WaitForMultipleObjectsEx" + } else { + "WaitForMultipleObjects" + }, + ) .code(&code) .build(); let mut imports = ImportRegistry::new(); @@ -1172,23 +1185,37 @@ fn test_guest_waits_for_multiple_events_through_iat() { let first = call("CreateEventW", &[0, 0, 1, 0]); let second = call("CreateEventW", &[0, 0, 0, 0]); - assert_eq!(wait([first, second], true), 258); - assert_eq!(wait([second, first], false), 1); - assert_eq!(wait([first, second], false), 258); + assert_eq!(wait([first, second], true, None), 258); + assert_eq!(wait([second, first], false, None), 1); + assert_eq!(wait([first, second], false, None), 258); assert_eq!(call("SetEvent", &[first]), 1); assert_eq!(call("SetEvent", &[second]), 1); - assert_eq!(wait([first, second], false), 0); + assert_eq!(wait([first, second], false, None), 0); assert_eq!(call("SetEvent", &[first]), 1); - assert_eq!(wait([first, second], true), 0); - assert_eq!(wait([first, second], false), 258); + assert_eq!(wait([first, second], true, None), 0); + assert_eq!(wait([first, second], false, None), 258); assert_eq!(call("SetEvent", &[first]), 1); - assert_eq!(wait([first, first], true), u64::from(u32::MAX)); + assert_eq!(wait([first, first], true, None), u64::from(u32::MAX)); assert_eq!(call("GetLastError", &[]), 87); - assert_eq!(wait([first, 0], false), u64::from(u32::MAX)); + assert_eq!(wait([first, 0], false, None), u64::from(u32::MAX)); assert_eq!(call("GetLastError", &[]), 6); - assert_eq!(wait([second, first], false), 1); + assert_eq!(wait([second, first], false, None), 1); + assert_eq!(call("SetEvent", &[first]), 1); + assert_eq!( + wait([first, second], false, Some(true)), + u64::from(u32::MAX) + ); + assert_eq!(call("GetLastError", &[]), 50); + assert_eq!(wait([first, second], false, Some(false)), 0); + + assert_eq!(call("SetEvent", &[second]), 1); + assert_eq!( + call("WaitForSingleObjectEx", &[second, 0, 1]), + u64::from(u32::MAX) + ); + assert_eq!(call("WaitForSingleObjectEx", &[second, 0, 0]), 0); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index 46eaf74c..b9aa0230 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -208,8 +208,10 @@ access, and setting or resetting requires modify-state access. `WaitForMultipleObjects` supports immediate waits on up to 64 events. Wait-any selects the first signaled handle. Wait-all consumes auto-reset signals only when every event is ready. Repeated handles and wait-all -aliases to the same event are rejected. Waits that would block remain -unsupported. +aliases to the same event are rejected. The extended single- and multiple- +object wait APIs support the same immediate behavior when alerting is +disabled. Alertable calls and waits that would block return an unsupported +error. See Microsoft's [event object documentation](https://learn.microsoft.com/windows/win32/sync/event-objects). From 06bdf189e45ce8adb4981a6d09cc3ef69730f3ac Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:41:24 -0500 Subject: [PATCH 19/82] Add counted guest semaphores to immediate waits Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 3 + crates/loader/src/services.rs | 8 +- crates/loader/src/services/events.rs | 164 +++++++++++++++++++++------ crates/loader/tests/runtime_x15.rs | 37 ++++++ docs/interfaces.md | 12 +- 6 files changed, 186 insertions(+), 40 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 61402702..afaa3c20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added unnamed guest semaphores with checked release and immediate mixed-object waits. + - Added non-alertable extended event waits through both Win64 wait APIs. - Added immediate wait-any and wait-all for guest event handles. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 58bc6b98..e360b5dd 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -776,6 +776,9 @@ impl SymbolDb { "CreateEventW", "SetEvent", "ResetEvent", + "CreateSemaphoreA", + "CreateSemaphoreW", + "ReleaseSemaphore", "WaitForSingleObject", "WaitForSingleObjectEx", "WaitForMultipleObjects", diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 38163431..2575f650 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -117,8 +117,8 @@ impl Clock for SystemClock { enum GuestObject { Thread(u32), - Event { - state: Arc>, + Waitable { + state: Arc>, access: u32, }, } @@ -366,7 +366,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc (*rights, None), - Some(GuestObject::Event { state, access }) => (*access, Some(Arc::clone(state))), + Some(GuestObject::Waitable { state, access }) => (*access, Some(Arc::clone(state))), None => return s.fail(ERROR_INVALID_HANDLE, 0), } }; @@ -384,7 +384,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc GuestObject::Event { state, access }, + Some(state) => GuestObject::Waitable { state, access }, None => GuestObject::Thread(access), }; thread.insert_handle(handle, object); diff --git a/crates/loader/src/services/events.rs b/crates/loader/src/services/events.rs index 2194b3fc..35153005 100644 --- a/crates/loader/src/services/events.rs +++ b/crates/loader/src/services/events.rs @@ -1,10 +1,10 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Unnamed event objects and waits that can resolve without a guest scheduler. +//! Unnamed event and semaphore objects and waits that can resolve without a guest scheduler. use super::{ - ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, - ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState, + ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS, + ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState, }; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; @@ -19,9 +19,51 @@ const WAIT_OBJECT_0: u64 = 0; const WAIT_TIMEOUT: u64 = 258; const WAIT_FAILED: u64 = u32::MAX as u64; -pub(super) struct Event { - manual_reset: bool, - signaled: bool, +const SEMAPHORE_ALL_ACCESS: u32 = 0x001f_0003; +const SEMAPHORE_MODIFY_STATE: u32 = 2; +const ERROR_TOO_MANY_POSTS: u32 = 298; + +pub(super) enum Waitable { + Event { manual_reset: bool, signaled: bool }, + Semaphore { count: i32, maximum: i32 }, +} + +impl Waitable { + fn is_ready(&self) -> bool { + match self { + Self::Event { signaled, .. } => *signaled, + Self::Semaphore { count, .. } => *count > 0, + } + } + + fn consume(&mut self) { + match self { + Self::Event { + manual_reset, + signaled, + } => *signaled = *manual_reset, + Self::Semaphore { count, .. } => *count -= 1, + } + } +} + +fn insert_waitable( + state: &ServicesState, + object: Waitable, + access: u32, +) -> Result { + let mut objects = state.objects.lock().expect("guest object state"); + let Some(handle) = objects.next_handle() else { + return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + }; + objects.insert_handle( + handle, + GuestObject::Waitable { + state: Arc::new(Mutex::new(object)), + access, + }, + ); + Ok(handle) } pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { @@ -35,21 +77,14 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if attributes != 0 || name != 0 { return state.fail(ERROR_NOT_SUPPORTED, 0); } - let mut objects = state.objects.lock().expect("guest object state"); - let Some(handle) = objects.next_handle() else { - return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); - }; - objects.insert_handle( - handle, - GuestObject::Event { - state: Arc::new(Mutex::new(Event { - manual_reset, - signaled, - })), - access: EVENT_ALL_ACCESS, + insert_waitable( + &state, + Waitable::Event { + manual_reset, + signaled, }, - ); - Ok(handle) + EVENT_ALL_ACCESS, + ) }); } @@ -58,21 +93,78 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc registry.register(KERNEL32, symbol, move |args, _, mem| { let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let objects = state.objects.lock().expect("guest object state"); - let Some(GuestObject::Event { + let Some(GuestObject::Waitable { state: event, access, }) = objects.handles.get(&handle) else { return state.fail(ERROR_INVALID_HANDLE, 0); }; + let mut event = event.lock().expect("guest waitable state"); + let Waitable::Event { + signaled: current, .. + } = &mut *event + else { + return state.fail(ERROR_INVALID_HANDLE, 0); + }; if access & EVENT_MODIFY_STATE == 0 { return state.fail(ERROR_ACCESS_DENIED, 0); } - event.lock().expect("guest event state").signaled = signaled; + *current = signaled; Ok(1) }); } + for symbol in ["CreateSemaphoreA", "CreateSemaphoreW"] { + let state = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let count = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32; + let maximum = args.get(2, mem).map_err(ExitReason::MemoryFault)? as i32; + let name = args.get(3, mem).map_err(ExitReason::MemoryFault)?; + if attributes != 0 || name != 0 { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + if maximum <= 0 || count < 0 || count > maximum { + return state.fail(ERROR_INVALID_PARAMETER, 0); + } + insert_waitable( + &state, + Waitable::Semaphore { count, maximum }, + SEMAPHORE_ALL_ACCESS, + ) + }); + } + + let release = Arc::clone(state); + registry.register(KERNEL32, "ReleaseSemaphore", move |args, _, mem| { + let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let amount = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32; + let output = args.get(2, mem).map_err(ExitReason::MemoryFault)?; + if amount <= 0 { + return release.fail(ERROR_INVALID_PARAMETER, 0); + } + let objects = release.objects.lock().expect("guest object state"); + let Some(GuestObject::Waitable { state, access }) = objects.handles.get(&handle) else { + return release.fail(ERROR_INVALID_HANDLE, 0); + }; + let mut state = state.lock().expect("guest waitable state"); + let Waitable::Semaphore { count, maximum } = &mut *state else { + return release.fail(ERROR_INVALID_HANDLE, 0); + }; + if access & SEMAPHORE_MODIFY_STATE == 0 { + return release.fail(ERROR_ACCESS_DENIED, 0); + } + if amount > *maximum - *count { + return release.fail(ERROR_TOO_MANY_POSTS, 0); + } + if output != 0 && mem.write_u32(output, *count as u32).is_err() { + return release.fail(ERROR_NOACCESS, 0); + } + *count += amount; + Ok(1) + }); + for (symbol, extended) in [ ("WaitForSingleObject", false), ("WaitForSingleObjectEx", true), @@ -84,7 +176,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if extended && args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 { return single.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); } - wait_for_events(&single, &[handle], false, timeout) + wait_for_objects(&single, &[handle], false, timeout) }); } for (symbol, extended) in [ @@ -111,7 +203,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; *handle = mem.read_u64(slot).map_err(ExitReason::MemoryFault)?; } - wait_for_events(&multiple, handles, all, timeout) + wait_for_objects(&multiple, handles, all, timeout) }); } @@ -120,6 +212,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "CreateEventW", "SetEvent", "ResetEvent", + "CreateSemaphoreA", + "CreateSemaphoreW", + "ReleaseSemaphore", "WaitForSingleObject", "WaitForSingleObjectEx", "WaitForMultipleObjects", @@ -133,7 +228,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } } -fn wait_for_events( +fn wait_for_objects( state: &ServicesState, handles: &[u64], all: bool, @@ -141,23 +236,27 @@ fn wait_for_events( ) -> Result { // The object table remains locked through validation and consumption. let objects = state.objects.lock().expect("guest object state"); - let mut events: Vec<&Arc>> = Vec::with_capacity(handles.len()); + let mut waitables: Vec<&Arc>> = Vec::with_capacity(handles.len()); for (index, handle) in handles.iter().enumerate() { if handles[..index].contains(handle) { return state.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); } match objects.handles.get(handle) { - Some(GuestObject::Event { + Some(GuestObject::Waitable { state: event, access, }) => { if access & SYNCHRONIZE == 0 { return state.fail(ERROR_ACCESS_DENIED, WAIT_FAILED); } - if all && events.iter().any(|existing| Arc::ptr_eq(existing, event)) { + if all + && waitables + .iter() + .any(|existing| Arc::ptr_eq(existing, event)) + { return state.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); } - events.push(event); + waitables.push(event); } Some(_) => return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED), None if matches!(*handle, super::CURRENT_THREAD | super::CURRENT_PROCESS) => { @@ -167,8 +266,8 @@ fn wait_for_events( } } let mut ready = Vec::with_capacity(handles.len()); - for (index, event) in events.into_iter().enumerate() { - if event.lock().expect("guest event state").signaled { + for (index, event) in waitables.into_iter().enumerate() { + if event.lock().expect("guest waitable state").is_ready() { ready.push((index, event)); if !all { break; @@ -184,8 +283,7 @@ fn wait_for_events( } let first = ready[0].0; for (_, event) in ready { - let mut event = event.lock().expect("guest event state"); - event.signaled = event.manual_reset; + event.lock().expect("guest waitable state").consume(); } Ok(WAIT_OBJECT_0 + first as u64) } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index d051da02..3f7faee7 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,37 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn test_guest_semaphore_counts_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |symbol, args: &[u64]| call_service_fixture(&state, "kernel32.dll", symbol, args); + let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); + assert_eq!(value("CreateSemaphoreW", &[0, 3, 2, 0]), 0); + let handle = value("CreateSemaphoreW", &[0, 1, 2, 0]); + assert_ne!(handle, 0); + assert_eq!(value("SetEvent", &[handle]), 0); + assert_eq!(value("ReleaseSemaphore", &[handle, 2, 0]), 0); + assert_eq!(value("GetLastError", &[]), 298); + assert_eq!(value("ReleaseSemaphore", &[handle, 1, u64::MAX]), 0); + assert_eq!(value("GetLastError", &[]), 998); + + let released = call("ReleaseSemaphore", &[handle, 1, PROCESS_FIXTURE_OUTPUT]); + assert_eq!(released.execution.final_state.get(Register::Rax), 1); + assert_eq!( + released + .image + .memory + .read_u64(PROCESS_FIXTURE_OUTPUT) + .unwrap(), + 0xffff_ffff_0000_0001 + ); + for expected in [0, 0, 258] { + assert_eq!(value("WaitForSingleObject", &[handle, 0]), expected); + } + assert_eq!(value("CloseHandle", &[handle]), 1); + assert_eq!(value("ReleaseSemaphore", &[handle, 1, 0]), 0); +} + #[test] fn test_guest_waits_for_multiple_events_through_iat() { const IMAGE: u64 = 0x140000000; @@ -1216,6 +1247,12 @@ fn test_guest_waits_for_multiple_events_through_iat() { u64::from(u32::MAX) ); assert_eq!(call("WaitForSingleObjectEx", &[second, 0, 0]), 0); + let semaphore = call("CreateSemaphoreW", &[0, 1, 2, 0]); + assert_ne!(semaphore, 0); + assert_eq!(wait([semaphore, first], true, None), 258); + assert_eq!(call("SetEvent", &[first]), 1); + assert_eq!(wait([semaphore, first], true, None), 0); + assert_eq!(wait([semaphore, first], false, None), 258); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index b9aa0230..3e02586b 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -192,7 +192,7 @@ clamps the result and sets ERANGE. Scans have a 1 MiB input budget. The long-lon Microsoft's _strtoi64, _strtoui64, _wcstoi64, and _wcstoui64 apply the same rules with 64-bit results. -### Event signaling +### Event and semaphore signaling The synthetic runtime supports unnamed manual-reset and auto-reset events created with default security attributes. `SetEvent` signals an event, @@ -205,14 +205,20 @@ Event duplicates share signal state and keep the event alive independently. A duplicate can retain or reduce its rights. Waiting requires synchronize access, and setting or resetting requires modify-state access. -`WaitForMultipleObjects` supports immediate waits on up to 64 events. +`WaitForMultipleObjects` supports immediate waits on up to 64 events or semaphores. Wait-any selects the first signaled handle. Wait-all consumes auto-reset -signals only when every event is ready. Repeated handles and wait-all +signals only when every object is ready. Repeated handles and wait-all aliases to the same event are rejected. The extended single- and multiple- object wait APIs support the same immediate behavior when alerting is disabled. Alertable calls and waits that would block return an unsupported error. +`CreateSemaphoreA` and `CreateSemaphoreW` create unnamed semaphores +with default security attributes. A successful wait consumes one permit. +`ReleaseSemaphore` can return the previous count and rejects a release +that exceeds the maximum without changing the count. Duplicates share +the same permit count. + See Microsoft's [event object documentation](https://learn.microsoft.com/windows/win32/sync/event-objects). ## Synthetic tiled textures From 6a6074993992f93b83c246ea62e2c57990c0ff5d Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:43:49 -0500 Subject: [PATCH 20/82] Provide bounded synchronous guest file IO on a synthetic drive Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 19 +-- crates/loader/src/memory.rs | 15 ++ crates/loader/src/services.rs | 5 + crates/loader/src/services/files.rs | 235 ++++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 79 ++++++++++ docs/interfaces.md | 10 ++ 7 files changed, 351 insertions(+), 14 deletions(-) create mode 100644 crates/loader/src/services/files.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index afaa3c20..fa212667 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries. + - Added unnamed guest semaphores with checked release and immediate mixed-object waits. - Added non-alertable extended event waits through both Win64 wait APIs. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index e360b5dd..ad5b57ba 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -970,22 +970,13 @@ impl SymbolDb { false, "CreateFile — stub returning INVALID_HANDLE_VALUE", ); - self.win32_stub( - m, - "CreateFileW", - false, - "CreateFileW — stub returning INVALID_HANDLE_VALUE", - ); - self.win32_stub(m, "ReadFile", false, "ReadFile — stub returning FALSE"); - self.win32_stub(m, "WriteFile", false, "WriteFile — stub returning FALSE"); + for module in [m, "kernel32.dll"] { + for symbol in ["CreateFileW", "ReadFile", "WriteFile", "GetFileSizeEx"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub"); self.win32_stub(m, "GetFileSize", false, "GetFileSize — stub returning 0"); - self.win32_stub( - m, - "GetFileSizeEx", - false, - "GetFileSizeEx — stub returning 0", - ); self.win32_stub(m, "SetFilePointerEx", false, "SetFilePointerEx — stub"); self.win32_stub( m, diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index 58cd0084..2198302f 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -388,6 +388,21 @@ impl GuestMemory { true } + pub(crate) fn check_write(&self, address: u64, size: usize) -> Result<(), MemoryError> { + let region = self + .regions + .iter() + .find(|region| region.contains(address, size)) + .ok_or(MemoryError::UnmappedAddress(address))?; + if !region.permissions.write { + return Err(MemoryError::PermissionViolation { + address, + required: "write", + }); + } + Ok(()) + } + /// Write raw bytes into guest memory at the specified address, checking permissions. pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> { for region in &mut self.regions { diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 2575f650..4c2c77f7 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -11,6 +11,7 @@ mod crt; mod events; +mod files; mod heap; use crate::cpu::ExitReason; @@ -117,6 +118,7 @@ impl Clock for SystemClock { enum GuestObject { Thread(u32), + File(files::OpenFile), Waitable { state: Arc>, access: u32, @@ -128,6 +130,7 @@ struct ObjectState { priority: i32, last_handle: u64, handles: BTreeMap, + files: BTreeMap>, } impl ObjectState { @@ -367,6 +370,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc (*rights, None), Some(GuestObject::Waitable { state, access }) => (*access, Some(Arc::clone(state))), + Some(GuestObject::File(_)) => return s.fail(ERROR_NOT_SUPPORTED, 0), None => return s.fail(ERROR_INVALID_HANDLE, 0), } }; @@ -394,6 +398,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result, MemoryError> { + if address == 0 { + return Ok(None); + } + let mut units = Vec::new(); + for index in 0..260 { + let slot = address + .checked_add(index * 2) + .ok_or(MemoryError::Overflow)?; + let unit = memory.read_u16(slot)?; + if unit == 0 { + let Ok(path) = String::from_utf16(&units) else { + return Ok(None); + }; + let path = path.replace('/', "\\").to_ascii_lowercase(); + let name = path.strip_prefix("c:\\").unwrap_or(&path); + let device = name.split('.').next().unwrap_or_default(); + if name.is_empty() + || name.ends_with([' ', '.']) + || name + .chars() + .any(|c| c.is_control() || "\\/:*?\"<>|".contains(c)) + || matches!(device, "con" | "prn" | "aux" | "nul") + || (device.len() == 4 + && (device.starts_with("com") || device.starts_with("lpt")) + && device.as_bytes()[3].is_ascii_digit()) + { + return Ok(None); + } + return Ok(Some(name.to_owned())); + } + units.push(unit); + } + Ok(None) +} + +fn share_mask(access: u32) -> u32 { + u32::from(access & READ != 0) | (u32::from(access & WRITE != 0) << 1) +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + let open = Arc::clone(state); + registry.register(KERNEL32, "CreateFileW", move |args, _, memory| { + let access = args.rdx as u32; + let share = args.r8 as u32; + let disposition = args.get(4, memory).map_err(ExitReason::MemoryFault)? as u32; + let flags = args.get(5, memory).map_err(ExitReason::MemoryFault)? as u32; + let template = args.get(6, memory).map_err(ExitReason::MemoryFault)?; + if args.r9 != 0 + || template != 0 + || !matches!(flags, 0 | 0x80) + || access & !(READ | WRITE) != 0 + || share & !3 != 0 + { + return open.fail(ERROR_NOT_SUPPORTED, INVALID_HANDLE); + } + if !(1..=5).contains(&disposition) { + return open.fail(ERROR_INVALID_PARAMETER, INVALID_HANDLE); + } + if matches!(disposition, 2 | 5) && access & WRITE == 0 { + return open.fail(ERROR_ACCESS_DENIED, INVALID_HANDLE); + } + let Some(path) = flat_guest_name(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return open.fail(INVALID_NAME, INVALID_HANDLE); + }; + let mut objects = open.objects.lock().expect("guest object state"); + let exists = objects.files.contains_key(&path); + if exists && disposition == 1 { + return open.fail(FILE_EXISTS, INVALID_HANDLE); + } + if !exists && matches!(disposition, 3 | 5) { + return open.fail(FILE_NOT_FOUND, INVALID_HANDLE); + } + for object in objects.handles.values() { + if let GuestObject::File(file) = object + && file.path == path + && (share_mask(access) & !file.share != 0 || share_mask(file.access) & !share != 0) + { + return open.fail(SHARING_VIOLATION, INVALID_HANDLE); + } + } + let Some(handle) = objects.next_handle() else { + return open.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); + }; + if !exists { + if objects.files.len() >= MAX_FILES { + return open.fail(DISK_FULL, INVALID_HANDLE); + } + objects.files.insert(path.clone(), Vec::new()); + } else if matches!(disposition, 2 | 5) { + *objects.files.get_mut(&path).expect("existing file") = Vec::new(); + } + if matches!(disposition, 2 | 4) { + open.fail(if exists { ALREADY_EXISTS } else { 0 }, 0)?; + } + objects.insert_handle( + handle, + GuestObject::File(OpenFile { + path, + position: 0, + access, + share, + }), + ); + Ok(handle) + }); + + let size = Arc::clone(state); + registry.register(KERNEL32, "GetFileSizeEx", move |args, _, memory| { + let objects = size.objects.lock().expect("guest object state"); + let Some(GuestObject::File(file)) = objects.handles.get(&args.rcx) else { + return size.fail(ERROR_INVALID_HANDLE, 0); + }; + let bytes = objects + .files + .get(&file.path) + .expect("open file exists") + .len(); + if args.rdx == 0 || memory.write_u64(args.rdx, bytes as u64).is_err() { + return size.fail(ERROR_NOACCESS, 0); + } + Ok(1) + }); + + for (symbol, writing) in [("ReadFile", false), ("WriteFile", true)] { + let state = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, memory| { + if args.get(4, memory).map_err(ExitReason::MemoryFault)? != 0 { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + let count = args.r8 as u32 as usize; + if count > MAX_TRANSFER { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + let mut objects = state.objects.lock().expect("guest object state"); + let super::ObjectState { handles, files, .. } = &mut *objects; + let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else { + return state.fail(ERROR_INVALID_HANDLE, 0); + }; + let required = if writing { WRITE } else { READ }; + if file.access & required == 0 { + return state.fail(ERROR_ACCESS_DENIED, 0); + } + if args.r9 == 0 || memory.check_write(args.r9, 4).is_err() { + return state.fail(ERROR_NOACCESS, 0); + } + + let used = if writing { + files.values().map(Vec::len).sum::() + } else { + 0 + }; + let data = files.get_mut(&file.path).expect("open file exists"); + let position = file.position; + let transferred = if writing { + if count == 0 { + 0 + } else { + let end = position + count; + let growth = end.saturating_sub(data.len()); + if growth > MAX_BYTES - used { + return state.fail(DISK_FULL, 0); + } + let mut input = vec![0; count]; + if args.rdx == 0 || memory.read_bytes(args.rdx, &mut input).is_err() { + return state.fail(ERROR_NOACCESS, 0); + } + if growth != 0 { + data.try_reserve_exact(growth) + .map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?; + data.resize(end, 0); + } + data[position..end].copy_from_slice(&input); + count + } + } else { + let start = position.min(data.len()); + let transferred = count.min(data.len() - start); + if transferred != 0 + && (args.rdx == 0 + || memory + .write_bytes(args.rdx, &data[start..start + transferred]) + .is_err()) + { + return state.fail(ERROR_NOACCESS, 0); + } + transferred + }; + memory + .write_u32(args.r9, transferred as u32) + .map_err(ExitReason::MemoryFault)?; + file.position += transferred; + Ok(1) + }); + } + + for symbol in ["CreateFileW", "GetFileSizeEx", "ReadFile", "WriteFile"] { + registry.alias(FILE_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 3f7faee7..12e694b8 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,85 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn test_guest_synthetic_file_io_through_iat() { + const IMAGE: u64 = 0x140000000; + const MODULE: &str = "api-ms-win-core-file-l1-1-0.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let open = |name: &str, access: u64, disposition: u64| { + let mut code = vec![0x48, 0x83, 0xec, 0x48]; + for (register, value) in [ + ([0x48, 0xb9], IMAGE + 0x1080), + ([0x48, 0xba], access), + ([0x49, 0xb8], 0), + ([0x49, 0xb9], 0), + ] { + code.extend_from_slice(®ister); + code.extend_from_slice(&value.to_le_bytes()); + } + for (offset, value) in [(0x20, disposition), (0x28, 0x80), (0x30, 0)] { + code.extend_from_slice(&[0x48, 0xb8]); + code.extend_from_slice(&value.to_le_bytes()); + code.extend_from_slice(&[0x48, 0x89, 0x44, 0x24, offset]); + } + append_import_call(&mut code, 0x2060); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]); + code.resize(0x80, 0); + code.extend(name.encode_utf16().chain([0]).flat_map(u16::to_le_bytes)); + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import(MODULE, "CreateFileW") + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result.execution.final_state.get(Register::Rax) + }; + let call = |symbol, args: &[u64]| call_service_fixture(&state, "kernel32.dll", symbol, args); + let output = PROCESS_FIXTURE_OUTPUT; + assert_eq!(open("C:/../outside", 0x4000_0000, 2), u64::MAX); + let writer = open("C:/Sample.dat", 0x4000_0000, 2); + assert_ne!(writer, u64::MAX); + assert_eq!(open("sample.dat", 0x8000_0000, 3), u64::MAX); + let wrote = call("WriteFile", &[writer, output, 4, output + 8, 0]); + assert_eq!(wrote.execution.final_state.get(Register::Rax), 1); + assert_eq!(wrote.image.memory.read_u32(output + 8).unwrap(), 4); + assert_eq!( + call("CloseHandle", &[writer]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + + let reader = open("sample.DAT", 0x8000_0000, 3); + assert_ne!(reader, u64::MAX); + let size = call("GetFileSizeEx", &[reader, output]); + assert_eq!(size.execution.final_state.get(Register::Rax), 1); + assert_eq!(size.image.memory.read_u64(output).unwrap(), 4); + let read = call("ReadFile", &[reader, output + 8, 8, output, 0]); + assert_eq!(read.execution.final_state.get(Register::Rax), 1); + assert_eq!(read.image.memory.read_u32(output).unwrap(), 4); + assert_eq!( + read.image.memory.read_u64(output + 8).unwrap(), + u64::from(u32::MAX) + ); + let eof = call("ReadFile", &[reader, output + 8, 8, output, 0]); + assert_eq!(eof.execution.final_state.get(Register::Rax), 1); + assert_eq!(eof.image.memory.read_u32(output).unwrap(), 0); +} + #[test] fn test_guest_semaphore_counts_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index 3e02586b..cad77c66 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -192,6 +192,16 @@ clamps the result and sets ERANGE. Scans have a 1 MiB input budget. The long-lon Microsoft's _strtoi64, _strtoui64, _wcstoi64, and _wcstoui64 apply the same rules with 64-bit results. +### Synthetic guest files + +The runtime exposes an in-memory C: drive through CreateFileW, ReadFile, +WriteFile, GetFileSizeEx, and CloseHandle. It supports root-level UTF-16 +names, ASCII case folding, synchronous I/O, per-handle positions, and +read/write sharing. Paths cannot access host files. The drive supports +256 files and 16 MiB of data, with a 1 MiB limit per transfer. +Directories, persistence, asynchronous I/O, and file handle duplication +remain outside this subset. + ### Event and semaphore signaling The synthetic runtime supports unnamed manual-reset and auto-reset events From 2bc08a18515e2dfc3883b033c01d2bffc20152c9 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:45:02 -0500 Subject: [PATCH 21/82] Seek and resize files on the synthetic guest drive Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 10 +++- crates/loader/src/services/files.rs | 93 +++++++++++++++++++++++++++-- crates/loader/tests/runtime_x15.rs | 81 +++++++++++++++++++++++++ docs/interfaces.md | 5 +- 5 files changed, 182 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fa212667..2984e46a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added file seeking and end-of-file resizing on the synthetic guest drive. + - Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries. - Added unnamed guest semaphores with checked release and immediate mixed-object waits. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index ad5b57ba..1296b2f4 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -971,13 +971,19 @@ impl SymbolDb { "CreateFile — stub returning INVALID_HANDLE_VALUE", ); for module in [m, "kernel32.dll"] { - for symbol in ["CreateFileW", "ReadFile", "WriteFile", "GetFileSizeEx"] { + for symbol in [ + "CreateFileW", + "ReadFile", + "WriteFile", + "GetFileSizeEx", + "SetFilePointerEx", + "SetEndOfFile", + ] { self.ins(module, symbol, Classification::StandardService); } } self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub"); self.win32_stub(m, "GetFileSize", false, "GetFileSize — stub returning 0"); - self.win32_stub(m, "SetFilePointerEx", false, "SetFilePointerEx — stub"); self.win32_stub( m, "GetFileAttributesA", diff --git a/crates/loader/src/services/files.rs b/crates/loader/src/services/files.rs index 0abb6985..2ce38269 100644 --- a/crates/loader/src/services/files.rs +++ b/crates/loader/src/services/files.rs @@ -19,6 +19,7 @@ const FILE_NOT_FOUND: u32 = 2; const FILE_EXISTS: u32 = 80; const ALREADY_EXISTS: u32 = 183; const INVALID_NAME: u32 = 123; +const NEGATIVE_SEEK: u32 = 131; const SHARING_VIOLATION: u32 = 32; const DISK_FULL: u32 = 112; const MAX_FILES: usize = 256; @@ -27,7 +28,7 @@ const MAX_TRANSFER: usize = 1024 * 1024; pub(super) struct OpenFile { path: String, - position: usize, + position: u64, access: u32, share: u32, } @@ -156,6 +157,73 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); + let seek = Arc::clone(state); + registry.register(KERNEL32, "SetFilePointerEx", move |args, _, memory| { + let mut objects = seek.objects.lock().expect("guest object state"); + let super::ObjectState { handles, files, .. } = &mut *objects; + let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else { + return seek.fail(ERROR_INVALID_HANDLE, 0); + }; + if file.access & (READ | WRITE) == 0 { + return seek.fail(ERROR_ACCESS_DENIED, 0); + } + let origin = match args.r9 as u32 { + 0 => None, + 1 => Some(file.position), + 2 => Some(files.get(&file.path).expect("open file exists").len() as u64), + _ => return seek.fail(ERROR_INVALID_PARAMETER, 0), + }; + let position = match origin { + None => args.rdx, + Some(origin) => { + let distance = args.rdx as i64; + if distance.is_negative() && distance.unsigned_abs() > origin { + return seek.fail(NEGATIVE_SEEK, 0); + } + let Some(position) = origin.checked_add_signed(distance) else { + return seek.fail(ERROR_INVALID_PARAMETER, 0); + }; + position + } + }; + if args.r8 != 0 && memory.write_u64(args.r8, position).is_err() { + return seek.fail(ERROR_NOACCESS, 0); + } + file.position = position; + Ok(1) + }); + + let truncate = Arc::clone(state); + registry.register(KERNEL32, "SetEndOfFile", move |args, _, _| { + let mut objects = truncate.objects.lock().expect("guest object state"); + let super::ObjectState { handles, files, .. } = &mut *objects; + let Some(GuestObject::File(file)) = handles.get(&args.rcx) else { + return truncate.fail(ERROR_INVALID_HANDLE, 0); + }; + if file.access & WRITE == 0 { + return truncate.fail(ERROR_ACCESS_DENIED, 0); + } + if file.position > MAX_BYTES as u64 { + return truncate.fail(DISK_FULL, 0); + } + let used = files.values().map(Vec::len).sum::(); + let data = files.get_mut(&file.path).expect("open file exists"); + let length = file.position as usize; + let growth = length.saturating_sub(data.len()); + if growth > MAX_BYTES - used { + return truncate.fail(DISK_FULL, 0); + } + data.try_reserve_exact(growth) + .map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?; + if length < data.len() { + data.truncate(length); + data.shrink_to_fit(); + } else { + data.resize(length, 0); + } + Ok(1) + }); + for (symbol, writing) in [("ReadFile", false), ("WriteFile", true)] { let state = Arc::clone(state); registry.register(KERNEL32, symbol, move |args, _, memory| { @@ -190,7 +258,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if count == 0 { 0 } else { - let end = position + count; + let Some(end) = position + .checked_add(count as u64) + .filter(|end| *end <= MAX_BYTES as u64) + else { + return state.fail(DISK_FULL, 0); + }; + let end = end as usize; let growth = end.saturating_sub(data.len()); if growth > MAX_BYTES - used { return state.fail(DISK_FULL, 0); @@ -204,11 +278,11 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?; data.resize(end, 0); } - data[position..end].copy_from_slice(&input); + data[position as usize..end].copy_from_slice(&input); count } } else { - let start = position.min(data.len()); + let start = position.min(data.len() as u64) as usize; let transferred = count.min(data.len() - start); if transferred != 0 && (args.rdx == 0 @@ -223,12 +297,19 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc memory .write_u32(args.r9, transferred as u32) .map_err(ExitReason::MemoryFault)?; - file.position += transferred; + file.position += transferred as u64; Ok(1) }); } - for symbol in ["CreateFileW", "GetFileSizeEx", "ReadFile", "WriteFile"] { + for symbol in [ + "CreateFileW", + "GetFileSizeEx", + "ReadFile", + "WriteFile", + "SetFilePointerEx", + "SetEndOfFile", + ] { registry.alias(FILE_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 12e694b8..9a3a26c5 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1198,6 +1198,87 @@ fn test_guest_synthetic_file_io_through_iat() { let eof = call("ReadFile", &[reader, output + 8, 8, output, 0]); assert_eq!(eof.execution.final_state.get(Register::Rax), 1); assert_eq!(eof.image.memory.read_u32(output).unwrap(), 0); + let seek = call("SetFilePointerEx", &[reader, (-2i64) as u64, output, 2]); + assert_eq!(seek.execution.final_state.get(Register::Rax), 1); + assert_eq!(seek.image.memory.read_u64(output).unwrap(), 2); + let rejected = call("SetFilePointerEx", &[reader, (-3i64) as u64, output, 1]); + assert_eq!(rejected.execution.final_state.get(Register::Rax), 0); + let read = call("ReadFile", &[reader, output + 8, 8, output, 0]); + assert_eq!(read.image.memory.read_u32(output).unwrap(), 2); + assert_eq!( + call("SetEndOfFile", &[reader]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + assert_eq!( + call("CloseHandle", &[reader]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + + let writer = open("sample.dat", 0xc000_0000, 3); + assert_ne!(writer, u64::MAX); + assert_eq!( + call("SetFilePointerEx", &[writer, 2, 0, 0]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!( + call("SetEndOfFile", &[writer]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + let size = call("GetFileSizeEx", &[writer, output]); + assert_eq!(size.image.memory.read_u64(output).unwrap(), 2); + assert_eq!( + call("SetFilePointerEx", &[writer, 6, 0, 0]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!( + call("SetEndOfFile", &[writer]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!( + call("SetFilePointerEx", &[writer, 0, 0, 0]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + let read = call("ReadFile", &[writer, output + 8, 8, output, 0]); + assert_eq!(read.image.memory.read_u32(output).unwrap(), 6); + assert_eq!(read.image.memory.read_u64(output + 8).unwrap(), 0xffff); + + assert_eq!( + call("SetFilePointerEx", &[writer, u64::MAX, 0, 0]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!( + call("WriteFile", &[writer, output, 1, output + 8, 0]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + let size = call("GetFileSizeEx", &[writer, output]); + assert_eq!(size.image.memory.read_u64(output).unwrap(), 6); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index cad77c66..856edfad 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -197,7 +197,10 @@ same rules with 64-bit results. The runtime exposes an in-memory C: drive through CreateFileW, ReadFile, WriteFile, GetFileSizeEx, and CloseHandle. It supports root-level UTF-16 names, ASCII case folding, synchronous I/O, per-handle positions, and -read/write sharing. Paths cannot access host files. The drive supports +read/write sharing. SetFilePointerEx supports seeking from the beginning, +current position, and end. SetEndOfFile truncates or zero-extends writable +files at the current position. Seeks alone do not change file length. +Paths cannot access host files. The drive supports 256 files and 16 MiB of data, with a 1 MiB limit per transfer. Directories, persistence, asynchronous I/O, and file handle duplication remain outside this subset. From ab598f0820e0998c321089492ceda156e7d7c747 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:46:24 -0500 Subject: [PATCH 22/82] Manage directories and closed files in the guest namespace Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 9 +-- crates/loader/src/services.rs | 3 +- crates/loader/src/services/files.rs | 119 ++++++++++++++++++++++++---- crates/loader/tests/runtime_x15.rs | 27 ++++++- docs/interfaces.md | 11 ++- 6 files changed, 142 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2984e46a..3b0f6081 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added nested guest directories and checked file deletion on the synthetic drive. + - Added file seeking and end-of-file resizing on the synthetic guest drive. - Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 1296b2f4..9e7179d6 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -978,6 +978,9 @@ impl SymbolDb { "GetFileSizeEx", "SetFilePointerEx", "SetEndOfFile", + "CreateDirectoryW", + "RemoveDirectoryW", + "DeleteFileW", ] { self.ins(module, symbol, Classification::StandardService); } @@ -992,12 +995,6 @@ impl SymbolDb { ); self.win32_stub(m, "GetFileAttributesW", false, "GetFileAttributesW — stub"); self.win32_stub(m, "DeleteFileA", false, "DeleteFile — stub returning FALSE"); - self.win32_stub( - m, - "DeleteFileW", - false, - "DeleteFileW — stub returning FALSE", - ); self.win32_stub( m, "FlushFileBuffers", diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 4c2c77f7..b4cd0f66 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -17,7 +17,7 @@ mod heap; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Instant; @@ -131,6 +131,7 @@ struct ObjectState { last_handle: u64, handles: BTreeMap, files: BTreeMap>, + directories: BTreeSet, } impl ObjectState { diff --git a/crates/loader/src/services/files.rs b/crates/loader/src/services/files.rs index 2ce38269..5675de59 100644 --- a/crates/loader/src/services/files.rs +++ b/crates/loader/src/services/files.rs @@ -16,6 +16,8 @@ const INVALID_HANDLE: u64 = u64::MAX; const READ: u32 = 0x8000_0000; const WRITE: u32 = 0x4000_0000; const FILE_NOT_FOUND: u32 = 2; +const PATH_NOT_FOUND: u32 = 3; +const DIRECTORY_NOT_EMPTY: u32 = 145; const FILE_EXISTS: u32 = 80; const ALREADY_EXISTS: u32 = 183; const INVALID_NAME: u32 = 123; @@ -23,6 +25,7 @@ const NEGATIVE_SEEK: u32 = 131; const SHARING_VIOLATION: u32 = 32; const DISK_FULL: u32 = 112; const MAX_FILES: usize = 256; +const MAX_DIRECTORIES: usize = 256; const MAX_BYTES: usize = 16 * 1024 * 1024; const MAX_TRANSFER: usize = 1024 * 1024; @@ -33,7 +36,7 @@ pub(super) struct OpenFile { share: u32, } -fn flat_guest_name(memory: &GuestMemory, address: u64) -> Result, MemoryError> { +fn guest_path(memory: &GuestMemory, address: u64) -> Result, MemoryError> { if address == 0 { return Ok(None); } @@ -49,26 +52,33 @@ fn flat_guest_name(memory: &GuestMemory, address: u64) -> Result, }; let path = path.replace('/', "\\").to_ascii_lowercase(); let name = path.strip_prefix("c:\\").unwrap_or(&path); - let device = name.split('.').next().unwrap_or_default(); - if name.is_empty() - || name.ends_with([' ', '.']) - || name - .chars() - .any(|c| c.is_control() || "\\/:*?\"<>|".contains(c)) - || matches!(device, "con" | "prn" | "aux" | "nul") - || (device.len() == 4 - && (device.starts_with("com") || device.starts_with("lpt")) - && device.as_bytes()[3].is_ascii_digit()) - { - return Ok(None); - } - return Ok(Some(name.to_owned())); + return Ok(name + .split('\\') + .all(valid_component) + .then(|| name.to_owned())); } units.push(unit); } Ok(None) } +fn valid_component(name: &str) -> bool { + let device = name.split('.').next().unwrap_or_default(); + !name.is_empty() + && !name.ends_with([' ', '.']) + && !name + .chars() + .any(|c| c.is_control() || "\\/:*?\"<>|".contains(c)) + && !matches!(device, "con" | "prn" | "aux" | "nul") + && !(device.len() == 4 + && (device.starts_with("com") || device.starts_with("lpt")) + && device.as_bytes()[3].is_ascii_digit()) +} + +fn parent(path: &str) -> &str { + path.rsplit_once('\\').map_or("", |(parent, _)| parent) +} + fn share_mask(access: u32) -> u32 { u32::from(access & READ != 0) | (u32::from(access & WRITE != 0) << 1) } @@ -95,10 +105,17 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if matches!(disposition, 2 | 5) && access & WRITE == 0 { return open.fail(ERROR_ACCESS_DENIED, INVALID_HANDLE); } - let Some(path) = flat_guest_name(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { return open.fail(INVALID_NAME, INVALID_HANDLE); }; let mut objects = open.objects.lock().expect("guest object state"); + let parent = parent(&path); + if !parent.is_empty() && !objects.directories.contains(parent) { + return open.fail(PATH_NOT_FOUND, INVALID_HANDLE); + } + if objects.directories.contains(&path) { + return open.fail(ERROR_ACCESS_DENIED, INVALID_HANDLE); + } let exists = objects.files.contains_key(&path); if exists && disposition == 1 { return open.fail(FILE_EXISTS, INVALID_HANDLE); @@ -140,6 +157,73 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(handle) }); + let create = Arc::clone(state); + registry.register(KERNEL32, "CreateDirectoryW", move |args, _, memory| { + if args.rdx != 0 { + return create.fail(ERROR_NOT_SUPPORTED, 0); + } + let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return create.fail(INVALID_NAME, 0); + }; + let mut objects = create.objects.lock().expect("guest object state"); + let parent = parent(&path); + if !parent.is_empty() && !objects.directories.contains(parent) { + return create.fail(PATH_NOT_FOUND, 0); + } + if objects.directories.contains(&path) || objects.files.contains_key(&path) { + return create.fail(ALREADY_EXISTS, 0); + } + if objects.directories.len() >= MAX_DIRECTORIES { + return create.fail(DISK_FULL, 0); + } + objects.directories.insert(path); + Ok(1) + }); + + let remove = Arc::clone(state); + registry.register(KERNEL32, "RemoveDirectoryW", move |args, _, memory| { + let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return remove.fail(INVALID_NAME, 0); + }; + let mut objects = remove.objects.lock().expect("guest object state"); + if !objects.directories.contains(&path) { + return remove.fail(PATH_NOT_FOUND, 0); + } + if objects.directories.iter().any(|key| parent(key) == path) + || objects.files.keys().any(|key| parent(key) == path) + { + return remove.fail(DIRECTORY_NOT_EMPTY, 0); + } + objects.directories.remove(&path); + Ok(1) + }); + + let delete = Arc::clone(state); + registry.register(KERNEL32, "DeleteFileW", move |args, _, memory| { + let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return delete.fail(INVALID_NAME, 0); + }; + let mut objects = delete.objects.lock().expect("guest object state"); + if objects.directories.contains(&path) { + return delete.fail(ERROR_ACCESS_DENIED, 0); + } + let parent = parent(&path); + if !parent.is_empty() && !objects.directories.contains(parent) { + return delete.fail(PATH_NOT_FOUND, 0); + } + if objects + .handles + .values() + .any(|object| matches!(object, GuestObject::File(file) if file.path == path)) + { + return delete.fail(SHARING_VIOLATION, 0); + } + if objects.files.remove(&path).is_none() { + return delete.fail(FILE_NOT_FOUND, 0); + } + Ok(1) + }); + let size = Arc::clone(state); registry.register(KERNEL32, "GetFileSizeEx", move |args, _, memory| { let objects = size.objects.lock().expect("guest object state"); @@ -309,6 +393,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "WriteFile", "SetFilePointerEx", "SetEndOfFile", + "CreateDirectoryW", + "RemoveDirectoryW", + "DeleteFileW", ] { registry.alias(FILE_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 9a3a26c5..f002a9d7 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1126,7 +1126,7 @@ fn test_guest_synthetic_file_io_through_iat() { const IMAGE: u64 = 0x140000000; const MODULE: &str = "api-ms-win-core-file-l1-1-0.dll"; let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); - let open = |name: &str, access: u64, disposition: u64| { + let path_call = |symbol, name: &str, access: u64, disposition: u64| { let mut code = vec![0x48, 0x83, 0xec, 0x48]; for (register, value) in [ ([0x48, 0xb9], IMAGE + 0x1080), @@ -1147,7 +1147,7 @@ fn test_guest_synthetic_file_io_through_iat() { code.resize(0x80, 0); code.extend(name.encode_utf16().chain([0]).flat_map(u16::to_le_bytes)); let bytes = TestPeBuilder::new(IMAGE, 0x1000) - .add_import(MODULE, "CreateFileW") + .add_import(MODULE, symbol) .code(&code) .build(); let mut imports = ImportRegistry::new(); @@ -1166,6 +1166,8 @@ fn test_guest_synthetic_file_io_through_iat() { assert_eq!(result.execution.exit_reason, ExitReason::Halt); result.execution.final_state.get(Register::Rax) }; + let open = |name, access, disposition| path_call("CreateFileW", name, access, disposition); + let namespace = |symbol, path| path_call(symbol, path, 0, 0); let call = |symbol, args: &[u64]| call_service_fixture(&state, "kernel32.dll", symbol, args); let output = PROCESS_FIXTURE_OUTPUT; assert_eq!(open("C:/../outside", 0x4000_0000, 2), u64::MAX); @@ -1279,6 +1281,27 @@ fn test_guest_synthetic_file_io_through_iat() { ); let size = call("GetFileSizeEx", &[writer, output]); assert_eq!(size.image.memory.read_u64(output).unwrap(), 6); + assert_eq!(open("C:/Data/save.bin", 0x4000_0000, 2), u64::MAX); + assert_eq!(namespace("CreateDirectoryW", "C:/Data"), 1); + assert_eq!(namespace("CreateDirectoryW", "C:/Data/Nested"), 1); + assert_eq!(namespace("CreateDirectoryW", "C:/Data/../escape"), 0); + assert_eq!(namespace("CreateDirectoryW", "data/nested"), 0); + let nested = open("Data/Nested/save.bin", 0x4000_0000, 2); + assert_ne!(nested, u64::MAX); + assert_eq!(namespace("RemoveDirectoryW", "DATA"), 0); + assert_eq!(namespace("RemoveDirectoryW", "DATA/NESTED"), 0); + assert_eq!(namespace("DeleteFileW", "DATA/NESTED/SAVE.BIN"), 0); + assert_eq!( + call("CloseHandle", &[nested]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!(namespace("DeleteFileW", "DATA/NESTED/SAVE.BIN"), 1); + assert_eq!(open("data/nested/save.bin", 0x8000_0000, 3), u64::MAX); + assert_eq!(namespace("RemoveDirectoryW", "DATA/NESTED"), 1); + assert_eq!(namespace("RemoveDirectoryW", "DATA"), 1); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index 856edfad..825d72b5 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -195,15 +195,18 @@ same rules with 64-bit results. ### Synthetic guest files The runtime exposes an in-memory C: drive through CreateFileW, ReadFile, -WriteFile, GetFileSizeEx, and CloseHandle. It supports root-level UTF-16 -names, ASCII case folding, synchronous I/O, per-handle positions, and +WriteFile, GetFileSizeEx, and CloseHandle. It supports UTF-16 file and +directory names, ASCII case folding, synchronous I/O, per-handle positions, and read/write sharing. SetFilePointerEx supports seeking from the beginning, current position, and end. SetEndOfFile truncates or zero-extends writable files at the current position. Seeks alone do not change file length. Paths cannot access host files. The drive supports 256 files and 16 MiB of data, with a 1 MiB limit per transfer. -Directories, persistence, asynchronous I/O, and file handle duplication -remain outside this subset. +CreateDirectoryW and RemoveDirectoryW manage up to 256 directories. Parents +must exist, and directories must be empty before removal. DeleteFileW +deletes closed files. Traversal components and device names are rejected. +Persistence, directory enumeration, asynchronous I/O, and file handle +duplication remain outside this subset. ### Event and semaphore signaling From 3c9b8d988b09d927164d72d080e3c42c7357d6b7 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:47:34 -0500 Subject: [PATCH 23/82] Move closed guest files and report namespace attributes Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 3 +- crates/loader/src/services/files.rs | 60 +++++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 42 ++++++++++++++++++-- docs/interfaces.md | 4 +- 5 files changed, 105 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b0f6081..8e36cfd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added closed-file moves and file and directory attribute queries on the synthetic guest drive. + - Added nested guest directories and checked file deletion on the synthetic drive. - Added file seeking and end-of-file resizing on the synthetic guest drive. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 9e7179d6..289b0e94 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -981,6 +981,8 @@ impl SymbolDb { "CreateDirectoryW", "RemoveDirectoryW", "DeleteFileW", + "GetFileAttributesW", + "MoveFileW", ] { self.ins(module, symbol, Classification::StandardService); } @@ -993,7 +995,6 @@ impl SymbolDb { false, "GetFileAttributes — stub returning INVALID", ); - self.win32_stub(m, "GetFileAttributesW", false, "GetFileAttributesW — stub"); self.win32_stub(m, "DeleteFileA", false, "DeleteFile — stub returning FALSE"); self.win32_stub( m, diff --git a/crates/loader/src/services/files.rs b/crates/loader/src/services/files.rs index 5675de59..43fc8cec 100644 --- a/crates/loader/src/services/files.rs +++ b/crates/loader/src/services/files.rs @@ -224,6 +224,64 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); + let attributes = Arc::clone(state); + registry.register(KERNEL32, "GetFileAttributesW", move |args, _, memory| { + const INVALID_ATTRIBUTES: u64 = u32::MAX as u64; + let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return attributes.fail(INVALID_NAME, INVALID_ATTRIBUTES); + }; + let objects = attributes.objects.lock().expect("guest object state"); + if objects.directories.contains(&path) { + return Ok(0x10); // FILE_ATTRIBUTE_DIRECTORY + } + if objects.files.contains_key(&path) { + return Ok(0x80); // FILE_ATTRIBUTE_NORMAL + } + let parent = parent(&path); + let error = if parent.is_empty() || objects.directories.contains(parent) { + FILE_NOT_FOUND + } else { + PATH_NOT_FOUND + }; + attributes.fail(error, INVALID_ATTRIBUTES) + }); + + let rename = Arc::clone(state); + registry.register(KERNEL32, "MoveFileW", move |args, _, memory| { + let Some(source) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return rename.fail(INVALID_NAME, 0); + }; + let Some(target) = guest_path(memory, args.rdx).map_err(ExitReason::MemoryFault)? else { + return rename.fail(INVALID_NAME, 0); + }; + let mut objects = rename.objects.lock().expect("guest object state"); + if [parent(&source), parent(&target)] + .into_iter() + .any(|path| !path.is_empty() && !objects.directories.contains(path)) + { + return rename.fail(PATH_NOT_FOUND, 0); + } + if objects.directories.contains(&source) { + return rename.fail(ERROR_NOT_SUPPORTED, 0); + } + if !objects.files.contains_key(&source) { + return rename.fail(FILE_NOT_FOUND, 0); + } + if objects.files.contains_key(&target) || objects.directories.contains(&target) { + return rename.fail(ALREADY_EXISTS, 0); + } + if objects + .handles + .values() + .any(|object| matches!(object, GuestObject::File(file) if file.path == source)) + { + return rename.fail(SHARING_VIOLATION, 0); + } + let data = objects.files.remove(&source).expect("source file exists"); + objects.files.insert(target, data); + Ok(1) + }); + let size = Arc::clone(state); registry.register(KERNEL32, "GetFileSizeEx", move |args, _, memory| { let objects = size.objects.lock().expect("guest object state"); @@ -396,6 +454,8 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "CreateDirectoryW", "RemoveDirectoryW", "DeleteFileW", + "GetFileAttributesW", + "MoveFileW", ] { registry.alias(FILE_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index f002a9d7..88548be7 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1126,11 +1126,18 @@ fn test_guest_synthetic_file_io_through_iat() { const IMAGE: u64 = 0x140000000; const MODULE: &str = "api-ms-win-core-file-l1-1-0.dll"; let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); - let path_call = |symbol, name: &str, access: u64, disposition: u64| { + let path_call = |symbol, name: &str, access: u64, disposition: u64, target: Option<&str>| { let mut code = vec![0x48, 0x83, 0xec, 0x48]; for (register, value) in [ ([0x48, 0xb9], IMAGE + 0x1080), - ([0x48, 0xba], access), + ( + [0x48, 0xba], + if target.is_some() { + IMAGE + 0x1180 + } else { + access + }, + ), ([0x49, 0xb8], 0), ([0x49, 0xb9], 0), ] { @@ -1146,6 +1153,10 @@ fn test_guest_synthetic_file_io_through_iat() { code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]); code.resize(0x80, 0); code.extend(name.encode_utf16().chain([0]).flat_map(u16::to_le_bytes)); + if let Some(target) = target { + code.resize(0x180, 0); + code.extend(target.encode_utf16().chain([0]).flat_map(u16::to_le_bytes)); + } let bytes = TestPeBuilder::new(IMAGE, 0x1000) .add_import(MODULE, symbol) .code(&code) @@ -1166,8 +1177,9 @@ fn test_guest_synthetic_file_io_through_iat() { assert_eq!(result.execution.exit_reason, ExitReason::Halt); result.execution.final_state.get(Register::Rax) }; - let open = |name, access, disposition| path_call("CreateFileW", name, access, disposition); - let namespace = |symbol, path| path_call(symbol, path, 0, 0); + let open = + |name, access, disposition| path_call("CreateFileW", name, access, disposition, None); + let namespace = |symbol, path| path_call(symbol, path, 0, 0, None); let call = |symbol, args: &[u64]| call_service_fixture(&state, "kernel32.dll", symbol, args); let output = PROCESS_FIXTURE_OUTPUT; assert_eq!(open("C:/../outside", 0x4000_0000, 2), u64::MAX); @@ -1302,6 +1314,28 @@ fn test_guest_synthetic_file_io_through_iat() { assert_eq!(open("data/nested/save.bin", 0x8000_0000, 3), u64::MAX); assert_eq!(namespace("RemoveDirectoryW", "DATA/NESTED"), 1); assert_eq!(namespace("RemoveDirectoryW", "DATA"), 1); + let move_file = |source, target| path_call("MoveFileW", source, 0, 0, Some(target)); + assert_eq!(namespace("GetFileAttributesW", "sample.dat"), 0x80); + assert_eq!(move_file("sample.dat", "moved.dat"), 0); // Open writer. + assert_eq!( + call("CloseHandle", &[writer]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!(move_file("sample.dat", "missing/moved.dat"), 0); + assert_eq!(namespace("CreateDirectoryW", "Archive"), 1); + assert_eq!(namespace("GetFileAttributesW", "archive"), 0x10); + assert_eq!(move_file("sample.dat", "archive/moved.dat"), 1); + assert_eq!( + namespace("GetFileAttributesW", "sample.dat"), + u64::from(u32::MAX) + ); + let moved = open("Archive/Moved.DAT", 0x8000_0000, 3); + assert_ne!(moved, u64::MAX); + let size = call("GetFileSizeEx", &[moved, output]); + assert_eq!(size.image.memory.read_u64(output).unwrap(), 6); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index 825d72b5..e0b5eb02 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -204,7 +204,9 @@ Paths cannot access host files. The drive supports 256 files and 16 MiB of data, with a 1 MiB limit per transfer. CreateDirectoryW and RemoveDirectoryW manage up to 256 directories. Parents must exist, and directories must be empty before removal. DeleteFileW -deletes closed files. Traversal components and device names are rejected. +deletes closed files. MoveFileW moves closed files to an unused name under +an existing directory. GetFileAttributesW distinguishes files and directories. +Traversal components and device names are rejected. Persistence, directory enumeration, asynchronous I/O, and file handle duplication remain outside this subset. From 6ecbd14915e9e0afee7b00d7ea1c30431587218e Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:49:25 -0500 Subject: [PATCH 24/82] Enumerate the synthetic guest namespace through typed search handles Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 3 + crates/loader/src/services.rs | 16 +-- crates/loader/src/services/files.rs | 166 +++++++++++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 70 +++++++++++- docs/interfaces.md | 8 +- 6 files changed, 249 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e36cfd8..b9045f06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest file and directory enumeration with typed search handles. + - Added closed-file moves and file and directory attribute queries on the synthetic guest drive. - Added nested guest directories and checked file deletion on the synthetic drive. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 289b0e94..e44e2c90 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -983,6 +983,9 @@ impl SymbolDb { "DeleteFileW", "GetFileAttributesW", "MoveFileW", + "FindFirstFileW", + "FindNextFileW", + "FindClose", ] { self.ins(module, symbol, Classification::StandardService); } diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index b4cd0f66..d4bad705 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -119,6 +119,7 @@ impl Clock for SystemClock { enum GuestObject { Thread(u32), File(files::OpenFile), + Search(files::Search), Waitable { state: Arc>, access: u32, @@ -333,13 +334,12 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc (*rights, None), Some(GuestObject::Waitable { state, access }) => (*access, Some(Arc::clone(state))), - Some(GuestObject::File(_)) => return s.fail(ERROR_NOT_SUPPORTED, 0), + Some(GuestObject::File(_) | GuestObject::Search(_)) => { + return s.fail(ERROR_NOT_SUPPORTED, 0); + } None => return s.fail(ERROR_INVALID_HANDLE, 0), } }; diff --git a/crates/loader/src/services/files.rs b/crates/loader/src/services/files.rs index 43fc8cec..2658c5c7 100644 --- a/crates/loader/src/services/files.rs +++ b/crates/loader/src/services/files.rs @@ -36,7 +36,7 @@ pub(super) struct OpenFile { share: u32, } -fn guest_path(memory: &GuestMemory, address: u64) -> Result, MemoryError> { +fn read_guest_path(memory: &GuestMemory, address: u64) -> Result, MemoryError> { if address == 0 { return Ok(None); } @@ -52,16 +52,80 @@ fn guest_path(memory: &GuestMemory, address: u64) -> Result, Memo }; let path = path.replace('/', "\\").to_ascii_lowercase(); let name = path.strip_prefix("c:\\").unwrap_or(&path); - return Ok(name - .split('\\') - .all(valid_component) - .then(|| name.to_owned())); + return Ok(Some(name.to_owned())); } units.push(unit); } Ok(None) } +fn guest_path(memory: &GuestMemory, address: u64) -> Result, MemoryError> { + Ok(read_guest_path(memory, address)?.filter(|name| name.split('\\').all(valid_component))) +} + +struct SearchEntry { + name: String, + attributes: u32, + size: u64, +} + +pub(super) struct Search { + entries: Vec, + next: usize, +} + +fn write_find_data( + memory: &mut GuestMemory, + output: u64, + entry: &SearchEntry, +) -> Result<(), MemoryError> { + if output == 0 { + return Err(MemoryError::UnmappedAddress(0)); + } + // WIN32_FIND_DATAW: attributes, three FILETIMEs, size high/low, + // two reserved DWORDs, WCHAR[260], then WCHAR[14]. + let mut bytes = [0u8; 592]; + bytes[..4].copy_from_slice(&entry.attributes.to_le_bytes()); + bytes[28..32].copy_from_slice(&((entry.size >> 32) as u32).to_le_bytes()); + bytes[32..36].copy_from_slice(&(entry.size as u32).to_le_bytes()); + for (slot, unit) in bytes[44..564] + .as_chunks_mut::<2>() + .0 + .iter_mut() + .zip(entry.name.encode_utf16()) + { + slot.copy_from_slice(&unit.to_le_bytes()); + } + memory.write_bytes(output, &bytes) +} + +fn wildcard_match(pattern: &str, name: &str) -> bool { + let pattern: Vec<_> = pattern.encode_utf16().collect(); + let name: Vec<_> = name.encode_utf16().collect(); + let (mut p, mut n, mut retry) = (0, 0, None); + while n < name.len() { + match pattern.get(p).copied() { + Some(42) => { + p += 1; + retry = Some((p, n)); + } + Some(unit) if unit == 63 || unit == name[n] => { + p += 1; + n += 1; + } + _ => { + let Some((after_star, previous)) = retry else { + return false; + }; + n = previous + 1; + p = after_star; + retry = Some((p, n)); + } + } + } + pattern[p..].iter().all(|&unit| unit == 42) +} + fn valid_component(name: &str) -> bool { let device = name.split('.').next().unwrap_or_default(); !name.is_empty() @@ -282,6 +346,95 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); + let find = Arc::clone(state); + registry.register(KERNEL32, "FindFirstFileW", move |args, _, memory| { + let Some(path) = read_guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { + return find.fail(INVALID_NAME, INVALID_HANDLE); + }; + let directory = parent(&path); + let pattern = path.rsplit('\\').next().unwrap_or_default(); + if path.starts_with('\\') + || (!directory.is_empty() && !directory.split('\\').all(valid_component)) + || !valid_component(&pattern.replace(['*', '?'], "x")) + { + return find.fail(INVALID_NAME, INVALID_HANDLE); + } + let pattern = if pattern == "*.*" { "*" } else { pattern }; + let mut objects = find.objects.lock().expect("guest object state"); + if !directory.is_empty() && !objects.directories.contains(directory) { + return find.fail(PATH_NOT_FOUND, INVALID_HANDLE); + } + let candidates = objects + .directories + .iter() + .map(|path| (path, 0x10, 0)) + .chain( + objects + .files + .iter() + .map(|(path, data)| (path, 0x80, data.len() as u64)), + ); + let mut entries = Vec::new(); + for (path, attributes, size) in candidates.filter(|(path, _, _)| parent(path) == directory) + { + let name = path.rsplit('\\').next().expect("candidate name"); + if wildcard_match(pattern, name) { + entries.push(SearchEntry { + name: name.to_owned(), + attributes, + size, + }); + } + } + entries.sort_by(|a, b| a.name.cmp(&b.name)); + let Some(first) = entries.first() else { + return find.fail(FILE_NOT_FOUND, INVALID_HANDLE); + }; + if objects + .handles + .values() + .filter(|object| matches!(object, GuestObject::Search(_))) + .count() + >= 32 + { + return find.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); + } + let Some(handle) = objects.next_handle() else { + return find.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); + }; + if write_find_data(memory, args.rdx, first).is_err() { + return find.fail(ERROR_NOACCESS, INVALID_HANDLE); + } + objects.insert_handle(handle, GuestObject::Search(Search { entries, next: 1 })); + Ok(handle) + }); + + let find_next = Arc::clone(state); + registry.register(KERNEL32, "FindNextFileW", move |args, _, memory| { + let mut objects = find_next.objects.lock().expect("guest object state"); + let Some(GuestObject::Search(search)) = objects.handles.get_mut(&args.rcx) else { + return find_next.fail(ERROR_INVALID_HANDLE, 0); + }; + let Some(entry) = search.entries.get(search.next) else { + return find_next.fail(18, 0); // ERROR_NO_MORE_FILES + }; + if write_find_data(memory, args.rdx, entry).is_err() { + return find_next.fail(ERROR_NOACCESS, 0); + } + search.next += 1; + Ok(1) + }); + + let find_close = Arc::clone(state); + registry.register(KERNEL32, "FindClose", move |args, _, _| { + let mut objects = find_close.objects.lock().expect("guest object state"); + if !matches!(objects.handles.get(&args.rcx), Some(GuestObject::Search(_))) { + return find_close.fail(ERROR_INVALID_HANDLE, 0); + } + objects.handles.remove(&args.rcx); + Ok(1) + }); + let size = Arc::clone(state); registry.register(KERNEL32, "GetFileSizeEx", move |args, _, memory| { let objects = size.objects.lock().expect("guest object state"); @@ -456,6 +609,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "DeleteFileW", "GetFileAttributesW", "MoveFileW", + "FindFirstFileW", + "FindNextFileW", + "FindClose", ] { registry.alias(FILE_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 88548be7..c64574c1 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1126,7 +1126,7 @@ fn test_guest_synthetic_file_io_through_iat() { const IMAGE: u64 = 0x140000000; const MODULE: &str = "api-ms-win-core-file-l1-1-0.dll"; let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); - let path_call = |symbol, name: &str, access: u64, disposition: u64, target: Option<&str>| { + let path_result = |symbol, name: &str, access: u64, disposition: u64, target: Option<&str>| { let mut code = vec![0x48, 0x83, 0xec, 0x48]; for (register, value) in [ ([0x48, 0xb9], IMAGE + 0x1080), @@ -1175,7 +1175,13 @@ fn test_guest_synthetic_file_io_through_iat() { ) .unwrap(); assert_eq!(result.execution.exit_reason, ExitReason::Halt); - result.execution.final_state.get(Register::Rax) + result + }; + let path_call = |symbol, name, access, disposition, target| { + path_result(symbol, name, access, disposition, target) + .execution + .final_state + .get(Register::Rax) }; let open = |name, access, disposition| path_call("CreateFileW", name, access, disposition, None); @@ -1336,6 +1342,66 @@ fn test_guest_synthetic_file_io_through_iat() { assert_ne!(moved, u64::MAX); let size = call("GetFileSizeEx", &[moved, output]); assert_eq!(size.image.memory.read_u64(output).unwrap(), 6); + assert_eq!(namespace("CreateDirectoryW", "archive/extra"), 1); + let find_data = output - 0x400; + let found = path_result("FindFirstFileW", "C:/Archive/*.*", find_data, 0, None); + let search = found.execution.final_state.get(Register::Rax); + assert_ne!(search, u64::MAX); + assert_eq!(found.image.memory.read_u32(find_data).unwrap(), 0x10); + assert_eq!( + found.image.memory.read_u16(find_data + 44).unwrap(), + u16::from(b'e') + ); + assert_eq!( + call("CloseHandle", &[search]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + assert_eq!( + call("FindNextFileW", &[search, u64::MAX]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + let next = call("FindNextFileW", &[search, find_data]); + assert_eq!(next.execution.final_state.get(Register::Rax), 1); + assert_eq!(next.image.memory.read_u32(find_data).unwrap(), 0x80); + assert_eq!(next.image.memory.read_u32(find_data + 32).unwrap(), 6); + assert_eq!( + next.image.memory.read_u16(find_data + 44).unwrap(), + u16::from(b'm') + ); + assert_eq!( + call("FindNextFileW", &[search, find_data]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + assert_eq!( + call("GetLastError", &[]) + .execution + .final_state + .get(Register::Rax), + 18 + ); + assert_eq!( + call("FindClose", &[search]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!( + call("FindClose", &[search]) + .execution + .final_state + .get(Register::Rax), + 0 + ); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index e0b5eb02..bc44ffb0 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -207,8 +207,12 @@ must exist, and directories must be empty before removal. DeleteFileW deletes closed files. MoveFileW moves closed files to an unused name under an existing directory. GetFileAttributesW distinguishes files and directories. Traversal components and device names are rejected. -Persistence, directory enumeration, asynchronous I/O, and file handle -duplication remain outside this subset. +FindFirstFileW, FindNextFileW, and FindClose enumerate a sorted snapshot of +direct children. The final path component accepts literal names, * and ? +wildcards, and *.* matches every name. Results include attributes, byte size, +and a UTF-16 name. Times and alternate names are zero. Up to 32 searches +can be open. DOS wildcard edge cases, persistence, asynchronous I/O, +and file handle duplication remain outside this subset. ### Event and semaphore signaling From 2de0483142521878d003fe0366a25608310d0180 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:50:28 -0500 Subject: [PATCH 25/82] Share guest file positions across duplicated handles Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/loader/src/services.rs | 33 ++++++++++++++++++--------- crates/loader/src/services/files.rs | 28 ++++++++++++++--------- crates/loader/tests/runtime_x15.rs | 35 +++++++++++++++++++++++++++++ docs/interfaces.md | 8 ++++--- 5 files changed, 82 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b9045f06..8c6411b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added same-process guest file handle duplication with a shared file position. + - Added guest file and directory enumeration with typed search handles. - Added closed-file moves and file and directory attribute queries on the synthetic guest drive. diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index d4bad705..7b86c54a 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -365,15 +365,23 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc (*rights, None), - Some(GuestObject::Waitable { state, access }) => (*access, Some(Arc::clone(state))), - Some(GuestObject::File(_) | GuestObject::Search(_)) => { - return s.fail(ERROR_NOT_SUPPORTED, 0); - } + Some(GuestObject::Thread(rights)) => (*rights, GuestObject::Thread(*rights)), + Some(GuestObject::Waitable { state, access }) => ( + *access, + GuestObject::Waitable { + state: Arc::clone(state), + access: *access, + }, + ), + Some(GuestObject::File(file)) => (file.access, GuestObject::File(file.clone())), + Some(GuestObject::Search(_)) => return s.fail(ERROR_NOT_SUPPORTED, 0), None => return s.fail(ERROR_INVALID_HANDLE, 0), } }; @@ -390,10 +398,13 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc GuestObject::Waitable { state, access }, - None => GuestObject::Thread(access), - }; + match &mut object { + GuestObject::Thread(rights) | GuestObject::Waitable { access: rights, .. } => { + *rights = access + } + GuestObject::File(file) => file.access = access, + GuestObject::Search(_) => unreachable!("search handles cannot be duplicated"), + } thread.insert_handle(handle, object); Ok(1) }); diff --git a/crates/loader/src/services/files.rs b/crates/loader/src/services/files.rs index 2658c5c7..8b573d4f 100644 --- a/crates/loader/src/services/files.rs +++ b/crates/loader/src/services/files.rs @@ -10,6 +10,7 @@ use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{GuestMemory, MemoryError}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; const FILE_API: &str = "api-ms-win-core-file-l1-1-0.dll"; const INVALID_HANDLE: u64 = u64::MAX; @@ -29,10 +30,13 @@ const MAX_DIRECTORIES: usize = 256; const MAX_BYTES: usize = 16 * 1024 * 1024; const MAX_TRANSFER: usize = 1024 * 1024; +#[derive(Clone)] pub(super) struct OpenFile { path: String, - position: u64, - access: u32, + // The object table serializes all operations on this open instance. + position: Arc, + open_access: u32, + pub(super) access: u32, share: u32, } @@ -190,7 +194,8 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc for object in objects.handles.values() { if let GuestObject::File(file) = object && file.path == path - && (share_mask(access) & !file.share != 0 || share_mask(file.access) & !share != 0) + && (share_mask(access) & !file.share != 0 + || share_mask(file.open_access) & !share != 0) { return open.fail(SHARING_VIOLATION, INVALID_HANDLE); } @@ -213,7 +218,8 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc handle, GuestObject::File(OpenFile { path, - position: 0, + position: Arc::new(AtomicU64::new(0)), + open_access: access, access, share, }), @@ -464,7 +470,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } let origin = match args.r9 as u32 { 0 => None, - 1 => Some(file.position), + 1 => Some(file.position.load(Ordering::Relaxed)), 2 => Some(files.get(&file.path).expect("open file exists").len() as u64), _ => return seek.fail(ERROR_INVALID_PARAMETER, 0), }; @@ -484,7 +490,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if args.r8 != 0 && memory.write_u64(args.r8, position).is_err() { return seek.fail(ERROR_NOACCESS, 0); } - file.position = position; + file.position.store(position, Ordering::Relaxed); Ok(1) }); @@ -498,12 +504,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if file.access & WRITE == 0 { return truncate.fail(ERROR_ACCESS_DENIED, 0); } - if file.position > MAX_BYTES as u64 { + let position = file.position.load(Ordering::Relaxed); + if position > MAX_BYTES as u64 { return truncate.fail(DISK_FULL, 0); } let used = files.values().map(Vec::len).sum::(); let data = files.get_mut(&file.path).expect("open file exists"); - let length = file.position as usize; + let length = position as usize; let growth = length.saturating_sub(data.len()); if growth > MAX_BYTES - used { return truncate.fail(DISK_FULL, 0); @@ -548,7 +555,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc 0 }; let data = files.get_mut(&file.path).expect("open file exists"); - let position = file.position; + let position = file.position.load(Ordering::Relaxed); let transferred = if writing { if count == 0 { 0 @@ -592,7 +599,8 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc memory .write_u32(args.r9, transferred as u32) .map_err(ExitReason::MemoryFault)?; - file.position += transferred as u64; + file.position + .store(position + transferred as u64, Ordering::Relaxed); Ok(1) }); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index c64574c1..56c26143 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1402,6 +1402,41 @@ fn test_guest_synthetic_file_io_through_iat() { .get(Register::Rax), 0 ); + let duplicate = call( + "DuplicateHandle", + &[u64::MAX, moved, u64::MAX, output, 0x8000_0000, 0, 0], + ); + assert_eq!(duplicate.execution.final_state.get(Register::Rax), 1); + let duplicate = duplicate.image.memory.read_u64(output).unwrap(); + assert_ne!(duplicate, moved); + let read = call("ReadFile", &[moved, output + 8, 2, output, 0]); + assert_eq!(read.image.memory.read_u32(output).unwrap(), 2); + let read = call("ReadFile", &[duplicate, output + 8, 8, output, 0]); + assert_eq!(read.image.memory.read_u32(output).unwrap(), 4); + assert_eq!(read.image.memory.read_u64(output + 8).unwrap(), 0); + assert_eq!( + call("CloseHandle", &[moved]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_eq!(open("archive/moved.dat", 0x8000_0000, 3), u64::MAX); + assert_eq!( + call("WriteFile", &[duplicate, output, 1, output + 8, 0]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + assert_eq!( + call("CloseHandle", &[duplicate]) + .execution + .final_state + .get(Register::Rax), + 1 + ); + assert_ne!(open("archive/moved.dat", 0x8000_0000, 3), u64::MAX); } #[test] diff --git a/docs/interfaces.md b/docs/interfaces.md index bc44ffb0..5c1db9b5 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -196,7 +196,7 @@ same rules with 64-bit results. The runtime exposes an in-memory C: drive through CreateFileW, ReadFile, WriteFile, GetFileSizeEx, and CloseHandle. It supports UTF-16 file and -directory names, ASCII case folding, synchronous I/O, per-handle positions, and +directory names, ASCII case folding, synchronous I/O, per-open file positions, and read/write sharing. SetFilePointerEx supports seeking from the beginning, current position, and end. SetEndOfFile truncates or zero-extends writable files at the current position. Seeks alone do not change file length. @@ -211,8 +211,10 @@ FindFirstFileW, FindNextFileW, and FindClose enumerate a sorted snapshot of direct children. The final path component accepts literal names, * and ? wildcards, and *.* matches every name. Results include attributes, byte size, and a UTF-16 name. Times and alternate names are zero. Up to 32 searches -can be open. DOS wildcard edge cases, persistence, asynchronous I/O, -and file handle duplication remain outside this subset. +can be open. Same-process file handle duplicates share the file position and keep the +original sharing reservation until the last duplicate closes. Access can +be reduced per handle. DOS wildcard edge cases, persistence, and +asynchronous I/O remain outside this subset. ### Event and semaphore signaling From c4ce9a4e38d279214823949a94c1c2408dfd7eaa Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:53:16 -0500 Subject: [PATCH 26/82] Resolve named exports from built-in guest modules Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 18 ++-- crates/loader/src/imports.rs | 47 ++++++++-- crates/loader/src/services.rs | 2 + crates/loader/src/services/modules.rs | 123 ++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 61 +++++++++++++ docs/interfaces.md | 9 ++ 7 files changed, 244 insertions(+), 18 deletions(-) create mode 100644 crates/loader/src/services/modules.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c814631f..ee84a822 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services. + - Added same-process guest file handle duplication with a shared file position. - Added guest file and directory enumeration with typed search handles. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index e44e2c90..09b9bb8a 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -887,19 +887,11 @@ impl SymbolDb { "LoadLibraryW — stub returning null", ); self.win32_stub(m, "FreeLibrary", false, "FreeLibrary — no-op stub"); - self.win32_stub( - m, - "GetModuleHandleA", - false, - "GetModuleHandle — stub returning synthetic base", - ); - self.win32_stub(m, "GetModuleHandleW", false, "GetModuleHandleW — stub"); - self.win32_stub( - m, - "GetProcAddress", - false, - "GetProcAddress — stub returning null", - ); + for module in [m, "kernel32.dll"] { + for symbol in ["GetModuleHandleA", "GetModuleHandleW", "GetProcAddress"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub( m, "GetModuleFileNameA", diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 3eb15c77..835b5b9e 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -11,6 +11,7 @@ use crate::memory::{GuestMemory, MemoryError}; use crate::pe::ParsedPe; use std::collections::HashMap; use std::fmt; +use std::sync::{Arc, RwLock}; /// Base virtual address range reserved for synthetic guest import dispatch trampolines. pub const IMPORT_TRAMPOLINE_BASE_VA: u64 = 0x0000_0007_F000_0000; @@ -129,10 +130,40 @@ pub struct ServiceDescriptor { pub status: ServiceStatus, } +#[derive(Clone, Default)] +pub(crate) struct DynamicTrampolines(Arc>>); + +impl DynamicTrampolines { + pub(crate) fn expose(&self, index: usize) -> u64 { + let address = trampoline_address(index); + self.0 + .write() + .expect("dynamic service trampolines") + .insert(address, index); + address + } + + fn get(&self, address: u64) -> Option { + if address < IMPORT_TRAMPOLINE_BASE_VA { + return None; + } + self.0 + .read() + .expect("dynamic service trampolines") + .get(&address) + .copied() + } +} + +fn trampoline_address(index: usize) -> u64 { + IMPORT_TRAMPOLINE_BASE_VA + index as u64 * IMPORT_TRAMPOLINE_STRIDE +} + /// Registry for resolving and binding import symbols to guest trampoline VAs. pub struct ImportRegistry { services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index handlers: Vec, + dynamic_trampolines: DynamicTrampolines, trampoline_to_service: HashMap, // Trampoline VA -> service_index } @@ -148,15 +179,20 @@ impl ImportRegistry { services: HashMap::new(), handlers: Vec::new(), trampoline_to_service: HashMap::new(), + dynamic_trampolines: DynamicTrampolines::default(), } } - fn service_index(&self, module: &str, symbol: &str) -> Option { + pub(crate) fn service_index(&self, module: &str, symbol: &str) -> Option { self.services .get(&(module.to_ascii_lowercase(), symbol.to_owned())) .copied() } + pub(crate) fn dynamic_trampolines(&self) -> DynamicTrampolines { + self.dynamic_trampolines.clone() + } + /// Check whether the exact import key has a binding, including stub handlers. pub fn has_binding(&self, module: &str, symbol: &str) -> bool { self.service_index(module, symbol).is_some() @@ -342,8 +378,7 @@ impl ImportRegistry { }; // Assign a deterministic synthetic trampoline VA - let trampoline_va = - IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE; + let trampoline_va = trampoline_address(service_idx); self.trampoline_to_service .insert(trampoline_va, service_idx); @@ -359,7 +394,7 @@ impl ImportRegistry { /// Check if target RIP matches a synthetic service trampoline. pub fn is_service_trampoline(&self, rip: u64) -> bool { - self.trampoline_to_service.contains_key(&rip) + self.trampoline_to_service.contains_key(&rip) || self.dynamic_trampolines.get(rip).is_some() } /// Dispatch a service call when guest RIP hits a service trampoline. @@ -369,9 +404,11 @@ impl ImportRegistry { cpu: &mut CpuState, memory: &mut GuestMemory, ) -> Result<(), ExitReason> { - let service_idx = *self + let service_idx = self .trampoline_to_service .get(&rip) + .copied() + .or_else(|| self.dynamic_trampolines.get(rip)) .ok_or(ExitReason::IllegalInstruction(0xFF))?; let descriptor = &self.handlers[service_idx]; diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 7b86c54a..b9a38c45 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -13,6 +13,7 @@ mod crt; mod events; mod files; mod heap; +mod modules; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; @@ -760,4 +761,5 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc, + exports: BTreeMap<(u64, String), usize>, +} + +fn read_name( + memory: &GuestMemory, + address: u64, + wide: bool, +) -> Result, MemoryError> { + let mut name = String::new(); + let width = if wide { 2 } else { 1 }; + for index in 0..260 { + let slot = address + .checked_add(index * width) + .ok_or(MemoryError::Overflow)?; + let unit = if wide { + memory.read_u16(slot)? + } else { + u16::from(memory.read_u8(slot)?) + }; + if unit == 0 { + return Ok(Some(name)); + } + if !(0x20..=0x7e).contains(&unit) { + return Ok(None); + } + name.push(char::from(unit as u8)); + } + Ok(None) +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + let modules = Arc::new(OnceLock::::new()); + for (symbol, wide) in [("GetModuleHandleA", false), ("GetModuleHandleW", true)] { + let state = Arc::clone(state); + let modules = Arc::clone(&modules); + registry.register(KERNEL32, symbol, move |args, _, memory| { + if args.rcx == 0 { + return state.fail(MODULE_NOT_FOUND, 0); + } + let Some(name) = read_name(memory, args.rcx, wide).map_err(ExitReason::MemoryFault)? + else { + return state.fail(MODULE_NOT_FOUND, 0); + }; + let mut name = name.to_ascii_lowercase(); + if !name.contains('.') { + name.push_str(".dll"); + } + let modules = modules.get().expect("built-in module catalog"); + match modules.names.get(&name) { + Some(&handle) => Ok(handle), + None => state.fail(MODULE_NOT_FOUND, 0), + } + }); + } + + let lookup = Arc::clone(&modules); + let trampolines = registry.dynamic_trampolines(); + let state = Arc::clone(state); + registry.register(KERNEL32, "GetProcAddress", move |args, _, memory| { + let modules = lookup.get().expect("built-in module catalog"); + if !matches!(args.rcx, MODULE_BASE | UCRT_HANDLE) { + return state.fail(ERROR_INVALID_HANDLE, 0); + } + // Ordinal entries require an independently verified export catalog. + if args.rdx <= u16::MAX as u64 { + return state.fail(PROCEDURE_NOT_FOUND, 0); + } + let Some(symbol) = read_name(memory, args.rdx, false).map_err(ExitReason::MemoryFault)? + else { + return state.fail(PROCEDURE_NOT_FOUND, 0); + }; + match modules.exports.get(&(args.rcx, symbol)) { + Some(&index) => Ok(trampolines.expose(index)), + None => state.fail(PROCEDURE_NOT_FOUND, 0), + } + }); + + for symbol in ["GetModuleHandleA", "GetModuleHandleW", "GetProcAddress"] { + registry.alias(LOADER_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } + + let mut catalog = Modules::default(); + for (module, handle) in [(KERNEL32, MODULE_BASE), (UCRT, UCRT_HANDLE)] { + catalog.names.insert(module.to_owned(), handle); + for (name, symbol, status) in registry.iter_registered() { + if name == module + && status != ServiceStatus::Stub + && let Some(index) = registry.service_index(name, symbol) + { + catalog.exports.insert((handle, symbol.to_owned()), index); + } + } + for (alias, _, canonical) in registry.iter_aliases() { + if canonical == module { + catalog.names.insert(alias.to_owned(), handle); + } + } + } + assert!(modules.set(catalog).is_ok()); +} + +const UCRT_HANDLE: u64 = MODULE_BASE + 0x10000; diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 56c26143..57b443b6 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,67 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn test_guest_resolves_and_calls_a_dynamic_export() { + const IMAGE: u64 = 0x140000000; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let run = |symbol: &str, invoke| { + let mut code = vec![0x48, 0x83, 0xec, 0x28, 0x48, 0xb9]; + code.extend_from_slice(&(IMAGE + 0x1080).to_le_bytes()); + append_import_call(&mut code, 0x2060); + code.extend_from_slice(&[0x48, 0x89, 0xc1, 0x48, 0xba]); + code.extend_from_slice(&(IMAGE + 0x10c0).to_le_bytes()); + append_import_call(&mut code, 0x21a0); + if invoke { + code.extend_from_slice(&[0xff, 0xd0]); // call rax + } + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]); + code.resize(0x80, 0); + code.extend_from_slice(b"KERNEL32\0"); + code.resize(0xc0, 0); + code.extend_from_slice(symbol.as_bytes()); + code.push(0); + let bytes = TestPeBuilder::new(IMAGE, 0x1000) + .add_import( + "api-ms-win-core-libraryloader-l1-2-0.dll", + "GetModuleHandleA", + ) + .add_import("kernel32.dll", "GetProcAddress") + .code(&code) + .build(); + let mut imports = ImportRegistry::new(); + register_standard_services(&mut imports, state.clone()); + let result = run_synthetic_startup( + &bytes, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + imports, + 100, + ) + .unwrap(); + assert_eq!(result.bound_imports, 2); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result.execution.final_state.get(Register::Rax) + }; + + assert_eq!( + run("GetCurrentProcessId", true), + u64::from(state.process_id) + ); + assert_eq!(run("getcurrentprocessid", false), 0); + assert_eq!( + call_service_fixture(&state, "kernel32.dll", "GetLastError", &[]) + .execution + .final_state + .get(Register::Rax), + 127 + ); + assert_eq!(run("SubmitGuestDraw", false), 0); +} + #[test] fn test_guest_synthetic_file_io_through_iat() { const IMAGE: u64 = 0x140000000; diff --git a/docs/interfaces.md b/docs/interfaces.md index 5c1db9b5..f2e9cd07 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -192,6 +192,15 @@ clamps the result and sets ERANGE. Scans have a 1 MiB input budget. The long-lon Microsoft's _strtoi64, _strtoui64, _wcstoi64, and _wcstoui64 apply the same rules with 64-bit results. +### Built-in guest modules + +GetModuleHandleA and GetModuleHandleW recognize synthetic Kernel32 and UCRT +module names and their registered API-set aliases. GetProcAddress resolves +case-sensitive named exports to guest service trampolines. The registry +captures built-in bindings at standard service registration and excludes +stubs. Missing names and unsupported ordinals fail explicitly. These APIs +expose synthetic module handles and never load host libraries. + ### Synthetic guest files The runtime exposes an in-memory C: drive through CreateFileW, ReadFile, From 3922f56d6865b3ecc37186f5b92ac0270a09bca1 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:07:05 -0500 Subject: [PATCH 27/82] Cover CRT boundary faults and atomic overlapping moves Signed-off-by: Adeeb Rahman --- .../tests/generated_runtime_integration.rs | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/loader/tests/generated_runtime_integration.rs b/crates/loader/tests/generated_runtime_integration.rs index 047de08d..5bda78df 100644 --- a/crates/loader/tests/generated_runtime_integration.rs +++ b/crates/loader/tests/generated_runtime_integration.rs @@ -3,7 +3,7 @@ use std::sync::Arc; use xenora_loader::cpu::{CpuState, ExitReason}; use xenora_loader::imports::{ImportRegistry, ServiceStatus, Win64Args}; -use xenora_loader::memory::{GuestMemory, MemoryPermissions}; +use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions}; use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; #[test] @@ -61,3 +61,51 @@ fn test_unsupported_stub_fails_explicitly() { let res = (desc.handler)(&args, &mut cpu, &mut mem); assert_eq!(res, Err(ExitReason::IllegalInstruction(0xFE))); } + +#[test] +fn crt_handlers_validate_memory_boundaries() { + let mut registry = ImportRegistry::new(); + register_standard_services( + &mut registry, + Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), + ); + let mut cpu = CpuState::new(0x1000, 0x8000); + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(0x1000, 4, MemoryPermissions::READ_WRITE, b"abcd") + .unwrap(); + memory + .map_region_with_data(0x1004, 4, MemoryPermissions::READ_WRITE, b"efgh") + .unwrap(); + let mut call = |symbol, rcx, rdx, r8, memory: &mut GuestMemory| { + let args = Win64Args { + rcx, + rdx, + r8, + r9: 0, + rsp: 0x8000, + }; + let service = registry.binding("ucrtbase.dll", symbol).unwrap(); + (service.handler)(&args, &mut cpu, memory) + }; + + assert_eq!(call("strnlen", 0x1000, 8, 0, &mut memory), Ok(8)); + assert_eq!( + call("strlen", 0x1000, 0, 0, &mut memory), + Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress( + 0x1008 + ))) + ); + assert_eq!( + call("memmove", 0x1005, 0x1000, 4, &mut memory), + Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress( + 0x1005 + ))) + ); + let mut bytes = [0; 8]; + memory.read_bytes(0x1000, &mut bytes).unwrap(); + assert_eq!(&bytes, b"abcdefgh"); + assert_eq!(call("memmove", 0x1002, 0x1000, 6, &mut memory), Ok(0x1002)); + memory.read_bytes(0x1000, &mut bytes).unwrap(); + assert_eq!(&bytes, b"ababcdef"); +} From 5617b883b9546cd401ce80150dd2e8ca2724e9e2 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:09:03 -0500 Subject: [PATCH 28/82] Execute emitted CRT and stub handlers in generated conformance tests Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 + crates/import-gen/src/codegen.rs | 355 ++++++---------------------- crates/import-gen/tests/pipeline.rs | 20 +- 3 files changed, 89 insertions(+), 288 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 69de0abd..8f7a791f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added + +- Generated import conformance tests now execute emitted service handlers and verify unsupported stubs. - Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`. - Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet. - Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware. diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 0c8423d0..5b161f9f 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -40,6 +40,13 @@ fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> { std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}")) } +fn unique_entries(manifest: &Manifest) -> impl Iterator { + let mut seen = std::collections::BTreeSet::new(); + manifest.entries.iter().filter(move |entry| { + seen.insert((entry.module.to_ascii_lowercase(), entry.symbol.as_str())) + }) +} + /// Generate all files from the manifest. pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles { let crt_rs = gen_crt(manifest); @@ -81,7 +88,7 @@ pub fn register_generated_crt_services(registry: &mut ImportRegistry) { "#, ); - for entry in manifest.entries.iter() { + for entry in unique_entries(manifest) { match &entry.classification { Classification::CrtNative { libc_sym, note } => { out.push_str(&gen_crt_native_registration( @@ -204,7 +211,7 @@ pub fn register_generated_stubs(registry: &mut ImportRegistry) { "#, ); - for entry in manifest.entries.iter() { + for entry in unique_entries(manifest) { if let Classification::Win32Stub { note, .. } = &entry.classification { out.push_str(&format!( r#" @@ -237,72 +244,65 @@ fn gen_tests(manifest: &Manifest) -> String { let mut out = file_header("generated_tests.rs"); out.push_str( r#" -//! Auto-generated conformance tests for CRT bindings. -//! Each test verifies that the generated service handler returns a correct value -//! for a canonical input against a known-good expected output. -//! Do not edit manually — regenerate with `xenora imports generate`. -//! -//! Run with: cargo test -p xenora-loader --test generated +//! Conformance tests for emitted service registrations. +//! Place this file and the two generated registration files together as +//! an integration test in a Cargo package that depends on xenora-loader. -use xenora_loader::imports::{ImportRegistry, Win64Args}; -use xenora_loader::cpu::CpuState; -use xenora_loader::memory::{GuestMemory, MemoryPermissions}; -use xenora_loader::services::register_standard_services; +pub use xenora_loader::{cpu, imports, memory}; -/// Build a minimal test registry with generated bindings loaded. -fn test_registry() -> ImportRegistry { - let mut reg = ImportRegistry::new(); - let clock = std::sync::Arc::new(xenora_loader::services::SystemClock); - let state = std::sync::Arc::new(xenora_loader::services::ServicesState::new(clock)); - register_standard_services(&mut reg, state); - // Generated registrations would be loaded here in integration. - reg +#[path = "generated_crt.rs"] +mod generated_crt; +#[path = "generated_stubs.rs"] +mod generated_stubs; + +use cpu::{CpuState, ExitReason}; +use imports::{ImportRegistry, ServiceStatus, Win64Args}; +use memory::GuestMemory; + +fn check(module: &str, symbol: &str, input: u64, status: ServiceStatus, expected: Result) { + let mut registry = ImportRegistry::new(); + generated_crt::register_generated_crt_services(&mut registry); + generated_stubs::register_generated_stubs(&mut registry); + let service = registry.binding(module, symbol).expect("generated binding"); + assert_eq!(service.status, status); + let args = Win64Args { rcx: input, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 }; + let mut cpu = CpuState::new(0x1000, 0x8000); + let mut memory = GuestMemory::new(); + assert_eq!((service.handler)(&args, &mut cpu, &mut memory), expected); } - -fn fresh_state() -> (CpuState, GuestMemory) { - let cpu = CpuState::new(0x1000, 0x8000); - let mut mem = GuestMemory::new(); - mem.map_region(0x1000, 0x20000, MemoryPermissions::READ_WRITE_EXECUTE) - .expect("map test region"); - (cpu, mem) -} - "#, ); - // Generate a test per CrtNative entry that has a testable canonical case - for entry in manifest.entries.iter() { - if let Classification::CrtNative { libc_sym, .. } = &entry.classification - && crt_dispatch_expr(&entry.symbol).is_some() - && let Some(test) = canonical_test(&entry.symbol, libc_sym) - { - out.push_str(&format!( - r#" + for (index, entry) in unique_entries(manifest).enumerate() { + let (input, status, expected) = match &entry.classification { + Classification::CrtNative { .. } if crt_dispatch_expr(&entry.symbol).is_some() => { + let Some((input, expected)) = canonical_integer_case(&entry.symbol) else { + continue; + }; + (input, "Partial", format!("Ok({expected})")) + } + Classification::CrtNative { .. } + | Classification::CrtWrapper { .. } + | Classification::RuntimeHelper { .. } + | Classification::Win32Stub { .. } => ( + 0, + "Stub", + "Err(ExitReason::IllegalInstruction(0xFE))".to_owned(), + ), + _ => continue, + }; + out.push_str(&format!( + r#" #[test] -fn generated_test_{fn_name}() {{ - {test} +fn generated_test_{name}_{index}() {{ + check({module:?}, {symbol:?}, {input}, ServiceStatus::{status}, {expected}); }} "#, - fn_name = symbol_to_ident_lower(&entry.symbol), - test = test, - )); - } + name = symbol_to_ident_lower(&entry.symbol), + module = entry.module, + symbol = entry.symbol, + )); } - - // Test that every generated stub is registered and returns without error - out.push_str( - r#" -#[test] -fn generated_stubs_are_all_registered() { - // Verify that the manifest-driven registration functions compile and - // that every generated stub returns Ok without panicking. - // This test validates the generated source compiles; individual stubs - // are tested separately when they have known-good canonical inputs. - let _ = test_registry(); -} -"#, - ); - out } @@ -380,228 +380,19 @@ fn crt_dispatch_expr(symbol: &str) -> Option { }) } -/// Returns a Rust test body for symbols where we can derive a known-good expected value. -fn canonical_test(symbol: &str, _libc_sym: &str) -> Option { - match symbol { - "strlen" => Some( - r#" - let (_cpu, mut mem) = fresh_state(); - // Write "hello\0" at 0x2000 (already mapped by fresh_state) - for (i, b) in b"hello\0".iter().enumerate() { - mem.write_u8(0x2000 + i as u64, *b).unwrap(); - } - let _args = Win64Args { rcx: 0x2000, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 }; - // strlen should return 5 - // (This test validates the generated dispatch body compiles and executes correctly.) - let result = { - let mut len: u64 = 0; - loop { - let b = mem.read_u8(0x2000 + len).unwrap(); - if b == 0 { break; } - len += 1; - } - len - }; - assert_eq!(result, 5, "strlen('hello') == 5"); -"# - .to_string(), - ), - "memset" => Some( - r#" - let (_cpu, mut mem) = fresh_state(); - for i in 0..8u64 { - mem.write_u8(0x3000 + i, 0xAA).unwrap(); - } - // memset(0x3000, 0xBB, 4) - let val: u8 = 0xBB; - for i in 0..4u64 { - mem.write_u8(0x3000 + i, val).unwrap(); - } - for i in 0..4u64 { - assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xBB, "memset byte {i}"); - } - // bytes 4..8 should still be 0xAA - for i in 4..8u64 { - assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xAA, "memset preserved byte {i}"); - } -"# - .to_string(), - ), - "memcmp" => Some( - r#" - let (_cpu, mut mem) = fresh_state(); - for (i, b) in b"ABCDE".iter().enumerate() { - mem.write_u8(0x4000 + i as u64, *b).unwrap(); - mem.write_u8(0x4100 + i as u64, *b).unwrap(); - } - // memcmp equal regions - let mut result = 0i64; - for i in 0..5u64 { - let ba = mem.read_u8(0x4000 + i).unwrap(); - let bb = mem.read_u8(0x4100 + i).unwrap(); - if ba != bb { result = ba as i64 - bb as i64; break; } - } - assert_eq!(result, 0, "memcmp equal regions"); -"# - .to_string(), - ), - "strcmp" => Some( - r#" - let (_cpu, mut mem) = fresh_state(); - for (i, b) in b"hello\0".iter().enumerate() { - mem.write_u8(0x5000 + i as u64, *b).unwrap(); - mem.write_u8(0x5100 + i as u64, *b).unwrap(); - } - let mut i = 0u64; - let result = loop { - let ca = mem.read_u8(0x5000 + i).unwrap(); - let cb = mem.read_u8(0x5100 + i).unwrap(); - if ca != cb { break (ca as i64 - cb as i64) as u64; } - if ca == 0 { break 0; } - i += 1; - }; - assert_eq!(result, 0, "strcmp equal strings"); -"# - .to_string(), - ), - // Math tests using known values - "sqrt" => Some( - r#" - // sqrt(4.0) == 2.0 — basic sanity check - let x: f64 = 4.0; - let result = x.sqrt(); - assert!((result - 2.0).abs() < 1e-10, "sqrt(4.0) = {result}"); -"# - .to_string(), - ), - "sqrtf" => Some( - r#" - let x: f32 = 9.0; - let result = x.sqrt(); - assert!((result - 3.0).abs() < 1e-6, "sqrtf(9.0) = {result}"); -"# - .to_string(), - ), - "fabs" => Some( - r#" - let x: f64 = -3.14; - let result = x.abs(); - assert!((result - 3.14).abs() < 1e-10, "fabs(-3.14) = {result}"); -"# - .to_string(), - ), - "fabsf" => Some( - r#" - let x: f32 = -2.5; - let result = x.abs(); - assert!((result - 2.5f32).abs() < 1e-6, "fabsf(-2.5) = {result}"); -"# - .to_string(), - ), - "isalpha" => Some( - r#" - let result_a = b'A'.is_ascii_alphabetic(); - let result_1 = b'1'.is_ascii_alphabetic(); - assert!(result_a, "isalpha('A') should be true"); - assert!(!result_1, "isalpha('1') should be false"); -"# - .to_string(), - ), - "isdigit" => Some( - r#" - assert!(b'5'.is_ascii_digit(), "isdigit('5') should be true"); - assert!(!b'x'.is_ascii_digit(), "isdigit('x') should be false"); -"# - .to_string(), - ), - "abs" => Some( - r#" - let x: i32 = -42; - assert_eq!(x.abs(), 42, "abs(-42) == 42"); -"# - .to_string(), - ), - "llabs" => Some( - r#" - let x: i64 = -9_000_000_000; - assert_eq!(x.unsigned_abs(), 9_000_000_000u64, "llabs(-9e9) == 9e9"); -"# - .to_string(), - ), - "cos" => Some( - r#" - let result = (0.0f64).cos(); - assert!((result - 1.0).abs() < 1e-10, "cos(0.0) = {result}"); -"# - .to_string(), - ), - "cosf" => Some( - r#" - let result = (0.0f32).cos(); - assert!((result - 1.0).abs() < 1e-6, "cosf(0.0) = {result}"); -"# - .to_string(), - ), - "sin" => Some( - r#" - let result = (0.0f64).sin(); - assert!(result.abs() < 1e-10, "sin(0.0) = {result}"); -"# - .to_string(), - ), - "sinf" => Some( - r#" - let result = (0.0f32).sin(); - assert!(result.abs() < 1e-6, "sinf(0.0) = {result}"); -"# - .to_string(), - ), - "floor" => Some( - r#" - let result = (3.7f64).floor(); - assert_eq!(result, 3.0, "floor(3.7) = {result}"); -"# - .to_string(), - ), - "ceil" => Some( - r#" - let result = (3.2f64).ceil(); - assert_eq!(result, 4.0, "ceil(3.2) = {result}"); -"# - .to_string(), - ), - "strncmp" => Some( - r#" - let (_cpu, mut mem) = fresh_state(); - for (i, b) in b"hello world\0".iter().enumerate() { - mem.write_u8(0x6000 + i as u64, *b).unwrap(); - mem.write_u8(0x6100 + i as u64, *b).unwrap(); - } - let n = 5usize; - let mut diff = 0i64; - for i in 0..n as u64 { - let ca = mem.read_u8(0x6000 + i).unwrap(); - let cb = mem.read_u8(0x6100 + i).unwrap(); - if ca != cb { diff = ca as i64 - cb as i64; break; } - } - assert_eq!(diff, 0, "strncmp first 5 chars match"); -"# - .to_string(), - ), - "tolower" => Some( - r#" - let c = b'A' as char; - assert_eq!(c.to_ascii_lowercase(), 'a'); -"# - .to_string(), - ), - "toupper" => Some( - r#" - let c = b'z' as char; - assert_eq!(c.to_ascii_uppercase(), 'Z'); -"# - .to_string(), - ), - _ => None, - } +/// Independent canonical inputs and expected integer return bits. +fn canonical_integer_case(symbol: &str) -> Option<(u64, u64)> { + Some(match symbol { + "abs" | "labs" | "llabs" => ((-42i64) as u64, 42), + "tolower" => (65, 97), + "toupper" => (122, 90), + "isalnum" | "isalpha" | "isupper" | "isxdigit" => (65, 1), + "isdigit" => (53, 1), + "islower" => (122, 1), + "isspace" => (32, 1), + "isprint" => (65, 1), + "iscntrl" => (127, 1), + "ispunct" => (33, 1), + _ => return None, + }) } diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 4455aa27..c3110a7b 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -38,6 +38,7 @@ fn test_manifest_and_codegen_pipeline() { let csv_content = r#""module","symbol_or_ordinal","iat_rva" "api-ms-win-crt-math-l1-1-0.dll","acos",0x1000 "api-ms-win-crt-string-l1-1-0.dll","tolower",0x1008 +"API-MS-WIN-CRT-STRING-L1-1-0.DLL","tolower",0x1048 "api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010 "custom.dll","UnknownCustomFunc",0x1018 "kernel32.dll","QueryPerformanceCounter",0x1020 @@ -53,27 +54,34 @@ fn test_manifest_and_codegen_pipeline() { std::fs::write(&csv_file, csv_content).unwrap(); let records = parse_csv(csv_file.to_str().unwrap()).unwrap(); - assert_eq!(records.len(), 9); + assert_eq!(records.len(), 10); let db = SymbolDb::builtin(); let manifest = Manifest::build(&records, &db); let summary = manifest.summary(); - assert_eq!(*summary.get("crt-native").unwrap_or(&0), 2); + assert_eq!(*summary.get("crt-native").unwrap_or(&0), 3); assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1); assert_eq!(*summary.get("manual").unwrap_or(&0), 1); assert_eq!(summary.get("standard-service"), Some(&5)); - assert_eq!(manifest.generatable().count(), 3); + assert_eq!(manifest.generatable().count(), 4); let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); - assert!(files.crt_rs.contains("tolower")); + assert_eq!(files.crt_rs.matches("\"tolower\"").count(), 1); let acos = files.crt_rs.split_once("\"acos\"").unwrap().1; - let (acos, _) = acos.split_once("registry.register_with_status").unwrap(); + let acos = acos.split("registry.register_with_status").next().unwrap(); assert!(acos.contains("ServiceStatus::Stub")); assert!(acos.contains("Err(ExitReason::IllegalInstruction(0xFE))")); - assert!(!files.tests_rs.contains("generated_test_acos")); + assert!(files.tests_rs.contains("generated_test_acos")); + assert!( + files + .tests_rs + .contains("generated_crt::register_generated_crt_services") + ); + assert!(files.tests_rs.contains("(service.handler)")); + assert!(files.tests_rs.contains("generated_test_createthread")); assert!(files.stubs_rs.contains("CreateThread")); assert!(!files.stubs_rs.contains("QueryPerformance")); assert!(!files.stubs_rs.contains("GetThreadId")); From 19465370d188c4be7b297414032bcace49d4d619 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:10:40 -0500 Subject: [PATCH 29/82] Report emitted adapters and stubs separately from catalog tiers Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/cli/src/main.rs | 7 +++- crates/import-gen/src/codegen.rs | 2 +- crates/import-gen/src/manifest.rs | 53 +++++++++++++++++++++++++---- crates/import-gen/tests/pipeline.rs | 10 ++++++ 5 files changed, 66 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f7a791f..ae36d864 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ remains unsupported. ### Added +- Import manifests now report emitted adapters, stubs, and existing runtime bindings separately from catalog classifications. + - Generated import conformance tests now execute emitted service handlers and verify unsupported stubs. - Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`. - Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet. diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 7d5ee3b0..870db507 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -334,12 +334,17 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode { let manifest = xenora_import_gen::Manifest::build(&records, &db); let summary = manifest.summary(); - println!("Classification summary:"); + println!("Catalog classification by import slot:"); for (tier, count) in &summary { let pct = (*count as f64 / records.len() as f64 * 100.0) as u32; println!(" - {tier}: {count} ({pct}%)"); } + println!("Emitted disposition by distinct import:"); + for (disposition, count) in manifest.emission_summary() { + println!(" - {disposition}: {count}"); + } + let files = xenora_import_gen::generate(&manifest, &db); if let Err(err) = files.write_all(&out_dir) { eprintln!("failed to write generated files: {err}"); diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 5b161f9f..9e058eec 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -338,7 +338,7 @@ fn symbol_to_ident_lower(sym: &str) -> String { } /// Returns a dispatch body for CRT calls with a compatible guest ABI adapter. -fn crt_dispatch_expr(symbol: &str) -> Option { +pub(crate) fn crt_dispatch_expr(symbol: &str) -> Option { Some(match symbol { // abs(int) -> int "abs" | "labs" => r#"let x = args.rcx as i32; diff --git a/crates/import-gen/src/manifest.rs b/crates/import-gen/src/manifest.rs index 34e6f0e3..0b6fa209 100644 --- a/crates/import-gen/src/manifest.rs +++ b/crates/import-gen/src/manifest.rs @@ -4,7 +4,7 @@ use crate::classify::{Classification, SymbolDb}; use crate::parse::ImportRecord; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; /// One classified import entry. #[derive(Clone, Debug)] @@ -19,6 +19,22 @@ impl ManifestEntry { pub fn tier(&self) -> &'static str { self.classification.tier_name() } + /// Runtime disposition of the generated output for this import. + pub fn emission(&self) -> &'static str { + match &self.classification { + Classification::StandardService => "runtime-service", + Classification::CrtNative { .. } + if crate::codegen::crt_dispatch_expr(&self.symbol).is_some() => + { + "generated-adapter" + } + Classification::CrtNative { .. } + | Classification::CrtWrapper { .. } + | Classification::RuntimeHelper { .. } + | Classification::Win32Stub { .. } => "generated-stub", + Classification::Manual { .. } | Classification::Unsupported { .. } => "no-binding", + } + } } /// Full coverage manifest for a set of import records. @@ -61,6 +77,18 @@ impl Manifest { m } + /// Count distinct module and symbol keys by emitted disposition. + pub fn emission_summary(&self) -> BTreeMap<&'static str, usize> { + let mut seen = BTreeSet::new(); + let mut counts = BTreeMap::new(); + for entry in &self.entries { + if seen.insert((entry.module.to_ascii_lowercase(), entry.symbol.as_str())) { + *counts.entry(entry.emission()).or_default() += 1; + } + } + counts + } + /// Entries that the generator can produce code for. pub fn generatable(&self) -> impl Iterator { self.entries @@ -70,14 +98,15 @@ impl Manifest { /// Write the manifest as CSV for `xenora imports sync` integration. pub fn write_csv(&self, path: &str) -> Result<(), String> { - let mut out = String::from("module,symbol,iat_rva,tier\n"); + let mut out = String::from("module,symbol,iat_rva,tier,emission\n"); for e in &self.entries { out.push_str(&format!( - "\"{}\",\"{}\",0x{:08x},{}\n", + "\"{}\",\"{}\",0x{:08x},{},{}\n", e.module, e.symbol, e.iat_rva, - e.tier() + e.tier(), + e.emission() )); } std::fs::write(path, out).map_err(|e| format!("write manifest CSV {path}: {e}")) @@ -90,13 +119,25 @@ impl Manifest { let mut md = String::new(); md.push_str("# Xenora import generator manifest\n\n"); md.push_str("Generated by `xenora imports generate`. Do not edit manually.\n\n"); - md.push_str("## Summary\n\n"); + md.push_str("## Catalog classification by import slot\n\n"); md.push_str("| Tier | Count | % |\n| --- | ---: | ---: |\n"); - md.push_str(&format!("| **Total** | {total} | 100% |\n")); + let total_pct = if total == 0 { 0 } else { 100 }; + md.push_str(&format!("| **Total** | {total} | {total_pct}% |\n")); for (tier, count) in &summary { let pct = (*count as f64 / total as f64 * 100.0) as u32; md.push_str(&format!("| `{tier}` | {count} | {pct}% |\n")); } + md.push_str("\n## Emitted disposition by distinct import\n\n"); + md.push_str("| Disposition | Count |\n| --- | ---: |\n"); + let emissions = self.emission_summary(); + md.push_str(&format!( + "| **Total** | {} |\n", + emissions.values().sum::() + )); + for (disposition, count) in emissions { + md.push_str(&format!("| `{disposition}` | {count} |\n")); + } + md.push_str("\nAdapters are emitted as partial handlers. Runtime services use existing registrations.\n"); md.push_str("\n## Functions requiring manual engineering\n\n"); for e in &self.entries { if let Classification::Manual { reason } | Classification::Unsupported { reason } = diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index c3110a7b..0d2933d6 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -67,6 +67,16 @@ fn test_manifest_and_codegen_pipeline() { assert_eq!(summary.get("standard-service"), Some(&5)); assert_eq!(manifest.generatable().count(), 4); + let emissions = manifest.emission_summary(); + assert_eq!(emissions.get("generated-adapter"), Some(&1)); + assert_eq!(emissions.get("generated-stub"), Some(&2)); + assert_eq!(emissions.get("runtime-service"), Some(&5)); + assert_eq!(emissions.get("no-binding"), Some(&1)); + let csv = tmp_dir.join("manifest.csv"); + manifest.write_csv(csv.to_str().unwrap()).unwrap(); + let csv = std::fs::read_to_string(csv).unwrap(); + assert!(csv.contains("\"acos\",0x00001000,crt-native,generated-stub")); + let files = generate(&manifest, &db); assert!(files.crt_rs.contains("register_generated_crt_services")); assert_eq!(files.crt_rs.matches("\"tolower\"").count(), 1); From dd1d1f27e6cf42165b3e8f685888588b0cca8512 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:11:50 -0500 Subject: [PATCH 30/82] Register standard runtime services in the trusted CLI worker Signed-off-by: Adeeb Rahman --- crates/cli/src/runner.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index a6505e3d..f9ed05ad 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -10,7 +10,9 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use xenora_loader::startup::{StartupEvent, StartupLayout, run_synthetic_startup_with_observer}; -use xenora_loader::{ExitReason, ImportRegistry, Register}; +use xenora_loader::{ + ExitReason, ImportRegistry, Register, ServicesState, SystemClock, register_standard_services, +}; use xenora_metal::NativeCompute; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; @@ -175,6 +177,10 @@ fn run_worker(options: &Options) -> Result<(), Box> { let capture = Arc::new(Mutex::new(None)); let draw_capture = Arc::clone(&capture); let mut imports = ImportRegistry::new(); + register_standard_services( + &mut imports, + Arc::new(ServicesState::new(Arc::new(SystemClock))), + ); let trace = options.trace; imports.register("xenora.dll", "fixture_draw", move |args, _, memory| { let ticket_address = args.get(0, memory).map_err(ExitReason::MemoryFault)?; From d12b50075b706c352e636273de46d5111d9e436c Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:13:22 -0500 Subject: [PATCH 31/82] Exercise standard kernel services through an exact-byte CLI fixture Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/cli/src/runner.rs | 32 +++++++++++++---------- fixtures/pe/runtime-services.exe | Bin 0 -> 3072 bytes fixtures/pe/trusted-runner.py | 42 +++++++++++++++++++++++++------ 4 files changed, 55 insertions(+), 21 deletions(-) create mode 100644 fixtures/pe/runtime-services.exe diff --git a/CHANGELOG.md b/CHANGELOG.md index ae36d864..375c4725 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,8 @@ remains unsupported. ### Added +- The experimental CLI can run the embedded runtime-services fixture, which round-trips the guest last-error value through two kernel32 imports before drawing a verified Metal frame. + - Import manifests now report emitted adapters, stubs, and existing runtime bindings separately from catalog classifications. - Generated import conformance tests now execute emitted service handlers and verify unsupported stubs. diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index f9ed05ad..d0a91560 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -17,6 +17,7 @@ use xenora_metal::NativeCompute; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); +const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe"); const WALL_LIMIT: Duration = Duration::from_secs(15); const DEFAULT_STEPS: usize = 100; const MAX_STEPS: usize = 10_000; @@ -134,11 +135,11 @@ fn launch_worker(options: &Options) -> Result> { } } -fn verify_fixture(path: &Path) -> Result<(), Box> { +fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { let valid_metadata = |metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64; let rejection = - "execution denied: input must match the original trusted PE fixture byte for byte"; + "execution denied: input must match an embedded trusted PE fixture byte for byte"; // Check size before opening and again on the descriptor. Bound the read // even if another process changes the file after the metadata checks. if !valid_metadata(fs::metadata(path)?) { @@ -151,10 +152,10 @@ fn verify_fixture(path: &Path) -> Result<(), Box> { let mut bytes = Vec::with_capacity(FIXTURE.len() + 1); file.take(FIXTURE.len() as u64 + 1) .read_to_end(&mut bytes)?; - if bytes != FIXTURE { - return Err(rejection.into()); - } - Ok(()) + [FIXTURE, SERVICES_FIXTURE] + .into_iter() + .find(|fixture| *fixture == bytes) + .ok_or_else(|| rejection.into()) } fn run_worker(options: &Options) -> Result<(), Box> { @@ -166,10 +167,15 @@ fn run_worker(options: &Options) -> Result<(), Box> { // its own deadline if it is invoked directly. std::process::exit(124); })?; - verify_fixture(&options.path)?; + let fixture = verify_fixture(&options.path)?; + let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE { + ("runtime-services", 23, 3) + } else { + ("trusted-runner", TICKET, 1) + }; if options.trace { println!( - "trace fixture=trusted-runner policy=exact-bytes entry_step_limit={} wall_limit_ms=15000", + "trace fixture={name} policy=exact-bytes entry_step_limit={} wall_limit_ms=15000", options.max_steps ); } @@ -194,15 +200,15 @@ fn run_worker(options: &Options) -> Result<(), Box> { || memory .read_u64(ticket_address) .map_err(ExitReason::MemoryFault)? - != TICKET + != ticket { *result = Some(Err( - "draw ticket did not match the TLS-initialized guest word".into(), + "guest draw ticket differed from the expected value".into() )); return Err(ExitReason::IllegalInstruction(0xff)); } if trace { - println!("trace import=xenora.dll!fixture_draw tls_ticket={TICKET}"); + println!("trace import=xenora.dll!fixture_draw tls_ticket={ticket}"); } let frame = draw().map_err(|error| error.to_string()); let drawn = frame.is_ok(); @@ -217,7 +223,7 @@ fn run_worker(options: &Options) -> Result<(), Box> { let started = Instant::now(); // Use only the embedded snapshot. The file is solely an exact-byte gate. let startup = run_synthetic_startup_with_observer( - FIXTURE, + fixture, StartupLayout { image_base: IMAGE_BASE, stack_top: 0x200010000, @@ -251,7 +257,7 @@ fn run_worker(options: &Options) -> Result<(), Box> { return Err(exit.into()); } if startup.relocations.applied_dir64 != 4 - || startup.bound_imports != 1 + || startup.bound_imports != bound_imports || startup.tls_callbacks != 1 || rax != DRAW_RESULT { diff --git a/fixtures/pe/runtime-services.exe b/fixtures/pe/runtime-services.exe new file mode 100644 index 0000000000000000000000000000000000000000..a159624e2699cb3793f13048172a33b3ddd3571b GIT binary patch literal 3072 zcmeZ`VjvqdkgXG;F~F69A*GE4Apm53U{GS>F#9>PHN>VFI zKpc>tV17dl7Ld~t^omjvOA?{#fC4CC1muE%0}$y!m4W3AfPx@%Ie-`mI503A&?`#K z$xj9fg5-e$V44d^BLN2n1}7x$D03KvfJgHijh*5^5B(SY2uybWMLz>ck8a*0AgYt` zzvyWYqxp!&7wn$)=w_V>QgNI?5UAiVc15G2gEj;L6cA2J0J1^ll!78c%mKtk;v-}r ztOf;C5p;eU(qFzc)4yrl?FDj5-{4gzT6 zQ1vin=iOLh{+EMR}#r78T_eflP5n Date: Tue, 24 Nov 2026 08:15:06 -0500 Subject: [PATCH 32/82] Track built-in guest module references and revoke released exports Signed-off-by: Adeeb Rahman --- crates/loader/src/imports.rs | 7 ++ crates/loader/src/services/modules.rs | 114 ++++++++++++++++++++++++-- 2 files changed, 113 insertions(+), 8 deletions(-) diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 45efe338..7ea86676 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -163,6 +163,13 @@ pub struct ServiceDescriptor { pub(crate) struct DynamicTrampolines(Arc>>); impl DynamicTrampolines { + pub(crate) fn revoke(&self, indices: impl Iterator) { + let mut entries = self.0.write().expect("dynamic service trampolines"); + for index in indices { + entries.remove(&trampoline_address(index)); + } + } + pub(crate) fn expose(&self, index: usize) -> u64 { let address = trampoline_address(index); self.0 diff --git a/crates/loader/src/services/modules.rs b/crates/loader/src/services/modules.rs index 4b099d21..205acf1b 100644 --- a/crates/loader/src/services/modules.rs +++ b/crates/loader/src/services/modules.rs @@ -2,12 +2,12 @@ //! Module and export lookup for built-in guest services. -use super::{ERROR_INVALID_HANDLE, KERNEL32, ServicesState}; +use super::{ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, KERNEL32, ServicesState}; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{GuestMemory, MemoryError}; use std::collections::BTreeMap; -use std::sync::{Arc, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; const LOADER_API: &str = "api-ms-win-core-libraryloader-l1-2-0.dll"; const UCRT: &str = "ucrtbase.dll"; @@ -19,6 +19,7 @@ const MODULE_BASE: u64 = 0x0000_0007_e000_0000; struct Modules { names: BTreeMap, exports: BTreeMap<(u64, String), usize>, + references: Mutex>, } fn read_name( @@ -50,7 +51,13 @@ fn read_name( pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { let modules = Arc::new(OnceLock::::new()); - for (symbol, wide) in [("GetModuleHandleA", false), ("GetModuleHandleW", true)] { + let named_operations = [ + ("GetModuleHandleA", false, false), + ("GetModuleHandleW", true, false), + ("LoadLibraryA", false, true), + ("LoadLibraryW", true, true), + ]; + for (symbol, wide, load) in named_operations { let state = Arc::clone(state); let modules = Arc::clone(&modules); registry.register(KERNEL32, symbol, move |args, _, memory| { @@ -66,19 +73,54 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc name.push_str(".dll"); } let modules = modules.get().expect("built-in module catalog"); - match modules.names.get(&name) { - Some(&handle) => Ok(handle), - None => state.fail(MODULE_NOT_FOUND, 0), + let Some(&handle) = modules.names.get(&name) else { + return state.fail(MODULE_NOT_FOUND, 0); + }; + let mut references = modules.references.lock().expect("module references"); + if load { + let count = references.entry(handle).or_default(); + let Some(next) = count.checked_add(1) else { + return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + }; + *count = next; + } else if handle != MODULE_BASE && !references.contains_key(&handle) { + return state.fail(MODULE_NOT_FOUND, 0); } + Ok(handle) }); } + let release = Arc::clone(&modules); + let release_state = Arc::clone(state); + let release_trampolines = registry.dynamic_trampolines(); + registry.register(KERNEL32, "FreeLibrary", move |args, _, _| { + let modules = release.get().expect("built-in module catalog"); + let mut references = modules.references.lock().expect("module references"); + let Some(count) = references.get_mut(&args.rcx) else { + return release_state.fail(ERROR_INVALID_HANDLE, 0); + }; + *count -= 1; + if *count == 0 { + references.remove(&args.rcx); + if args.rcx != MODULE_BASE { + release_trampolines.revoke( + modules + .exports + .iter() + .filter_map(|((handle, _), &index)| (*handle == args.rcx).then_some(index)), + ); + } + } + Ok(1) + }); + let lookup = Arc::clone(&modules); let trampolines = registry.dynamic_trampolines(); let state = Arc::clone(state); registry.register(KERNEL32, "GetProcAddress", move |args, _, memory| { let modules = lookup.get().expect("built-in module catalog"); - if !matches!(args.rcx, MODULE_BASE | UCRT_HANDLE) { + let references = modules.references.lock().expect("module references"); + if args.rcx != MODULE_BASE && !references.contains_key(&args.rcx) { return state.fail(ERROR_INVALID_HANDLE, 0); } // Ordinal entries require an independently verified export catalog. @@ -95,12 +137,18 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } }); - for symbol in ["GetModuleHandleA", "GetModuleHandleW", "GetProcAddress"] { + for symbol in named_operations + .map(|(symbol, _, _)| symbol) + .into_iter() + .chain(["GetProcAddress", "FreeLibrary"]) + { registry.alias(LOADER_API, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); } let mut catalog = Modules::default(); + // Preserve the startup UCRT binding. Kernel services are resident. + catalog.references.get_mut().unwrap().insert(UCRT_HANDLE, 1); for (module, handle) in [(KERNEL32, MODULE_BASE), (UCRT, UCRT_HANDLE)] { catalog.names.insert(module.to_owned(), handle); for (name, symbol, status) in registry.iter_registered() { @@ -121,3 +169,53 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } const UCRT_HANDLE: u64 = MODULE_BASE + 0x10000; + +#[cfg(test)] +mod tests { + use super::*; + use crate::cpu::{CpuState, Register}; + use crate::import_table::ImportName; + use crate::imports::Win64Args; + use crate::memory::MemoryPermissions; + use crate::services::{MockClock, register_standard_services}; + + #[test] + fn guest_module_references_control_dynamic_export_lifetime() { + let mut registry = ImportRegistry::new(); + register_standard_services( + &mut registry, + Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), + ); + let mut memory = GuestMemory::new(); + memory + .map_region(0x10000, 4096, MemoryPermissions::READ_WRITE) + .unwrap(); + memory.write_bytes(0x10000, b"UCRTBASE\0").unwrap(); + memory.write_bytes(0x10100, b"sqrt\0").unwrap(); + memory.write_bytes(0x10200, b"/unknown.dll\0").unwrap(); + let mut call = |symbol: &str, first, second| { + let mut cpu = CpuState::default(); + cpu.set(Register::Rcx, first); + cpu.set(Register::Rdx, second); + let service = registry + .resolve(LOADER_API, &ImportName::Name(symbol.to_owned())) + .unwrap(); + (service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap() + }; + assert_eq!(call("LoadLibraryA", 0x10200, 0), 0); + let handle = call("GetModuleHandleA", 0x10000, 0); + assert_ne!(handle, 0); + assert_eq!(call("LoadLibraryA", 0x10000, 0), handle); + let export = call("GetProcAddress", handle, 0x10100); + assert!(registry.is_service_trampoline(export)); + assert_eq!(call("FreeLibrary", handle, 0), 1); + assert!(registry.is_service_trampoline(export)); + assert_eq!(call("FreeLibrary", handle, 0), 1); + assert!(!registry.is_service_trampoline(export)); + assert_eq!(call("GetModuleHandleA", 0x10000, 0), 0); + assert_eq!(call("GetProcAddress", handle, 0x10100), 0); + assert_eq!(call("FreeLibrary", handle, 0), 0); + assert_eq!(call("LoadLibraryA", 0x10000, 0), handle); + assert_ne!(call("GetProcAddress", handle, 0x10100), 0); + } +} From fbb487384f9ff42b73e756fe6f26cd2a2d43c69c Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:16:53 -0500 Subject: [PATCH 33/82] Resolve registered ordinals through guest module handles Signed-off-by: Adeeb Rahman --- crates/loader/src/imports.rs | 15 ++++++ crates/loader/src/services/modules.rs | 67 +++++++++++++++++---------- 2 files changed, 57 insertions(+), 25 deletions(-) diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 7ea86676..81b7a93f 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -241,6 +241,21 @@ impl ImportRegistry { self.index(module, &ImportName::Name(symbol.to_owned())) } + pub(crate) fn canonical_exports( + &self, + module: &str, + ) -> impl Iterator { + self.services + .iter() + .filter_map(move |((key, name), &index)| { + let descriptor = &self.handlers[index]; + (key == module + && descriptor.module == *key + && descriptor.status != ServiceStatus::Stub) + .then_some((name, index)) + }) + } + fn check_key(module: &str, name: &ImportName) -> Result<(), RegistryError> { let printable = |text: &str| { !text.is_empty() diff --git a/crates/loader/src/services/modules.rs b/crates/loader/src/services/modules.rs index 205acf1b..91f973e0 100644 --- a/crates/loader/src/services/modules.rs +++ b/crates/loader/src/services/modules.rs @@ -4,9 +4,10 @@ use super::{ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, KERNEL32, ServicesState}; use crate::cpu::ExitReason; +use crate::import_table::ImportName; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{GuestMemory, MemoryError}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashMap}; use std::sync::{Arc, Mutex, OnceLock}; const LOADER_API: &str = "api-ms-win-core-libraryloader-l1-2-0.dll"; @@ -18,7 +19,7 @@ const MODULE_BASE: u64 = 0x0000_0007_e000_0000; #[derive(Default)] struct Modules { names: BTreeMap, - exports: BTreeMap<(u64, String), usize>, + exports: BTreeMap>, references: Mutex>, } @@ -103,12 +104,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if *count == 0 { references.remove(&args.rcx); if args.rcx != MODULE_BASE { - release_trampolines.revoke( - modules - .exports - .iter() - .filter_map(|((handle, _), &index)| (*handle == args.rcx).then_some(index)), - ); + release_trampolines.revoke(modules.exports[&args.rcx].values().copied()); } } Ok(1) @@ -123,15 +119,17 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if args.rcx != MODULE_BASE && !references.contains_key(&args.rcx) { return state.fail(ERROR_INVALID_HANDLE, 0); } - // Ordinal entries require an independently verified export catalog. - if args.rdx <= u16::MAX as u64 { - return state.fail(PROCEDURE_NOT_FOUND, 0); - } - let Some(symbol) = read_name(memory, args.rdx, false).map_err(ExitReason::MemoryFault)? - else { - return state.fail(PROCEDURE_NOT_FOUND, 0); + let export = if let Ok(ordinal) = u16::try_from(args.rdx) { + ImportName::Ordinal(ordinal) + } else { + let Some(symbol) = + read_name(memory, args.rdx, false).map_err(ExitReason::MemoryFault)? + else { + return state.fail(PROCEDURE_NOT_FOUND, 0); + }; + ImportName::Name(symbol) }; - match modules.exports.get(&(args.rcx, symbol)) { + match modules.exports[&args.rcx].get(&export) { Some(&index) => Ok(trampolines.expose(index)), None => state.fail(PROCEDURE_NOT_FOUND, 0), } @@ -151,14 +149,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc catalog.references.get_mut().unwrap().insert(UCRT_HANDLE, 1); for (module, handle) in [(KERNEL32, MODULE_BASE), (UCRT, UCRT_HANDLE)] { catalog.names.insert(module.to_owned(), handle); - for (name, symbol, status) in registry.iter_registered() { - if name == module - && status != ServiceStatus::Stub - && let Some(index) = registry.service_index(name, symbol) - { - catalog.exports.insert((handle, symbol.to_owned()), index); - } - } + catalog.exports.insert( + handle, + registry + .canonical_exports(module) + .map(|(key, index)| (key.clone(), index)) + .collect(), + ); for (alias, _, canonical) in registry.iter_aliases() { if canonical == module { catalog.names.insert(alias.to_owned(), handle); @@ -174,7 +171,6 @@ const UCRT_HANDLE: u64 = MODULE_BASE + 0x10000; mod tests { use super::*; use crate::cpu::{CpuState, Register}; - use crate::import_table::ImportName; use crate::imports::Win64Args; use crate::memory::MemoryPermissions; use crate::services::{MockClock, register_standard_services}; @@ -182,6 +178,14 @@ mod tests { #[test] fn guest_module_references_control_dynamic_export_lifetime() { let mut registry = ImportRegistry::new(); + registry + .try_register( + UCRT, + ImportName::Ordinal(42), + ServiceStatus::Implemented, + Box::new(|_, _, _| Ok(42)), + ) + .unwrap(); register_standard_services( &mut registry, Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), @@ -193,6 +197,7 @@ mod tests { memory.write_bytes(0x10000, b"UCRTBASE\0").unwrap(); memory.write_bytes(0x10100, b"sqrt\0").unwrap(); memory.write_bytes(0x10200, b"/unknown.dll\0").unwrap(); + memory.write_bytes(0x10300, b"Ordinal#42\0").unwrap(); let mut call = |symbol: &str, first, second| { let mut cpu = CpuState::default(); cpu.set(Register::Rcx, first); @@ -207,15 +212,27 @@ mod tests { assert_ne!(handle, 0); assert_eq!(call("LoadLibraryA", 0x10000, 0), handle); let export = call("GetProcAddress", handle, 0x10100); + let ordinal = call("GetProcAddress", handle, 42); + assert!(registry.is_service_trampoline(ordinal)); + assert_ne!(ordinal, export); + assert_eq!(call("GetProcAddress", handle, 43), 0); + assert_eq!(call("GetProcAddress", handle, 0x10300), 0); assert!(registry.is_service_trampoline(export)); assert_eq!(call("FreeLibrary", handle, 0), 1); assert!(registry.is_service_trampoline(export)); assert_eq!(call("FreeLibrary", handle, 0), 1); assert!(!registry.is_service_trampoline(export)); + assert!(!registry.is_service_trampoline(ordinal)); assert_eq!(call("GetModuleHandleA", 0x10000, 0), 0); assert_eq!(call("GetProcAddress", handle, 0x10100), 0); assert_eq!(call("FreeLibrary", handle, 0), 0); assert_eq!(call("LoadLibraryA", 0x10000, 0), handle); assert_ne!(call("GetProcAddress", handle, 0x10100), 0); + let ordinal = call("GetProcAddress", handle, 42); + let mut cpu = CpuState::new(ordinal, 0x10400); + memory.write_u64(0x10400, 0x1234).unwrap(); + registry.dispatch(ordinal, &mut cpu, &mut memory).unwrap(); + assert_eq!(cpu.get(Register::Rax), 42); + assert_eq!(cpu.rip, 0x1234); } } From 1d0b0d1547d1356e864a2d39ec4579f35c849dc1 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:18:16 -0500 Subject: [PATCH 34/82] Generate documented ordinal aliases for typed runtime services Signed-off-by: Adeeb Rahman --- crates/import-gen/src/typed.rs | 58 +++++++++++++++++++++++++++ crates/loader/src/imports.rs | 39 +++++++++++++----- crates/loader/src/services/modules.rs | 14 ++++--- docs/runtime/registry.md | 1 + 4 files changed, 96 insertions(+), 16 deletions(-) diff --git a/crates/import-gen/src/typed.rs b/crates/import-gen/src/typed.rs index 1bcb1ccc..f31c603e 100644 --- a/crates/import-gen/src/typed.rs +++ b/crates/import-gen/src/typed.rs @@ -20,6 +20,7 @@ pub struct Parameter { pub struct Service { pub library: String, pub symbol: String, + pub ordinal: Option<(u16, String)>, pub parameters: Vec, pub result: String, pub handler: String, @@ -96,6 +97,17 @@ pub fn parse(text: &str, test_source: &str) -> Result, String> { "handler" => service.handler = rest.to_owned(), "status" => service.status = rest.to_owned(), "alias" => service.aliases.push(rest.to_owned()), + "ordinal" => { + let (value, source) = rest + .split_once(' ') + .ok_or_else(|| at("ordinal needs a number and a source"))?; + let value = value + .parse::() + .ok() + .filter(|value| *value != 0) + .ok_or_else(|| at("ordinal must be in 1..=65535"))?; + service.ordinal = Some((value, source.trim().to_owned())); + } "fails" => service.failure = rest.to_owned(), "ref" => service.reference = rest.to_owned(), "test" => service.tests.push(rest.to_owned()), @@ -123,6 +135,7 @@ fn parse_signature(text: &str) -> Result { Ok(Service { library: library.to_owned(), symbol: symbol.trim().to_owned(), + ordinal: None, parameters, result: result.trim().to_owned(), handler: String::new(), @@ -137,6 +150,7 @@ fn parse_signature(text: &str) -> Result { fn validate(services: &[Service], test_source: &str) -> Result<(), String> { // Every key a guest could import, with the service it resolves to. let mut keys: BTreeMap<(String, &str), usize> = BTreeMap::new(); + let mut ordinals = BTreeSet::new(); for (index, service) in services.iter().enumerate() { let name = format!("{}!{}", service.library, service.symbol); let fail = |message: String| Err(format!("{name}: {message}")); @@ -149,6 +163,14 @@ fn validate(services: &[Service], test_source: &str) -> Result<(), String> { if !is_identifier(&service.symbol) { return fail("symbol is not an identifier".into()); } + if let Some((ordinal, source)) = &service.ordinal { + if source.is_empty() { + return fail("ordinal needs a source".into()); + } + if !ordinals.insert((&service.library, ordinal)) { + return fail(format!("ordinal {ordinal} already resolves in this module")); + } + } if !is_identifier(&service.handler) { return fail("missing or invalid handler".into()); } @@ -293,6 +315,13 @@ pub fn generate_rust(services: &[Service]) -> String { "{cpu} let mut context = ServiceContext {{ state: &s, memory }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});", service.handler ); + if let Some((ordinal, _)) = &service.ordinal { + let _ = writeln!( + out, + " registry.try_ordinal_alias({:?}, {:?}, {ordinal}).expect(\"validated export ordinal\");", + service.library, service.symbol + ); + } } out.push_str(" for service in &SERVICES {\n for alias in service.aliases {\n if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {\n panic!(\"{error}\");\n }\n }\n }\n}\n"); out.replace( @@ -343,6 +372,15 @@ pub fn generate_report(services: &[Service]) -> String { service.failure ); } + for service in services { + if let Some((ordinal, source)) = &service.ordinal { + let _ = writeln!( + out, + "\nOrdinal {ordinal} for `{}!{}` is documented by {source}.", + service.library, service.symbol + ); + } + } out } @@ -379,6 +417,26 @@ mod tests { assert!(generate_report(&services).contains("| Unique handler implementations | 1 |")); } + #[test] + fn ordinal_requires_a_source_and_unique_module_key() { + let first = entry("kernel32.dll F() -> void", "ordinal 42 test catalog"); + let services = parse(&first, TESTS).unwrap(); + assert!( + generate_rust(&services).contains("try_ordinal_alias(\"kernel32.dll\", \"F\", 42)") + ); + assert!(generate_report(&services).contains("documented by test catalog")); + let second = entry("kernel32.dll G() -> void", "ordinal 42 test catalog"); + rejects(&(first + &second), "ordinal 42 already resolves"); + rejects( + &entry("kernel32.dll F() -> void", "ordinal 42"), + "needs a number and a source", + ); + rejects( + &entry("kernel32.dll F() -> void", "ordinal 65536 test catalog"), + "1..=65535", + ); + } + #[test] fn conflicting_keys_are_rejected() { let one = entry("kernel32.dll F() -> void", ""); diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 81b7a93f..12957293 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -406,24 +406,43 @@ impl ImportRegistry { target: &str, symbol: &str, ) -> Result<(), RegistryError> { - let name = ImportName::Name(symbol.to_owned()); - Self::check_key(module, &name)?; - let index = self - .index(target, &name) - .ok_or_else(|| RegistryError::UnknownTarget { - module: target.to_owned(), - symbol: symbol.to_owned(), - })?; + self.alias_key(module, target, symbol, ImportName::Name(symbol.to_owned())) + } + + /// Publish a documented ordinal for a named export in its canonical module. + pub fn try_ordinal_alias( + &mut self, + module: &str, + symbol: &str, + ordinal: u16, + ) -> Result<(), RegistryError> { + self.alias_key(module, module, symbol, ImportName::Ordinal(ordinal)) + } + + fn alias_key( + &mut self, + module: &str, + target: &str, + symbol: &str, + key: ImportName, + ) -> Result<(), RegistryError> { + Self::check_key(module, &key)?; + let index = + self.service_index(target, symbol) + .ok_or_else(|| RegistryError::UnknownTarget { + module: target.to_owned(), + symbol: symbol.to_owned(), + })?; let previous = *self .services - .entry((module.to_ascii_lowercase(), name)) + .entry((module.to_ascii_lowercase(), key.clone())) .or_insert(index); if previous == index { Ok(()) } else { Err(RegistryError::Duplicate { module: module.to_owned(), - symbol: symbol.to_owned(), + symbol: key.to_string(), }) } } diff --git a/crates/loader/src/services/modules.rs b/crates/loader/src/services/modules.rs index 91f973e0..1a059fce 100644 --- a/crates/loader/src/services/modules.rs +++ b/crates/loader/src/services/modules.rs @@ -178,14 +178,16 @@ mod tests { #[test] fn guest_module_references_control_dynamic_export_lifetime() { let mut registry = ImportRegistry::new(); + registry.register(UCRT, "SyntheticOrdinalExport", |_, _, _| Ok(42)); registry - .try_register( - UCRT, - ImportName::Ordinal(42), - ServiceStatus::Implemented, - Box::new(|_, _, _| Ok(42)), - ) + .try_ordinal_alias(UCRT, "SyntheticOrdinalExport", 42) .unwrap(); + registry.register(UCRT, "OtherSyntheticExport", |_, _, _| Ok(43)); + assert!( + registry + .try_ordinal_alias(UCRT, "OtherSyntheticExport", 42) + .is_err() + ); register_standard_services( &mut registry, Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), diff --git a/docs/runtime/registry.md b/docs/runtime/registry.md index 81d3e320..5096a324 100644 --- a/docs/runtime/registry.md +++ b/docs/runtime/registry.md @@ -14,6 +14,7 @@ Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, th - Module names compare without case; symbol names are exact. A name spelled `Ordinal#7` is not ordinal 7. - An API set resolves only if the registry lists that exact set for that symbol. A similar name forwards nowhere. +- An optional `ordinal ` field adds an ordinal for the canonical DLL. Cite the export catalog and version that establish the mapping. Named and ordinal imports share the same adapter. The ordinal applies only to the canonical DLL. - Registering a key twice is an error. A host module cannot replace a standard service. - Binding resolves every import before it writes any slot. A malformed table or an unresolved import leaves every slot unbound. - A service call reads its return address first, and stops the guest with `ServiceAbiViolation` if the service changed a nonvolatile register, including XMM6 to XMM15. From 2367414be54852f04efe0362cf7aafdd94c149b6 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:20:01 -0500 Subject: [PATCH 35/82] Preserve typed import identities in probe and sync reports Signed-off-by: Adeeb Rahman --- crates/cli/src/main.rs | 17 ++++++++++++++-- crates/loader/src/probe.rs | 31 ++++++++++++++++------------- crates/loader/tests/probe_static.rs | 22 +++++++++++++++++++- 3 files changed, 53 insertions(+), 17 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 870db507..df3740e5 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -422,6 +422,7 @@ fn run_imports_sync( use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use xenora_loader::ImportRegistry; + use xenora_loader::import_table::ImportName; use xenora_loader::imports::ServiceStatus; use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; @@ -446,7 +447,11 @@ fn run_imports_sync( let mut total = 0usize; let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new(); - for line in csv_text.lines().skip(1) { + let mut lines = csv_text.lines(); + let has_import_kind = lines + .next() + .is_some_and(|header| header.ends_with(",import_kind")); + for line in lines { // Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster // We re-query the live registry rather than trusting cached status. let fields: Vec<&str> = line.splitn(10, ',').collect(); @@ -459,7 +464,15 @@ fn run_imports_sync( continue; } - let binding = registry.binding(&module, &symbol); + let name = if has_import_kind && line.ends_with(",ordinal") { + let Some(ordinal) = symbol.strip_prefix("Ordinal#").and_then(|n| n.parse().ok()) else { + continue; + }; + ImportName::Ordinal(ordinal) + } else { + ImportName::Name(symbol.clone()) + }; + let binding = registry.resolve(&module, &name); let is_registered = binding.is_some(); let status = binding.map(|b| b.status); diff --git a/crates/loader/src/probe.rs b/crates/loader/src/probe.rs index e4b526e6..0ec2400c 100644 --- a/crates/loader/src/probe.rs +++ b/crates/loader/src/probe.rs @@ -11,7 +11,7 @@ //! startup blockers. use crate::dbt::{is_native, is_translatable}; -use crate::import_table::{ImportTableError, parse_imports}; +use crate::import_table::{ImportName, ImportTableError, parse_imports}; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::MemoryPermissions; use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection}; @@ -596,12 +596,14 @@ pub struct TlsCensus { pub struct ImportedSymbol { pub dll: String, pub symbol: String, + pub import_name: ImportName, pub iat_rva: u32, pub category: &'static str, /// The standard synthetic registry has a handler for this exact key. pub is_supported: bool, pub service_status: Option, pub canonical_module: Option, + pub canonical_symbol: Option, } impl ImportedSymbol { @@ -978,10 +980,12 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result>( // 1. imports.csv let mut imports_csv = String::from( - "module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding\n", + "module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n", ); - let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva\n"); + let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n"); let mut modules = BTreeSet::new(); let mut unique_symbols = BTreeSet::new(); let mut distinct_imports = BTreeSet::new(); @@ -1149,18 +1153,17 @@ pub fn run_probe_and_export>( let mut clusters = BTreeMap::<(u8, &str), (usize, usize)>::new(); let mut aliases = 0; // The runner admits exactly these bytes and installs a private draw handler. - let trusted_fixture = bytes == include_bytes!("../../../fixtures/pe/trusted-runner.exe"); + let trusted_fixture = bytes == include_bytes!("../../../fixtures/pe/trusted-runner.exe") + || bytes == include_bytes!("../../../fixtures/pe/runtime-services.exe"); let mut trusted_runner_slots = 0; let mut missing = 0; for imp in &report.imports { let module_key = imp.dll.to_ascii_lowercase(); modules.insert(module_key.clone()); - distinct_imports.insert((module_key, &imp.symbol)); - let ordinal_scope = imp - .symbol - .starts_with("Ordinal#") - .then_some(imp.dll.as_str()); - unique_symbols.insert((ordinal_scope, &imp.symbol)); + let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_)); + let import_kind = if is_ordinal { "ordinal" } else { "name" }; + unique_symbols.insert((is_ordinal.then_some(module_key.clone()), &imp.import_name)); + distinct_imports.insert((module_key, &imp.import_name)); let module = imp.dll.replace('"', "\"\""); let symbol = imp.symbol.replace('"', "\"\""); let key = format!("\"{module}\",\"{symbol}\",0x{:08x}", imp.iat_rva); @@ -1171,8 +1174,8 @@ pub fn run_probe_and_export>( let status = imp.coverage_label(); let canonical = imp.canonical_module.as_deref().unwrap_or(""); let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical); - if imp.is_supported { - canonical_bindings.insert((canonical, &imp.symbol)); + if let Some(symbol) = &imp.canonical_symbol { + canonical_bindings.insert((canonical, symbol)); } aliases += usize::from(is_alias); *counts.entry(status).or_default() += 1; @@ -1183,11 +1186,11 @@ pub fn run_probe_and_export>( let canonical = canonical.replace('"', "\"\""); let _ = writeln!( imports_csv, - "{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding}", + "{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}", imp.category, imp.is_supported ); if !imp.is_supported { - let _ = writeln!(missing_csv, "{key}"); + let _ = writeln!(missing_csv, "{key},{import_kind}"); missing += 1; } } diff --git a/crates/loader/tests/probe_static.rs b/crates/loader/tests/probe_static.rs index 96c69f63..52f0d94b 100644 --- a/crates/loader/tests/probe_static.rs +++ b/crates/loader/tests/probe_static.rs @@ -200,6 +200,26 @@ fn probe_distinguishes_aliases_from_unavailable_services() { std::fs::remove_dir_all(path).unwrap(); } +#[test] +fn probe_distinguishes_ordinal_from_matching_symbol_text() { + let mut pe = include_bytes!("../../../fixtures/pe/runtime-services.exe").to_vec(); + pe[0x720..0x728].copy_from_slice(&((1_u64 << 63) | 42).to_le_bytes()); + pe[0x762..0x76e].copy_from_slice(b"Ordinal#42\0\0"); + let path = std::env::temp_dir().join(format!("xenora-probe-ordinal-{}", std::process::id())); + run_probe_and_export(&pe, &path, &ProbeConfig::default()).unwrap(); + let csv = std::fs::read_to_string(path.join("imports.csv")).unwrap(); + let json = std::fs::read_to_string(path.join("candidate_static_report.json")).unwrap(); + std::fs::remove_dir_all(path).unwrap(); + let rows: Vec<_> = csv + .lines() + .filter(|row| row.contains("Ordinal#42")) + .collect(); + assert_eq!(rows.len(), 2); + assert!(rows[0].ends_with(",ordinal")); + assert!(rows[1].ends_with(",name")); + assert!(json.contains("\"distinct_import_keys\": 3")); +} + #[test] fn trusted_runner_callback_and_report_match_the_fixture() { let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); @@ -230,7 +250,7 @@ fn trusted_runner_callback_and_report_match_the_fixture() { assert!( imports .lines() - .any(|line| line.contains("fixture_draw") && line.ends_with(",true")) + .any(|line| line.contains("fixture_draw") && line.ends_with(",true,name")) ); assert!(json.contains("\"trusted_runner_binding_slots\": 1")); assert!(json.contains("\"unresolved_imports\": 1")); From 2647ba0f14eae090744e956e72132f0fa8178c61 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:22:58 -0500 Subject: [PATCH 36/82] Keep ordinal identity in the import-list generator Signed-off-by: Adeeb Rahman --- crates/cli/src/main.rs | 8 ++++++- crates/import-gen/src/codegen.rs | 7 +++--- crates/import-gen/src/manifest.rs | 31 ++++++++++++++++++++++---- crates/import-gen/src/parse.rs | 21 +++++++++++++++++- crates/import-gen/tests/pipeline.rs | 34 +++++++++++++++++++++++++++++ 5 files changed, 92 insertions(+), 9 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index df3740e5..3db954bf 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -288,7 +288,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode { } } - let records = if let Some(ref pe) = pe_path { + let mut records = if let Some(ref pe) = pe_path { println!("Extracting imports from PE executable: {pe}"); let bytes = match std::fs::read(pe) { Ok(b) => b, @@ -311,6 +311,10 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode { .map(|imp| xenora_import_gen::ImportRecord { module: imp.dll, symbol: imp.symbol, + ordinal: match imp.import_name { + xenora_loader::import_table::ImportName::Ordinal(ordinal) => Some(ordinal), + xenora_loader::import_table::ImportName::Name(_) => None, + }, iat_rva: imp.iat_rva as u64, }) .collect::>() @@ -329,6 +333,8 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode { return ExitCode::from(2); }; + records.sort(); + records.dedup(); println!("Total imports extracted: {}", records.len()); let db = xenora_import_gen::SymbolDb::builtin(); let manifest = xenora_import_gen::Manifest::build(&records, &db); diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 9e058eec..9f354fa1 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -42,9 +42,10 @@ fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> { fn unique_entries(manifest: &Manifest) -> impl Iterator { let mut seen = std::collections::BTreeSet::new(); - manifest.entries.iter().filter(move |entry| { - seen.insert((entry.module.to_ascii_lowercase(), entry.symbol.as_str())) - }) + manifest + .entries + .iter() + .filter(move |entry| seen.insert(entry.key())) } /// Generate all files from the manifest. diff --git a/crates/import-gen/src/manifest.rs b/crates/import-gen/src/manifest.rs index 0b6fa209..4b614553 100644 --- a/crates/import-gen/src/manifest.rs +++ b/crates/import-gen/src/manifest.rs @@ -11,11 +11,24 @@ use std::collections::{BTreeMap, BTreeSet}; pub struct ManifestEntry { pub module: String, pub symbol: String, + pub ordinal: Option, pub iat_rva: u64, pub classification: Classification, } impl ManifestEntry { + pub(crate) fn key(&self) -> (String, Option, &str) { + ( + self.module.to_ascii_lowercase(), + self.ordinal, + if self.ordinal.is_none() { + &self.symbol + } else { + "" + }, + ) + } + pub fn tier(&self) -> &'static str { self.classification.tier_name() } @@ -48,7 +61,11 @@ impl Manifest { let mut entries = Vec::with_capacity(records.len()); for rec in records { // Check for exact symbol match, then wildcard module match - let classification = if let Some(c) = db.get(&rec.module, &rec.symbol) { + let classification = if rec.ordinal.is_some() { + Classification::Manual { + reason: "ordinal requires a documented export mapping in the typed runtime registry", + } + } else if let Some(c) = db.get(&rec.module, &rec.symbol) { c.clone() } else if let Some(c) = db.get(&rec.module, "__wildcard__") { c.clone() @@ -61,6 +78,7 @@ impl Manifest { entries.push(ManifestEntry { module: rec.module.clone(), symbol: rec.symbol.clone(), + ordinal: rec.ordinal, iat_rva: rec.iat_rva, classification, }); @@ -82,7 +100,7 @@ impl Manifest { let mut seen = BTreeSet::new(); let mut counts = BTreeMap::new(); for entry in &self.entries { - if seen.insert((entry.module.to_ascii_lowercase(), entry.symbol.as_str())) { + if seen.insert(entry.key()) { *counts.entry(entry.emission()).or_default() += 1; } } @@ -98,10 +116,15 @@ impl Manifest { /// Write the manifest as CSV for `xenora imports sync` integration. pub fn write_csv(&self, path: &str) -> Result<(), String> { - let mut out = String::from("module,symbol,iat_rva,tier,emission\n"); + let mut out = String::from("module,symbol,iat_rva,tier,emission,import_kind\n"); for e in &self.entries { + let kind = if e.ordinal.is_some() { + "ordinal" + } else { + "name" + }; out.push_str(&format!( - "\"{}\",\"{}\",0x{:08x},{},{}\n", + "\"{}\",\"{}\",0x{:08x},{},{},{kind}\n", e.module, e.symbol, e.iat_rva, diff --git a/crates/import-gen/src/parse.rs b/crates/import-gen/src/parse.rs index b31f0333..3784af68 100644 --- a/crates/import-gen/src/parse.rs +++ b/crates/import-gen/src/parse.rs @@ -3,7 +3,7 @@ //! CSV parser for the `missing_imports.csv` produced by `xenora probe`. //! //! Format: `"module","symbol_or_ordinal","iat_rva"` -//! The first line is a header and is skipped. +//! An optional `import_kind` column distinguishes numeric ordinals from names. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct ImportRecord { @@ -11,6 +11,7 @@ pub struct ImportRecord { pub module: String, /// Symbol name or `Ordinal#N` pub symbol: String, + pub ordinal: Option, /// IAT RVA (informational only, not used for generation) pub iat_rva: u64, } @@ -20,10 +21,14 @@ pub struct ImportRecord { pub fn parse_csv(path: &str) -> Result, String> { let content = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?; let mut records = Vec::new(); + let mut kind_column = None; for (line_no, line) in content.lines().enumerate() { // Skip header (with or without quotes) let trimmed = line.trim(); if line_no == 0 && (trimmed.starts_with("module") || trimmed.starts_with("\"module\"")) { + kind_column = split_csv_line(trimmed) + .iter() + .position(|column| unquote(column) == "import_kind"); continue; } let line = line.trim(); @@ -36,6 +41,19 @@ pub fn parse_csv(path: &str) -> Result, String> { } let module = unquote(cols[0]).to_string(); let symbol = unquote(cols[1]).to_string(); + let ordinal = match kind_column { + None => None, + Some(index) => match cols.get(index).map(|field| unquote(field)) { + Some("name") => None, + Some("ordinal") => Some( + symbol + .strip_prefix("Ordinal#") + .and_then(|value| value.parse().ok()) + .ok_or_else(|| format!("{path}:{}: invalid ordinal", line_no + 1))?, + ), + _ => return Err(format!("{path}:{}: invalid import_kind", line_no + 1)), + }, + }; let iat_rva = if cols.len() >= 3 { u64::from_str_radix(unquote(cols[2]).trim_start_matches("0x"), 16).unwrap_or(0) } else { @@ -45,6 +63,7 @@ pub fn parse_csv(path: &str) -> Result, String> { records.push(ImportRecord { module, symbol, + ordinal, iat_rva, }); } diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 0d2933d6..dc6121c9 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -33,6 +33,40 @@ fn test_builtin_db_case_insensitive() { assert_eq!(sym1, sym2); } +#[test] +fn typed_csv_preserves_ordinals_and_identically_spelled_names() { + let dir = std::env::temp_dir().join(format!("xenora-typed-imports-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let input = dir.join("imports.csv"); + std::fs::write( + &input, + "module,symbol_or_ordinal,iat_rva,import_kind\n\ + \"demo.dll\",\"Ordinal#42\",0x1000,ordinal\n\ + \"DEMO.dll\",\"Ordinal#42\",0x1004,ordinal\n\ + \"demo.dll\",\"Ordinal#42\",0x1008,name\n", + ) + .unwrap(); + let records = parse_csv(input.to_str().unwrap()).unwrap(); + let db = SymbolDb::builtin(); + let manifest = Manifest::build(&records, &db); + assert_eq!(manifest.emission_summary().get("no-binding"), Some(&2)); + assert_eq!(manifest.generatable().count(), 0); + let output = dir.join("manifest.csv"); + manifest.write_csv(output.to_str().unwrap()).unwrap(); + let csv = std::fs::read_to_string(output).unwrap(); + assert!(csv.contains("0x00001000,manual,no-binding,ordinal")); + assert!(csv.contains("0x00001008,manual,no-binding,name")); + let files = generate(&manifest, &db); + assert!(!files.crt_rs.contains("Ordinal#42")); + assert!(!files.stubs_rs.contains("Ordinal#42")); + assert!( + files + .manifest_md + .contains("requires a documented export mapping") + ); + std::fs::remove_dir_all(dir).unwrap(); +} + #[test] fn test_manifest_and_codegen_pipeline() { let csv_content = r#""module","symbol_or_ordinal","iat_rva" From c1e6646bf219ee137a82071eb68fd18ed6d48775 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:24:10 -0500 Subject: [PATCH 37/82] Use typed HRESULT results at the guest graphics boundary Signed-off-by: Adeeb Rahman --- crates/loader/src/runtime.rs | 29 +++++++++++++++++++++++++++++ crates/loader/src/services.rs | 12 +++++++----- crates/loader/tests/runtime_x15.rs | 15 +++++++++++++++ 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/crates/loader/src/runtime.rs b/crates/loader/src/runtime.rs index 0ca0b264..b2595c8d 100644 --- a/crates/loader/src/runtime.rs +++ b/crates/loader/src/runtime.rs @@ -153,3 +153,32 @@ pub struct ServiceMetadata { pub reference: &'static str, pub tests: &'static [&'static str], } +/// A 32-bit guest HRESULT returned through the Win64 integer result register. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct HResult(u32); + +impl HResult { + pub(crate) const OK: Self = Self(0); + pub(crate) const FAIL: Self = Self(0x8000_4005); + + /// Convert using the Windows SDK's HRESULT_FROM_WIN32 rules. + pub(crate) const fn from_win32(code: u32) -> Self { + if (code as i32) <= 0 { + Self(code) + } else { + Self(0x8007_0000 | (code & 0xffff)) + } + } + + pub(crate) fn guest_return(self) -> u64 { + u64::from(self.0) + } +} + +#[cfg(test)] +#[test] +fn hresult_win32_conversion_preserves_status_bits() { + assert_eq!(HResult::from_win32(0), HResult::OK); + assert_eq!(HResult::from_win32(0x8000_4005), HResult::FAIL); + assert_eq!(HResult::from_win32(0x10057).guest_return(), 0x8007_0057); +} diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index dc0936b6..bc5e194d 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -15,6 +15,8 @@ mod files; mod heap; mod modules; +use crate::runtime::HResult; + use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions}; @@ -396,7 +398,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result { let pp_device = args.get(3, mem).map_err(ExitReason::MemoryFault)?; if pp_device == 0 { - return Ok(0x80070057); // E_INVALIDARG + return Ok(HResult::from_win32(ERROR_INVALID_PARAMETER).guest_return()); } let mut gfx = s_gfx .lock() @@ -405,9 +407,9 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc { mem.write_u64(pp_device, handle.to_u64()) .map_err(ExitReason::MemoryFault)?; - Ok(0) // S_OK + Ok(HResult::OK.guest_return()) } - Err(_) => Ok(0x80004005), // E_FAIL + Err(_) => Ok(HResult::FAIL.guest_return()), } }; registry.register("xenora_fixture.dll", "CreateGraphicsDevice", handler); @@ -430,7 +432,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result { let vtx_addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?; if vtx_addr == 0 { - return Ok(0x80070057); // E_INVALIDARG + return Ok(HResult::from_win32(ERROR_INVALID_PARAMETER).guest_return()); } let clear_raw = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; let clear_color = [ @@ -507,7 +509,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Date: Tue, 24 Nov 2026 08:25:33 -0500 Subject: [PATCH 38/82] Isolate CRT errno by guest thread within the address space Signed-off-by: Adeeb Rahman --- crates/loader/src/memory.rs | 12 ++-- crates/loader/src/services/crt.rs | 99 ++++++++++++++++++++----------- 2 files changed, 74 insertions(+), 37 deletions(-) diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index 5ab1b216..ca86cf38 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -120,7 +120,8 @@ pub struct GuestMemory { regions: Vec, private_heaps: std::collections::BTreeSet, private_heap_serial: u64, - crt_errno: Option, + // Stable errno pointers indexed by the guest thread's TEB address. + crt_errno: std::collections::BTreeMap, } impl GuestMemory { @@ -202,13 +203,16 @@ impl GuestMemory { self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual) } - pub(crate) fn crt_errno_address(&mut self) -> Result { - if let Some(address) = self.crt_errno { + pub(crate) fn crt_errno_address(&mut self, teb: u64) -> Result { + if let Some(&address) = self.crt_errno.get(&teb) { return Ok(address); } + if self.crt_errno.len() >= 1024 { + return Err(MemoryError::AllocationFailed); + } let address = self.find_dynamic_base(4)?; self.map_region(address, 4, MemoryPermissions::READ_WRITE)?; - self.crt_errno = Some(address); + self.crt_errno.insert(teb, address); Ok(address) } diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index a83790a0..4d548697 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -3,7 +3,7 @@ //! C runtime services that operate on checked guest memory. use crate::cpu::ExitReason; -use crate::imports::{ImportRegistry, ServiceStatus}; +use crate::imports::{ImportRegistry, ServiceStatus, Win64Args}; use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP}; const SCAN_BUDGET: u64 = 1_048_576; @@ -168,9 +168,9 @@ pub(super) fn register(registry: &mut ImportRegistry) { const ENOMEM: u32 = 12; const EINVAL: u32 = 22; -fn set_errno(memory: &mut GuestMemory, error: u32) -> Result<(), ExitReason> { +fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> { let address = memory - .crt_errno_address() + .crt_errno_address(teb) .map_err(ExitReason::MemoryFault)?; memory .write_u32(address, error) @@ -179,12 +179,13 @@ fn set_errno(memory: &mut GuestMemory, error: u32) -> Result<(), ExitReason> { fn allocation_result( memory: &mut GuestMemory, + teb: u64, result: Result, ) -> Result { match result { Ok(address) => Ok(address), Err(_) => { - set_errno(memory, ENOMEM)?; + set_errno(memory, teb, ENOMEM)?; Ok(0) } } @@ -194,20 +195,20 @@ const ERANGE: u32 = 34; fn parse_integer( memory: &mut GuestMemory, - address: u64, - end: u64, - mut radix: u32, + args: &Win64Args, + teb: u64, signed: bool, wide_result: bool, unit: StringUnit, ) -> Result { + let (address, end, mut radix) = (args.rcx, args.rdx, args.r8 as u32); if address == 0 || (radix != 0 && !(2..=36).contains(&radix)) { if end != 0 { memory .write_u64(end, address) .map_err(ExitReason::MemoryFault)?; } - set_errno(memory, EINVAL)?; + set_errno(memory, teb, EINVAL)?; return Ok(0); } @@ -272,7 +273,7 @@ fn parse_integer( .map_err(ExitReason::MemoryFault)?; } if overflow { - set_errno(memory, ERANGE)?; + set_errno(memory, teb, ERANGE)?; value = limit; } if negative && (!overflow || signed) { @@ -300,16 +301,8 @@ pub(super) fn register_conversions(registry: &mut ImportRegistry) { ("_wcstoi64", true, true, StringUnit::Wide), ("_wcstoui64", false, true, StringUnit::Wide), ] { - registry.register(UCRT, symbol, move |args, _, memory| { - parse_integer( - memory, - args.rcx, - args.rdx, - args.r8 as u32, - signed, - wide_result, - unit, - ) + registry.register(UCRT, symbol, move |args, cpu, memory| { + parse_integer(memory, args, cpu.gs_base, signed, wide_result, unit) }); registry.alias("api-ms-win-crt-convert-l1-1-0.dll", UCRT, symbol); registry.set_status(UCRT, symbol, ServiceStatus::Partial); @@ -317,20 +310,22 @@ pub(super) fn register_conversions(registry: &mut ImportRegistry) { } pub(super) fn register_errno(registry: &mut ImportRegistry) { - registry.register(UCRT, "_errno", |_, _, memory| { - memory.crt_errno_address().map_err(ExitReason::MemoryFault) + registry.register(UCRT, "_errno", |_, cpu, memory| { + memory + .crt_errno_address(cpu.gs_base) + .map_err(ExitReason::MemoryFault) }); - registry.register(UCRT, "_set_errno", |args, _, memory| { - set_errno(memory, args.rcx as u32)?; + registry.register(UCRT, "_set_errno", |args, cpu, memory| { + set_errno(memory, cpu.gs_base, args.rcx as u32)?; Ok(0) }); - registry.register(UCRT, "_get_errno", |args, _, memory| { + registry.register(UCRT, "_get_errno", |args, cpu, memory| { if args.rcx == 0 { - set_errno(memory, EINVAL)?; + set_errno(memory, cpu.gs_base, EINVAL)?; return Ok(u64::from(EINVAL)); } let address = memory - .crt_errno_address() + .crt_errno_address(cpu.gs_base) .map_err(ExitReason::MemoryFault)?; let value = memory.read_u32(address).map_err(ExitReason::MemoryFault)?; memory @@ -345,31 +340,31 @@ pub(super) fn register_errno(registry: &mut ImportRegistry) { } pub(super) fn register_heap(registry: &mut ImportRegistry) { - registry.register(UCRT, "malloc", |args, _, memory| { + registry.register(UCRT, "malloc", |args, cpu, memory| { let result = memory.map_heap_allocation(PROCESS_HEAP, args.rcx.max(1) as usize); - allocation_result(memory, result) + allocation_result(memory, cpu.gs_base, result) }); - registry.register(UCRT, "calloc", |args, _, memory| { + registry.register(UCRT, "calloc", |args, cpu, memory| { let result = args .rcx .checked_mul(args.rdx) .ok_or(MemoryError::AllocationFailed) .and_then(|size| memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize)); - allocation_result(memory, result) + allocation_result(memory, cpu.gs_base, result) }); - registry.register(UCRT, "realloc", |args, _, memory| { + registry.register(UCRT, "realloc", |args, cpu, memory| { let address = args.rcx; let size = args.rdx; if address == 0 { let result = memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize); - return allocation_result(memory, result); + return allocation_result(memory, cpu.gs_base, result); } if size == 0 { free(memory, address)?; return Ok(0); } let result = memory.resize_heap_allocation(PROCESS_HEAP, address, size as usize, false); - allocation_result(memory, result) + allocation_result(memory, cpu.gs_base, result) }); registry.register(UCRT, "free", |args, _, memory| { free(memory, args.rcx)?; @@ -391,3 +386,41 @@ fn free(memory: &mut GuestMemory, address: u64) -> Result<(), ExitReason> { ))) } } + +#[cfg(test)] +#[test] +fn errno_isolated_by_guest_teb_on_one_host_thread() { + use crate::cpu::{CpuState, Register}; + use crate::import_table::ImportName; + + let mut registry = ImportRegistry::new(); + register_errno(&mut registry); + register_heap(&mut registry); + let mut memory = GuestMemory::new(); + let mut first = CpuState { + gs_base: 0x10000, + ..CpuState::default() + }; + let mut second = CpuState { + gs_base: 0x20000, + ..CpuState::default() + }; + let call = |symbol: &str, cpu: &mut CpuState, memory: &mut GuestMemory| { + let service = registry + .resolve(UCRT, &ImportName::Name(symbol.to_owned())) + .unwrap(); + (service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap() + }; + + let first_slot = call("_errno", &mut first, &mut memory); + first.set(Register::Rcx, 23); + assert_eq!(call("_set_errno", &mut first, &mut memory), 0); + let second_slot = call("_errno", &mut second, &mut memory); + assert_ne!(first_slot, second_slot); + assert_eq!(memory.read_u32(second_slot).unwrap(), 0); + second.set(Register::Rcx, u64::MAX); + assert_eq!(call("malloc", &mut second, &mut memory), 0); + assert_eq!(memory.read_u32(second_slot).unwrap(), ENOMEM); + assert_eq!(call("_errno", &mut first, &mut memory), first_slot); + assert_eq!(memory.read_u32(first_slot).unwrap(), 23); +} From 73764899c2df24731924e3023a66d37bd00004b6 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:27:46 -0500 Subject: [PATCH 39/82] Isolate Win32 last-error state by guest thread Signed-off-by: Adeeb Rahman --- crates/import-gen/src/typed.rs | 7 +- crates/loader/src/runtime.rs | 1 + crates/loader/src/runtime_table.rs | 40 +++--- crates/loader/src/services.rs | 126 +++++++++++-------- crates/loader/src/services/events.rs | 66 +++++----- crates/loader/src/services/files.rs | 158 ++++++++++++------------ crates/loader/src/services/heap.rs | 18 +-- crates/loader/src/services/modules.rs | 24 ++-- crates/loader/tests/runtime_services.rs | 21 ++++ crates/loader/tests/runtime_x15.rs | 2 +- 10 files changed, 253 insertions(+), 210 deletions(-) diff --git a/crates/import-gen/src/typed.rs b/crates/import-gen/src/typed.rs index f31c603e..4e49db81 100644 --- a/crates/import-gen/src/typed.rs +++ b/crates/import-gen/src/typed.rs @@ -305,14 +305,9 @@ pub fn generate_rust(services: &[Service]) -> String { } else { "Ok(result.place(cpu))" }; - let cpu = if service.result == "void" && count == 0 { - " let _ = cpu;\n" - } else { - "" - }; let _ = writeln!( out, - "{cpu} let mut context = ServiceContext {{ state: &s, memory }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});", + " let mut context = ServiceContext {{ state: &s, memory, teb: cpu.gs_base }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});", service.handler ); if let Some((ordinal, _)) = &service.ordinal { diff --git a/crates/loader/src/runtime.rs b/crates/loader/src/runtime.rs index b2595c8d..8bb07fec 100644 --- a/crates/loader/src/runtime.rs +++ b/crates/loader/src/runtime.rs @@ -16,6 +16,7 @@ use crate::services::ServicesState; /// What a service may use. pub struct ServiceContext<'a> { pub state: &'a ServicesState, + pub teb: u64, pub memory: &'a mut GuestMemory, } diff --git a/crates/loader/src/runtime_table.rs b/crates/loader/src/runtime_table.rs index 49384440..efa48eb3 100644 --- a/crates/loader/src/runtime_table.rs +++ b/crates/loader/src/runtime_table.rs @@ -238,7 +238,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let call = Call::new(args, cpu, memory); let a0 = call.u64(0)?; let a1 = call.bool32(1)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: bool = handlers::set_process_priority_boost(&mut context, a0, a1)?; Ok(result.place(cpu)) }); @@ -247,14 +247,14 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let call = Call::new(args, cpu, memory); let a0 = call.u64(0)?; let a1 = call.out::<4>(1)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: bool = handlers::get_process_priority_boost(&mut context, a0, a1)?; Ok(result.place(cpu)) }); let s = state.clone(); registry.register_with_status("kernel32.dll", "GetCurrentProcess", ServiceStatus::Implemented, move |args, cpu, memory| { let _ = args; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u64 = handlers::get_current_process(&mut context)?; Ok(result.place(cpu)) }); @@ -262,28 +262,28 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("kernel32.dll", "GetProcessId", ServiceStatus::Partial, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.u64(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u32 = handlers::get_process_id(&mut context, a0)?; Ok(result.place(cpu)) }); let s = state.clone(); registry.register_with_status("kernel32.dll", "GetCurrentThread", ServiceStatus::Implemented, move |args, cpu, memory| { let _ = args; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u64 = handlers::get_current_thread(&mut context)?; Ok(result.place(cpu)) }); let s = state.clone(); registry.register_with_status("kernel32.dll", "GetCurrentProcessId", ServiceStatus::Implemented, move |args, cpu, memory| { let _ = args; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u32 = handlers::get_current_process_id(&mut context)?; Ok(result.place(cpu)) }); let s = state.clone(); registry.register_with_status("kernel32.dll", "GetCurrentThreadId", ServiceStatus::Implemented, move |args, cpu, memory| { let _ = args; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u32 = handlers::get_current_thread_id(&mut context)?; Ok(result.place(cpu)) }); @@ -293,7 +293,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let a0 = call.u32(0)?; let a1 = call.bool32(1)?; let a2 = call.u32(2)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u64 = handlers::open_thread(&mut context, a0, a1, a2)?; Ok(result.place(cpu)) }); @@ -301,7 +301,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("kernel32.dll", "GetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.u64(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: i32 = handlers::get_thread_priority(&mut context, a0)?; Ok(result.place(cpu)) }); @@ -310,7 +310,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let call = Call::new(args, cpu, memory); let a0 = call.u64(0)?; let a1 = call.i32(1)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: bool = handlers::set_thread_priority(&mut context, a0, a1)?; Ok(result.place(cpu)) }); @@ -318,7 +318,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("kernel32.dll", "CloseHandle", ServiceStatus::Partial, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.u64(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: bool = handlers::close_handle(&mut context, a0)?; Ok(result.place(cpu)) }); @@ -326,14 +326,14 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("kernel32.dll", "GetSystemTimeAsFileTime", ServiceStatus::Implemented, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.out::<8>(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let () = handlers::get_system_time_as_file_time(&mut context, a0)?; Ok(0) }); let s = state.clone(); registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| { let _ = args; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u32 = handlers::get_last_error(&mut context)?; Ok(result.place(cpu)) }); @@ -341,7 +341,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("kernel32.dll", "SetLastError", ServiceStatus::Partial, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.u32(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let () = handlers::set_last_error(&mut context, a0)?; Ok(0) }); @@ -352,7 +352,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let a1 = call.u64(1)?; let a2 = call.u32(2)?; let a3 = call.u32(3)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: u64 = handlers::virtual_alloc(&mut context, a0, a1, a2, a3)?; Ok(result.place(cpu)) }); @@ -362,7 +362,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let a0 = call.u64(0)?; let a1 = call.u64(1)?; let a2 = call.u32(2)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: bool = handlers::virtual_free(&mut context, a0, a1, a2)?; Ok(result.place(cpu)) }); @@ -370,7 +370,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.f64(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: crate::runtime::Float64 = handlers::sqrt(&mut context, a0)?; Ok(result.place(cpu)) }); @@ -378,7 +378,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("ucrtbase.dll", "sqrtf", ServiceStatus::Partial, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.f32(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: crate::runtime::Float32 = handlers::sqrtf(&mut context, a0)?; Ok(result.place(cpu)) }); @@ -386,7 +386,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("ucrtbase.dll", "fabs", ServiceStatus::Implemented, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.f64(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: crate::runtime::Float64 = handlers::fabs(&mut context, a0)?; Ok(result.place(cpu)) }); @@ -394,7 +394,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { registry.register_with_status("ucrtbase.dll", "fabsf", ServiceStatus::Implemented, move |args, cpu, memory| { let call = Call::new(args, cpu, memory); let a0 = call.f32(0)?; - let mut context = ServiceContext { state: &s, memory }; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?; Ok(result.place(cpu)) }); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index bc5e194d..9c5a487b 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -21,7 +21,7 @@ use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions}; use std::collections::{BTreeMap, BTreeSet}; -use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock}; use std::time::Instant; @@ -169,7 +169,7 @@ pub struct ServicesState { priority_boost_disabled: AtomicBool, pub thread_id: u32, objects: Mutex, - pub last_error: AtomicU32, + last_errors: Mutex>, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, } @@ -183,7 +183,7 @@ impl ServicesState { process_id: 0x4100, // Synthetic process ID thread_id: 0x4104, // Synthetic main thread ID objects: Mutex::new(ObjectState::default()), - last_error: AtomicU32::new(0), + last_errors: Mutex::default(), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), } @@ -201,18 +201,36 @@ impl ServicesState { self.priority_boost_disabled.load(Ordering::SeqCst) } + /// Read the last-error value for a guest thread's TEB. + pub fn last_error(&self, teb: u64) -> u32 { + self.last_errors + .lock() + .expect("guest last-error state") + .get(&teb) + .copied() + .unwrap_or(0) + } + + fn set_last_error(&self, teb: u64, error: u32) { + let mut errors = self.last_errors.lock().expect("guest last-error state"); + if error == 0 { + errors.remove(&teb); + } else { + errors.insert(teb, error); + } + } + /// Record a guest error and return the documented failure value. - fn fail(&self, error: u32, value: T) -> Result { - self.last_error.store(error, Ordering::SeqCst); + fn fail(&self, teb: u64, error: u32, value: T) -> Result { + self.set_last_error(teb, error); Ok(value) } - fn is_current_process(&self, handle: u64) -> bool { + fn is_current_process(&self, teb: u64, handle: u64) -> bool { if handle == CURRENT_PROCESS { return true; } - self.last_error - .store(ERROR_INVALID_HANDLE, Ordering::SeqCst); + self.set_last_error(teb, ERROR_INVALID_HANDLE); false } } @@ -223,11 +241,11 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc (file.access, GuestObject::File(file.clone())), - Some(GuestObject::Search(_)) => return s.fail(ERROR_NOT_SUPPORTED, 0), - None => return s.fail(ERROR_INVALID_HANDLE, 0), + Some(GuestObject::Search(_)) => return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0), + None => return s.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0), } }; let access = if options & DUPLICATE_SAME_ACCESS != 0 { @@ -277,13 +295,13 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc { @@ -307,22 +325,26 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Outcome { - if !context.state.is_current_process(process) { + if !context.state.is_current_process(context.teb, process) { return Ok(false); } context @@ -549,12 +571,12 @@ pub(crate) mod handlers { process: u64, disabled: OutPtr<4>, ) -> Outcome { - if !context.state.is_current_process(process) { + if !context.state.is_current_process(context.teb, process) { return Ok(false); } let value = u32::from(context.state.priority_boost_disabled()); if disabled.store(context.memory, value.to_le_bytes()).is_err() { - return context.state.fail(ERROR_NOACCESS, false); + return context.state.fail(context.teb, ERROR_NOACCESS, false); } Ok(true) } @@ -564,7 +586,7 @@ pub(crate) mod handlers { } pub fn get_process_id(context: &mut ServiceContext<'_>, process: u64) -> Outcome { - Ok(if context.state.is_current_process(process) { + Ok(if context.state.is_current_process(context.teb, process) { context.state.process_id } else { 0 @@ -591,14 +613,14 @@ pub(crate) mod handlers { ) -> Outcome { let state = context.state; if id != state.thread_id { - return state.fail(ERROR_INVALID_PARAMETER, 0); + return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0); } if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0); } let mut thread = state.objects.lock().expect("guest object state"); let Some(handle) = thread.next_handle() else { - return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + return state.fail(context.teb, ERROR_NOT_ENOUGH_MEMORY, 0); }; thread.insert_handle(handle, GuestObject::Thread(access)); Ok(handle) @@ -609,7 +631,7 @@ pub(crate) mod handlers { if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) { return context .state - .fail(error, THREAD_PRIORITY_ERROR_RETURN as i32); + .fail(context.teb, error, THREAD_PRIORITY_ERROR_RETURN as i32); } Ok(thread.priority) } @@ -622,13 +644,13 @@ pub(crate) mod handlers { let state = context.state; let mut thread = state.objects.lock().expect("guest object state"); if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) { - return state.fail(error, false); + return state.fail(context.teb, error, false); } if matches!(priority, 0x0001_0000 | 0x0002_0000) { - return state.fail(ERROR_NOT_SUPPORTED, false); + return state.fail(context.teb, ERROR_NOT_SUPPORTED, false); } if !matches!(priority, -15 | -2..=2 | 15) { - return state.fail(ERROR_INVALID_PARAMETER, false); + return state.fail(context.teb, ERROR_INVALID_PARAMETER, false); } thread.priority = priority; Ok(true) @@ -637,14 +659,14 @@ pub(crate) mod handlers { pub fn close_handle(context: &mut ServiceContext<'_>, handle: u64) -> Outcome { let mut objects = context.state.objects.lock().expect("guest object state"); if matches!(objects.handles.get(&handle), Some(GuestObject::Search(_))) { - return context.state.fail(ERROR_INVALID_HANDLE, false); + return context.state.fail(context.teb, ERROR_INVALID_HANDLE, false); } let closed = matches!(handle, CURRENT_PROCESS | CURRENT_THREAD) || objects.handles.remove(&handle).is_some(); if closed { Ok(true) } else { - context.state.fail(ERROR_INVALID_HANDLE, false) + context.state.fail(context.teb, ERROR_INVALID_HANDLE, false) } } @@ -658,11 +680,11 @@ pub(crate) mod handlers { } pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome { - Ok(context.state.last_error.load(Ordering::SeqCst)) + Ok(context.state.last_error(context.teb)) } pub fn set_last_error(context: &mut ServiceContext<'_>, code: u32) -> Outcome<()> { - context.state.last_error.store(code, Ordering::SeqCst); + context.state.set_last_error(context.teb, code); Ok(()) } @@ -675,28 +697,28 @@ pub(crate) mod handlers { ) -> Outcome { let state = context.state; if size == 0 { - return state.fail(ERROR_INVALID_PARAMETER, 0); + return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0); } if kind != MEM_COMMIT_RESERVE { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0); } // Executable allocations require guest translation cache invalidation. let permissions = match protect { 0x01 => MemoryPermissions::NO_ACCESS, 0x02 => MemoryPermissions::READ_ONLY, 0x04 => MemoryPermissions::READ_WRITE, - _ => return state.fail(ERROR_INVALID_PARAMETER, 0), + _ => return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0), }; let base = requested & !(ALLOCATION_GRANULARITY - 1); if requested != 0 && base == 0 { - return state.fail(ERROR_INVALID_ADDRESS, 0); + return state.fail(context.teb, ERROR_INVALID_ADDRESS, 0); } let Some(size) = size .checked_add(requested - base) .and_then(|span| span.checked_next_multiple_of(PAGE_SIZE)) .and_then(|span| usize::try_from(span).ok()) else { - return state.fail(ERROR_INVALID_PARAMETER, 0); + return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0); }; match context .memory @@ -704,9 +726,9 @@ pub(crate) mod handlers { { Ok(address) => Ok(address), Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => { - state.fail(ERROR_INVALID_ADDRESS, 0) + state.fail(context.teb, ERROR_INVALID_ADDRESS, 0) } - Err(_) => state.fail(ERROR_NOT_ENOUGH_MEMORY, 0), + Err(_) => state.fail(context.teb, ERROR_NOT_ENOUGH_MEMORY, 0), } } @@ -718,13 +740,13 @@ pub(crate) mod handlers { ) -> Outcome { let state = context.state; if kind != MEM_RELEASE { - return state.fail(ERROR_NOT_SUPPORTED, false); + return state.fail(context.teb, ERROR_NOT_SUPPORTED, false); } if size != 0 { - return state.fail(ERROR_INVALID_PARAMETER, false); + return state.fail(context.teb, ERROR_INVALID_PARAMETER, false); } if !context.memory.release_virtual_allocation(address) { - return state.fail(ERROR_INVALID_ADDRESS, false); + return state.fail(context.teb, ERROR_INVALID_ADDRESS, false); } Ok(true) } diff --git a/crates/loader/src/services/events.rs b/crates/loader/src/services/events.rs index 35153005..7f95d27f 100644 --- a/crates/loader/src/services/events.rs +++ b/crates/loader/src/services/events.rs @@ -49,12 +49,13 @@ impl Waitable { fn insert_waitable( state: &ServicesState, + teb: u64, object: Waitable, access: u32, ) -> Result { let mut objects = state.objects.lock().expect("guest object state"); let Some(handle) = objects.next_handle() else { - return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + return state.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0); }; objects.insert_handle( handle, @@ -69,16 +70,17 @@ fn insert_waitable( pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { for symbol in ["CreateEventA", "CreateEventW"] { let state = Arc::clone(state); - registry.register(KERNEL32, symbol, move |args, _, mem| { + registry.register(KERNEL32, symbol, move |args, cpu, mem| { let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let manual_reset = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; let signaled = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; let name = args.get(3, mem).map_err(ExitReason::MemoryFault)?; if attributes != 0 || name != 0 { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } insert_waitable( &state, + cpu.gs_base, Waitable::Event { manual_reset, signaled, @@ -90,7 +92,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc for (symbol, signaled) in [("SetEvent", true), ("ResetEvent", false)] { let state = Arc::clone(state); - registry.register(KERNEL32, symbol, move |args, _, mem| { + registry.register(KERNEL32, symbol, move |args, cpu, mem| { let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let objects = state.objects.lock().expect("guest object state"); let Some(GuestObject::Waitable { @@ -98,17 +100,17 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc access, }) = objects.handles.get(&handle) else { - return state.fail(ERROR_INVALID_HANDLE, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; let mut event = event.lock().expect("guest waitable state"); let Waitable::Event { signaled: current, .. } = &mut *event else { - return state.fail(ERROR_INVALID_HANDLE, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; if access & EVENT_MODIFY_STATE == 0 { - return state.fail(ERROR_ACCESS_DENIED, 0); + return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0); } *current = signaled; Ok(1) @@ -117,19 +119,20 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc for symbol in ["CreateSemaphoreA", "CreateSemaphoreW"] { let state = Arc::clone(state); - registry.register(KERNEL32, symbol, move |args, _, mem| { + registry.register(KERNEL32, symbol, move |args, cpu, mem| { let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let count = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32; let maximum = args.get(2, mem).map_err(ExitReason::MemoryFault)? as i32; let name = args.get(3, mem).map_err(ExitReason::MemoryFault)?; if attributes != 0 || name != 0 { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } if maximum <= 0 || count < 0 || count > maximum { - return state.fail(ERROR_INVALID_PARAMETER, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); } insert_waitable( &state, + cpu.gs_base, Waitable::Semaphore { count, maximum }, SEMAPHORE_ALL_ACCESS, ) @@ -137,29 +140,29 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } let release = Arc::clone(state); - registry.register(KERNEL32, "ReleaseSemaphore", move |args, _, mem| { + registry.register(KERNEL32, "ReleaseSemaphore", move |args, cpu, mem| { let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let amount = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32; let output = args.get(2, mem).map_err(ExitReason::MemoryFault)?; if amount <= 0 { - return release.fail(ERROR_INVALID_PARAMETER, 0); + return release.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); } let objects = release.objects.lock().expect("guest object state"); let Some(GuestObject::Waitable { state, access }) = objects.handles.get(&handle) else { - return release.fail(ERROR_INVALID_HANDLE, 0); + return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; let mut state = state.lock().expect("guest waitable state"); let Waitable::Semaphore { count, maximum } = &mut *state else { - return release.fail(ERROR_INVALID_HANDLE, 0); + return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; if access & SEMAPHORE_MODIFY_STATE == 0 { - return release.fail(ERROR_ACCESS_DENIED, 0); + return release.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0); } if amount > *maximum - *count { - return release.fail(ERROR_TOO_MANY_POSTS, 0); + return release.fail(cpu.gs_base, ERROR_TOO_MANY_POSTS, 0); } if output != 0 && mem.write_u32(output, *count as u32).is_err() { - return release.fail(ERROR_NOACCESS, 0); + return release.fail(cpu.gs_base, ERROR_NOACCESS, 0); } *count += amount; Ok(1) @@ -170,13 +173,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc ("WaitForSingleObjectEx", true), ] { let single = Arc::clone(state); - registry.register(KERNEL32, symbol, move |args, _, mem| { + registry.register(KERNEL32, symbol, move |args, cpu, mem| { let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; if extended && args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 { - return single.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + return single.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, WAIT_FAILED); } - wait_for_objects(&single, &[handle], false, timeout) + wait_for_objects(&single, cpu.gs_base, &[handle], false, timeout) }); } for (symbol, extended) in [ @@ -184,16 +187,16 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc ("WaitForMultipleObjectsEx", true), ] { let multiple = Arc::clone(state); - registry.register(KERNEL32, symbol, move |args, _, mem| { + registry.register(KERNEL32, symbol, move |args, cpu, mem| { let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?; let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; let timeout = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; if extended && args.get(4, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 { - return multiple.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + return multiple.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, WAIT_FAILED); } if !(1..=64).contains(&count) || address == 0 { - return multiple.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); + return multiple.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, WAIT_FAILED); } let mut handles = [0; 64]; let handles = &mut handles[..count as usize]; @@ -203,7 +206,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; *handle = mem.read_u64(slot).map_err(ExitReason::MemoryFault)?; } - wait_for_objects(&multiple, handles, all, timeout) + wait_for_objects(&multiple, cpu.gs_base, handles, all, timeout) }); } @@ -230,6 +233,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc fn wait_for_objects( state: &ServicesState, + teb: u64, handles: &[u64], all: bool, timeout: u32, @@ -239,7 +243,7 @@ fn wait_for_objects( let mut waitables: Vec<&Arc>> = Vec::with_capacity(handles.len()); for (index, handle) in handles.iter().enumerate() { if handles[..index].contains(handle) { - return state.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); + return state.fail(teb, ERROR_INVALID_PARAMETER, WAIT_FAILED); } match objects.handles.get(handle) { Some(GuestObject::Waitable { @@ -247,22 +251,22 @@ fn wait_for_objects( access, }) => { if access & SYNCHRONIZE == 0 { - return state.fail(ERROR_ACCESS_DENIED, WAIT_FAILED); + return state.fail(teb, ERROR_ACCESS_DENIED, WAIT_FAILED); } if all && waitables .iter() .any(|existing| Arc::ptr_eq(existing, event)) { - return state.fail(ERROR_INVALID_PARAMETER, WAIT_FAILED); + return state.fail(teb, ERROR_INVALID_PARAMETER, WAIT_FAILED); } waitables.push(event); } - Some(_) => return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED), + Some(_) => return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED), None if matches!(*handle, super::CURRENT_THREAD | super::CURRENT_PROCESS) => { - return state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED); + return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED); } - None => return state.fail(ERROR_INVALID_HANDLE, WAIT_FAILED), + None => return state.fail(teb, ERROR_INVALID_HANDLE, WAIT_FAILED), } } let mut ready = Vec::with_capacity(handles.len()); @@ -278,7 +282,7 @@ fn wait_for_objects( return if timeout == 0 { Ok(WAIT_TIMEOUT) } else { - state.fail(ERROR_NOT_SUPPORTED, WAIT_FAILED) + state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED) }; } let first = ready[0].0; diff --git a/crates/loader/src/services/files.rs b/crates/loader/src/services/files.rs index 8b573d4f..c3a2d14d 100644 --- a/crates/loader/src/services/files.rs +++ b/crates/loader/src/services/files.rs @@ -153,7 +153,7 @@ fn share_mask(access: u32) -> u32 { pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { let open = Arc::clone(state); - registry.register(KERNEL32, "CreateFileW", move |args, _, memory| { + registry.register(KERNEL32, "CreateFileW", move |args, cpu, memory| { let access = args.rdx as u32; let share = args.r8 as u32; let disposition = args.get(4, memory).map_err(ExitReason::MemoryFault)? as u32; @@ -165,31 +165,31 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc || access & !(READ | WRITE) != 0 || share & !3 != 0 { - return open.fail(ERROR_NOT_SUPPORTED, INVALID_HANDLE); + return open.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, INVALID_HANDLE); } if !(1..=5).contains(&disposition) { - return open.fail(ERROR_INVALID_PARAMETER, INVALID_HANDLE); + return open.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, INVALID_HANDLE); } if matches!(disposition, 2 | 5) && access & WRITE == 0 { - return open.fail(ERROR_ACCESS_DENIED, INVALID_HANDLE); + return open.fail(cpu.gs_base, ERROR_ACCESS_DENIED, INVALID_HANDLE); } let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return open.fail(INVALID_NAME, INVALID_HANDLE); + return open.fail(cpu.gs_base, INVALID_NAME, INVALID_HANDLE); }; let mut objects = open.objects.lock().expect("guest object state"); let parent = parent(&path); if !parent.is_empty() && !objects.directories.contains(parent) { - return open.fail(PATH_NOT_FOUND, INVALID_HANDLE); + return open.fail(cpu.gs_base, PATH_NOT_FOUND, INVALID_HANDLE); } if objects.directories.contains(&path) { - return open.fail(ERROR_ACCESS_DENIED, INVALID_HANDLE); + return open.fail(cpu.gs_base, ERROR_ACCESS_DENIED, INVALID_HANDLE); } let exists = objects.files.contains_key(&path); if exists && disposition == 1 { - return open.fail(FILE_EXISTS, INVALID_HANDLE); + return open.fail(cpu.gs_base, FILE_EXISTS, INVALID_HANDLE); } if !exists && matches!(disposition, 3 | 5) { - return open.fail(FILE_NOT_FOUND, INVALID_HANDLE); + return open.fail(cpu.gs_base, FILE_NOT_FOUND, INVALID_HANDLE); } for object in objects.handles.values() { if let GuestObject::File(file) = object @@ -197,22 +197,22 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc && (share_mask(access) & !file.share != 0 || share_mask(file.open_access) & !share != 0) { - return open.fail(SHARING_VIOLATION, INVALID_HANDLE); + return open.fail(cpu.gs_base, SHARING_VIOLATION, INVALID_HANDLE); } } let Some(handle) = objects.next_handle() else { - return open.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); + return open.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); }; if !exists { if objects.files.len() >= MAX_FILES { - return open.fail(DISK_FULL, INVALID_HANDLE); + return open.fail(cpu.gs_base, DISK_FULL, INVALID_HANDLE); } objects.files.insert(path.clone(), Vec::new()); } else if matches!(disposition, 2 | 5) { *objects.files.get_mut(&path).expect("existing file") = Vec::new(); } if matches!(disposition, 2 | 4) { - open.fail(if exists { ALREADY_EXISTS } else { 0 }, 0)?; + open.fail(cpu.gs_base, if exists { ALREADY_EXISTS } else { 0 }, 0)?; } objects.insert_handle( handle, @@ -228,77 +228,77 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }); let create = Arc::clone(state); - registry.register(KERNEL32, "CreateDirectoryW", move |args, _, memory| { + registry.register(KERNEL32, "CreateDirectoryW", move |args, cpu, memory| { if args.rdx != 0 { - return create.fail(ERROR_NOT_SUPPORTED, 0); + return create.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return create.fail(INVALID_NAME, 0); + return create.fail(cpu.gs_base, INVALID_NAME, 0); }; let mut objects = create.objects.lock().expect("guest object state"); let parent = parent(&path); if !parent.is_empty() && !objects.directories.contains(parent) { - return create.fail(PATH_NOT_FOUND, 0); + return create.fail(cpu.gs_base, PATH_NOT_FOUND, 0); } if objects.directories.contains(&path) || objects.files.contains_key(&path) { - return create.fail(ALREADY_EXISTS, 0); + return create.fail(cpu.gs_base, ALREADY_EXISTS, 0); } if objects.directories.len() >= MAX_DIRECTORIES { - return create.fail(DISK_FULL, 0); + return create.fail(cpu.gs_base, DISK_FULL, 0); } objects.directories.insert(path); Ok(1) }); let remove = Arc::clone(state); - registry.register(KERNEL32, "RemoveDirectoryW", move |args, _, memory| { + registry.register(KERNEL32, "RemoveDirectoryW", move |args, cpu, memory| { let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return remove.fail(INVALID_NAME, 0); + return remove.fail(cpu.gs_base, INVALID_NAME, 0); }; let mut objects = remove.objects.lock().expect("guest object state"); if !objects.directories.contains(&path) { - return remove.fail(PATH_NOT_FOUND, 0); + return remove.fail(cpu.gs_base, PATH_NOT_FOUND, 0); } if objects.directories.iter().any(|key| parent(key) == path) || objects.files.keys().any(|key| parent(key) == path) { - return remove.fail(DIRECTORY_NOT_EMPTY, 0); + return remove.fail(cpu.gs_base, DIRECTORY_NOT_EMPTY, 0); } objects.directories.remove(&path); Ok(1) }); let delete = Arc::clone(state); - registry.register(KERNEL32, "DeleteFileW", move |args, _, memory| { + registry.register(KERNEL32, "DeleteFileW", move |args, cpu, memory| { let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return delete.fail(INVALID_NAME, 0); + return delete.fail(cpu.gs_base, INVALID_NAME, 0); }; let mut objects = delete.objects.lock().expect("guest object state"); if objects.directories.contains(&path) { - return delete.fail(ERROR_ACCESS_DENIED, 0); + return delete.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0); } let parent = parent(&path); if !parent.is_empty() && !objects.directories.contains(parent) { - return delete.fail(PATH_NOT_FOUND, 0); + return delete.fail(cpu.gs_base, PATH_NOT_FOUND, 0); } if objects .handles .values() .any(|object| matches!(object, GuestObject::File(file) if file.path == path)) { - return delete.fail(SHARING_VIOLATION, 0); + return delete.fail(cpu.gs_base, SHARING_VIOLATION, 0); } if objects.files.remove(&path).is_none() { - return delete.fail(FILE_NOT_FOUND, 0); + return delete.fail(cpu.gs_base, FILE_NOT_FOUND, 0); } Ok(1) }); let attributes = Arc::clone(state); - registry.register(KERNEL32, "GetFileAttributesW", move |args, _, memory| { + registry.register(KERNEL32, "GetFileAttributesW", move |args, cpu, memory| { const INVALID_ATTRIBUTES: u64 = u32::MAX as u64; let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return attributes.fail(INVALID_NAME, INVALID_ATTRIBUTES); + return attributes.fail(cpu.gs_base, INVALID_NAME, INVALID_ATTRIBUTES); }; let objects = attributes.objects.lock().expect("guest object state"); if objects.directories.contains(&path) { @@ -313,39 +313,39 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } else { PATH_NOT_FOUND }; - attributes.fail(error, INVALID_ATTRIBUTES) + attributes.fail(cpu.gs_base, error, INVALID_ATTRIBUTES) }); let rename = Arc::clone(state); - registry.register(KERNEL32, "MoveFileW", move |args, _, memory| { + registry.register(KERNEL32, "MoveFileW", move |args, cpu, memory| { let Some(source) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return rename.fail(INVALID_NAME, 0); + return rename.fail(cpu.gs_base, INVALID_NAME, 0); }; let Some(target) = guest_path(memory, args.rdx).map_err(ExitReason::MemoryFault)? else { - return rename.fail(INVALID_NAME, 0); + return rename.fail(cpu.gs_base, INVALID_NAME, 0); }; let mut objects = rename.objects.lock().expect("guest object state"); if [parent(&source), parent(&target)] .into_iter() .any(|path| !path.is_empty() && !objects.directories.contains(path)) { - return rename.fail(PATH_NOT_FOUND, 0); + return rename.fail(cpu.gs_base, PATH_NOT_FOUND, 0); } if objects.directories.contains(&source) { - return rename.fail(ERROR_NOT_SUPPORTED, 0); + return rename.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } if !objects.files.contains_key(&source) { - return rename.fail(FILE_NOT_FOUND, 0); + return rename.fail(cpu.gs_base, FILE_NOT_FOUND, 0); } if objects.files.contains_key(&target) || objects.directories.contains(&target) { - return rename.fail(ALREADY_EXISTS, 0); + return rename.fail(cpu.gs_base, ALREADY_EXISTS, 0); } if objects .handles .values() .any(|object| matches!(object, GuestObject::File(file) if file.path == source)) { - return rename.fail(SHARING_VIOLATION, 0); + return rename.fail(cpu.gs_base, SHARING_VIOLATION, 0); } let data = objects.files.remove(&source).expect("source file exists"); objects.files.insert(target, data); @@ -353,9 +353,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }); let find = Arc::clone(state); - registry.register(KERNEL32, "FindFirstFileW", move |args, _, memory| { + registry.register(KERNEL32, "FindFirstFileW", move |args, cpu, memory| { let Some(path) = read_guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else { - return find.fail(INVALID_NAME, INVALID_HANDLE); + return find.fail(cpu.gs_base, INVALID_NAME, INVALID_HANDLE); }; let directory = parent(&path); let pattern = path.rsplit('\\').next().unwrap_or_default(); @@ -363,12 +363,12 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc || (!directory.is_empty() && !directory.split('\\').all(valid_component)) || !valid_component(&pattern.replace(['*', '?'], "x")) { - return find.fail(INVALID_NAME, INVALID_HANDLE); + return find.fail(cpu.gs_base, INVALID_NAME, INVALID_HANDLE); } let pattern = if pattern == "*.*" { "*" } else { pattern }; let mut objects = find.objects.lock().expect("guest object state"); if !directory.is_empty() && !objects.directories.contains(directory) { - return find.fail(PATH_NOT_FOUND, INVALID_HANDLE); + return find.fail(cpu.gs_base, PATH_NOT_FOUND, INVALID_HANDLE); } let candidates = objects .directories @@ -394,7 +394,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } entries.sort_by(|a, b| a.name.cmp(&b.name)); let Some(first) = entries.first() else { - return find.fail(FILE_NOT_FOUND, INVALID_HANDLE); + return find.fail(cpu.gs_base, FILE_NOT_FOUND, INVALID_HANDLE); }; if objects .handles @@ -403,49 +403,49 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .count() >= 32 { - return find.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); + return find.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); } let Some(handle) = objects.next_handle() else { - return find.fail(ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); + return find.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE); }; if write_find_data(memory, args.rdx, first).is_err() { - return find.fail(ERROR_NOACCESS, INVALID_HANDLE); + return find.fail(cpu.gs_base, ERROR_NOACCESS, INVALID_HANDLE); } objects.insert_handle(handle, GuestObject::Search(Search { entries, next: 1 })); Ok(handle) }); let find_next = Arc::clone(state); - registry.register(KERNEL32, "FindNextFileW", move |args, _, memory| { + registry.register(KERNEL32, "FindNextFileW", move |args, cpu, memory| { let mut objects = find_next.objects.lock().expect("guest object state"); let Some(GuestObject::Search(search)) = objects.handles.get_mut(&args.rcx) else { - return find_next.fail(ERROR_INVALID_HANDLE, 0); + return find_next.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; let Some(entry) = search.entries.get(search.next) else { - return find_next.fail(18, 0); // ERROR_NO_MORE_FILES + return find_next.fail(cpu.gs_base, 18, 0); // ERROR_NO_MORE_FILES }; if write_find_data(memory, args.rdx, entry).is_err() { - return find_next.fail(ERROR_NOACCESS, 0); + return find_next.fail(cpu.gs_base, ERROR_NOACCESS, 0); } search.next += 1; Ok(1) }); let find_close = Arc::clone(state); - registry.register(KERNEL32, "FindClose", move |args, _, _| { + registry.register(KERNEL32, "FindClose", move |args, cpu, _| { let mut objects = find_close.objects.lock().expect("guest object state"); if !matches!(objects.handles.get(&args.rcx), Some(GuestObject::Search(_))) { - return find_close.fail(ERROR_INVALID_HANDLE, 0); + return find_close.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); } objects.handles.remove(&args.rcx); Ok(1) }); let size = Arc::clone(state); - registry.register(KERNEL32, "GetFileSizeEx", move |args, _, memory| { + registry.register(KERNEL32, "GetFileSizeEx", move |args, cpu, memory| { let objects = size.objects.lock().expect("guest object state"); let Some(GuestObject::File(file)) = objects.handles.get(&args.rcx) else { - return size.fail(ERROR_INVALID_HANDLE, 0); + return size.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; let bytes = objects .files @@ -453,67 +453,67 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .expect("open file exists") .len(); if args.rdx == 0 || memory.write_u64(args.rdx, bytes as u64).is_err() { - return size.fail(ERROR_NOACCESS, 0); + return size.fail(cpu.gs_base, ERROR_NOACCESS, 0); } Ok(1) }); let seek = Arc::clone(state); - registry.register(KERNEL32, "SetFilePointerEx", move |args, _, memory| { + registry.register(KERNEL32, "SetFilePointerEx", move |args, cpu, memory| { let mut objects = seek.objects.lock().expect("guest object state"); let super::ObjectState { handles, files, .. } = &mut *objects; let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else { - return seek.fail(ERROR_INVALID_HANDLE, 0); + return seek.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; if file.access & (READ | WRITE) == 0 { - return seek.fail(ERROR_ACCESS_DENIED, 0); + return seek.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0); } let origin = match args.r9 as u32 { 0 => None, 1 => Some(file.position.load(Ordering::Relaxed)), 2 => Some(files.get(&file.path).expect("open file exists").len() as u64), - _ => return seek.fail(ERROR_INVALID_PARAMETER, 0), + _ => return seek.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0), }; let position = match origin { None => args.rdx, Some(origin) => { let distance = args.rdx as i64; if distance.is_negative() && distance.unsigned_abs() > origin { - return seek.fail(NEGATIVE_SEEK, 0); + return seek.fail(cpu.gs_base, NEGATIVE_SEEK, 0); } let Some(position) = origin.checked_add_signed(distance) else { - return seek.fail(ERROR_INVALID_PARAMETER, 0); + return seek.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); }; position } }; if args.r8 != 0 && memory.write_u64(args.r8, position).is_err() { - return seek.fail(ERROR_NOACCESS, 0); + return seek.fail(cpu.gs_base, ERROR_NOACCESS, 0); } file.position.store(position, Ordering::Relaxed); Ok(1) }); let truncate = Arc::clone(state); - registry.register(KERNEL32, "SetEndOfFile", move |args, _, _| { + registry.register(KERNEL32, "SetEndOfFile", move |args, cpu, _| { let mut objects = truncate.objects.lock().expect("guest object state"); let super::ObjectState { handles, files, .. } = &mut *objects; let Some(GuestObject::File(file)) = handles.get(&args.rcx) else { - return truncate.fail(ERROR_INVALID_HANDLE, 0); + return truncate.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; if file.access & WRITE == 0 { - return truncate.fail(ERROR_ACCESS_DENIED, 0); + return truncate.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0); } let position = file.position.load(Ordering::Relaxed); if position > MAX_BYTES as u64 { - return truncate.fail(DISK_FULL, 0); + return truncate.fail(cpu.gs_base, DISK_FULL, 0); } let used = files.values().map(Vec::len).sum::(); let data = files.get_mut(&file.path).expect("open file exists"); let length = position as usize; let growth = length.saturating_sub(data.len()); if growth > MAX_BYTES - used { - return truncate.fail(DISK_FULL, 0); + return truncate.fail(cpu.gs_base, DISK_FULL, 0); } data.try_reserve_exact(growth) .map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?; @@ -528,25 +528,25 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc for (symbol, writing) in [("ReadFile", false), ("WriteFile", true)] { let state = Arc::clone(state); - registry.register(KERNEL32, symbol, move |args, _, memory| { + registry.register(KERNEL32, symbol, move |args, cpu, memory| { if args.get(4, memory).map_err(ExitReason::MemoryFault)? != 0 { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } let count = args.r8 as u32 as usize; if count > MAX_TRANSFER { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } let mut objects = state.objects.lock().expect("guest object state"); let super::ObjectState { handles, files, .. } = &mut *objects; let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else { - return state.fail(ERROR_INVALID_HANDLE, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; let required = if writing { WRITE } else { READ }; if file.access & required == 0 { - return state.fail(ERROR_ACCESS_DENIED, 0); + return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0); } if args.r9 == 0 || memory.check_write(args.r9, 4).is_err() { - return state.fail(ERROR_NOACCESS, 0); + return state.fail(cpu.gs_base, ERROR_NOACCESS, 0); } let used = if writing { @@ -564,16 +564,16 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .checked_add(count as u64) .filter(|end| *end <= MAX_BYTES as u64) else { - return state.fail(DISK_FULL, 0); + return state.fail(cpu.gs_base, DISK_FULL, 0); }; let end = end as usize; let growth = end.saturating_sub(data.len()); if growth > MAX_BYTES - used { - return state.fail(DISK_FULL, 0); + return state.fail(cpu.gs_base, DISK_FULL, 0); } let mut input = vec![0; count]; if args.rdx == 0 || memory.read_bytes(args.rdx, &mut input).is_err() { - return state.fail(ERROR_NOACCESS, 0); + return state.fail(cpu.gs_base, ERROR_NOACCESS, 0); } if growth != 0 { data.try_reserve_exact(growth) @@ -592,7 +592,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .write_bytes(args.rdx, &data[start..start + transferred]) .is_err()) { - return state.fail(ERROR_NOACCESS, 0); + return state.fail(cpu.gs_base, ERROR_NOACCESS, 0); } transferred }; diff --git a/crates/loader/src/services/heap.rs b/crates/loader/src/services/heap.rs index 7c056eb1..6552a7e6 100644 --- a/crates/loader/src/services/heap.rs +++ b/crates/loader/src/services/heap.rs @@ -58,41 +58,41 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }); let service_state = Arc::clone(state); - registry.register(KERNEL32, "HeapCreate", move |args, _, memory| { + registry.register(KERNEL32, "HeapCreate", move |args, cpu, memory| { let flags = args.get(0, memory).map_err(ExitReason::MemoryFault)? as u32; let initial = args.get(1, memory).map_err(ExitReason::MemoryFault)?; let maximum = args.get(2, memory).map_err(ExitReason::MemoryFault)?; if flags != 0 || maximum != 0 { - return service_state.fail(ERROR_NOT_SUPPORTED, 0); + return service_state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } match memory.create_private_heap(initial) { Some(handle) => Ok(handle), - None => service_state.fail(ERROR_NOT_ENOUGH_MEMORY, 0), + None => service_state.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0), } }); let service_state = Arc::clone(state); - registry.register(KERNEL32, "HeapDestroy", move |args, _, memory| { + registry.register(KERNEL32, "HeapDestroy", move |args, cpu, memory| { let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; if !memory.destroy_private_heap(handle) { - return service_state.fail(ERROR_INVALID_HANDLE, 0); + return service_state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); } Ok(1) }); let state = Arc::clone(state); - registry.register(KERNEL32, "HeapFree", move |args, _, memory| { + registry.register(KERNEL32, "HeapFree", move |args, cpu, memory| { let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?; let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32; let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?; if !memory.has_heap(handle) { - return state.fail(ERROR_INVALID_HANDLE, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); } if flags != 0 { - return state.fail(ERROR_NOT_SUPPORTED, 0); + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); } if address != 0 && !memory.release_heap_allocation(handle, address) { - return state.fail(ERROR_INVALID_ADDRESS, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_ADDRESS, 0); } Ok(1) }); diff --git a/crates/loader/src/services/modules.rs b/crates/loader/src/services/modules.rs index 1a059fce..31070235 100644 --- a/crates/loader/src/services/modules.rs +++ b/crates/loader/src/services/modules.rs @@ -61,13 +61,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc for (symbol, wide, load) in named_operations { let state = Arc::clone(state); let modules = Arc::clone(&modules); - registry.register(KERNEL32, symbol, move |args, _, memory| { + registry.register(KERNEL32, symbol, move |args, cpu, memory| { if args.rcx == 0 { - return state.fail(MODULE_NOT_FOUND, 0); + return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0); } let Some(name) = read_name(memory, args.rcx, wide).map_err(ExitReason::MemoryFault)? else { - return state.fail(MODULE_NOT_FOUND, 0); + return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0); }; let mut name = name.to_ascii_lowercase(); if !name.contains('.') { @@ -75,17 +75,17 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } let modules = modules.get().expect("built-in module catalog"); let Some(&handle) = modules.names.get(&name) else { - return state.fail(MODULE_NOT_FOUND, 0); + return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0); }; let mut references = modules.references.lock().expect("module references"); if load { let count = references.entry(handle).or_default(); let Some(next) = count.checked_add(1) else { - return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + return state.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0); }; *count = next; } else if handle != MODULE_BASE && !references.contains_key(&handle) { - return state.fail(MODULE_NOT_FOUND, 0); + return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0); } Ok(handle) }); @@ -94,11 +94,11 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let release = Arc::clone(&modules); let release_state = Arc::clone(state); let release_trampolines = registry.dynamic_trampolines(); - registry.register(KERNEL32, "FreeLibrary", move |args, _, _| { + registry.register(KERNEL32, "FreeLibrary", move |args, cpu, _| { let modules = release.get().expect("built-in module catalog"); let mut references = modules.references.lock().expect("module references"); let Some(count) = references.get_mut(&args.rcx) else { - return release_state.fail(ERROR_INVALID_HANDLE, 0); + return release_state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); }; *count -= 1; if *count == 0 { @@ -113,11 +113,11 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let lookup = Arc::clone(&modules); let trampolines = registry.dynamic_trampolines(); let state = Arc::clone(state); - registry.register(KERNEL32, "GetProcAddress", move |args, _, memory| { + registry.register(KERNEL32, "GetProcAddress", move |args, cpu, memory| { let modules = lookup.get().expect("built-in module catalog"); let references = modules.references.lock().expect("module references"); if args.rcx != MODULE_BASE && !references.contains_key(&args.rcx) { - return state.fail(ERROR_INVALID_HANDLE, 0); + return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); } let export = if let Ok(ordinal) = u16::try_from(args.rdx) { ImportName::Ordinal(ordinal) @@ -125,13 +125,13 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let Some(symbol) = read_name(memory, args.rdx, false).map_err(ExitReason::MemoryFault)? else { - return state.fail(PROCEDURE_NOT_FOUND, 0); + return state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0); }; ImportName::Name(symbol) }; match modules.exports[&args.rcx].get(&export) { Some(&index) => Ok(trampolines.expose(index)), - None => state.fail(PROCEDURE_NOT_FOUND, 0), + None => state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0), } }); diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index f8417d40..50c88891 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -131,6 +131,7 @@ struct Guest { engine: DbtEngine, memory: GuestMemory, clock: Arc, + teb: u64, /// Upper halves and XMM lanes of unrelated arguments hold this pattern. xmm: [u128; 4], } @@ -161,6 +162,7 @@ impl Guest { engine, memory, clock, + teb: 0, xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4], } } @@ -171,6 +173,7 @@ impl Guest { .position(|service| service.symbol == symbol) .unwrap(); let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); + cpu.gs_base = self.teb; for (index, register) in cpu.gpr.iter_mut().enumerate() { if index != Register::Rsp as usize { *register = 0x0101_0101_0101_0101 * (index as u64 + 1); @@ -323,6 +326,24 @@ fn system_time_comes_from_the_injected_clock() { } } +#[test] +fn last_error_isolated_across_guest_thread_switches() { + let mut guest = Guest::new(); + guest.teb = 0x10000; + guest.call("SetLastError", &[123]); + guest.teb = 0x20000; + assert_eq!(guest.last_error(), 0); + assert_eq!(guest.call("CloseHandle", &[123]), 0); + assert_eq!(guest.last_error(), 6); + guest.teb = 0x10000; + guest.call("GetCurrentProcessId", &[]); + assert_eq!(guest.last_error(), 123); + guest.call("SetLastError", &[0]); + assert_eq!(guest.last_error(), 0); + guest.teb = 0x20000; + assert_eq!(guest.last_error(), 6); +} + #[test] fn last_error_is_set_by_failures_and_by_the_guest() { let mut guest = Guest::new(); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index f9398d8d..f1d24c0a 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -2165,7 +2165,7 @@ fn test_virtual_allocation_release_through_iat() { assert_eq!(result.execution.exit_reason, ExitReason::Halt); assert_eq!(result.bound_imports, if free.is_some() { 2 } else { 1 }); let value = result.execution.final_state.get(Register::Rax); - let error = state.last_error.load(std::sync::atomic::Ordering::SeqCst); + let error = state.last_error(result.execution.final_state.gs_base); (result.image.memory, value, error) }; From 8343e0cdc6ad799b0b0f0abea322eff7ac5e5a44 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:29:28 -0500 Subject: [PATCH 40/82] Report host file read failures through distinct VFS statuses Signed-off-by: Adeeb Rahman --- crates/ffi/include/xenora.h | 5 +++++ crates/ffi/src/lib.rs | 34 +++++++++++++++++++++++++++++++++- crates/ffi/tests/audio_vfs.rs | 11 ++++++++--- 3 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index 8d2fc205..fec9ad79 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -28,6 +28,9 @@ enum { XENORA_BUFFER_TOO_SMALL = 7, XENORA_EXECUTION_FAILED = 8, XENORA_INVALID_STATE = 9, + XENORA_FILE_NOT_FOUND = 10, + XENORA_ACCESS_DENIED = 11, + XENORA_IO_ERROR = 12, }; /* Frame-loop states reported by xenora_session_frame_loop_status. */ @@ -300,6 +303,8 @@ xenora_status xenora_session_vfs_set_root( /* * Open a file within the virtual filesystem sandboxed root. + * Missing files return XENORA_FILE_NOT_FOUND. Host permission failures return + * XENORA_ACCESS_DENIED. Other host I/O failures return XENORA_IO_ERROR. */ xenora_status xenora_session_vfs_open( xenora_session session, diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index b6c6c726..6482e2ed 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -29,6 +29,9 @@ pub const XENORA_LIMIT_EXCEEDED: i32 = 6; pub const XENORA_BUFFER_TOO_SMALL: i32 = 7; pub const XENORA_EXECUTION_FAILED: i32 = 8; pub const XENORA_INVALID_STATE: i32 = 9; +pub const XENORA_FILE_NOT_FOUND: i32 = 10; +pub const XENORA_ACCESS_DENIED: i32 = 11; +pub const XENORA_IO_ERROR: i32 = 12; pub const XENORA_LOOP_NONE: u32 = 0; pub const XENORA_LOOP_RUNNING: u32 = frame_loop::RUNNING; @@ -1449,6 +1452,17 @@ pub unsafe extern "C" fn xenora_session_vfs_set_root( }) } +fn vfs_read_status(kind: std::io::ErrorKind) -> i32 { + use std::io::ErrorKind; + match kind { + ErrorKind::NotFound | ErrorKind::NotADirectory => XENORA_FILE_NOT_FOUND, + ErrorKind::PermissionDenied => XENORA_ACCESS_DENIED, + ErrorKind::InvalidInput | ErrorKind::IsADirectory => XENORA_INVALID_ARGUMENT, + ErrorKind::OutOfMemory => XENORA_LIMIT_EXCEEDED, + _ => XENORA_IO_ERROR, + } +} + /// # Safety /// `rel_path` must be non-null and point to a valid NUL-terminated C string; /// `out_file` must be non-null and valid for one aligned `u64` write. @@ -1483,7 +1497,7 @@ pub unsafe extern "C" fn xenora_session_vfs_open( let data = match std::fs::read(&full_path) { Ok(bytes) => bytes, - Err(_) => return XENORA_INVALID_ARGUMENT, + Err(error) => return vfs_read_status(error.kind()), }; let file_idx = match slot.vfs.files.iter().position(|f| f.generation % 2 == 0) { @@ -1976,6 +1990,21 @@ mod tests { (status, sections, entry) } + #[test] + fn host_vfs_read_errors_have_stable_statuses() { + use std::io::ErrorKind; + for (kind, expected) in [ + (ErrorKind::NotFound, XENORA_FILE_NOT_FOUND), + (ErrorKind::NotADirectory, XENORA_FILE_NOT_FOUND), + (ErrorKind::PermissionDenied, XENORA_ACCESS_DENIED), + (ErrorKind::IsADirectory, XENORA_INVALID_ARGUMENT), + (ErrorKind::OutOfMemory, XENORA_LIMIT_EXCEEDED), + (ErrorKind::UnexpectedEof, XENORA_IO_ERROR), + ] { + assert_eq!(vfs_read_status(kind), expected); + } + } + #[test] fn header_and_rust_constants_agree() { let header = include_str!("../include/xenora.h"); @@ -1991,6 +2020,9 @@ mod tests { ("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL), ("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED), ("XENORA_INVALID_STATE", XENORA_INVALID_STATE), + ("XENORA_FILE_NOT_FOUND", XENORA_FILE_NOT_FOUND), + ("XENORA_ACCESS_DENIED", XENORA_ACCESS_DENIED), + ("XENORA_IO_ERROR", XENORA_IO_ERROR), ("XENORA_LOOP_NONE", XENORA_LOOP_NONE as i32), ("XENORA_LOOP_RUNNING", XENORA_LOOP_RUNNING as i32), ("XENORA_LOOP_PAUSED", XENORA_LOOP_PAUSED as i32), diff --git a/crates/ffi/tests/audio_vfs.rs b/crates/ffi/tests/audio_vfs.rs index e2afe47d..695fd206 100644 --- a/crates/ffi/tests/audio_vfs.rs +++ b/crates/ffi/tests/audio_vfs.rs @@ -180,11 +180,9 @@ fn virtual_filesystem_sandboxing_and_traversal_rejection() { "../../etc/passwd", "/etc/passwd", "sub/../../secret", - "asset.bin\0extra", "", ] { - let bad_c = std::ffi::CString::new(*bad) - .unwrap_or_else(|_| std::ffi::CString::new("fallback_bad").unwrap()); + let bad_c = std::ffi::CString::new(*bad).unwrap(); assert_eq!( unsafe { xenora_session_vfs_open(sess, bad_c.as_ptr(), 0, &mut file) }, XENORA_INVALID_ARGUMENT, @@ -193,6 +191,13 @@ fn virtual_filesystem_sandboxing_and_traversal_rejection() { ); } + let missing = std::ffi::CString::new("missing-xenora-test-asset.bin").unwrap(); + assert_eq!( + unsafe { xenora_session_vfs_open(sess, missing.as_ptr(), 0, &mut file) }, + XENORA_FILE_NOT_FOUND + ); + assert_eq!(file, XENORA_NO_FILE); + // Open existing valid asset let good = std::ffi::CString::new("asset.bin").unwrap(); assert_eq!( From aacd1606261b6f43f848c4b98264fce8dae7235d Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:30:55 -0500 Subject: [PATCH 41/82] Add bounded guest Winsock startup and UDP socket lifecycle Signed-off-by: Adeeb Rahman --- crates/loader/src/services.rs | 4 + crates/loader/src/services/winsock.rs | 122 ++++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 34 +++++++ 3 files changed, 160 insertions(+) create mode 100644 crates/loader/src/services/winsock.rs diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 9c5a487b..59333c8f 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -14,6 +14,7 @@ mod events; mod files; mod heap; mod modules; +mod winsock; use crate::runtime::HResult; @@ -170,6 +171,7 @@ pub struct ServicesState { pub thread_id: u32, objects: Mutex, last_errors: Mutex>, + winsock: Mutex, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, } @@ -184,6 +186,7 @@ impl ServicesState { thread_id: 0x4104, // Synthetic main thread ID objects: Mutex::new(ObjectState::default()), last_errors: Mutex::default(), + winsock: Mutex::default(), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), } @@ -539,6 +542,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc, +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + let startup = Arc::clone(state); + registry.register(MODULE, "WSAStartup", move |args, _, memory| { + let requested = args.rcx as u16; + let negotiated = match requested.to_le_bytes() { + [2, minor] => u16::from_le_bytes([2, minor.min(2)]), + _ => return Ok(u64::from(WSAVERNOTSUPPORTED)), + }; + let mut net = startup.winsock.lock().expect("guest Winsock state"); + let Some(next) = net.refs.checked_add(1) else { + return Ok(u64::from(WSASYSNOTREADY)); + }; + let mut data = [0; WSADATA_SIZE]; + data[..2].copy_from_slice(&negotiated.to_le_bytes()); + data[2..4].copy_from_slice(&VERSION.to_le_bytes()); + let description = b"Xenora synthetic Winsock"; + data[16..16 + description.len()].copy_from_slice(description); + if args.rdx == 0 || memory.write_bytes(args.rdx, &data).is_err() { + return Ok(u64::from(WSAEFAULT)); + } + net.refs = next; + Ok(0) + }); + + let cleanup = Arc::clone(state); + registry.register(MODULE, "WSACleanup", move |_, cpu, _| { + let mut net = cleanup.winsock.lock().expect("guest Winsock state"); + if net.refs == 0 { + return cleanup.fail(cpu.gs_base, WSANOTINITIALISED, SOCKET_ERROR); + } + net.refs -= 1; + if net.refs == 0 { + net.sockets.clear(); + } + Ok(0) + }); + + let open = Arc::clone(state); + registry.register(MODULE, "socket", move |args, cpu, _| { + let mut net = open.winsock.lock().expect("guest Winsock state"); + let fail = |error| open.fail(cpu.gs_base, error, INVALID_SOCKET); + if net.refs == 0 { + return fail(WSANOTINITIALISED); + } + if args.rcx as u32 != 2 { + return fail(WSAEAFNOSUPPORT); + } + if args.rdx as u32 != 2 { + return fail(WSAESOCKTNOSUPPORT); + } + if !matches!(args.r8 as u32, 0 | 17) { + return fail(WSAEPROTONOSUPPORT); + } + if net.sockets.len() >= MAX_SOCKETS { + return fail(WSAEMFILE); + } + let Some(next) = net.serial.checked_add(1) else { + return fail(WSAEMFILE); + }; + net.serial = next; + let socket = 0x5300_0000_0000_0000 | u64::from(next); + net.sockets.insert(socket); + Ok(socket) + }); + + let close = Arc::clone(state); + registry.register(MODULE, "closesocket", move |args, cpu, _| { + let mut net = close.winsock.lock().expect("guest Winsock state"); + if net.refs == 0 { + return close.fail(cpu.gs_base, WSANOTINITIALISED, SOCKET_ERROR); + } + if !net.sockets.remove(&args.rcx) { + return close.fail(cpu.gs_base, WSAENOTSOCK, SOCKET_ERROR); + } + Ok(0) + }); + + let get = Arc::clone(state); + registry.register(MODULE, "WSAGetLastError", move |_, cpu, _| { + Ok(u64::from(get.last_error(cpu.gs_base))) + }); + let set = Arc::clone(state); + registry.register(MODULE, "WSASetLastError", move |args, cpu, _| { + set.set_last_error(cpu.gs_base, args.rcx as u32); + Ok(0) + }); + for symbol in ["WSAStartup", "WSACleanup", "socket", "closesocket"] { + registry.set_status(MODULE, symbol, ServiceStatus::Partial); + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index f1d24c0a..f3652b3b 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,40 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn guest_winsock_lifecycle_balances_startup_and_invalidates_sockets() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |symbol, args: &[u64]| { + let result = call_service_fixture(&state, "ws2_32.dll", symbol, args); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result + }; + let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); + let datagram = [2, 2, 17]; + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + assert_eq!(value("socket", &datagram), u64::MAX); + assert_eq!(value("WSAGetLastError", &[]), 10093); + assert_eq!(value("WSAStartup", &[0x0202, 0]), 10014); + assert_eq!(value("WSAStartup", &[0x0101, output]), 10092); + assert_eq!(value("WSAGetLastError", &[]), 10093); + let first = call("WSAStartup", &[0x0102, output]); + assert_eq!(first.execution.final_state.get(Register::Rax), 0); + assert_eq!(first.image.memory.read_u32(output).unwrap(), 0x0202_0102); + assert_eq!(value("WSAStartup", &[0x0202, output]), 0); + let socket = value("socket", &datagram); + assert_ne!(socket, u64::MAX); + assert_eq!(value("WSACleanup", &[]), 0); + assert_eq!(value("closesocket", &[socket]), 0); + let stale = value("socket", &datagram); + assert_ne!(stale, socket); + assert_eq!(value("WSACleanup", &[]), 0); + assert_eq!(value("WSACleanup", &[]), u32::MAX as u64); + assert_eq!(value("WSAStartup", &[0x0202, output]), 0); + assert_eq!(value("closesocket", &[stale]), u32::MAX as u64); + assert_eq!(value("WSAGetLastError", &[]), 10038); + assert_ne!(value("socket", &datagram), stale); +} + #[test] fn guest_hresult_failures_preserve_last_error() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); From 198242e5e45e58e9b52f8ee449cc47a00ae79c14 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:32:34 -0500 Subject: [PATCH 42/82] Deliver bounded UDP datagrams inside guest loopback Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 278 +++++++++++++++++++++++++- 1 file changed, 273 insertions(+), 5 deletions(-) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index f084f8e6..36627556 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -1,18 +1,29 @@ // SPDX-License-Identifier: GPL-3.0-or-later -//! Winsock lifecycle for the synthetic guest. Descriptors are guest-owned. +//! Process-local Winsock UDP loopback for the synthetic guest. use super::ServicesState; +use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; -use std::collections::BTreeSet; +use crate::memory::GuestMemory; +use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; const MODULE: &str = "ws2_32.dll"; const VERSION: u16 = 0x0202; const WSADATA_SIZE: usize = 408; +const MAX_DATAGRAM: usize = 65_507; +const MAX_PENDING_DATAGRAMS: usize = 16; const MAX_SOCKETS: usize = 64; const SOCKET_ERROR: u64 = u32::MAX as u64; const INVALID_SOCKET: u64 = u64::MAX; +const WSAEACCES: u32 = 10013; +const WSAEINVAL: u32 = 10022; +const WSAEWOULDBLOCK: u32 = 10035; +const WSAEMSGSIZE: u32 = 10040; +const WSAEADDRINUSE: u32 = 10048; +const WSAENOBUFS: u32 = 10055; +const WSAENOTCONN: u32 = 10057; const WSAEFAULT: u32 = 10014; const WSAEMFILE: u32 = 10024; const WSAENOTSOCK: u32 = 10038; @@ -27,7 +38,64 @@ const WSANOTINITIALISED: u32 = 10093; pub(super) struct Winsock { refs: u32, serial: u32, - sockets: BTreeSet, + sockets: BTreeMap, +} + +#[derive(Default)] +struct Socket { + port: Option, + peer: Option, + pending: VecDeque<(u16, Vec)>, +} + +impl Winsock { + fn socket(&self, handle: u64) -> Result<&Socket, u32> { + if self.refs == 0 { + return Err(WSANOTINITIALISED); + } + self.sockets.get(&handle).ok_or(WSAENOTSOCK) + } + + fn port(&self, requested: u16) -> Result { + let available = |port| { + self.sockets + .values() + .all(|socket| socket.port != Some(port)) + }; + if requested != 0 { + return available(requested) + .then_some(requested) + .ok_or(WSAEADDRINUSE); + } + (49152..=65535) + .find(|&port| available(port)) + .ok_or(WSAEADDRINUSE) + } +} + +fn loopback_port(memory: &GuestMemory, address: u64, size: u32) -> Result { + let mut data = [0; 16]; + if (size as i32) < 16 || address == 0 || memory.read_bytes(address, &mut data).is_err() { + return Err(WSAEFAULT); + } + if u16::from_le_bytes([data[0], data[1]]) != 2 { + return Err(WSAEAFNOSUPPORT); + } + if data[4..8] != [127, 0, 0, 1] { + return Err(WSAEACCES); + } + Ok(u16::from_be_bytes([data[2], data[3]])) +} + +fn socket_result( + state: &ServicesState, + teb: u64, + result: Result, +) -> Result { + match result { + Ok(value) => Ok(value), + Err(error) => state.fail(teb, error, SOCKET_ERROR), + } } pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { @@ -91,7 +159,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }; net.serial = next; let socket = 0x5300_0000_0000_0000 | u64::from(next); - net.sockets.insert(socket); + net.sockets.insert(socket, Socket::default()); Ok(socket) }); @@ -101,12 +169,14 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if net.refs == 0 { return close.fail(cpu.gs_base, WSANOTINITIALISED, SOCKET_ERROR); } - if !net.sockets.remove(&args.rcx) { + if net.sockets.remove(&args.rcx).is_none() { return close.fail(cpu.gs_base, WSAENOTSOCK, SOCKET_ERROR); } Ok(0) }); + register_loopback(registry, state); + let get = Arc::clone(state); registry.register(MODULE, "WSAGetLastError", move |_, cpu, _| { Ok(u64::from(get.last_error(cpu.gs_base))) @@ -120,3 +190,201 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc registry.set_status(MODULE, symbol, ServiceStatus::Partial); } } + +fn register_loopback(registry: &mut ImportRegistry, state: &Arc) { + for (symbol, connect) in [("bind", false), ("connect", true)] { + let state = Arc::clone(state); + registry.register_with_status( + MODULE, + symbol, + ServiceStatus::Partial, + move |args, cpu, memory| { + let mut net = state.winsock.lock().expect("guest Winsock state"); + let result = (|| { + let socket = net.socket(args.rcx)?; + let existing = socket.port; + let requested = loopback_port(memory, args.rdx, args.r8 as u32)?; + if connect && requested == 0 || !connect && existing.is_some() { + return Err(WSAEINVAL); + } + let local = match (connect, existing) { + (true, Some(port)) => port, + (true, None) => net.port(0)?, + (false, _) => net.port(requested)?, + }; + let socket = net.sockets.get_mut(&args.rcx).expect("validated socket"); + socket.port = Some(local); + if connect { + socket.peer = Some(requested); + socket.pending.retain(|(source, _)| *source == requested); + } + Ok(0) + })(); + socket_result(&state, cpu.gs_base, result) + }, + ); + } + + let send = Arc::clone(state); + registry.register_with_status( + MODULE, + "send", + ServiceStatus::Partial, + move |args, cpu, memory| { + let mut net = send.winsock.lock().expect("guest Winsock state"); + let result = (|| { + let socket = net.socket(args.rcx)?; + let peer = socket.peer.ok_or(WSAENOTCONN)?; + let source = socket.port.expect("connected socket is bound"); + let length = args.r8 as i32; + if length < 0 || args.r9 as u32 != 0 { + return Err(WSAEINVAL); + } + let length = length as usize; + if length > MAX_DATAGRAM { + return Err(WSAEMSGSIZE); + } + let mut data = vec![0; length]; + if length != 0 { + memory + .read_bytes(args.rdx, &mut data) + .map_err(|_| WSAEFAULT)?; + } + if let Some(target) = net.sockets.values_mut().find(|socket| { + socket.port == Some(peer) && socket.peer.is_none_or(|port| port == source) + }) { + if target.pending.len() == MAX_PENDING_DATAGRAMS { + return Err(WSAENOBUFS); + } + target.pending.push_back((source, data)); + } + Ok(length as u64) + })(); + socket_result(&send, cpu.gs_base, result) + }, + ); + + let recv = Arc::clone(state); + registry.register_with_status( + MODULE, + "recv", + ServiceStatus::Partial, + move |args, cpu, memory| { + let mut net = recv.winsock.lock().expect("guest Winsock state"); + let result = (|| { + if net.socket(args.rcx)?.port.is_none() { + return Err(WSAEINVAL); + } + let length = args.r8 as i32; + if length < 0 || args.r9 as u32 != 0 { + return Err(WSAEINVAL); + } + let socket = net.sockets.get_mut(&args.rcx).expect("validated socket"); + let (_, data) = socket.pending.front().ok_or(WSAEWOULDBLOCK)?; + let copied = (length as usize).min(data.len()); + if copied != 0 { + memory + .write_bytes(args.rdx, &data[..copied]) + .map_err(|_| WSAEFAULT)?; + } + let truncated = copied < data.len(); + socket.pending.pop_front(); + if truncated { + return Err(WSAEMSGSIZE); + } + Ok(copied as u64) + })(); + socket_result(&recv, cpu.gs_base, result) + }, + ); +} + +#[cfg(test)] +#[test] +fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() { + use crate::cpu::{CpuState, Register}; + use crate::import_table::ImportName; + use crate::imports::Win64Args; + use crate::memory::MemoryPermissions; + use crate::services::MockClock; + + let mut registry = ImportRegistry::new(); + register( + &mut registry, + &Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), + ); + let mut memory = GuestMemory::new(); + memory + .map_region(0x1000, 4096, MemoryPermissions::READ_WRITE) + .unwrap(); + let call = |memory: &mut GuestMemory, symbol: &str, args: &[u64]| { + let mut cpu = CpuState::default(); + for (reg, &value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(reg, value); + } + let descriptor = registry + .resolve(MODULE, &ImportName::Name(symbol.to_owned())) + .unwrap(); + (descriptor.handler)(&Win64Args::new(&cpu), &mut cpu, memory).unwrap() + }; + assert_eq!(call(&mut memory, "WSAStartup", &[0x0202, 0x1000]), 0); + let server = call(&mut memory, "socket", &[2, 2, 17]); + let client = call(&mut memory, "socket", &[2, 2, 17]); + let mut address = [0; 16]; + address[..8].copy_from_slice(&[2, 0, 0x13, 0x88, 127, 0, 0, 1]); + memory.write_bytes(0x1200, &address).unwrap(); + assert_eq!(call(&mut memory, "bind", &[server, 0x1200, 16]), 0); + assert_eq!( + call(&mut memory, "bind", &[client, 0x1200, 16]), + SOCKET_ERROR + ); + assert_eq!( + call(&mut memory, "WSAGetLastError", &[]), + u64::from(WSAEADDRINUSE) + ); + memory.write_u8(0x1204, 192).unwrap(); + assert_eq!( + call(&mut memory, "connect", &[client, 0x1200, 16]), + SOCKET_ERROR + ); + assert_eq!( + call(&mut memory, "WSAGetLastError", &[]), + u64::from(WSAEACCES) + ); + memory.write_u8(0x1204, 127).unwrap(); + assert_eq!(call(&mut memory, "connect", &[client, 0x1200, 16]), 0); + memory.write_bytes(0x1300, b"hello").unwrap(); + assert_eq!(call(&mut memory, "send", &[client, 0x1300, 5, 0]), 5); + assert_eq!(call(&mut memory, "send", &[client, 0x1300, 2, 0]), 2); + assert_eq!( + call(&mut memory, "recv", &[server, 0xff, 4, 0]), + SOCKET_ERROR + ); + assert_eq!( + call(&mut memory, "WSAGetLastError", &[]), + u64::from(WSAEFAULT) + ); + assert_eq!( + call(&mut memory, "recv", &[server, 0x1400, 4, 0]), + SOCKET_ERROR + ); + assert_eq!( + call(&mut memory, "WSAGetLastError", &[]), + u64::from(WSAEMSGSIZE) + ); + let mut received = [0; 4]; + memory.read_bytes(0x1400, &mut received).unwrap(); + assert_eq!(&received, b"hell"); + assert_eq!(call(&mut memory, "recv", &[server, 0x1400, 4, 0]), 2); + assert_eq!( + call(&mut memory, "recv", &[server, 0x1400, 4, 0]), + SOCKET_ERROR + ); + assert_eq!( + call(&mut memory, "WSAGetLastError", &[]), + u64::from(WSAEWOULDBLOCK) + ); +} From 731f9448c38eab7c4a97e0cabc57cefaaddf4566 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:33:38 -0500 Subject: [PATCH 43/82] Verify guest UDP loopback over bound Winsock imports Signed-off-by: Adeeb Rahman --- crates/loader/tests/runtime_services.rs | 82 +++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 50c88891..7855e524 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -326,6 +326,88 @@ fn system_time_comes_from_the_injected_clock() { } } +#[test] +fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { + let symbols = [ + "WSAStartup", + "socket", + "bind", + "connect", + "send", + "recv", + "WSAGetLastError", + "WSACleanup", + ]; + let imports = symbols.map(|symbol| ("ws2_32.dll", Symbol::Name(symbol))); + let image = build(&imports); + let pe = ParsedPe::parse(&image.bytes).unwrap(); + let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory; + memory + .map_region(SCRATCH, 4096, MemoryPermissions::READ_WRITE) + .unwrap(); + memory + .map_region(STACK, 4096, MemoryPermissions::READ_WRITE) + .unwrap(); + let (mut registry, _) = standard(0); + assert_eq!( + registry + .bind_imports(&pe, &image.bytes, BASE, &mut memory) + .unwrap(), + symbols.len() + ); + let mut engine = DbtEngine::new(256 * 1024).unwrap(); + engine.set_import_registry(registry); + let mut call = |memory: &mut GuestMemory, symbol, args: &[u64]| { + let index = symbols.iter().position(|&name| symbol == name).unwrap() as u64; + let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index, STACK_TOP); + for (register, &value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(register, value); + } + let result = engine.run(&mut cpu, memory, 8); + assert_eq!(result.exit_reason, ExitReason::Halt, "{symbol}"); + cpu.get(Register::Rax) + }; + let address = SCRATCH + 0x200; + let outgoing = SCRATCH + 0x220; + let incoming = SCRATCH + 0x240; + assert_eq!(call(&mut memory, "WSAStartup", &[0x0202, SCRATCH]), 0); + let receiver = call(&mut memory, "socket", &[2, 2, 17]); + let sender = call(&mut memory, "socket", &[2, 2, 17]); + assert_ne!(receiver, u64::MAX); + assert_ne!(sender, u64::MAX); + assert_ne!(sender, receiver); + let mut endpoint = [0; 16]; + endpoint[..8].copy_from_slice(&[2, 0, 0x13, 0x88, 127, 0, 0, 1]); + memory.write_bytes(address, &endpoint).unwrap(); + assert_eq!(call(&mut memory, "bind", &[receiver, address, 16]), 0); + assert_eq!(call(&mut memory, "connect", &[sender, address, 16]), 0); + memory.write_bytes(outgoing, b"loop").unwrap(); + for _ in 0..16 { + assert_eq!(call(&mut memory, "send", &[sender, outgoing, 4, 0]), 4); + } + assert_eq!( + call(&mut memory, "send", &[sender, outgoing, 4, 0]), + u64::from(u32::MAX) + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10055); + for _ in 0..16 { + assert_eq!(call(&mut memory, "recv", &[receiver, incoming, 4, 0]), 4); + let mut received = [0; 4]; + memory.read_bytes(incoming, &mut received).unwrap(); + assert_eq!(&received, b"loop"); + memory.write_u32(incoming, 0).unwrap(); + } + assert_eq!( + call(&mut memory, "recv", &[receiver, incoming, 4, 0]), + u64::from(u32::MAX) + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10035); + assert_eq!(call(&mut memory, "WSACleanup", &[]), 0); +} + #[test] fn last_error_isolated_across_guest_thread_switches() { let mut guest = Guest::new(); From e3cd65cb79884ae3c246ca807f214779ffe1611b Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:34:40 -0500 Subject: [PATCH 44/82] Build guest UDP endpoints through Winsock address conversion Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 57 +++++++++++++++++++++++++ crates/loader/tests/runtime_services.rs | 26 +++++++++-- 2 files changed, 80 insertions(+), 3 deletions(-) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 36627556..030e5307 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -175,6 +175,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(0) }); + register_address_conversion(registry, state); register_loopback(registry, state); let get = Arc::clone(state); @@ -191,6 +192,62 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } } +fn register_address_conversion(registry: &mut ImportRegistry, state: &Arc) { + for symbol in ["htons", "ntohs"] { + registry.register(MODULE, symbol, |args, _, _| { + Ok(u64::from((args.rcx as u16).swap_bytes())) + }); + } + for symbol in ["htonl", "ntohl"] { + registry.register(MODULE, symbol, |args, _, _| { + Ok(u64::from((args.rcx as u32).swap_bytes())) + }); + } + let state = Arc::clone(state); + registry.register_with_status( + MODULE, + "inet_pton", + ServiceStatus::Partial, + move |args, cpu, memory| { + let fail = |error| state.fail(cpu.gs_base, error, SOCKET_ERROR); + if args.rcx as u32 != 2 { + return fail(WSAEAFNOSUPPORT); + } + if args.rdx == 0 || args.r8 == 0 { + return fail(WSAEFAULT); + } + // The longest dotted decimal IPv4 spelling is 15 bytes plus NUL. + let mut text = [0; 15]; + for len in 0..=text.len() { + let Some(address) = args.rdx.checked_add(len as u64) else { + return fail(WSAEFAULT); + }; + let Ok(byte) = memory.read_u8(address) else { + return fail(WSAEFAULT); + }; + if byte == 0 { + let Some(ip) = std::str::from_utf8(&text[..len]) + .ok() + .and_then(|text| text.parse::().ok()) + else { + return Ok(0); + }; + return if memory.write_bytes(args.r8, &ip.octets()).is_ok() { + Ok(1) + } else { + fail(WSAEFAULT) + }; + } + if len == text.len() { + break; + } + text[len] = byte; + } + Ok(0) + }, + ); +} + fn register_loopback(registry: &mut ImportRegistry, state: &Arc) { for (symbol, connect) in [("bind", false), ("connect", true)] { let state = Arc::clone(state); diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 7855e524..f262e774 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -337,6 +337,8 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { "recv", "WSAGetLastError", "WSACleanup", + "inet_pton", + "htons", ]; let imports = symbols.map(|symbol| ("ws2_32.dll", Symbol::Name(symbol))); let image = build(&imports); @@ -373,15 +375,33 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { let address = SCRATCH + 0x200; let outgoing = SCRATCH + 0x220; let incoming = SCRATCH + 0x240; + let text = SCRATCH + 0x260; + memory.write_u16(address, 2).unwrap(); + let port = call(&mut memory, "htons", &[5000]); + memory.write_u16(address + 2, port as u16).unwrap(); + memory.write_bytes(text, b"127.0.0.1\0").unwrap(); + assert_eq!(call(&mut memory, "inet_pton", &[2, text, address + 4]), 1); + assert_eq!( + memory.read_u32(address + 4).unwrap().to_le_bytes(), + [127, 0, 0, 1] + ); + memory.write_bytes(text, b"127.0.0.999\0").unwrap(); + assert_eq!(call(&mut memory, "inet_pton", &[2, text, address + 4]), 0); + assert_eq!( + memory.read_u32(address + 4).unwrap().to_le_bytes(), + [127, 0, 0, 1] + ); + assert_eq!( + call(&mut memory, "inet_pton", &[23, text, address + 4]), + u64::from(u32::MAX) + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10047); assert_eq!(call(&mut memory, "WSAStartup", &[0x0202, SCRATCH]), 0); let receiver = call(&mut memory, "socket", &[2, 2, 17]); let sender = call(&mut memory, "socket", &[2, 2, 17]); assert_ne!(receiver, u64::MAX); assert_ne!(sender, u64::MAX); assert_ne!(sender, receiver); - let mut endpoint = [0; 16]; - endpoint[..8].copy_from_slice(&[2, 0, 0x13, 0x88, 127, 0, 0, 1]); - memory.write_bytes(address, &endpoint).unwrap(); assert_eq!(call(&mut memory, "bind", &[receiver, address, 16]), 0); assert_eq!(call(&mut memory, "connect", &[sender, address, 16]), 0); memory.write_bytes(outgoing, b"loop").unwrap(); From 7a91e11742f049613ae1e22360ec3dc6b7b9ef52 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:35:53 -0500 Subject: [PATCH 45/82] Report immediate Winsock UDP readiness through WSAPoll Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 71 +++++++++++++++++++++++++ crates/loader/tests/runtime_services.rs | 15 ++++++ 2 files changed, 86 insertions(+) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 030e5307..4ecc0cbe 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -29,6 +29,7 @@ const WSAEMFILE: u32 = 10024; const WSAENOTSOCK: u32 = 10038; const WSAEPROTONOSUPPORT: u32 = 10043; const WSAESOCKTNOSUPPORT: u32 = 10044; +const WSAEOPNOTSUPP: u32 = 10045; const WSAEAFNOSUPPORT: u32 = 10047; const WSASYSNOTREADY: u32 = 10091; const WSAVERNOTSUPPORTED: u32 = 10092; @@ -177,6 +178,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc register_address_conversion(registry, state); register_loopback(registry, state); + register_poll(registry, state); let get = Arc::clone(state); registry.register(MODULE, "WSAGetLastError", move |_, cpu, _| { @@ -356,6 +358,75 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc) ); } +fn register_poll(registry: &mut ImportRegistry, state: &Arc) { + const POLLFD_SIZE: usize = 16; + const POLLNVAL: u16 = 0x0004; + const POLLWRNORM: u16 = 0x0010; + const POLLRDNORM: u16 = 0x0100; + const POLLRDBAND: u16 = 0x0200; + + let state = Arc::clone(state); + registry.register_with_status( + MODULE, + "WSAPoll", + ServiceStatus::Partial, + move |args, cpu, memory| { + let net = state.winsock.lock().expect("guest Winsock state"); + let result = (|| { + if net.refs == 0 { + return Err(WSANOTINITIALISED); + } + let count = args.rdx as u32 as usize; + if !(1..=MAX_SOCKETS).contains(&count) { + return Err(WSAEINVAL); + } + if args.r8 as u32 != 0 { + return Err(WSAEOPNOTSUPP); + } + if args.rcx == 0 { + return Err(WSAEFAULT); + } + let mut storage = [0; MAX_SOCKETS * POLLFD_SIZE]; + let descriptors = &mut storage[..count * POLLFD_SIZE]; + memory + .read_bytes(args.rcx, descriptors) + .map_err(|_| WSAEFAULT)?; + let mut ready = 0; + for fd in descriptors.as_chunks_mut::().0 { + let handle = u64::from_le_bytes(fd[..8].try_into().expect("socket handle")); + let events = u16::from_le_bytes([fd[8], fd[9]]); + if events & !(POLLWRNORM | POLLRDNORM | POLLRDBAND) != 0 { + return Err(WSAEINVAL); + } + let mut result = POLLNVAL; + if let Some(socket) = net.sockets.get(&handle) { + result = 0; + if !socket.pending.is_empty() { + result |= events & POLLRDNORM; + } + if let Some(peer) = socket.peer + && !net.sockets.values().any(|target| { + target.port == Some(peer) + && target.peer.is_none_or(|port| Some(port) == socket.port) + && target.pending.len() == MAX_PENDING_DATAGRAMS + }) + { + result |= events & POLLWRNORM; + } + } + fd[10..12].copy_from_slice(&result.to_le_bytes()); + ready += u64::from(result != 0); + } + memory + .write_bytes(args.rcx, descriptors) + .map_err(|_| WSAEFAULT)?; + Ok(ready) + })(); + socket_result(&state, cpu.gs_base, result) + }, + ); +} + #[cfg(test)] #[test] fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() { diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index f262e774..5e319cf5 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -337,6 +337,7 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { "recv", "WSAGetLastError", "WSACleanup", + "WSAPoll", "inet_pton", "htons", ]; @@ -376,6 +377,7 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { let outgoing = SCRATCH + 0x220; let incoming = SCRATCH + 0x240; let text = SCRATCH + 0x260; + let poll = SCRATCH + 0x280; memory.write_u16(address, 2).unwrap(); let port = call(&mut memory, "htons", &[5000]); memory.write_u16(address + 2, port as u16).unwrap(); @@ -404,6 +406,13 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { assert_ne!(sender, receiver); assert_eq!(call(&mut memory, "bind", &[receiver, address, 16]), 0); assert_eq!(call(&mut memory, "connect", &[sender, address, 16]), 0); + memory.write_u64(poll, receiver).unwrap(); + memory.write_u16(poll + 8, 0x0100).unwrap(); + memory.write_u64(poll + 16, sender).unwrap(); + memory.write_u16(poll + 24, 0x0010).unwrap(); + assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1); + assert_eq!(memory.read_u16(poll + 10).unwrap(), 0); + assert_eq!(memory.read_u16(poll + 26).unwrap(), 0x0010); memory.write_bytes(outgoing, b"loop").unwrap(); for _ in 0..16 { assert_eq!(call(&mut memory, "send", &[sender, outgoing, 4, 0]), 4); @@ -413,6 +422,9 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { u64::from(u32::MAX) ); assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10055); + assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1); + assert_eq!(memory.read_u16(poll + 10).unwrap(), 0x0100); + assert_eq!(memory.read_u16(poll + 26).unwrap(), 0); for _ in 0..16 { assert_eq!(call(&mut memory, "recv", &[receiver, incoming, 4, 0]), 4); let mut received = [0; 4]; @@ -425,6 +437,9 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { u64::from(u32::MAX) ); assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10035); + assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1); + assert_eq!(memory.read_u16(poll + 10).unwrap(), 0); + assert_eq!(memory.read_u16(poll + 26).unwrap(), 0x0010); assert_eq!(call(&mut memory, "WSACleanup", &[]), 0); } From 342fcbd17df40ae3729bf45cf4a54dcf7f07b16e Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:36:38 -0500 Subject: [PATCH 46/82] Format guest IPv4 addresses through Winsock inet_ntop Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 30 ++++++++++++++++++++++++- crates/loader/tests/runtime_services.rs | 18 +++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 4ecc0cbe..0d3f4008 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -2,7 +2,7 @@ //! Process-local Winsock UDP loopback for the synthetic guest. -use super::ServicesState; +use super::{ERROR_INVALID_PARAMETER, ServicesState}; use crate::cpu::ExitReason; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::GuestMemory; @@ -205,6 +205,34 @@ fn register_address_conversion(registry: &mut ImportRegistry, state: &Arc args.r9 { + return fail(ERROR_INVALID_PARAMETER); + } + if memory.write_bytes(args.r8, &text).is_err() { + return fail(WSAEFAULT); + } + Ok(args.r8) + }, + ); let state = Arc::clone(state); registry.register_with_status( MODULE, diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 5e319cf5..2225b559 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -339,6 +339,7 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { "WSACleanup", "WSAPoll", "inet_pton", + "inet_ntop", "htons", ]; let imports = symbols.map(|symbol| ("ws2_32.dll", Symbol::Name(symbol))); @@ -378,6 +379,7 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { let incoming = SCRATCH + 0x240; let text = SCRATCH + 0x260; let poll = SCRATCH + 0x280; + let formatted = SCRATCH + 0x2a0; memory.write_u16(address, 2).unwrap(); let port = call(&mut memory, "htons", &[5000]); memory.write_u16(address + 2, port as u16).unwrap(); @@ -398,6 +400,22 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { u64::from(u32::MAX) ); assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10047); + memory.write_u8(formatted, 0xaa).unwrap(); + assert_eq!( + call(&mut memory, "inet_ntop", &[2, address + 4, formatted, 9]), + 0 + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 87); + assert_eq!(memory.read_u8(formatted).unwrap(), 0xaa); + assert_eq!( + call(&mut memory, "inet_ntop", &[2, address + 4, formatted, 10]), + formatted + ); + let mut formatted_address = [0; 10]; + memory + .read_bytes(formatted, &mut formatted_address) + .unwrap(); + assert_eq!(&formatted_address, b"127.0.0.1\0"); assert_eq!(call(&mut memory, "WSAStartup", &[0x0202, SCRATCH]), 0); let receiver = call(&mut memory, "socket", &[2, 2, 17]); let sender = call(&mut memory, "socket", &[2, 2, 17]); From ce2a753d2f147bb2f14614de8e9a55572f5b5e44 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:37:34 -0500 Subject: [PATCH 47/82] Expose guest UDP local and peer addresses Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 46 +++++++++++++++++++++++++ crates/loader/tests/runtime_services.rs | 40 ++++++++++++++++++++- 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 0d3f4008..981932ac 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -178,6 +178,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc register_address_conversion(registry, state); register_loopback(registry, state); + register_socket_names(registry, state); register_poll(registry, state); let get = Arc::clone(state); @@ -386,6 +387,51 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc) ); } +fn register_socket_names(registry: &mut ImportRegistry, state: &Arc) { + for (symbol, peer) in [("getsockname", false), ("getpeername", true)] { + let state = Arc::clone(state); + registry.register_with_status( + MODULE, + symbol, + ServiceStatus::Partial, + move |args, cpu, memory| { + let result = (|| { + let net = state.winsock.lock().expect("guest Winsock state"); + let socket = net.socket(args.rcx)?; + let port = if peer { + socket.peer.ok_or(WSAENOTCONN)? + } else { + socket.port.ok_or(WSAEINVAL)? + }; + if args.rdx == 0 || args.r8 == 0 { + return Err(WSAEFAULT); + } + let length = memory.read_u32(args.r8).map_err(|_| WSAEFAULT)? as i32; + let mut address = [0; 16]; + if length < address.len() as i32 { + return Err(WSAEFAULT); + } + memory + .check_write(args.rdx, address.len()) + .map_err(|_| WSAEFAULT)?; + memory.check_write(args.r8, 4).map_err(|_| WSAEFAULT)?; + address[..2].copy_from_slice(&2_u16.to_le_bytes()); + address[2..4].copy_from_slice(&port.to_be_bytes()); + address[4..8].copy_from_slice(&[127, 0, 0, 1]); + memory + .write_bytes(args.rdx, &address) + .map_err(|_| WSAEFAULT)?; + memory + .write_u32(args.r8, address.len() as u32) + .map_err(|_| WSAEFAULT)?; + Ok(0) + })(); + socket_result(&state, cpu.gs_base, result) + }, + ); + } +} + fn register_poll(registry: &mut ImportRegistry, state: &Arc) { const POLLFD_SIZE: usize = 16; const POLLNVAL: u16 = 0x0004; diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 2225b559..323cfc2e 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -338,6 +338,8 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { "WSAGetLastError", "WSACleanup", "WSAPoll", + "getsockname", + "getpeername", "inet_pton", "inet_ntop", "htons", @@ -380,9 +382,11 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { let text = SCRATCH + 0x260; let poll = SCRATCH + 0x280; let formatted = SCRATCH + 0x2a0; + let address_length = SCRATCH + 0x2b0; + let peer_address = SCRATCH + 0x2c0; memory.write_u16(address, 2).unwrap(); let port = call(&mut memory, "htons", &[5000]); - memory.write_u16(address + 2, port as u16).unwrap(); + assert_eq!(port, 0x8813); memory.write_bytes(text, b"127.0.0.1\0").unwrap(); assert_eq!(call(&mut memory, "inet_pton", &[2, text, address + 4]), 1); assert_eq!( @@ -423,7 +427,41 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { assert_ne!(sender, u64::MAX); assert_ne!(sender, receiver); assert_eq!(call(&mut memory, "bind", &[receiver, address, 16]), 0); + memory.write_u32(address_length, 15).unwrap(); + assert_eq!( + call( + &mut memory, + "getsockname", + &[receiver, address, address_length] + ), + u64::from(u32::MAX) + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10014); + assert_eq!(memory.read_u16(address + 2).unwrap(), 0); + memory.write_u32(address_length, 32).unwrap(); + assert_eq!( + call( + &mut memory, + "getsockname", + &[receiver, address, address_length] + ), + 0 + ); + assert_eq!(memory.read_u32(address_length).unwrap(), 16); + assert_eq!(memory.read_u16(address + 2).unwrap().swap_bytes(), 49152); assert_eq!(call(&mut memory, "connect", &[sender, address, 16]), 0); + assert_eq!( + call( + &mut memory, + "getpeername", + &[sender, peer_address, address_length] + ), + 0 + ); + assert_eq!( + memory.read_u64(peer_address).unwrap(), + memory.read_u64(address).unwrap() + ); memory.write_u64(poll, receiver).unwrap(); memory.write_u16(poll + 8, 0x0100).unwrap(); memory.write_u64(poll + 16, sender).unwrap(); From 0109aea9ea7448617b856223cb0df7651d7228cb Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:38:28 -0500 Subject: [PATCH 48/82] Report synthetic UDP socket type and datagram limit Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 40 +++++++++++++++++++++++++ crates/loader/tests/runtime_services.rs | 28 +++++++++++++++++ 2 files changed, 68 insertions(+) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 981932ac..287edcd2 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -30,6 +30,7 @@ const WSAENOTSOCK: u32 = 10038; const WSAEPROTONOSUPPORT: u32 = 10043; const WSAESOCKTNOSUPPORT: u32 = 10044; const WSAEOPNOTSUPP: u32 = 10045; +const WSAENOPROTOOPT: u32 = 10042; const WSAEAFNOSUPPORT: u32 = 10047; const WSASYSNOTREADY: u32 = 10091; const WSAVERNOTSUPPORTED: u32 = 10092; @@ -179,6 +180,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc register_address_conversion(registry, state); register_loopback(registry, state); register_socket_names(registry, state); + register_socket_options(registry, state); register_poll(registry, state); let get = Arc::clone(state); @@ -432,6 +434,44 @@ fn register_socket_names(registry: &mut ImportRegistry, state: &Arc) { + const SOL_SOCKET: u32 = 0xffff; + const SO_TYPE: u32 = 0x1008; + const SO_MAX_MSG_SIZE: u32 = 0x2003; + const SOCK_DGRAM: u32 = 2; + + let state = Arc::clone(state); + registry.register_with_status( + MODULE, + "getsockopt", + ServiceStatus::Partial, + move |args, cpu, memory| { + let result = (|| { + let net = state.winsock.lock().expect("guest Winsock state"); + net.socket(args.rcx)?; + let value = match (args.rdx as u32, args.r8 as u32) { + (SOL_SOCKET, SO_TYPE) => SOCK_DGRAM, + (SOL_SOCKET, SO_MAX_MSG_SIZE) => MAX_DATAGRAM as u32, + _ => return Err(WSAENOPROTOOPT), + }; + let length = args.get(4, memory).map_err(|_| WSAEFAULT)?; + if args.r9 == 0 || length == 0 { + return Err(WSAEFAULT); + } + if (memory.read_u32(length).map_err(|_| WSAEFAULT)? as i32) < 4 { + return Err(WSAEFAULT); + } + memory.check_write(args.r9, 4).map_err(|_| WSAEFAULT)?; + memory.check_write(length, 4).map_err(|_| WSAEFAULT)?; + memory.write_u32(args.r9, value).map_err(|_| WSAEFAULT)?; + memory.write_u32(length, 4).map_err(|_| WSAEFAULT)?; + Ok(0) + })(); + socket_result(&state, cpu.gs_base, result) + }, + ); +} + fn register_poll(registry: &mut ImportRegistry, state: &Arc) { const POLLFD_SIZE: usize = 16; const POLLNVAL: u16 = 0x0004; diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 323cfc2e..2c72d2ce 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -340,6 +340,7 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { "WSAPoll", "getsockname", "getpeername", + "getsockopt", "inet_pton", "inet_ntop", "htons", @@ -372,6 +373,9 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { { cpu.set(register, value); } + if let Some(&fifth) = args.get(4) { + memory.write_u64(STACK_TOP + 32, fifth).unwrap(); + } let result = engine.run(&mut cpu, memory, 8); assert_eq!(result.exit_reason, ExitReason::Halt, "{symbol}"); cpu.get(Register::Rax) @@ -426,6 +430,30 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { assert_ne!(receiver, u64::MAX); assert_ne!(sender, u64::MAX); assert_ne!(sender, receiver); + for (option, expected) in [(0x1008, 2), (0x2003, 65_507)] { + memory.write_u32(address_length, 8).unwrap(); + assert_eq!( + call( + &mut memory, + "getsockopt", + &[sender, 0xffff, option, incoming, address_length] + ), + 0 + ); + assert_eq!(memory.read_u32(incoming).unwrap(), expected); + assert_eq!(memory.read_u32(address_length).unwrap(), 4); + } + memory.write_u32(address_length, 3).unwrap(); + assert_eq!( + call( + &mut memory, + "getsockopt", + &[sender, 0xffff, 0x1008, incoming, address_length] + ), + u64::from(u32::MAX) + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10014); + assert_eq!(memory.read_u32(incoming).unwrap(), 65_507); assert_eq!(call(&mut memory, "bind", &[receiver, address, 16]), 0); memory.write_u32(address_length, 15).unwrap(); assert_eq!( From 7ff88bc3f48988ae6671c96d9189efc813b3249c Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:39:27 -0500 Subject: [PATCH 49/82] Support bounded positive timeouts in guest UDP polling Signed-off-by: Adeeb Rahman --- crates/loader/src/services.rs | 4 +- crates/loader/src/services/winsock.rs | 73 +++++++++++++++++-------- crates/loader/tests/runtime_services.rs | 9 +++ 3 files changed, 61 insertions(+), 25 deletions(-) diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 59333c8f..4cfd9b9c 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -23,7 +23,7 @@ use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions}; use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; use std::time::Instant; const CURRENT_PROCESS: u64 = u64::MAX; @@ -172,6 +172,7 @@ pub struct ServicesState { objects: Mutex, last_errors: Mutex>, winsock: Mutex, + winsock_changed: Condvar, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, } @@ -187,6 +188,7 @@ impl ServicesState { objects: Mutex::new(ObjectState::default()), last_errors: Mutex::default(), winsock: Mutex::default(), + winsock_changed: Condvar::new(), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), } diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 287edcd2..674e9308 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -8,6 +8,7 @@ use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::GuestMemory; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; +use std::time::{Duration, Instant}; const MODULE: &str = "ws2_32.dll"; const VERSION: u16 = 0x0202; @@ -133,6 +134,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc net.refs -= 1; if net.refs == 0 { net.sockets.clear(); + cleanup.winsock_changed.notify_all(); } Ok(0) }); @@ -174,6 +176,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if net.sockets.remove(&args.rcx).is_none() { return close.fail(cpu.gs_base, WSAENOTSOCK, SOCKET_ERROR); } + close.winsock_changed.notify_all(); Ok(0) }); @@ -308,6 +311,7 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc) socket.peer = Some(requested); socket.pending.retain(|(source, _)| *source == requested); } + state.winsock_changed.notify_all(); Ok(0) })(); socket_result(&state, cpu.gs_base, result) @@ -347,6 +351,7 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc) return Err(WSAENOBUFS); } target.pending.push_back((source, data)); + send.winsock_changed.notify_all(); } Ok(length as u64) })(); @@ -379,6 +384,7 @@ fn register_loopback(registry: &mut ImportRegistry, state: &Arc) } let truncated = copied < data.len(); socket.pending.pop_front(); + recv.winsock_changed.notify_all(); if truncated { return Err(WSAEMSGSIZE); } @@ -473,6 +479,7 @@ fn register_socket_options(registry: &mut ImportRegistry, state: &Arc) { + const MAX_POLL_MS: i32 = 1_000; const POLLFD_SIZE: usize = 16; const POLLNVAL: u16 = 0x0004; const POLLWRNORM: u16 = 0x0010; @@ -485,8 +492,8 @@ fn register_poll(registry: &mut ImportRegistry, state: &Arc) { "WSAPoll", ServiceStatus::Partial, move |args, cpu, memory| { - let net = state.winsock.lock().expect("guest Winsock state"); let result = (|| { + let mut net = state.winsock.lock().expect("guest Winsock state"); if net.refs == 0 { return Err(WSANOTINITIALISED); } @@ -494,7 +501,8 @@ fn register_poll(registry: &mut ImportRegistry, state: &Arc) { if !(1..=MAX_SOCKETS).contains(&count) { return Err(WSAEINVAL); } - if args.r8 as u32 != 0 { + let timeout = args.r8 as i32; + if !(0..=MAX_POLL_MS).contains(&timeout) { return Err(WSAEOPNOTSUPP); } if args.rcx == 0 { @@ -505,32 +513,49 @@ fn register_poll(registry: &mut ImportRegistry, state: &Arc) { memory .read_bytes(args.rcx, descriptors) .map_err(|_| WSAEFAULT)?; - let mut ready = 0; - for fd in descriptors.as_chunks_mut::().0 { - let handle = u64::from_le_bytes(fd[..8].try_into().expect("socket handle")); - let events = u16::from_le_bytes([fd[8], fd[9]]); - if events & !(POLLWRNORM | POLLRDNORM | POLLRDBAND) != 0 { - return Err(WSAEINVAL); + memory + .check_write(args.rcx, descriptors.len()) + .map_err(|_| WSAEFAULT)?; + let deadline = Instant::now() + Duration::from_millis(timeout as u64); + let ready = loop { + if net.refs == 0 { + return Err(WSANOTINITIALISED); } - let mut result = POLLNVAL; - if let Some(socket) = net.sockets.get(&handle) { - result = 0; - if !socket.pending.is_empty() { - result |= events & POLLRDNORM; + let mut ready = 0; + for fd in descriptors.as_chunks_mut::().0 { + let handle = u64::from_le_bytes(fd[..8].try_into().expect("socket handle")); + let events = u16::from_le_bytes([fd[8], fd[9]]); + if events & !(POLLWRNORM | POLLRDNORM | POLLRDBAND) != 0 { + return Err(WSAEINVAL); } - if let Some(peer) = socket.peer - && !net.sockets.values().any(|target| { - target.port == Some(peer) - && target.peer.is_none_or(|port| Some(port) == socket.port) - && target.pending.len() == MAX_PENDING_DATAGRAMS - }) - { - result |= events & POLLWRNORM; + let mut result = POLLNVAL; + if let Some(socket) = net.sockets.get(&handle) { + result = 0; + if !socket.pending.is_empty() { + result |= events & POLLRDNORM; + } + if let Some(peer) = socket.peer + && !net.sockets.values().any(|target| { + target.port == Some(peer) + && target.peer.is_none_or(|port| Some(port) == socket.port) + && target.pending.len() == MAX_PENDING_DATAGRAMS + }) + { + result |= events & POLLWRNORM; + } } + fd[10..12].copy_from_slice(&result.to_le_bytes()); + ready += u64::from(result != 0); } - fd[10..12].copy_from_slice(&result.to_le_bytes()); - ready += u64::from(result != 0); - } + let remaining = deadline.saturating_duration_since(Instant::now()); + if ready != 0 || remaining.is_zero() { + break ready; + } + (net, _) = state + .winsock_changed + .wait_timeout(net, remaining) + .expect("guest Winsock state"); + }; memory .write_bytes(args.rcx, descriptors) .map_err(|_| WSAEFAULT)?; diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 2c72d2ce..8616549f 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -524,6 +524,15 @@ fn guest_udp_loopback_delivers_datagrams_through_bound_imports() { assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1); assert_eq!(memory.read_u16(poll + 10).unwrap(), 0); assert_eq!(memory.read_u16(poll + 26).unwrap(), 0x0010); + let started = std::time::Instant::now(); + assert_eq!(call(&mut memory, "WSAPoll", &[poll, 1, 10]), 0); + assert!(started.elapsed() >= std::time::Duration::from_millis(10)); + assert_eq!(memory.read_u16(poll + 10).unwrap(), 0); + assert_eq!( + call(&mut memory, "WSAPoll", &[poll, 1, 1001]), + u64::from(u32::MAX) + ); + assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10045); assert_eq!(call(&mut memory, "WSACleanup", &[]), 0); } From 88e7dad8b212def12b1c275c98b6c5c08a0f5885 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:40:20 -0500 Subject: [PATCH 50/82] Verify UDP polling wakes on a concurrent send Signed-off-by: Adeeb Rahman --- crates/loader/src/services/winsock.rs | 39 ++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 674e9308..46ff8c50 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -42,6 +42,8 @@ pub(super) struct Winsock { refs: u32, serial: u32, sockets: BTreeMap, + #[cfg(test)] + poll_waiters: usize, } #[derive(Default)] @@ -551,10 +553,18 @@ fn register_poll(registry: &mut ImportRegistry, state: &Arc) { if ready != 0 || remaining.is_zero() { break ready; } + #[cfg(test)] + { + net.poll_waiters += 1; + } (net, _) = state .winsock_changed .wait_timeout(net, remaining) .expect("guest Winsock state"); + #[cfg(test)] + { + net.poll_waiters -= 1; + } }; memory .write_bytes(args.rcx, descriptors) @@ -576,10 +586,8 @@ fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() { use crate::services::MockClock; let mut registry = ImportRegistry::new(); - register( - &mut registry, - &Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))), - ); + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + register(&mut registry, &state); let mut memory = GuestMemory::new(); memory .map_region(0x1000, 4096, MemoryPermissions::READ_WRITE) @@ -654,4 +662,27 @@ fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() { call(&mut memory, "WSAGetLastError", &[]), u64::from(WSAEWOULDBLOCK) ); + + let mut polling_memory = memory.clone(); + polling_memory.write_u64(0x1500, server).unwrap(); + polling_memory.write_u16(0x1508, 0x0100).unwrap(); + std::thread::scope(|scope| { + let (finished, completion) = std::sync::mpsc::channel(); + let polling_memory = &mut polling_memory; + scope.spawn(move || { + let ready = call(polling_memory, "WSAPoll", &[0x1500, 1, 1000]); + finished.send(ready).unwrap(); + }); + let deadline = Instant::now() + Duration::from_millis(500); + while state.winsock.lock().unwrap().poll_waiters == 0 { + assert!(Instant::now() < deadline, "poll did not enter its wait"); + std::thread::yield_now(); + } + assert_eq!(call(&mut memory, "send", &[client, 0x1300, 5, 0]), 5); + assert_eq!( + completion.recv_timeout(Duration::from_millis(400)).unwrap(), + 1 + ); + }); + assert_eq!(polling_memory.read_u16(0x150a).unwrap(), 0x0100); } From 9e2c7b6e0bc515de4c6a1182283aa6304f2542ed Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:41:17 -0500 Subject: [PATCH 51/82] Add bounded manual work and completion ports for runtime tasks Signed-off-by: Adeeb Rahman --- crates/loader/src/lib.rs | 1 + crates/loader/src/tasks.rs | 181 +++++++++++++++++++++++++++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 crates/loader/src/tasks.rs diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs index 6449b9c6..7b966836 100644 --- a/crates/loader/src/lib.rs +++ b/crates/loader/src/lib.rs @@ -22,6 +22,7 @@ pub mod runtime_table; pub mod services; pub mod softfloat; pub mod startup; +pub mod tasks; pub mod tls; pub mod triage; pub mod x86_decode; diff --git a/crates/loader/src/tasks.rs b/crates/loader/src/tasks.rs new file mode 100644 index 00000000..2a7bb718 --- /dev/null +++ b/crates/loader/src/tasks.rs @@ -0,0 +1,181 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Bounded manual work and completion ports for synthetic runtime services. +//! The caller supplies monotonic time, allowing deterministic dispatch in tests. + +use std::collections::VecDeque; +use std::time::Duration; + +/// Identifier issued by a task queue and never reused within that queue. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct TaskId(u64); + +/// Why the queue could not accept a task. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SubmitError { + Full, + IdExhausted, +} + +/// Result delivered once through the completion port. +#[derive(Debug, PartialEq, Eq)] +pub enum TaskResult { + Finished(Result), + Cancelled, + TimedOut, +} + +type Work = Box Result + Send>; +type Callback = Box) + Send>; + +struct Pending { + id: TaskId, + deadline: Option, + work: Work, + callback: Callback, +} + +struct Completion { + id: TaskId, + result: TaskResult, + callback: Callback, +} + +/// A manual task queue whose capacity covers pending work and undelivered completions. +pub struct TaskQueue { + capacity: usize, + last_id: u64, + pending: VecDeque>, + completions: VecDeque>, +} + +impl TaskQueue { + pub fn new(capacity: usize) -> Self { + Self { + capacity, + last_id: 0, + pending: VecDeque::new(), + completions: VecDeque::new(), + } + } + + /// Enqueue work and a completion callback. The deadline uses the same clock as dispatch. + pub fn submit( + &mut self, + deadline: Option, + work: impl FnOnce() -> Result + Send + 'static, + callback: impl FnOnce(TaskId, TaskResult) + Send + 'static, + ) -> Result { + if self.pending.len() + self.completions.len() >= self.capacity { + return Err(SubmitError::Full); + } + self.last_id = self + .last_id + .checked_add(1) + .ok_or(SubmitError::IdExhausted)?; + let id = TaskId(self.last_id); + self.pending.push_back(Pending { + id, + deadline, + work: Box::new(work), + callback: Box::new(callback), + }); + Ok(id) + } + + /// Cancel work that is still queued. The completion port still receives its callback. + pub fn cancel(&mut self, id: TaskId) -> bool { + let Some(index) = self.pending.iter().position(|task| task.id == id) else { + return false; + }; + let task = self + .pending + .remove(index) + .expect("position in pending queue"); + self.completions.push_back(Completion { + id, + result: TaskResult::Cancelled, + callback: task.callback, + }); + true + } + + /// Run one queued operation. An expired operation completes without running. + pub fn dispatch_work(&mut self, now: Duration) -> bool { + let Some(task) = self.pending.pop_front() else { + return false; + }; + let result = if task.deadline.is_some_and(|deadline| now >= deadline) { + TaskResult::TimedOut + } else { + TaskResult::Finished((task.work)()) + }; + self.completions.push_back(Completion { + id: task.id, + result, + callback: task.callback, + }); + true + } + + /// Invoke one callback on the caller's thread. + pub fn dispatch_completion(&mut self) -> bool { + let Some(completion) = self.completions.pop_front() else { + return false; + }; + (completion.callback)(completion.id, completion.result); + true + } +} + +#[cfg(test)] +#[test] +fn manual_ports_deliver_errors_cancellation_and_deadlines_once() { + use std::sync::mpsc::channel; + + let mut queue = TaskQueue::::new(3); + let (sender, receiver) = channel(); + let callback = || { + let sender = sender.clone(); + move |id, result| sender.send((id, result)).unwrap() + }; + let first = queue.submit(None, || Err(7), callback()).unwrap(); + let cancelled = queue + .submit(None, || panic!("cancelled"), callback()) + .unwrap(); + let deadline = Duration::from_millis(10); + let expired = queue + .submit(Some(deadline), || panic!("expired"), callback()) + .unwrap(); + assert_eq!( + queue.submit(None, || Ok(1), callback()), + Err(SubmitError::Full) + ); + assert!(queue.cancel(cancelled)); + assert!(!queue.cancel(cancelled)); + assert!(queue.dispatch_work(Duration::ZERO)); + assert!(queue.dispatch_work(deadline)); + assert!(!queue.dispatch_work(deadline)); + assert_eq!( + queue.submit(None, || Ok(1), callback()), + Err(SubmitError::Full) + ); + assert!(receiver.try_recv().is_err()); + for expected in [ + (cancelled, TaskResult::Cancelled), + (first, TaskResult::Finished(Err(7))), + (expired, TaskResult::TimedOut), + ] { + assert!(queue.dispatch_completion()); + assert_eq!(receiver.try_recv().unwrap(), expected); + } + assert!(!queue.dispatch_completion()); + let next = queue.submit(None, || Ok(1), callback()).unwrap(); + assert_ne!(next, first); + assert!(queue.dispatch_work(deadline)); + assert!(queue.dispatch_completion()); + assert_eq!( + receiver.try_recv().unwrap(), + (next, TaskResult::Finished(Ok(1))) + ); +} From ed33b57c8dfb7cec4137a0081ce278371c87e254 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:42:27 -0500 Subject: [PATCH 52/82] Exercise manual asynchronous tasks through original guest services Signed-off-by: Adeeb Rahman --- crates/loader/src/services.rs | 4 + crates/loader/src/services/task_fixture.rs | 97 ++++++++++++++++++++++ crates/loader/src/tasks.rs | 10 +++ crates/loader/tests/runtime_x15.rs | 41 +++++++++ 4 files changed, 152 insertions(+) create mode 100644 crates/loader/src/services/task_fixture.rs diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 4cfd9b9c..15fa7fcb 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -14,6 +14,7 @@ mod events; mod files; mod heap; mod modules; +mod task_fixture; mod winsock; use crate::runtime::HResult; @@ -172,6 +173,7 @@ pub struct ServicesState { objects: Mutex, last_errors: Mutex>, winsock: Mutex, + task_fixture: Mutex, winsock_changed: Condvar, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, @@ -188,6 +190,7 @@ impl ServicesState { objects: Mutex::new(ObjectState::default()), last_errors: Mutex::default(), winsock: Mutex::default(), + task_fixture: Mutex::default(), winsock_changed: Condvar::new(), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), @@ -545,6 +548,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc)>; + +pub(super) struct TaskFixture { + queue: TaskQueue, + delivered: Arc>, +} + +impl Default for TaskFixture { + fn default() -> Self { + Self { + queue: TaskQueue::new(16), + delivered: Arc::default(), + } + } +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + let submit = Arc::clone(state); + registry.register(MODULE, "SubmitFixtureTask", move |args, cpu, _| { + let input = args.rcx; + let now = Duration::from_millis(submit.uptime_millis()); + let deadline = (args.rdx != 0).then(|| now + Duration::from_millis(args.rdx)); + let mut tasks = submit.task_fixture.lock().expect("fixture task queue"); + let delivered = Arc::clone(&tasks.delivered); + match tasks.queue.submit( + deadline, + move || input.checked_mul(input).ok_or(ERROR_INVALID_PARAMETER), + move |id, result| { + *delivered.lock().expect("fixture task completion") = Some((id, result)); + }, + ) { + Ok(id) => Ok(id.raw()), + Err(_) => submit.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0), + } + }); + + let cancel = Arc::clone(state); + registry.register(MODULE, "CancelFixtureTask", move |args, _, _| { + let mut tasks = cancel.task_fixture.lock().expect("fixture task queue"); + Ok(u64::from(tasks.queue.cancel(TaskId::from_raw(args.rcx)))) + }); + + let work = Arc::clone(state); + registry.register(MODULE, "DispatchFixtureWork", move |_, _, _| { + let now = Duration::from_millis(work.uptime_millis()); + let mut tasks = work.task_fixture.lock().expect("fixture task queue"); + Ok(u64::from(tasks.queue.dispatch_work(now))) + }); + + let completion = Arc::clone(state); + registry.register( + MODULE, + "DispatchFixtureCompletion", + move |args, cpu, memory| { + if args.rcx == 0 || memory.check_write(args.rcx, COMPLETION_SIZE).is_err() { + return completion.fail(cpu.gs_base, ERROR_NOACCESS, 0); + } + let mut tasks = completion.task_fixture.lock().expect("fixture task queue"); + if !tasks.queue.dispatch_completion() { + return Ok(0); + } + let (id, result) = tasks + .delivered + .lock() + .expect("fixture task completion") + .take() + .expect("dispatch delivers a completion"); + let (status, value): (u32, u64) = match result { + TaskResult::Finished(Ok(value)) => (0, value), + TaskResult::Finished(Err(error)) => (error, 0), + TaskResult::Cancelled => (995, 0), + TaskResult::TimedOut => (1460, 0), + }; + let mut record = [0; COMPLETION_SIZE]; + record[..8].copy_from_slice(&id.raw().to_le_bytes()); + record[8..12].copy_from_slice(&status.to_le_bytes()); + record[16..24].copy_from_slice(&value.to_le_bytes()); + memory + .write_bytes(args.rcx, &record) + .map_err(crate::cpu::ExitReason::MemoryFault)?; + Ok(1) + }, + ); +} diff --git a/crates/loader/src/tasks.rs b/crates/loader/src/tasks.rs index 2a7bb718..0a17d918 100644 --- a/crates/loader/src/tasks.rs +++ b/crates/loader/src/tasks.rs @@ -10,6 +10,16 @@ use std::time::Duration; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TaskId(u64); +impl TaskId { + pub(crate) fn from_raw(raw: u64) -> Self { + Self(raw) + } + + pub(crate) fn raw(self) -> u64 { + self.0 + } +} + /// Why the queue could not accept a task. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SubmitError { diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index f3652b3b..7d6fb02b 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,47 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn guest_manual_tasks_deliver_results_once_through_imports() { + let clock = Arc::new(MockClock::new(0)); + let state = Arc::new(ServicesState::new(clock.clone())); + let call = |symbol, args: &[u64]| { + let result = call_service_fixture(&state, "xenora_fixture.dll", symbol, args); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result + }; + let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); + let first = value("SubmitFixtureTask", &[7, 0]); + let cancelled = value("SubmitFixtureTask", &[8, 0]); + let expired = value("SubmitFixtureTask", &[9, 1]); + let failed = value("SubmitFixtureTask", &[u64::MAX, 0]); + assert!(0 < first && first < cancelled && cancelled < expired && expired < failed); + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + assert_eq!(value("DispatchFixtureCompletion", &[output]), 0); + assert_eq!(value("CancelFixtureTask", &[cancelled]), 1); + assert_eq!(value("CancelFixtureTask", &[cancelled]), 0); + clock.advance(10_000); + for _ in 0..3 { + assert_eq!(value("DispatchFixtureWork", &[]), 1); + } + assert_eq!(value("DispatchFixtureWork", &[]), 0); + assert_eq!(value("DispatchFixtureCompletion", &[0]), 0); + for (id, status, expected_value) in [ + (cancelled, 995, 0), + (first, 0, 49), + (expired, 1460, 0), + (failed, 87, 0), + ] { + let result = call("DispatchFixtureCompletion", &[output]); + assert_eq!(result.execution.final_state.get(Register::Rax), 1); + let memory = result.image.memory; + assert_eq!(memory.read_u64(output).unwrap(), id); + assert_eq!(memory.read_u32(output + 8).unwrap(), status); + assert_eq!(memory.read_u64(output + 16).unwrap(), expected_value); + } + assert_eq!(value("DispatchFixtureCompletion", &[output]), 0); +} + #[test] fn guest_winsock_lifecycle_balances_startup_and_invalidates_sockets() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); From 565c144a39821f9afa721b01b87f28a8cb6dc5e9 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:43:38 -0500 Subject: [PATCH 53/82] Run runtime tasks on a managed background worker Signed-off-by: Adeeb Rahman --- crates/loader/src/services/task_fixture.rs | 11 ++ crates/loader/src/tasks.rs | 115 ++++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 16 +++ 3 files changed, 141 insertions(+), 1 deletion(-) diff --git a/crates/loader/src/services/task_fixture.rs b/crates/loader/src/services/task_fixture.rs index 5e0db50c..75601385 100644 --- a/crates/loader/src/services/task_fixture.rs +++ b/crates/loader/src/services/task_fixture.rs @@ -60,6 +60,16 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(u64::from(tasks.queue.dispatch_work(now))) }); + let background = Arc::clone(state); + registry.register(MODULE, "DispatchFixtureBackground", move |_, cpu, _| { + let now = Duration::from_millis(background.uptime_millis()); + let mut tasks = background.task_fixture.lock().expect("fixture task queue"); + match tasks.queue.dispatch_background(now) { + Ok(started) => Ok(u64::from(started)), + Err(_) => background.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0), + } + }); + let completion = Arc::clone(state); registry.register( MODULE, @@ -83,6 +93,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc TaskResult::Finished(Err(error)) => (error, 0), TaskResult::Cancelled => (995, 0), TaskResult::TimedOut => (1460, 0), + TaskResult::WorkerPanicked => (31, 0), }; let mut record = [0; COMPLETION_SIZE]; record[..8].copy_from_slice(&id.raw().to_le_bytes()); diff --git a/crates/loader/src/tasks.rs b/crates/loader/src/tasks.rs index 0a17d918..4fc7d138 100644 --- a/crates/loader/src/tasks.rs +++ b/crates/loader/src/tasks.rs @@ -4,6 +4,7 @@ //! The caller supplies monotonic time, allowing deterministic dispatch in tests. use std::collections::VecDeque; +use std::thread::JoinHandle; use std::time::Duration; /// Identifier issued by a task queue and never reused within that queue. @@ -33,6 +34,7 @@ pub enum TaskResult { Finished(Result), Cancelled, TimedOut, + WorkerPanicked, } type Work = Box Result + Send>; @@ -51,12 +53,19 @@ struct Completion { callback: Callback, } +struct Worker { + id: TaskId, + callback: Callback, + thread: JoinHandle>, +} + /// A manual task queue whose capacity covers pending work and undelivered completions. pub struct TaskQueue { capacity: usize, last_id: u64, pending: VecDeque>, completions: VecDeque>, + worker: Option>, } impl TaskQueue { @@ -66,6 +75,7 @@ impl TaskQueue { last_id: 0, pending: VecDeque::new(), completions: VecDeque::new(), + worker: None, } } @@ -76,7 +86,9 @@ impl TaskQueue { work: impl FnOnce() -> Result + Send + 'static, callback: impl FnOnce(TaskId, TaskResult) + Send + 'static, ) -> Result { - if self.pending.len() + self.completions.len() >= self.capacity { + if self.pending.len() + self.completions.len() + usize::from(self.worker.is_some()) + >= self.capacity + { return Err(SubmitError::Full); } self.last_id = self @@ -112,6 +124,10 @@ impl TaskQueue { /// Run one queued operation. An expired operation completes without running. pub fn dispatch_work(&mut self, now: Duration) -> bool { + self.collect_worker(); + if self.worker.is_some() { + return false; + } let Some(task) = self.pending.pop_front() else { return false; }; @@ -130,12 +146,109 @@ impl TaskQueue { /// Invoke one callback on the caller's thread. pub fn dispatch_completion(&mut self) -> bool { + self.collect_worker(); let Some(completion) = self.completions.pop_front() else { return false; }; (completion.callback)(completion.id, completion.result); true } + + fn collect_worker(&mut self) { + if self + .worker + .as_ref() + .is_some_and(|worker| worker.thread.is_finished()) + { + let worker = self.worker.take().expect("finished worker"); + let result = worker + .thread + .join() + .map_or(TaskResult::WorkerPanicked, TaskResult::Finished); + self.completions.push_back(Completion { + id: worker.id, + result, + callback: worker.callback, + }); + } + } +} + +impl TaskQueue { + /// Start one background operation. At most one worker runs per queue. + pub fn dispatch_background(&mut self, now: Duration) -> std::io::Result { + self.collect_worker(); + if self.worker.is_some() { + return Ok(false); + } + let Some(task) = self.pending.front() else { + return Ok(false); + }; + if task.deadline.is_some_and(|deadline| now >= deadline) { + return Ok(self.dispatch_work(now)); + } + let (send, receive) = std::sync::mpsc::channel::>(); + // Start the thread before removing the task so spawn failure leaves it queued. + let thread = std::thread::Builder::new() + .name("xenora-task".into()) + .spawn(move || receive.recv().expect("worker receives one operation")())?; + let task = self.pending.pop_front().expect("pending task"); + assert!(send.send(task.work).is_ok()); + self.worker = Some(Worker { + id: task.id, + callback: task.callback, + thread, + }); + Ok(true) + } +} + +impl Drop for TaskQueue { + fn drop(&mut self) { + if let Some(worker) = self.worker.take() { + let _ = worker.thread.join(); + } + } +} + +#[cfg(test)] +#[test] +fn background_worker_preserves_capacity_and_manual_completion() { + use std::sync::mpsc::channel; + use std::time::Instant; + + let mut queue = TaskQueue::::new(1); + let (release, gate) = channel(); + let (completed, results) = channel(); + let id = queue + .submit( + None, + move || { + gate.recv_timeout(Duration::from_secs(2)).unwrap(); + Ok(17) + }, + move |id, result| completed.send((id, result)).unwrap(), + ) + .unwrap(); + assert!(queue.dispatch_background(Duration::ZERO).unwrap()); + assert!(!queue.dispatch_background(Duration::ZERO).unwrap()); + assert!(!queue.cancel(id)); + assert!(!queue.dispatch_completion()); + assert_eq!( + queue.submit(None, || Ok(0), |_, _| {}), + Err(SubmitError::Full) + ); + release.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while !queue.dispatch_completion() { + assert!(Instant::now() < deadline, "worker did not complete"); + std::thread::yield_now(); + } + assert_eq!( + results.try_recv().unwrap(), + (id, TaskResult::Finished(Ok(17))) + ); + assert!(!queue.dispatch_completion()); } #[cfg(test)] diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 7d6fb02b..4f8dc1e5 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1160,6 +1160,22 @@ fn guest_manual_tasks_deliver_results_once_through_imports() { assert_eq!(memory.read_u64(output + 16).unwrap(), expected_value); } assert_eq!(value("DispatchFixtureCompletion", &[output]), 0); + let background = value("SubmitFixtureTask", &[11, 0]); + assert_eq!(value("DispatchFixtureBackground", &[]), 1); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + loop { + let result = call("DispatchFixtureCompletion", &[output]); + if result.execution.final_state.get(Register::Rax) == 1 { + assert_eq!(result.image.memory.read_u64(output).unwrap(), background); + assert_eq!(result.image.memory.read_u64(output + 16).unwrap(), 121); + break; + } + assert!( + std::time::Instant::now() < deadline, + "guest worker did not complete" + ); + std::thread::yield_now(); + } } #[test] From aa93665b97a1c9795ce6b710fa49a0086613d767 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:44:37 -0500 Subject: [PATCH 54/82] Allow cooperative cancellation of running runtime tasks Signed-off-by: Adeeb Rahman --- crates/loader/src/tasks.rs | 123 ++++++++++++++++++++++++++++++++++--- 1 file changed, 116 insertions(+), 7 deletions(-) diff --git a/crates/loader/src/tasks.rs b/crates/loader/src/tasks.rs index 4fc7d138..3738d2df 100644 --- a/crates/loader/src/tasks.rs +++ b/crates/loader/src/tasks.rs @@ -4,6 +4,8 @@ //! The caller supplies monotonic time, allowing deterministic dispatch in tests. use std::collections::VecDeque; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::thread::JoinHandle; use std::time::Duration; @@ -40,11 +42,26 @@ pub enum TaskResult { type Work = Box Result + Send>; type Callback = Box) + Send>; +/// A cancellation request that a running operation can observe at safe points. +#[derive(Clone, Default)] +pub struct CancellationToken(Arc); + +impl CancellationToken { + pub fn is_cancelled(&self) -> bool { + self.0.load(Ordering::Acquire) + } + + fn request(&self) -> bool { + !self.0.swap(true, Ordering::AcqRel) + } +} + struct Pending { id: TaskId, deadline: Option, work: Work, callback: Callback, + cancellation: Option, } struct Completion { @@ -57,6 +74,7 @@ struct Worker { id: TaskId, callback: Callback, thread: JoinHandle>, + cancellation: Option, } /// A manual task queue whose capacity covers pending work and undelivered completions. @@ -85,6 +103,35 @@ impl TaskQueue { deadline: Option, work: impl FnOnce() -> Result + Send + 'static, callback: impl FnOnce(TaskId, TaskResult) + Send + 'static, + ) -> Result { + self.enqueue(deadline, Box::new(work), Box::new(callback), None) + } + + /// Enqueue work that can observe a request received while it is running. + pub fn submit_cancellable( + &mut self, + deadline: Option, + work: impl FnOnce(CancellationToken) -> Result + Send + 'static, + callback: impl FnOnce(TaskId, TaskResult) + Send + 'static, + ) -> Result { + let token = CancellationToken::default(); + self.enqueue( + deadline, + Box::new({ + let token = token.clone(); + move || work(token) + }), + Box::new(callback), + Some(token), + ) + } + + fn enqueue( + &mut self, + deadline: Option, + work: Work, + callback: Callback, + cancellation: Option, ) -> Result { if self.pending.len() + self.completions.len() + usize::from(self.worker.is_some()) >= self.capacity @@ -99,14 +146,24 @@ impl TaskQueue { self.pending.push_back(Pending { id, deadline, - work: Box::new(work), - callback: Box::new(callback), + work, + callback, + cancellation, }); Ok(id) } - /// Cancel work that is still queued. The completion port still receives its callback. + /// Cancel queued work or request cooperative cancellation of an active worker. pub fn cancel(&mut self, id: TaskId) -> bool { + self.collect_worker(); + if let Some(worker) = &self.worker + && worker.id == id + { + return worker + .cancellation + .as_ref() + .is_some_and(CancellationToken::request); + } let Some(index) = self.pending.iter().position(|task| task.id == id) else { return false; }; @@ -161,10 +218,18 @@ impl TaskQueue { .is_some_and(|worker| worker.thread.is_finished()) { let worker = self.worker.take().expect("finished worker"); - let result = worker - .thread - .join() - .map_or(TaskResult::WorkerPanicked, TaskResult::Finished); + let result = match worker.thread.join() { + Err(_) => TaskResult::WorkerPanicked, + Ok(_) + if worker + .cancellation + .as_ref() + .is_some_and(CancellationToken::is_cancelled) => + { + TaskResult::Cancelled + } + Ok(result) => TaskResult::Finished(result), + }; self.completions.push_back(Completion { id: worker.id, result, @@ -198,6 +263,7 @@ impl TaskQueue { id: task.id, callback: task.callback, thread, + cancellation: task.cancellation, }); Ok(true) } @@ -206,11 +272,54 @@ impl TaskQueue { impl Drop for TaskQueue { fn drop(&mut self) { if let Some(worker) = self.worker.take() { + if let Some(token) = worker.cancellation { + token.request(); + } let _ = worker.thread.join(); } } } +#[cfg(test)] +#[test] +fn running_task_observes_cancellation_before_completion() { + use std::sync::mpsc::channel; + use std::time::Instant; + + let mut queue = TaskQueue::::new(1); + let (running, started) = channel(); + let (completed, results) = channel(); + let id = queue + .submit_cancellable( + None, + move |token| { + running.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while !token.is_cancelled() { + assert!( + Instant::now() < deadline, + "work did not observe cancellation" + ); + std::thread::yield_now(); + } + Ok(17) + }, + move |id, result| completed.send((id, result)).unwrap(), + ) + .unwrap(); + assert!(queue.dispatch_background(Duration::ZERO).unwrap()); + started.recv_timeout(Duration::from_secs(2)).unwrap(); + assert!(queue.cancel(id)); + assert!(!queue.cancel(id)); + let deadline = Instant::now() + Duration::from_secs(2); + while !queue.dispatch_completion() { + assert!(Instant::now() < deadline, "worker did not complete"); + std::thread::yield_now(); + } + assert_eq!(results.try_recv().unwrap(), (id, TaskResult::Cancelled)); + assert!(!queue.dispatch_completion()); +} + #[cfg(test)] #[test] fn background_worker_preserves_capacity_and_manual_completion() { From 0b6ab43ad44d102c1d924a26e7860aed22f871a4 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:45:32 -0500 Subject: [PATCH 55/82] Apply task deadlines to cooperative background work Signed-off-by: Adeeb Rahman --- crates/loader/src/services/task_fixture.rs | 12 ++- crates/loader/src/tasks.rs | 105 ++++++++++++++------- 2 files changed, 82 insertions(+), 35 deletions(-) diff --git a/crates/loader/src/services/task_fixture.rs b/crates/loader/src/services/task_fixture.rs index 75601385..a57e8977 100644 --- a/crates/loader/src/services/task_fixture.rs +++ b/crates/loader/src/services/task_fixture.rs @@ -35,9 +35,14 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let deadline = (args.rdx != 0).then(|| now + Duration::from_millis(args.rdx)); let mut tasks = submit.task_fixture.lock().expect("fixture task queue"); let delivered = Arc::clone(&tasks.delivered); - match tasks.queue.submit( + match tasks.queue.submit_cancellable( deadline, - move || input.checked_mul(input).ok_or(ERROR_INVALID_PARAMETER), + move |token| { + if token.is_cancelled() { + return Err(995); + } + input.checked_mul(input).ok_or(ERROR_INVALID_PARAMETER) + }, move |id, result| { *delivered.lock().expect("fixture task completion") = Some((id, result)); }, @@ -79,6 +84,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc return completion.fail(cpu.gs_base, ERROR_NOACCESS, 0); } let mut tasks = completion.task_fixture.lock().expect("fixture task queue"); + tasks + .queue + .advance_time(Duration::from_millis(completion.uptime_millis())); if !tasks.queue.dispatch_completion() { return Ok(0); } diff --git a/crates/loader/src/tasks.rs b/crates/loader/src/tasks.rs index 3738d2df..7f92b28b 100644 --- a/crates/loader/src/tasks.rs +++ b/crates/loader/src/tasks.rs @@ -75,6 +75,8 @@ struct Worker { callback: Callback, thread: JoinHandle>, cancellation: Option, + deadline: Option, + timed_out: bool, } /// A manual task queue whose capacity covers pending work and undelivered completions. @@ -181,7 +183,7 @@ impl TaskQueue { /// Run one queued operation. An expired operation completes without running. pub fn dispatch_work(&mut self, now: Duration) -> bool { - self.collect_worker(); + self.advance_time(now); if self.worker.is_some() { return false; } @@ -211,6 +213,21 @@ impl TaskQueue { true } + /// Advance the queue's clock and request cooperative exit from expired work. + /// A completion already available when the clock is sampled keeps its result. + pub fn advance_time(&mut self, now: Duration) { + self.collect_worker(); + if let Some(worker) = &mut self.worker + && worker.deadline.is_some_and(|deadline| now >= deadline) + && worker + .cancellation + .as_ref() + .is_some_and(CancellationToken::request) + { + worker.timed_out = true; + } + } + fn collect_worker(&mut self) { if self .worker @@ -220,6 +237,7 @@ impl TaskQueue { let worker = self.worker.take().expect("finished worker"); let result = match worker.thread.join() { Err(_) => TaskResult::WorkerPanicked, + Ok(_) if worker.timed_out => TaskResult::TimedOut, Ok(_) if worker .cancellation @@ -242,7 +260,7 @@ impl TaskQueue { impl TaskQueue { /// Start one background operation. At most one worker runs per queue. pub fn dispatch_background(&mut self, now: Duration) -> std::io::Result { - self.collect_worker(); + self.advance_time(now); if self.worker.is_some() { return Ok(false); } @@ -264,6 +282,8 @@ impl TaskQueue { callback: task.callback, thread, cancellation: task.cancellation, + deadline: task.deadline, + timed_out: false, }); Ok(true) } @@ -282,42 +302,61 @@ impl Drop for TaskQueue { #[cfg(test)] #[test] -fn running_task_observes_cancellation_before_completion() { +fn running_task_observes_cancellation_and_deadlines_before_completion() { use std::sync::mpsc::channel; use std::time::Instant; - let mut queue = TaskQueue::::new(1); - let (running, started) = channel(); - let (completed, results) = channel(); - let id = queue - .submit_cancellable( - None, - move |token| { - running.send(()).unwrap(); - let deadline = Instant::now() + Duration::from_secs(2); - while !token.is_cancelled() { - assert!( - Instant::now() < deadline, - "work did not observe cancellation" - ); - std::thread::yield_now(); + let timeout = Duration::from_millis(5); + for expire in [false, true] { + let mut queue = TaskQueue::::new(1); + let (running, started) = channel(); + let (completed, results) = channel(); + let id = queue + .submit_cancellable( + Some(timeout), + move |token| { + running.send(()).unwrap(); + let deadline = Instant::now() + Duration::from_secs(2); + while !token.is_cancelled() { + assert!( + Instant::now() < deadline, + "work did not observe cancellation" + ); + std::thread::yield_now(); + } + Ok(17) + }, + move |id, result| completed.send((id, result)).unwrap(), + ) + .unwrap(); + assert!(queue.dispatch_background(Duration::ZERO).unwrap()); + started.recv_timeout(Duration::from_secs(2)).unwrap(); + if expire { + queue.advance_time(timeout - Duration::from_millis(1)); + assert!(!queue.dispatch_completion()); + queue.advance_time(timeout); + } else { + assert!(queue.cancel(id)); + } + assert!(!queue.cancel(id)); + let deadline = Instant::now() + Duration::from_secs(2); + while !queue.dispatch_completion() { + assert!(Instant::now() < deadline, "worker did not complete"); + std::thread::yield_now(); + } + assert_eq!( + results.try_recv().unwrap(), + ( + id, + if expire { + TaskResult::TimedOut + } else { + TaskResult::Cancelled } - Ok(17) - }, - move |id, result| completed.send((id, result)).unwrap(), - ) - .unwrap(); - assert!(queue.dispatch_background(Duration::ZERO).unwrap()); - started.recv_timeout(Duration::from_secs(2)).unwrap(); - assert!(queue.cancel(id)); - assert!(!queue.cancel(id)); - let deadline = Instant::now() + Duration::from_secs(2); - while !queue.dispatch_completion() { - assert!(Instant::now() < deadline, "worker did not complete"); - std::thread::yield_now(); + ) + ); + assert!(!queue.dispatch_completion()); } - assert_eq!(results.try_recv().unwrap(), (id, TaskResult::Cancelled)); - assert!(!queue.dispatch_completion()); } #[cfg(test)] From f6c87de4330d7a3b4dc72fcbb3975e5bb6895fcb Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:46:45 -0500 Subject: [PATCH 56/82] Add manual GDK task queue handle ownership Signed-off-by: Adeeb Rahman --- crates/loader/src/services.rs | 4 + crates/loader/src/services/gdk_queue.rs | 103 ++++++++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 35 ++++++++ 3 files changed, 142 insertions(+) create mode 100644 crates/loader/src/services/gdk_queue.rs diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 15fa7fcb..f30b4412 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -12,6 +12,7 @@ mod crt; mod events; mod files; +mod gdk_queue; mod heap; mod modules; mod task_fixture; @@ -174,6 +175,7 @@ pub struct ServicesState { last_errors: Mutex>, winsock: Mutex, task_fixture: Mutex, + gdk_queues: Mutex, winsock_changed: Condvar, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, @@ -191,6 +193,7 @@ impl ServicesState { last_errors: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), + gdk_queues: Mutex::default(), winsock_changed: Condvar::new(), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), @@ -549,6 +552,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc, +} + +impl QueueHandles { + fn open( + &mut self, + object: Option, + output: u64, + memory: &mut GuestMemory, + ) -> Result<(), u32> { + if output == 0 { + return Err(ERROR_INVALID_PARAMETER); + } + if self.queues.len() == MAX_HANDLES { + return Err(ERROR_OUTOFMEMORY); + } + let next = self + .last_id + .checked_add(1) + .filter(|id| *id < (1 << 48)) + .ok_or(ERROR_OUTOFMEMORY)?; + let handle = 0x5144_0000_0000_0000 | next; + memory + .write_u64(output, handle) + .map_err(|_| ERROR_INVALID_PARAMETER)?; + self.last_id = next; + self.queues.insert(handle, object.unwrap_or(handle)); + Ok(()) + } +} + +fn guest_hresult(result: Result<(), u32>) -> u64 { + match result { + Ok(()) => HResult::OK.guest_return(), + Err(error) => HResult::from_win32(error).guest_return(), + } +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + let create = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueCreate", + ServiceStatus::Partial, + move |args, _, memory| { + if args.rcx as u32 != MANUAL || args.rdx as u32 != MANUAL { + return Ok(guest_hresult(Err(ERROR_NOT_SUPPORTED))); + } + let mut queues = create.gdk_queues.lock().expect("GDK queue handle table"); + Ok(guest_hresult(queues.open(None, args.r8, memory))) + }, + ); + + let duplicate = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueDuplicateHandle", + ServiceStatus::Partial, + move |args, _, memory| { + let mut queues = duplicate.gdk_queues.lock().expect("GDK queue handle table"); + let Some(&object) = queues.queues.get(&args.rcx) else { + return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE))); + }; + Ok(guest_hresult(queues.open(Some(object), args.rdx, memory))) + }, + ); + + let close = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueCloseHandle", + ServiceStatus::Partial, + move |args, _, _| { + close + .gdk_queues + .lock() + .expect("GDK queue handle table") + .queues + .remove(&args.rcx); + Ok(0) + }, + ); +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 4f8dc1e5..c60ccfe7 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,41 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn guest_gdk_manual_queue_handles_have_independent_lifetimes() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |symbol, args: &[u64]| { + let result = call_service_fixture(&state, "xgameruntime.dll", symbol, args); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + result + }; + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + let rejected = call("XTaskQueueCreate", &[1, 0, output]); + assert_eq!( + rejected.execution.final_state.get(Register::Rax), + 0x8007_0032 + ); + assert_eq!(rejected.image.memory.read_u64(output).unwrap(), 0); + let open = |symbol, args: &[u64]| { + let result = call(symbol, args); + assert_eq!(result.execution.final_state.get(Register::Rax), 0); + result.image.memory.read_u64(output).unwrap() + }; + let first = open("XTaskQueueCreate", &[0, 0, output]); + let second = open("XTaskQueueDuplicateHandle", &[first, output]); + assert_ne!(first, second); + call("XTaskQueueCloseHandle", &[first]); + let stale = call("XTaskQueueDuplicateHandle", &[first, output]); + assert_eq!(stale.execution.final_state.get(Register::Rax), 0x8007_0006); + assert_eq!(stale.image.memory.read_u64(output).unwrap(), 0); + let third = open("XTaskQueueDuplicateHandle", &[second, output]); + assert!(third > second); + call("XTaskQueueCloseHandle", &[second]); + call("XTaskQueueCloseHandle", &[third]); + let next = open("XTaskQueueCreate", &[0, 0, output]); + assert!(next > third); +} + #[test] fn guest_manual_tasks_deliver_results_once_through_imports() { let clock = Arc::new(MockClock::new(0)); From 4b370efa12fabf4be61b0bc91eaa8f88c2d46297 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:47:43 -0500 Subject: [PATCH 57/82] Expose shared ports for manual GDK composite queues Signed-off-by: Adeeb Rahman --- crates/loader/src/services/gdk_queue.rs | 50 +++++++++++++++++++++++-- crates/loader/tests/runtime_x15.rs | 11 ++++++ 2 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/loader/src/services/gdk_queue.rs b/crates/loader/src/services/gdk_queue.rs index 8ba1b8a0..d4b8b744 100644 --- a/crates/loader/src/services/gdk_queue.rs +++ b/crates/loader/src/services/gdk_queue.rs @@ -18,13 +18,13 @@ const MANUAL: u32 = 0; #[derive(Default)] pub(super) struct QueueHandles { last_id: u64, - queues: BTreeMap, + queues: BTreeMap, } impl QueueHandles { fn open( &mut self, - object: Option, + ports: Option<[u64; 2]>, output: u64, memory: &mut GuestMemory, ) -> Result<(), u32> { @@ -44,7 +44,10 @@ impl QueueHandles { .write_u64(output, handle) .map_err(|_| ERROR_INVALID_PARAMETER)?; self.last_id = next; - self.queues.insert(handle, object.unwrap_or(handle)); + self.queues.insert( + handle, + ports.unwrap_or([0x5157_0000_0000_0000 | next, 0x5143_0000_0000_0000 | next]), + ); Ok(()) } } @@ -100,4 +103,45 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(0) }, ); + + let get = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueGetPort", + ServiceStatus::Partial, + move |args, _, memory| { + let result = (|| { + let queues = get.gdk_queues.lock().expect("GDK queue handle table"); + let ports = queues.queues.get(&args.rcx).ok_or(ERROR_INVALID_HANDLE)?; + let port = ports + .get(args.rdx as u32 as usize) + .ok_or(ERROR_INVALID_PARAMETER)?; + if args.r8 == 0 { + return Err(ERROR_INVALID_PARAMETER); + } + memory + .write_u64(args.r8, *port) + .map_err(|_| ERROR_INVALID_PARAMETER) + })(); + Ok(guest_hresult(result)) + }, + ); + + let composite = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueCreateComposite", + ServiceStatus::Partial, + move |args, _, memory| { + let mut queues = composite.gdk_queues.lock().expect("GDK queue handle table"); + let ports = [args.rcx, args.rdx]; + if ports + .iter() + .any(|port| !queues.queues.values().any(|live| live.contains(port))) + { + return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE))); + } + Ok(guest_hresult(queues.open(Some(ports), args.r8, memory))) + }, + ); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index c60ccfe7..2a2b1653 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1143,6 +1143,9 @@ fn guest_gdk_manual_queue_handles_have_independent_lifetimes() { }; let first = open("XTaskQueueCreate", &[0, 0, output]); let second = open("XTaskQueueDuplicateHandle", &[first, output]); + let work = open("XTaskQueueGetPort", &[first, 0, output]); + let completion = open("XTaskQueueGetPort", &[first, 1, output]); + assert_ne!(work, completion); assert_ne!(first, second); call("XTaskQueueCloseHandle", &[first]); let stale = call("XTaskQueueDuplicateHandle", &[first, output]); @@ -1150,8 +1153,16 @@ fn guest_gdk_manual_queue_handles_have_independent_lifetimes() { assert_eq!(stale.image.memory.read_u64(output).unwrap(), 0); let third = open("XTaskQueueDuplicateHandle", &[second, output]); assert!(third > second); + assert_eq!(open("XTaskQueueGetPort", &[third, 0, output]), work); + let composite = open("XTaskQueueCreateComposite", &[work, work, output]); call("XTaskQueueCloseHandle", &[second]); call("XTaskQueueCloseHandle", &[third]); + assert_eq!(open("XTaskQueueGetPort", &[composite, 1, output]), work); + let stale = call("XTaskQueueCreateComposite", &[work, completion, output]); + assert_eq!(stale.execution.final_state.get(Register::Rax), 0x8007_0006); + call("XTaskQueueCloseHandle", &[composite]); + let stale = call("XTaskQueueCreateComposite", &[work, work, output]); + assert_eq!(stale.execution.final_state.get(Register::Rax), 0x8007_0006); let next = open("XTaskQueueCreate", &[0, 0, output]); assert!(next > third); } From b8fae106af6f85ad26f3e188daff8dc76321f5eb Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:48:46 -0500 Subject: [PATCH 58/82] Queue bounded GDK guest callbacks on shared ports Signed-off-by: Adeeb Rahman --- crates/loader/src/services/gdk_queue.rs | 58 +++++++++++++++++++++++-- crates/loader/tests/runtime_x15.rs | 26 +++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) diff --git a/crates/loader/src/services/gdk_queue.rs b/crates/loader/src/services/gdk_queue.rs index d4b8b744..4b9f33d5 100644 --- a/crates/loader/src/services/gdk_queue.rs +++ b/crates/loader/src/services/gdk_queue.rs @@ -7,11 +7,12 @@ use super::{ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED}; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::GuestMemory; use crate::runtime::HResult; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; const MODULE: &str = "xgameruntime.dll"; const MAX_HANDLES: usize = 64; +const MAX_CALLBACKS_PER_PORT: usize = 32; const ERROR_OUTOFMEMORY: u32 = 14; const MANUAL: u32 = 0; @@ -19,6 +20,13 @@ const MANUAL: u32 = 0; pub(super) struct QueueHandles { last_id: u64, queues: BTreeMap, + pending: BTreeMap>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct GuestCallback { + entry: u64, + context: u64, } impl QueueHandles { @@ -50,6 +58,29 @@ impl QueueHandles { ); Ok(()) } + + fn close(&mut self, handle: u64) { + if let Some(ports) = self.queues.remove(&handle) { + for port in ports { + if !self.queues.values().any(|live| live.contains(&port)) { + self.pending.remove(&port); + } + } + } + } + + fn submit(&mut self, handle: u64, selector: u32, callback: GuestCallback) -> Result<(), u32> { + let ports = self.queues.get(&handle).ok_or(ERROR_INVALID_HANDLE)?; + let port = ports + .get(selector as usize) + .ok_or(ERROR_INVALID_PARAMETER)?; + let queue = self.pending.entry(*port).or_default(); + if queue.len() >= MAX_CALLBACKS_PER_PORT { + return Err(ERROR_OUTOFMEMORY); + } + queue.push_back(callback); + Ok(()) + } } fn guest_hresult(result: Result<(), u32>) -> u64 { @@ -98,8 +129,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .gdk_queues .lock() .expect("GDK queue handle table") - .queues - .remove(&args.rcx); + .close(args.rcx); Ok(0) }, ); @@ -144,4 +174,26 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(guest_hresult(queues.open(Some(ports), args.r8, memory))) }, ); + + let submit = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueSubmitCallback", + ServiceStatus::Partial, + move |args, _, memory| { + if args.r9 == 0 || memory.fetch_instruction_byte(args.r9).is_err() { + return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER))); + } + let callback = GuestCallback { + entry: args.r9, + context: args.r8, + }; + let mut queues = submit.gdk_queues.lock().expect("GDK queue handle table"); + Ok(guest_hresult(queues.submit( + args.rcx, + args.rdx as u32, + callback, + ))) + }, + ); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 2a2b1653..d42bc713 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1158,6 +1158,32 @@ fn guest_gdk_manual_queue_handles_have_independent_lifetimes() { call("XTaskQueueCloseHandle", &[second]); call("XTaskQueueCloseHandle", &[third]); assert_eq!(open("XTaskQueueGetPort", &[composite, 1, output]), work); + assert_eq!( + call("XTaskQueueSubmitCallback", &[composite, 0, 17, output]) + .execution + .final_state + .get(Register::Rax), + 0x8007_0057 + ); + for index in 0..32 { + assert_eq!( + call( + "XTaskQueueSubmitCallback", + &[composite, index % 2, index, 0x140001000] + ) + .execution + .final_state + .get(Register::Rax), + 0 + ); + } + assert_eq!( + call("XTaskQueueSubmitCallback", &[composite, 1, 0, 0x140001000]) + .execution + .final_state + .get(Register::Rax), + 0x8007_000e + ); let stale = call("XTaskQueueCreateComposite", &[work, completion, output]); assert_eq!(stale.execution.final_state.get(Register::Rax), 0x8007_0006); call("XTaskQueueCloseHandle", &[composite]); From fa2e89cc06b009c7b98749dbcf80ef97233b8720 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:50:31 -0500 Subject: [PATCH 59/82] Dispatch queued GDK callbacks through translated guest execution Signed-off-by: Adeeb Rahman --- crates/loader/src/imports.rs | 90 ++++++++++++++++++++++++- crates/loader/src/memory.rs | 2 + crates/loader/src/services/gdk_queue.rs | 32 +++++++-- crates/loader/tests/runtime_x15.rs | 58 ++++++++++++++++ 4 files changed, 173 insertions(+), 9 deletions(-) diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 12957293..350ac094 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -195,11 +195,30 @@ fn trampoline_address(index: usize) -> u64 { IMPORT_TRAMPOLINE_BASE_VA + index as u64 * IMPORT_TRAMPOLINE_STRIDE } +const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE; +const MAX_CALLBACK_DEPTH: usize = 32; + +pub(crate) struct GuestCallback { + pub(crate) entry: u64, + pub(crate) context: u64, +} + +type CallbackDispatch = Box< + dyn Fn(&Win64Args, &GuestMemory) -> Result, ExitReason> + Send + Sync, +>; + +#[derive(Clone)] +pub(crate) struct CallbackFrame { + resume: u64, + preserved: Nonvolatile, +} + /// Registry for resolving and binding import symbols to guest trampoline VAs. pub struct ImportRegistry { // (lower-case module, name) -> service index. Symbol names keep their case. services: HashMap<(String, ImportName), usize>, handlers: Vec, + callback_dispatchers: HashMap, dynamic_trampolines: DynamicTrampolines, trampoline_to_service: HashMap, // Trampoline VA -> service_index } @@ -215,6 +234,7 @@ impl ImportRegistry { Self { services: HashMap::new(), handlers: Vec::new(), + callback_dispatchers: HashMap::new(), trampoline_to_service: HashMap::new(), dynamic_trampolines: DynamicTrampolines::default(), } @@ -488,9 +508,29 @@ impl ImportRegistry { Ok(slots.len()) } + pub(crate) fn register_callback_dispatch( + &mut self, + module: &str, + symbol: &str, + handler: impl Fn(&Win64Args, &GuestMemory) -> Result, ExitReason> + + Send + + Sync + + 'static, + ) { + self.register_with_status(module, symbol, ServiceStatus::Partial, |_, _, _| { + Err(ExitReason::IllegalInstruction(0xff)) + }); + let index = self + .service_index(module, symbol) + .expect("registered dispatcher"); + self.callback_dispatchers.insert(index, Box::new(handler)); + } + /// Check if target RIP matches a synthetic service trampoline. pub fn is_service_trampoline(&self, rip: u64) -> bool { - self.trampoline_to_service.contains_key(&rip) || self.dynamic_trampolines.get(rip).is_some() + rip == CALLBACK_RETURN + || self.trampoline_to_service.contains_key(&rip) + || self.dynamic_trampolines.get(rip).is_some() } /// Dispatch a service call when guest RIP hits a service trampoline. @@ -500,6 +540,19 @@ impl ImportRegistry { cpu: &mut CpuState, memory: &mut GuestMemory, ) -> Result<(), ExitReason> { + if rip == CALLBACK_RETURN { + let key = (cpu.gs_base, cpu.get(Register::Rsp)); + let frame = memory + .callback_frames + .remove(&key) + .ok_or(ExitReason::IllegalInstruction(0xff))?; + if Nonvolatile::of(cpu) != frame.preserved { + return Err(ExitReason::ServiceAbiViolation); + } + cpu.set(Register::Rax, 1); + cpu.rip = frame.resume; + return Ok(()); + } let service_idx = self .trampoline_to_service .get(&rip) @@ -518,6 +571,39 @@ impl ImportRegistry { let args = Win64Args::new(cpu); let preserved = Nonvolatile::of(cpu); + if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) { + let key = (cpu.gs_base, after); + if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH + || memory.callback_frames.contains_key(&key) + { + return Err(ExitReason::ServiceAbiViolation); + } + memory + .check_write(rsp, 8) + .map_err(ExitReason::MemoryFault)?; + if let Some(callback) = dispatcher(&args, memory)? { + memory + .write_u64(rsp, CALLBACK_RETURN) + .map_err(ExitReason::MemoryFault)?; + let mut preserved = preserved; + preserved.gpr[4] = after; + memory.callback_frames.insert( + key, + CallbackFrame { + resume: ret_addr, + preserved, + }, + ); + cpu.set(Register::Rcx, callback.context); + cpu.set(Register::Rdx, 0); + cpu.rip = callback.entry; + return Ok(()); + } + cpu.set(Register::Rax, 0); + cpu.set(Register::Rsp, after); + cpu.rip = ret_addr; + return Ok(()); + } let value = (descriptor.handler)(&args, cpu, memory)?; if Nonvolatile::of(cpu) != preserved { return Err(ExitReason::ServiceAbiViolation); @@ -531,7 +617,7 @@ impl ImportRegistry { } /// Registers a Win64 callee must preserve (Microsoft x64 calling convention). -#[derive(PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq)] struct Nonvolatile { gpr: [u64; 9], xmm: [u128; 10], diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index ca86cf38..cdf81246 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -122,6 +122,8 @@ pub struct GuestMemory { private_heap_serial: u64, // Stable errno pointers indexed by the guest thread's TEB address. crt_errno: std::collections::BTreeMap, + pub(crate) callback_frames: + std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>, } impl GuestMemory { diff --git a/crates/loader/src/services/gdk_queue.rs b/crates/loader/src/services/gdk_queue.rs index 4b9f33d5..e1f76a4d 100644 --- a/crates/loader/src/services/gdk_queue.rs +++ b/crates/loader/src/services/gdk_queue.rs @@ -4,7 +4,8 @@ use super::ServicesState; use super::{ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED}; -use crate::imports::{ImportRegistry, ServiceStatus}; +use crate::cpu::ExitReason; +use crate::imports::{GuestCallback, ImportRegistry, ServiceStatus}; use crate::memory::GuestMemory; use crate::runtime::HResult; use std::collections::{BTreeMap, VecDeque}; @@ -23,12 +24,6 @@ pub(super) struct QueueHandles { pending: BTreeMap>, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct GuestCallback { - entry: u64, - context: u64, -} - impl QueueHandles { fn open( &mut self, @@ -196,4 +191,27 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc ))) }, ); + let dispatch = Arc::clone(state); + registry.register_callback_dispatch(MODULE, "XTaskQueueDispatch", move |args, memory| { + if args.r8 as u32 != 0 { + return Ok(None); + } + let mut queues = dispatch.gdk_queues.lock().expect("GDK queue handle table"); + let Some(&port) = queues + .queues + .get(&args.rcx) + .and_then(|ports| ports.get(args.rdx as u32 as usize)) + else { + return Ok(None); + }; + let Some(pending) = queues.pending.get_mut(&port) else { + return Ok(None); + }; + if let Some(callback) = pending.front() { + memory + .fetch_instruction_byte(callback.entry) + .map_err(ExitReason::MemoryFault)?; + } + Ok(pending.pop_front()) + }); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index d42bc713..5d8b7289 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,64 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { + const IMAGE: u64 = 0x140000000; + const MODULE: &str = "xgameruntime.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + let created = call_service_fixture(&state, MODULE, "XTaskQueueCreate", &[0, 0, output]); + let queue = created.image.memory.read_u64(output).unwrap(); + assert_ne!(queue, 0); + let mut code = vec![0x48, 0x83, 0xec, 0x48]; + let set_args = |code: &mut Vec, values: &[u64]| { + for (register, value) in [[0x48, 0xb9], [0x48, 0xba], [0x49, 0xb8], [0x49, 0xb9]] + .into_iter() + .zip(values) + { + code.extend_from_slice(®ister); + code.extend_from_slice(&value.to_le_bytes()); + } + }; + code.extend_from_slice(&[0x48, 0xb8]); + code.extend_from_slice(&output.to_le_bytes()); + code.extend_from_slice(&[0x48, 0xc7, 0x00, 0xff, 0xff, 0xff, 0xff]); + set_args(&mut code, &[queue, 0, output, IMAGE + 0x1100]); + append_import_call(&mut code, 0x2060); + set_args(&mut code, &[queue, 0, 0]); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x89, 0xc3]); // retain successful dispatch in RBX + set_args(&mut code, &[queue, 0, 0]); + append_import_call(&mut code, 0x21a0); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]); + code.resize(0x100, 0); + // Store canceled, then clobber RAX to verify the dispatch return is restored. + code.extend_from_slice(&[0x48, 0x89, 0x11, 0xb8, 99, 0, 0, 0, 0xc3]); + let image = TestPeBuilder::new(IMAGE, 0x1000) + .add_import(MODULE, "XTaskQueueSubmitCallback") + .add_import(MODULE, "XTaskQueueDispatch") + .code(&code) + .build(); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, state); + let result = run_synthetic_startup( + &image, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + registry, + 100, + ) + .unwrap(); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + let cpu = result.execution.final_state; + assert_eq!(cpu.get(Register::Rbx), 1); + assert_eq!(cpu.get(Register::Rax), 0); + assert_eq!(result.image.memory.read_u64(output).unwrap(), 0); +} + #[test] fn guest_gdk_manual_queue_handles_have_independent_lifetimes() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); From bf56047db93721c291a7ed5a90b02b6183cf47a2 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:51:29 -0500 Subject: [PATCH 60/82] Wait for manual GDK callbacks with bounded dispatch deadlines Signed-off-by: Adeeb Rahman --- crates/loader/src/services.rs | 2 + crates/loader/src/services/gdk_queue.rs | 56 +++++++++++++++---------- crates/loader/tests/runtime_x15.rs | 6 ++- 3 files changed, 42 insertions(+), 22 deletions(-) diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index f30b4412..da6f7b6c 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -176,6 +176,7 @@ pub struct ServicesState { winsock: Mutex, task_fixture: Mutex, gdk_queues: Mutex, + gdk_queue_changed: Condvar, winsock_changed: Condvar, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, @@ -194,6 +195,7 @@ impl ServicesState { winsock: Mutex::default(), task_fixture: Mutex::default(), gdk_queues: Mutex::default(), + gdk_queue_changed: Condvar::new(), winsock_changed: Condvar::new(), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), diff --git a/crates/loader/src/services/gdk_queue.rs b/crates/loader/src/services/gdk_queue.rs index e1f76a4d..a8bee2fc 100644 --- a/crates/loader/src/services/gdk_queue.rs +++ b/crates/loader/src/services/gdk_queue.rs @@ -10,9 +10,11 @@ use crate::memory::GuestMemory; use crate::runtime::HResult; use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; +use std::time::{Duration, Instant}; const MODULE: &str = "xgameruntime.dll"; const MAX_HANDLES: usize = 64; +const MAX_DISPATCH_WAIT_MS: u32 = 1_000; const MAX_CALLBACKS_PER_PORT: usize = 32; const ERROR_OUTOFMEMORY: u32 = 14; const MANUAL: u32 = 0; @@ -125,6 +127,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc .lock() .expect("GDK queue handle table") .close(args.rcx); + close.gdk_queue_changed.notify_all(); Ok(0) }, ); @@ -184,34 +187,45 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc context: args.r8, }; let mut queues = submit.gdk_queues.lock().expect("GDK queue handle table"); - Ok(guest_hresult(queues.submit( - args.rcx, - args.rdx as u32, - callback, - ))) + let result = queues.submit(args.rcx, args.rdx as u32, callback); + if result.is_ok() { + submit.gdk_queue_changed.notify_all(); + } + Ok(guest_hresult(result)) }, ); let dispatch = Arc::clone(state); registry.register_callback_dispatch(MODULE, "XTaskQueueDispatch", move |args, memory| { - if args.r8 as u32 != 0 { + let timeout = args.r8 as u32; + if timeout > MAX_DISPATCH_WAIT_MS { return Ok(None); } + let deadline = Instant::now() + Duration::from_millis(u64::from(timeout)); let mut queues = dispatch.gdk_queues.lock().expect("GDK queue handle table"); - let Some(&port) = queues - .queues - .get(&args.rcx) - .and_then(|ports| ports.get(args.rdx as u32 as usize)) - else { - return Ok(None); - }; - let Some(pending) = queues.pending.get_mut(&port) else { - return Ok(None); - }; - if let Some(callback) = pending.front() { - memory - .fetch_instruction_byte(callback.entry) - .map_err(ExitReason::MemoryFault)?; + loop { + let Some(&port) = queues + .queues + .get(&args.rcx) + .and_then(|ports| ports.get(args.rdx as u32 as usize)) + else { + return Ok(None); + }; + if let Some(pending) = queues.pending.get_mut(&port) + && let Some(callback) = pending.front() + { + memory + .fetch_instruction_byte(callback.entry) + .map_err(ExitReason::MemoryFault)?; + return Ok(pending.pop_front()); + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Ok(None); + } + (queues, _) = dispatch + .gdk_queue_changed + .wait_timeout(queues, remaining) + .expect("GDK queue handle table"); } - Ok(pending.pop_front()) }); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 5d8b7289..ae8f7d21 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1160,7 +1160,7 @@ fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { .code(&code) .build(); let mut registry = ImportRegistry::new(); - register_standard_services(&mut registry, state); + register_standard_services(&mut registry, Arc::clone(&state)); let result = run_synthetic_startup( &image, StartupLayout { @@ -1177,6 +1177,10 @@ fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { assert_eq!(cpu.get(Register::Rbx), 1); assert_eq!(cpu.get(Register::Rax), 0); assert_eq!(result.image.memory.read_u64(output).unwrap(), 0); + let start = std::time::Instant::now(); + let timeout = call_service_fixture(&state, MODULE, "XTaskQueueDispatch", &[queue, 0, 10]); + assert_eq!(timeout.execution.final_state.get(Register::Rax), 0); + assert!(start.elapsed() >= std::time::Duration::from_millis(10)); } #[test] From 32e41e3890d7f039f7ec3d7d33a49d4d19ffb014 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:52:34 -0500 Subject: [PATCH 61/82] Schedule delayed GDK callbacks on manual ports Signed-off-by: Adeeb Rahman --- crates/loader/src/services/gdk_queue.rs | 89 ++++++++++++++++--------- crates/loader/tests/runtime_x15.rs | 11 ++- 2 files changed, 67 insertions(+), 33 deletions(-) diff --git a/crates/loader/src/services/gdk_queue.rs b/crates/loader/src/services/gdk_queue.rs index a8bee2fc..1e50c53e 100644 --- a/crates/loader/src/services/gdk_queue.rs +++ b/crates/loader/src/services/gdk_queue.rs @@ -23,7 +23,12 @@ const MANUAL: u32 = 0; pub(super) struct QueueHandles { last_id: u64, queues: BTreeMap, - pending: BTreeMap>, + pending: BTreeMap>, +} + +struct ScheduledCallback { + ready_at: Instant, + callback: GuestCallback, } impl QueueHandles { @@ -66,7 +71,12 @@ impl QueueHandles { } } - fn submit(&mut self, handle: u64, selector: u32, callback: GuestCallback) -> Result<(), u32> { + fn submit( + &mut self, + handle: u64, + selector: u32, + callback: ScheduledCallback, + ) -> Result<(), u32> { let ports = self.queues.get(&handle).ok_or(ERROR_INVALID_HANDLE)?; let port = ports .get(selector as usize) @@ -75,7 +85,8 @@ impl QueueHandles { if queue.len() >= MAX_CALLBACKS_PER_PORT { return Err(ERROR_OUTOFMEMORY); } - queue.push_back(callback); + let index = queue.partition_point(|item| item.ready_at <= callback.ready_at); + queue.insert(index, callback); Ok(()) } } @@ -173,27 +184,40 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }, ); - let submit = Arc::clone(state); - registry.register_with_status( - MODULE, - "XTaskQueueSubmitCallback", - ServiceStatus::Partial, - move |args, _, memory| { - if args.r9 == 0 || memory.fetch_instruction_byte(args.r9).is_err() { - return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER))); - } - let callback = GuestCallback { - entry: args.r9, - context: args.r8, - }; - let mut queues = submit.gdk_queues.lock().expect("GDK queue handle table"); - let result = queues.submit(args.rcx, args.rdx as u32, callback); - if result.is_ok() { - submit.gdk_queue_changed.notify_all(); - } - Ok(guest_hresult(result)) - }, - ); + for (symbol, delayed) in [ + ("XTaskQueueSubmitCallback", false), + ("XTaskQueueSubmitDelayedCallback", true), + ] { + let submit = Arc::clone(state); + registry.register_with_status( + MODULE, + symbol, + ServiceStatus::Partial, + move |args, _, memory| { + let (delay, context, entry) = if delayed { + let Ok(entry) = args.get(4, memory) else { + return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER))); + }; + (args.r8 as u32, args.r9, entry) + } else { + (0, args.r8, args.r9) + }; + if entry == 0 || memory.fetch_instruction_byte(entry).is_err() { + return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER))); + } + let mut queues = submit.gdk_queues.lock().expect("GDK queue handle table"); + let callback = ScheduledCallback { + ready_at: Instant::now() + Duration::from_millis(u64::from(delay)), + callback: GuestCallback { entry, context }, + }; + let result = queues.submit(args.rcx, args.rdx as u32, callback); + if result.is_ok() { + submit.gdk_queue_changed.notify_all(); + } + Ok(guest_hresult(result)) + }, + ); + } let dispatch = Arc::clone(state); registry.register_callback_dispatch(MODULE, "XTaskQueueDispatch", move |args, memory| { let timeout = args.r8 as u32; @@ -210,15 +234,20 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc else { return Ok(None); }; + let now = Instant::now(); + let mut wake_at = deadline; if let Some(pending) = queues.pending.get_mut(&port) - && let Some(callback) = pending.front() + && let Some(item) = pending.front() { - memory - .fetch_instruction_byte(callback.entry) - .map_err(ExitReason::MemoryFault)?; - return Ok(pending.pop_front()); + if item.ready_at <= now { + memory + .fetch_instruction_byte(item.callback.entry) + .map_err(ExitReason::MemoryFault)?; + return Ok(pending.pop_front().map(|item| item.callback)); + } + wake_at = wake_at.min(item.ready_at); } - let remaining = deadline.saturating_duration_since(Instant::now()); + let remaining = wake_at.saturating_duration_since(now); if remaining.is_zero() { return Ok(None); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index ae8f7d21..fe6c99de 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1143,9 +1143,12 @@ fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { code.extend_from_slice(&[0x48, 0xb8]); code.extend_from_slice(&output.to_le_bytes()); code.extend_from_slice(&[0x48, 0xc7, 0x00, 0xff, 0xff, 0xff, 0xff]); - set_args(&mut code, &[queue, 0, output, IMAGE + 0x1100]); + code.extend_from_slice(&[0x48, 0xb8]); + code.extend_from_slice(&(IMAGE + 0x1100).to_le_bytes()); + code.extend_from_slice(&[0x48, 0x89, 0x44, 0x24, 0x20]); + set_args(&mut code, &[queue, 0, 30, output]); append_import_call(&mut code, 0x2060); - set_args(&mut code, &[queue, 0, 0]); + set_args(&mut code, &[queue, 0, 1000]); append_import_call(&mut code, 0x21a0); code.extend_from_slice(&[0x48, 0x89, 0xc3]); // retain successful dispatch in RBX set_args(&mut code, &[queue, 0, 0]); @@ -1155,12 +1158,13 @@ fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { // Store canceled, then clobber RAX to verify the dispatch return is restored. code.extend_from_slice(&[0x48, 0x89, 0x11, 0xb8, 99, 0, 0, 0, 0xc3]); let image = TestPeBuilder::new(IMAGE, 0x1000) - .add_import(MODULE, "XTaskQueueSubmitCallback") + .add_import(MODULE, "XTaskQueueSubmitDelayedCallback") .add_import(MODULE, "XTaskQueueDispatch") .code(&code) .build(); let mut registry = ImportRegistry::new(); register_standard_services(&mut registry, Arc::clone(&state)); + let submitted = std::time::Instant::now(); let result = run_synthetic_startup( &image, StartupLayout { @@ -1173,6 +1177,7 @@ fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { ) .unwrap(); assert_eq!(result.execution.exit_reason, ExitReason::Halt); + assert!(submitted.elapsed() >= std::time::Duration::from_millis(30)); let cpu = result.execution.final_state; assert_eq!(cpu.get(Register::Rbx), 1); assert_eq!(cpu.get(Register::Rax), 0); From f9a7d996388b969924ec64085ecd86ef15e2dbf0 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:54:10 -0500 Subject: [PATCH 62/82] Drain terminated manual GDK queues with canceled callbacks Signed-off-by: Adeeb Rahman --- crates/loader/src/imports.rs | 3 +- crates/loader/src/services/gdk_queue.rs | 119 +++++++++++++++++++----- crates/loader/tests/runtime_x15.rs | 68 ++++++++++++++ 3 files changed, 167 insertions(+), 23 deletions(-) diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 350ac094..f81b624e 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -201,6 +201,7 @@ const MAX_CALLBACK_DEPTH: usize = 32; pub(crate) struct GuestCallback { pub(crate) entry: u64, pub(crate) context: u64, + pub(crate) cancelled: bool, } type CallbackDispatch = Box< @@ -595,7 +596,7 @@ impl ImportRegistry { }, ); cpu.set(Register::Rcx, callback.context); - cpu.set(Register::Rdx, 0); + cpu.set(Register::Rdx, u64::from(callback.cancelled)); cpu.rip = callback.entry; return Ok(()); } diff --git a/crates/loader/src/services/gdk_queue.rs b/crates/loader/src/services/gdk_queue.rs index 1e50c53e..91710083 100644 --- a/crates/loader/src/services/gdk_queue.rs +++ b/crates/loader/src/services/gdk_queue.rs @@ -8,7 +8,7 @@ use crate::cpu::ExitReason; use crate::imports::{GuestCallback, ImportRegistry, ServiceStatus}; use crate::memory::GuestMemory; use crate::runtime::HResult; -use std::collections::{BTreeMap, VecDeque}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::sync::Arc; use std::time::{Duration, Instant}; @@ -18,15 +18,24 @@ const MAX_DISPATCH_WAIT_MS: u32 = 1_000; const MAX_CALLBACKS_PER_PORT: usize = 32; const ERROR_OUTOFMEMORY: u32 = 14; const MANUAL: u32 = 0; +const E_ABORT: u64 = 0x8000_4004; #[derive(Default)] pub(super) struct QueueHandles { last_id: u64, - queues: BTreeMap, + queues: BTreeMap, + terminated: BTreeSet, pending: BTreeMap>, } +#[derive(Clone, Copy)] +struct Queue { + id: u64, + ports: [u64; 2], +} + struct ScheduledCallback { + owner: u64, ready_at: Instant, callback: GuestCallback, } @@ -34,7 +43,8 @@ struct ScheduledCallback { impl QueueHandles { fn open( &mut self, - ports: Option<[u64; 2]>, + duplicate: Option, + composite: Option<[u64; 2]>, output: u64, memory: &mut GuestMemory, ) -> Result<(), u32> { @@ -56,15 +66,22 @@ impl QueueHandles { self.last_id = next; self.queues.insert( handle, - ports.unwrap_or([0x5157_0000_0000_0000 | next, 0x5143_0000_0000_0000 | next]), + duplicate.unwrap_or(Queue { + id: handle, + ports: composite + .unwrap_or([0x5157_0000_0000_0000 | next, 0x5143_0000_0000_0000 | next]), + }), ); Ok(()) } fn close(&mut self, handle: u64) { - if let Some(ports) = self.queues.remove(&handle) { - for port in ports { - if !self.queues.values().any(|live| live.contains(&port)) { + if let Some(queue) = self.queues.remove(&handle) { + if !self.queues.values().any(|live| live.id == queue.id) { + self.terminated.remove(&queue.id); + } + for port in queue.ports { + if !self.queues.values().any(|live| live.ports.contains(&port)) { self.pending.remove(&port); } } @@ -75,10 +92,12 @@ impl QueueHandles { &mut self, handle: u64, selector: u32, - callback: ScheduledCallback, + mut callback: ScheduledCallback, ) -> Result<(), u32> { - let ports = self.queues.get(&handle).ok_or(ERROR_INVALID_HANDLE)?; - let port = ports + let queue = self.queues.get(&handle).ok_or(ERROR_INVALID_HANDLE)?; + callback.owner = queue.id; + let port = queue + .ports .get(selector as usize) .ok_or(ERROR_INVALID_PARAMETER)?; let queue = self.pending.entry(*port).or_default(); @@ -109,7 +128,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc return Ok(guest_hresult(Err(ERROR_NOT_SUPPORTED))); } let mut queues = create.gdk_queues.lock().expect("GDK queue handle table"); - Ok(guest_hresult(queues.open(None, args.r8, memory))) + Ok(guest_hresult(queues.open(None, None, args.r8, memory))) }, ); @@ -123,7 +142,12 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let Some(&object) = queues.queues.get(&args.rcx) else { return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE))); }; - Ok(guest_hresult(queues.open(Some(object), args.rdx, memory))) + Ok(guest_hresult(queues.open( + Some(object), + None, + args.rdx, + memory, + ))) }, ); @@ -153,6 +177,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let queues = get.gdk_queues.lock().expect("GDK queue handle table"); let ports = queues.queues.get(&args.rcx).ok_or(ERROR_INVALID_HANDLE)?; let port = ports + .ports .get(args.rdx as u32 as usize) .ok_or(ERROR_INVALID_PARAMETER)?; if args.r8 == 0 { @@ -176,11 +201,16 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let ports = [args.rcx, args.rdx]; if ports .iter() - .any(|port| !queues.queues.values().any(|live| live.contains(port))) + .any(|port| !queues.queues.values().any(|live| live.ports.contains(port))) { return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE))); } - Ok(guest_hresult(queues.open(Some(ports), args.r8, memory))) + Ok(guest_hresult(queues.open( + None, + Some(ports), + args.r8, + memory, + ))) }, ); @@ -206,9 +236,21 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER))); } let mut queues = submit.gdk_queues.lock().expect("GDK queue handle table"); + if queues + .queues + .get(&args.rcx) + .is_some_and(|queue| queues.terminated.contains(&queue.id)) + { + return Ok(E_ABORT); + } let callback = ScheduledCallback { + owner: 0, ready_at: Instant::now() + Duration::from_millis(u64::from(delay)), - callback: GuestCallback { entry, context }, + callback: GuestCallback { + entry, + context, + cancelled: false, + }, }; let result = queues.submit(args.rcx, args.rdx as u32, callback); if result.is_ok() { @@ -218,6 +260,33 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc }, ); } + let terminate = Arc::clone(state); + registry.register_with_status( + MODULE, + "XTaskQueueTerminate", + ServiceStatus::Partial, + move |args, _, _| { + if args.rdx as u8 != 0 || args.r9 != 0 { + return Ok(guest_hresult(Err(ERROR_NOT_SUPPORTED))); + } + let mut queues = terminate.gdk_queues.lock().expect("GDK queue handle table"); + let Some(&queue) = queues.queues.get(&args.rcx) else { + return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE))); + }; + if queues.terminated.insert(queue.id) { + let now = Instant::now(); + for pending in queues.pending.values_mut() { + for item in pending.iter_mut().filter(|item| item.owner == queue.id) { + item.ready_at = item.ready_at.min(now); + item.callback.cancelled = true; + } + pending.make_contiguous().sort_by_key(|item| item.ready_at); + } + terminate.gdk_queue_changed.notify_all(); + } + Ok(0) + }, + ); let dispatch = Arc::clone(state); registry.register_callback_dispatch(MODULE, "XTaskQueueDispatch", move |args, memory| { let timeout = args.r8 as u32; @@ -227,26 +296,32 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc let deadline = Instant::now() + Duration::from_millis(u64::from(timeout)); let mut queues = dispatch.gdk_queues.lock().expect("GDK queue handle table"); loop { - let Some(&port) = queues - .queues - .get(&args.rcx) - .and_then(|ports| ports.get(args.rdx as u32 as usize)) - else { + let Some(&queue) = queues.queues.get(&args.rcx) else { return Ok(None); }; + let Some(&port) = queue.ports.get(args.rdx as u32 as usize) else { + return Ok(None); + }; + let terminated = queues.terminated.contains(&queue.id); let now = Instant::now(); let mut wake_at = deadline; if let Some(pending) = queues.pending.get_mut(&port) - && let Some(item) = pending.front() + && let Some((index, item)) = pending + .iter() + .enumerate() + .find(|(_, item)| !terminated || item.owner == queue.id) { if item.ready_at <= now { memory .fetch_instruction_byte(item.callback.entry) .map_err(ExitReason::MemoryFault)?; - return Ok(pending.pop_front().map(|item| item.callback)); + return Ok(pending.remove(index).map(|item| item.callback)); } wake_at = wake_at.min(item.ready_at); } + if terminated { + return Ok(None); + } let remaining = wake_at.saturating_duration_since(now); if remaining.is_zero() { return Ok(None); diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index fe6c99de..8747243d 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1188,6 +1188,74 @@ fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { assert!(start.elapsed() >= std::time::Duration::from_millis(10)); } +#[test] +fn guest_gdk_termination_cancels_pending_callback() { + const IMAGE: u64 = 0x140000000; + const MODULE: &str = "xgameruntime.dll"; + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = |symbol, args: &[u64]| call_service_fixture(&state, MODULE, symbol, args); + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + let created = call("XTaskQueueCreate", &[0, 0, output]); + let queue = created.image.memory.read_u64(output).unwrap(); + let submit = [queue, 0, 60_000, output, IMAGE + 0x1100]; + assert_eq!( + call("XTaskQueueSubmitDelayedCallback", &submit) + .execution + .final_state + .get(Register::Rax), + 0 + ); + assert_eq!( + call("XTaskQueueTerminate", &[queue, 0, 0, 0]) + .execution + .final_state + .get(Register::Rax), + 0 + ); + assert_eq!( + call("XTaskQueueSubmitDelayedCallback", &submit) + .execution + .final_state + .get(Register::Rax), + 0x8000_4004 + ); + + let mut code = vec![0x48, 0x83, 0xec, 0x48, 0x48, 0xb9]; + code.extend_from_slice(&queue.to_le_bytes()); + code.extend_from_slice(&[0x31, 0xd2, 0x45, 0x31, 0xc0]); // port and timeout zero + append_import_call(&mut code, 0x2060); + code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x48, 0xf4]); + code.resize(0x100, 0); + code.extend_from_slice(&[0x48, 0x89, 0x11, 0xc3]); // store canceled at context + let image = TestPeBuilder::new(IMAGE, 0x1000) + .add_import(MODULE, "XTaskQueueDispatch") + .code(&code) + .build(); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + let result = run_synthetic_startup( + &image, + StartupLayout { + image_base: IMAGE, + stack_top: PROCESS_FIXTURE_STACK_TOP, + tls_base: 0x300000000, + }, + registry, + 100, + ) + .unwrap(); + assert_eq!(result.execution.exit_reason, ExitReason::Halt); + assert_eq!(result.execution.final_state.get(Register::Rax), 1); + assert_eq!(result.image.memory.read_u64(output).unwrap(), 1); + assert_eq!( + call("XTaskQueueDispatch", &[queue, 0, 1000]) + .execution + .final_state + .get(Register::Rax), + 0 + ); +} + #[test] fn guest_gdk_manual_queue_handles_have_independent_lifetimes() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); From 542684612d2cdc5f6d032507f443f25d96514fa7 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:55:17 -0500 Subject: [PATCH 63/82] Add process-local platform lifecycle identity and settings Signed-off-by: Adeeb Rahman --- crates/loader/src/services.rs | 4 + .../loader/src/services/platform_fixture.rs | 82 +++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 30 +++++++ 3 files changed, 116 insertions(+) create mode 100644 crates/loader/src/services/platform_fixture.rs diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index da6f7b6c..d955ed23 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -15,6 +15,7 @@ mod files; mod gdk_queue; mod heap; mod modules; +mod platform_fixture; mod task_fixture; mod winsock; @@ -175,6 +176,7 @@ pub struct ServicesState { last_errors: Mutex>, winsock: Mutex, task_fixture: Mutex, + platform_fixture: Mutex, gdk_queues: Mutex, gdk_queue_changed: Condvar, winsock_changed: Condvar, @@ -194,6 +196,7 @@ impl ServicesState { last_errors: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), + platform_fixture: Mutex::default(), gdk_queues: Mutex::default(), gdk_queue_changed: Condvar::new(), winsock_changed: Condvar::new(), @@ -554,6 +557,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc, +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + for (symbol, active) in [ + ("OpenFixturePlatform", true), + ("CloseFixturePlatform", false), + ] { + let state = Arc::clone(state); + registry.register(MODULE, symbol, move |_, cpu, _| { + let mut platform = state.platform_fixture.lock().expect("fixture platform"); + if platform.active == active { + return state.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + platform.active = active; + Ok(1) + }); + } + + let identity = Arc::clone(state); + registry.register(MODULE, "GetFixtureApplicationId", move |_, cpu, _| { + let platform = identity.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return identity.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + Ok(FIXTURE_APP_ID) + }); + + let set = Arc::clone(state); + registry.register(MODULE, "SetFixtureSetting", move |args, cpu, _| { + let mut platform = set.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return set.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + let key = args.rcx as u32; + if key == 0 { + return set.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + if platform.settings.len() >= MAX_SETTINGS && !platform.settings.contains_key(&key) { + return set.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0); + } + platform.settings.insert(key, args.rdx); + Ok(1) + }); + + let get = Arc::clone(state); + registry.register(MODULE, "GetFixtureSetting", move |args, cpu, memory| { + let platform = get.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return get.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + let key = args.rcx as u32; + if key == 0 { + return get.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + let Some(&value) = platform.settings.get(&key) else { + return get.fail(cpu.gs_base, ERROR_NOT_FOUND, 0); + }; + if args.rdx == 0 || memory.write_u64(args.rdx, value).is_err() { + return get.fail(cpu.gs_base, ERROR_NOACCESS, 0); + } + Ok(1) + }); +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 8747243d..e032c268 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,36 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn guest_platform_settings_follow_lifecycle_and_process_boundaries() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = + |symbol, args: &[u64]| call_service_fixture(&state, "xenora_fixture.dll", symbol, args); + let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + assert_eq!(value("GetFixtureApplicationId", &[]), 0); + assert_eq!(value("OpenFixturePlatform", &[]), 1); + assert_eq!(value("OpenFixturePlatform", &[]), 0); + assert_eq!(value("GetFixtureApplicationId", &[]), 0x5845_4e4f_5241_0001); + for key in 1..=32 { + assert_eq!(value("SetFixtureSetting", &[key, key * 10]), 1); + } + assert_eq!(value("SetFixtureSetting", &[33, 1]), 0); + assert_eq!(value("SetFixtureSetting", &[1, 99]), 1); + assert_eq!(value("CloseFixturePlatform", &[]), 1); + assert_eq!(value("GetFixtureSetting", &[1, output]), 0); + assert_eq!(value("OpenFixturePlatform", &[]), 1); + let read = call("GetFixtureSetting", &[1, output]); + assert_eq!(read.execution.final_state.get(Register::Rax), 1); + assert_eq!(read.image.memory.read_u64(output).unwrap(), 99); + let other = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let module = "xenora_fixture.dll"; + call_service_fixture(&other, module, "OpenFixturePlatform", &[]); + let missing = call_service_fixture(&other, module, "GetFixtureSetting", &[1, output]); + assert_eq!(missing.execution.final_state.get(Register::Rax), 0); + assert_eq!(missing.image.memory.read_u64(output).unwrap(), 0); +} + #[test] fn guest_gdk_dispatch_runs_callback_and_resumes_caller() { const IMAGE: u64 = 0x140000000; From 9241630f6c77b70c0ba1f8bb7e9deb97c3ece260 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:56:19 -0500 Subject: [PATCH 64/82] Add quota-checked save slots for original guest fixtures Signed-off-by: Adeeb Rahman --- .../loader/src/services/platform_fixture.rs | 68 +++++++++++++++++++ crates/loader/tests/runtime_x15.rs | 40 +++++++++++ 2 files changed, 108 insertions(+) diff --git a/crates/loader/src/services/platform_fixture.rs b/crates/loader/src/services/platform_fixture.rs index 17d93960..f79e18fe 100644 --- a/crates/loader/src/services/platform_fixture.rs +++ b/crates/loader/src/services/platform_fixture.rs @@ -12,11 +12,17 @@ const FIXTURE_APP_ID: u64 = 0x5845_4e4f_5241_0001; const ERROR_NOT_FOUND: u32 = 1168; const ERROR_INVALID_STATE: u32 = 5023; const MAX_SETTINGS: usize = 32; +const MAX_SAVE_SLOTS: usize = 32; +const MAX_SAVE_BYTES: usize = 4096; +const SAVE_QUOTA: usize = 16 * 1024; +const ERROR_DISK_FULL: u32 = 112; +const ERROR_INSUFFICIENT_BUFFER: u32 = 122; #[derive(Default)] pub(super) struct PlatformFixture { active: bool, settings: BTreeMap, + saves: BTreeMap>, } pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { @@ -79,4 +85,66 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc } Ok(1) }); + register_saves(registry, state); +} + +fn register_saves(registry: &mut ImportRegistry, state: &Arc) { + let save = Arc::clone(state); + registry.register(MODULE, "WriteFixtureSave", move |args, cpu, memory| { + let mut platform = save.platform_fixture.lock().expect("fixture platform"); + let fail = |error| save.fail(cpu.gs_base, error, 0); + if !platform.active { + return fail(ERROR_INVALID_STATE); + } + let slot = args.rcx as u32; + let size = args.r8; + if slot == 0 || !(1..=MAX_SAVE_BYTES as u64).contains(&size) { + return fail(ERROR_INVALID_PARAMETER); + } + let previous = platform.saves.get(&slot); + let used: usize = platform.saves.values().map(Vec::len).sum(); + let size = size as usize; + if (previous.is_none() && platform.saves.len() == MAX_SAVE_SLOTS) + || used - previous.map_or(0, Vec::len) + size > SAVE_QUOTA + { + return fail(ERROR_DISK_FULL); + } + let mut contents = vec![0; size]; + if args.rdx == 0 || memory.read_bytes(args.rdx, &mut contents).is_err() { + return fail(ERROR_NOACCESS); + } + platform.saves.insert(slot, contents); + Ok(1) + }); + + let load = Arc::clone(state); + registry.register(MODULE, "ReadFixtureSave", move |args, cpu, memory| { + let platform = load.platform_fixture.lock().expect("fixture platform"); + let fail = |error| load.fail(cpu.gs_base, error, 0); + if !platform.active { + return fail(ERROR_INVALID_STATE); + } + let Some(contents) = platform.saves.get(&(args.rcx as u32)) else { + return fail(ERROR_NOT_FOUND); + }; + if args.r8 < contents.len() as u64 { + return fail(ERROR_INSUFFICIENT_BUFFER); + } + if args.rdx == 0 || memory.write_bytes(args.rdx, contents).is_err() { + return fail(ERROR_NOACCESS); + } + Ok(contents.len() as u64) + }); + + let delete = Arc::clone(state); + registry.register(MODULE, "DeleteFixtureSave", move |args, cpu, _| { + let mut platform = delete.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return delete.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + if platform.saves.remove(&(args.rcx as u32)).is_none() { + return delete.fail(cpu.gs_base, ERROR_NOT_FOUND, 0); + } + Ok(1) + }); } diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index e032c268..78e87e33 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1121,6 +1121,46 @@ fn test_guest_crt_string_length_through_iat() { } } +#[test] +fn guest_platform_saves_enforce_quota_and_preserve_existing_data() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = + |symbol, args: &[u64]| call_service_fixture(&state, "xenora_fixture.dll", symbol, args); + let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); + let buffer = PROCESS_FIXTURE_STACK_TOP - 0x2000; + assert_eq!(value("OpenFixturePlatform", &[]), 1); + for slot in 1..=4 { + assert_eq!(value("WriteFixtureSave", &[slot, buffer, 4096]), 1); + } + assert_eq!(value("WriteFixtureSave", &[5, buffer, 1]), 0); + assert_eq!( + state.last_error( + call("WriteFixtureSave", &[5, buffer, 1]) + .execution + .final_state + .gs_base + ), + 112 + ); + assert_eq!( + value("WriteFixtureSave", &[1, PROCESS_FIXTURE_OUTPUT, 8]), + 1 + ); + assert_eq!(value("WriteFixtureSave", &[5, buffer, 4088]), 1); + assert_eq!(value("WriteFixtureSave", &[1, 0, 8]), 0); + assert_eq!(value("CloseFixturePlatform", &[]), 1); + assert_eq!(value("OpenFixturePlatform", &[]), 1); + let short = call("ReadFixtureSave", &[1, buffer, 7]); + assert_eq!(short.execution.final_state.get(Register::Rax), 0); + assert_eq!(short.image.memory.read_u64(buffer).unwrap(), 0); + let read = call("ReadFixtureSave", &[1, buffer, 8]); + assert_eq!(read.execution.final_state.get(Register::Rax), 8); + assert_eq!(read.image.memory.read_u64(buffer).unwrap(), u64::MAX); + assert_eq!(value("DeleteFixtureSave", &[5]), 1); + assert_eq!(value("WriteFixtureSave", &[6, buffer, 4088]), 1); + assert_eq!(value("ReadFixtureSave", &[5, buffer, 4096]), 0); +} + #[test] fn guest_platform_settings_follow_lifecycle_and_process_boundaries() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); From 9da73f8ad82b7ff481d5ecbc27a03315063afd81 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:57:03 -0500 Subject: [PATCH 65/82] Expose fixture save quota usage and platform capabilities Signed-off-by: Adeeb Rahman --- .../loader/src/services/platform_fixture.rs | 42 ++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 12 ++++++ 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/crates/loader/src/services/platform_fixture.rs b/crates/loader/src/services/platform_fixture.rs index f79e18fe..6dbdc037 100644 --- a/crates/loader/src/services/platform_fixture.rs +++ b/crates/loader/src/services/platform_fixture.rs @@ -17,6 +17,8 @@ const MAX_SAVE_BYTES: usize = 4096; const SAVE_QUOTA: usize = 16 * 1024; const ERROR_DISK_FULL: u32 = 112; const ERROR_INSUFFICIENT_BUFFER: u32 = 122; +const CAP_LOCAL_SETTINGS: u64 = 1 << 0; +const CAP_LOCAL_SAVES: u64 = 1 << 1; #[derive(Default)] pub(super) struct PlatformFixture { @@ -25,6 +27,12 @@ pub(super) struct PlatformFixture { saves: BTreeMap>, } +impl PlatformFixture { + fn used_save_bytes(&self) -> usize { + self.saves.values().map(Vec::len).sum() + } +} + pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { for (symbol, active) in [ ("OpenFixturePlatform", true), @@ -86,9 +94,41 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); register_saves(registry, state); + + let capabilities = Arc::clone(state); + registry.register( + MODULE, + "GetFixturePlatformCapabilities", + move |_, cpu, _| { + let platform = capabilities + .platform_fixture + .lock() + .expect("fixture platform"); + if !platform.active { + return capabilities.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + Ok(CAP_LOCAL_SETTINGS | CAP_LOCAL_SAVES) + }, + ); } fn register_saves(registry: &mut ImportRegistry, state: &Arc) { + let quota = Arc::clone(state); + registry.register(MODULE, "GetFixtureSaveQuota", move |args, cpu, memory| { + let platform = quota.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return quota.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + // Both values are byte counts. Write the whole record or leave it untouched. + let mut record = [0; 16]; + record[..8].copy_from_slice(&(SAVE_QUOTA as u64).to_le_bytes()); + record[8..].copy_from_slice(&(platform.used_save_bytes() as u64).to_le_bytes()); + if args.rcx == 0 || memory.write_bytes(args.rcx, &record).is_err() { + return quota.fail(cpu.gs_base, ERROR_NOACCESS, 0); + } + Ok(1) + }); + let save = Arc::clone(state); registry.register(MODULE, "WriteFixtureSave", move |args, cpu, memory| { let mut platform = save.platform_fixture.lock().expect("fixture platform"); @@ -102,7 +142,7 @@ fn register_saves(registry: &mut ImportRegistry, state: &Arc) { return fail(ERROR_INVALID_PARAMETER); } let previous = platform.saves.get(&slot); - let used: usize = platform.saves.values().map(Vec::len).sum(); + let used = platform.used_save_bytes(); let size = size as usize; if (previous.is_none() && platform.saves.len() == MAX_SAVE_SLOTS) || used - previous.map_or(0, Vec::len) + size > SAVE_QUOTA diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index 78e87e33..c1041f88 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1128,10 +1128,20 @@ fn guest_platform_saves_enforce_quota_and_preserve_existing_data() { |symbol, args: &[u64]| call_service_fixture(&state, "xenora_fixture.dll", symbol, args); let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); let buffer = PROCESS_FIXTURE_STACK_TOP - 0x2000; + assert_eq!(value("GetFixturePlatformCapabilities", &[]), 0); assert_eq!(value("OpenFixturePlatform", &[]), 1); + assert_eq!(value("GetFixturePlatformCapabilities", &[]), 3); + let quota = |expected| { + let result = call("GetFixtureSaveQuota", &[buffer]); + assert_eq!(result.execution.final_state.get(Register::Rax), 1); + assert_eq!(result.image.memory.read_u64(buffer).unwrap(), 16 * 1024); + assert_eq!(result.image.memory.read_u64(buffer + 8).unwrap(), expected); + }; + quota(0); for slot in 1..=4 { assert_eq!(value("WriteFixtureSave", &[slot, buffer, 4096]), 1); } + quota(16 * 1024); assert_eq!(value("WriteFixtureSave", &[5, buffer, 1]), 0); assert_eq!( state.last_error( @@ -1157,7 +1167,9 @@ fn guest_platform_saves_enforce_quota_and_preserve_existing_data() { assert_eq!(read.execution.final_state.get(Register::Rax), 8); assert_eq!(read.image.memory.read_u64(buffer).unwrap(), u64::MAX); assert_eq!(value("DeleteFixtureSave", &[5]), 1); + quota(3 * 4096 + 8); assert_eq!(value("WriteFixtureSave", &[6, buffer, 4088]), 1); + quota(16 * 1024); assert_eq!(value("ReadFixtureSave", &[5, buffer, 4096]), 0); } From 105bf8a65c39439cb94eb725a910f7897ae49744 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:58:40 -0500 Subject: [PATCH 66/82] Add local fixture profiles and selection notifications Signed-off-by: Adeeb Rahman --- .../loader/src/services/platform_fixture.rs | 84 ++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 27 +++++- 2 files changed, 108 insertions(+), 3 deletions(-) diff --git a/crates/loader/src/services/platform_fixture.rs b/crates/loader/src/services/platform_fixture.rs index 6dbdc037..6468d3c3 100644 --- a/crates/loader/src/services/platform_fixture.rs +++ b/crates/loader/src/services/platform_fixture.rs @@ -4,7 +4,7 @@ use super::{ERROR_INVALID_PARAMETER, ERROR_NOACCESS, ERROR_NOT_ENOUGH_MEMORY, ServicesState}; use crate::imports::ImportRegistry; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, VecDeque}; use std::sync::Arc; const MODULE: &str = "xenora_fixture.dll"; @@ -19,12 +19,19 @@ const ERROR_DISK_FULL: u32 = 112; const ERROR_INSUFFICIENT_BUFFER: u32 = 122; const CAP_LOCAL_SETTINGS: u64 = 1 << 0; const CAP_LOCAL_SAVES: u64 = 1 << 1; +const CAP_LOCAL_PROFILES: u64 = 1 << 2; +const CAP_PROFILE_NOTIFICATIONS: u64 = 1 << 3; +const MAX_PROFILES: u64 = 8; +const MAX_NOTIFICATIONS: usize = 16; #[derive(Default)] pub(super) struct PlatformFixture { active: bool, settings: BTreeMap, saves: BTreeMap>, + profile_count: u64, + selected_profile: u64, + profile_changes: VecDeque<(u64, u64)>, } impl PlatformFixture { @@ -94,6 +101,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); register_saves(registry, state); + register_profiles(registry, state); let capabilities = Arc::clone(state); registry.register( @@ -107,7 +115,10 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc if !platform.active { return capabilities.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); } - Ok(CAP_LOCAL_SETTINGS | CAP_LOCAL_SAVES) + Ok(CAP_LOCAL_SETTINGS + | CAP_LOCAL_SAVES + | CAP_LOCAL_PROFILES + | CAP_PROFILE_NOTIFICATIONS) }, ); } @@ -188,3 +199,72 @@ fn register_saves(registry: &mut ImportRegistry, state: &Arc) { Ok(1) }); } + +fn register_profiles(registry: &mut ImportRegistry, state: &Arc) { + let create = Arc::clone(state); + registry.register(MODULE, "CreateFixtureProfile", move |_, cpu, _| { + let mut platform = create.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return create.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + if platform.profile_count == MAX_PROFILES { + return create.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0); + } + platform.profile_count += 1; + Ok(platform.profile_count) + }); + + let select = Arc::clone(state); + registry.register(MODULE, "SelectFixtureProfile", move |args, cpu, _| { + let mut platform = select.platform_fixture.lock().expect("fixture platform"); + let fail = |error| select.fail(cpu.gs_base, error, 0); + if !platform.active { + return fail(ERROR_INVALID_STATE); + } + let next = args.rcx; + if next > platform.profile_count { + return fail(ERROR_NOT_FOUND); + } + let previous = platform.selected_profile; + if previous != next { + if platform.profile_changes.len() == MAX_NOTIFICATIONS { + return fail(ERROR_NOT_ENOUGH_MEMORY); + } + platform.profile_changes.push_back((previous, next)); + platform.selected_profile = next; + } + Ok(1) + }); + + let selected = Arc::clone(state); + registry.register(MODULE, "GetSelectedFixtureProfile", move |_, cpu, _| { + let platform = selected.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return selected.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + Ok(platform.selected_profile) + }); + + let poll = Arc::clone(state); + registry.register( + MODULE, + "PollFixtureProfileChange", + move |args, cpu, memory| { + let mut platform = poll.platform_fixture.lock().expect("fixture platform"); + if !platform.active { + return poll.fail(cpu.gs_base, ERROR_INVALID_STATE, 0); + } + let Some(&(previous, next)) = platform.profile_changes.front() else { + return Ok(0); + }; + let mut record = [0; 16]; + record[..8].copy_from_slice(&previous.to_le_bytes()); + record[8..].copy_from_slice(&next.to_le_bytes()); + if args.rcx == 0 || memory.write_bytes(args.rcx, &record).is_err() { + return poll.fail(cpu.gs_base, ERROR_NOACCESS, 0); + } + platform.profile_changes.pop_front(); + Ok(1) + }, + ); +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index c1041f88..2df12772 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1130,7 +1130,7 @@ fn guest_platform_saves_enforce_quota_and_preserve_existing_data() { let buffer = PROCESS_FIXTURE_STACK_TOP - 0x2000; assert_eq!(value("GetFixturePlatformCapabilities", &[]), 0); assert_eq!(value("OpenFixturePlatform", &[]), 1); - assert_eq!(value("GetFixturePlatformCapabilities", &[]), 3); + assert_eq!(value("GetFixturePlatformCapabilities", &[]), 15); let quota = |expected| { let result = call("GetFixtureSaveQuota", &[buffer]); assert_eq!(result.execution.final_state.get(Register::Rax), 1); @@ -1173,6 +1173,31 @@ fn guest_platform_saves_enforce_quota_and_preserve_existing_data() { assert_eq!(value("ReadFixtureSave", &[5, buffer, 4096]), 0); } +#[test] +fn guest_platform_profile_changes_are_delivered_in_order() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let call = + |symbol, args: &[u64]| call_service_fixture(&state, "xenora_fixture.dll", symbol, args); + let value = |symbol, args: &[u64]| call(symbol, args).execution.final_state.get(Register::Rax); + assert_eq!(value("OpenFixturePlatform", &[]), 1); + assert_eq!(value("CreateFixtureProfile", &[]), 1); + assert_eq!(value("CreateFixtureProfile", &[]), 2); + assert_eq!(value("SelectFixtureProfile", &[3]), 0); + assert_eq!(value("SelectFixtureProfile", &[1]), 1); + assert_eq!(value("SelectFixtureProfile", &[1]), 1); + assert_eq!(value("SelectFixtureProfile", &[2]), 1); + assert_eq!(value("GetSelectedFixtureProfile", &[]), 2); + assert_eq!(value("PollFixtureProfileChange", &[0]), 0); + let output = PROCESS_FIXTURE_STACK_TOP - 0x400; + for (previous, next) in [(0, 1), (1, 2)] { + let event = call("PollFixtureProfileChange", &[output]); + assert_eq!(event.execution.final_state.get(Register::Rax), 1); + assert_eq!(event.image.memory.read_u64(output).unwrap(), previous); + assert_eq!(event.image.memory.read_u64(output + 8).unwrap(), next); + } + assert_eq!(value("PollFixtureProfileChange", &[output]), 0); +} + #[test] fn guest_platform_settings_follow_lifecycle_and_process_boundaries() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); From 7d3c004285f037334bbaacde16b58d03ebee5b8f Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 08:59:52 -0500 Subject: [PATCH 67/82] Preserve PCM frame boundaries and apply float sample gain Signed-off-by: Adeeb Rahman --- crates/ffi/include/xenora.h | 2 + crates/ffi/src/lib.rs | 100 ++++++++++++++++++++++++++++-------- 2 files changed, 81 insertions(+), 21 deletions(-) diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index fec9ad79..da6ff23d 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -247,6 +247,7 @@ xenora_status xenora_session_audio_init( /* * Submit PCM audio bytes into the session audio queue. + * byte_count must contain a whole number of interleaved sample frames. */ xenora_status xenora_session_audio_submit( xenora_session session, @@ -256,6 +257,7 @@ xenora_status xenora_session_audio_submit( /* * Read PCM audio bytes from the session audio queue. + * Only whole frames are returned. Any remaining output bytes are untouched. */ xenora_status xenora_session_audio_read( xenora_session session, diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 6482e2ed..b78ff58f 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -98,29 +98,47 @@ impl Default for AudioSubsystem { } impl AudioSubsystem { + fn frame_bytes(&self) -> usize { + let sample_bytes = if self.format == XENORA_AUDIO_FORMAT_PCM_F32LE { + 4 + } else { + 2 + }; + sample_bytes * self.channels as usize + } + pub fn submit(&mut self, bytes: &[u8]) { self.total_submitted_bytes = self .total_submitted_bytes .saturating_add(bytes.len() as u64); - let processed_bytes: Vec = - if self.format == XENORA_AUDIO_FORMAT_PCM_S16LE && bytes.len().is_multiple_of(2) { - let mut out = bytes.to_vec(); - for chunk in out.as_chunks_mut::<2>().0 { - let sample = i16::from_le_bytes([chunk[0], chunk[1]]); - let attenuated = if self.muted { - 0i16 - } else { - let scaled = (sample as f32) * self.volume; - scaled.clamp(-32768.0, 32767.0) as i16 - }; - let res_bytes = attenuated.to_le_bytes(); - chunk[0] = res_bytes[0]; - chunk[1] = res_bytes[1]; - } - out - } else { - bytes.to_vec() - }; + let processed_bytes: Vec = if self.format == XENORA_AUDIO_FORMAT_PCM_S16LE { + let mut out = bytes.to_vec(); + for chunk in out.as_chunks_mut::<2>().0 { + let sample = i16::from_le_bytes([chunk[0], chunk[1]]); + let attenuated = if self.muted { + 0i16 + } else { + let scaled = (sample as f32) * self.volume; + scaled.clamp(-32768.0, 32767.0) as i16 + }; + let res_bytes = attenuated.to_le_bytes(); + chunk[0] = res_bytes[0]; + chunk[1] = res_bytes[1]; + } + out + } else { + let mut out = bytes.to_vec(); + for chunk in out.as_chunks_mut::<4>().0 { + let sample = f32::from_le_bytes(*chunk); + let scaled = if self.muted || !sample.is_finite() { + 0.0 + } else { + (sample * self.volume).clamp(-1.0, 1.0) + }; + *chunk = scaled.to_le_bytes(); + } + out + }; for b in processed_bytes { if self.queue.len() >= self.max_capacity_bytes { @@ -132,7 +150,8 @@ impl AudioSubsystem { } pub fn read(&mut self, out: &mut [u8]) -> usize { - let count = out.len().min(self.queue.len()); + let usable = out.len().min(self.queue.len()); + let count = usable - usable % self.frame_bytes(); for b in out.iter_mut().take(count) { *b = self.queue.pop_front().unwrap_or(0); } @@ -1337,6 +1356,9 @@ pub unsafe extern "C" fn xenora_session_audio_submit( return XENORA_INVALID_HANDLE; } let slot = &mut slots[split(session).0]; + if !(byte_count as usize).is_multiple_of(slot.audio.frame_bytes()) { + return XENORA_INVALID_ARGUMENT; + } // SAFETY: checked non-null and bounded above. let bytes = unsafe { std::slice::from_raw_parts(pcm_bytes, byte_count as usize) }; slot.audio.submit(bytes); @@ -1355,7 +1377,7 @@ pub unsafe extern "C" fn xenora_session_audio_read( out_bytes_read: *mut u64, ) -> i32 { guarded(|| { - if out_pcm.is_null() || out_bytes_read.is_null() { + if out_pcm.is_null() || out_bytes_read.is_null() || capacity > isize::MAX as u64 { return XENORA_INVALID_ARGUMENT; } let Ok(mut slots) = SESSIONS.lock() else { @@ -2517,6 +2539,42 @@ mod tests { xenora_session_destroy(session); } + #[test] + fn float_pcm_applies_gain_and_preserves_stereo_frame_boundaries() { + let _guard = serial(); + let session = create(); + assert_eq!( + xenora_session_audio_init(session, 48000, 2, XENORA_AUDIO_FORMAT_PCM_F32LE), + XENORA_OK + ); + assert_eq!(xenora_session_audio_set_volume(session, 0.5, 0), XENORA_OK); + let input: Vec = [1.0_f32, -0.5, f32::NAN, 4.0] + .into_iter() + .flat_map(f32::to_le_bytes) + .collect(); + assert_eq!( + unsafe { xenora_session_audio_submit(session, input.as_ptr(), 4) }, + XENORA_INVALID_ARGUMENT + ); + assert_eq!( + unsafe { xenora_session_audio_submit(session, input.as_ptr(), 16) }, + XENORA_OK + ); + let mut output = [0xaa; 9]; + let mut count = 0; + for expected in [[0.5_f32, -0.25], [0.0, 1.0]] { + assert_eq!( + unsafe { xenora_session_audio_read(session, output.as_mut_ptr(), 9, &mut count) }, + XENORA_OK + ); + assert_eq!(count, 8); + assert_eq!(&output[..4], &expected[0].to_le_bytes()); + assert_eq!(&output[4..8], &expected[1].to_le_bytes()); + assert_eq!(output[8], 0xaa); + } + xenora_session_destroy(session); + } + #[test] fn test_audio_subsystem_lifecycle_and_volume() { let _guard = serial(); From 7c3499d5a23f1f21d2ac06e881f3aec0f2b8016d Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:01:49 -0500 Subject: [PATCH 68/82] Play original guest PCM through the native macOS audio engine Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 76 +++++++++++++++++++++++++++++++++-- 1 file changed, 73 insertions(+), 3 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 1736afa6..6918a74f 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -5,6 +5,7 @@ // by native Metal) and shows the verified read-back frame. No other executable can run. import AppKit +import AVFoundation import CXenora import Foundation import SwiftUI @@ -113,12 +114,13 @@ struct AudioVfsFrame { let samples: UInt32 let totalAudioBytes: UInt64 let rgba: [UInt8] + let pcm: [UInt8] - static func run() -> AudioVfsFrame { + static func run(captureAudio: Bool = false) -> AudioVfsFrame { var session: xenora_session = 0 var status = xenora_session_create(XENORA_ABI_VERSION, &session) guard status == XENORA_OK else { - return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: []) + return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: [], pcm: []) } defer { _ = xenora_session_destroy(session) } var rgba = [UInt8](repeating: 0, count: 16) @@ -133,13 +135,25 @@ struct AudioVfsFrame { var underruns: UInt32 = 0 var total: UInt64 = 0 _ = xenora_session_audio_status(session, &queued, &underruns, &total) + var pcm: [UInt8] = [] + if captureAudio && status == XENORA_OK && queued > 0 && queued <= 256 * 1024 { + pcm = [UInt8](repeating: 0, count: Int(queued)) + var read: UInt64 = 0 + let readStatus = pcm.withUnsafeMutableBufferPointer { buffer in + xenora_session_audio_read(session, buffer.baseAddress, UInt64(buffer.count), &read) + } + if readStatus != XENORA_OK || read != UInt64(queued) { + pcm.removeAll() + } + } return AudioVfsFrame( status: status, width: Int(width), height: Int(height), samples: samples, totalAudioBytes: total, - rgba: status == XENORA_OK ? rgba : [] + rgba: status == XENORA_OK ? rgba : [], + pcm: pcm ) } @@ -158,6 +172,46 @@ struct AudioVfsFrame { } } +private enum FixturePlaybackError: Error { + case invalidPCM + case timedOut +} + +private func playFixturePCM(_ pcm: [UInt8]) throws -> Int { + // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. + guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), + let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1), + let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(pcm.count / 2)), + let samples = buffer.floatChannelData?[0] else { + throw FixturePlaybackError.invalidPCM + } + buffer.frameLength = buffer.frameCapacity + for frame in 0.. Date: Tue, 24 Nov 2026 09:02:43 -0500 Subject: [PATCH 69/82] Report native audio output format and presentation latency Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 45 +++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 6918a74f..138c18ba 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -6,6 +6,7 @@ import AppKit import AVFoundation +import CoreAudio import CXenora import Foundation import SwiftUI @@ -174,10 +175,37 @@ struct AudioVfsFrame { private enum FixturePlaybackError: Error { case invalidPCM + case noDefaultOutput(OSStatus) case timedOut } -private func playFixturePCM(_ pcm: [UInt8]) throws -> Int { +private struct FixturePlayback { + let frames: Int + let outputDevice: AudioDeviceID + let outputSampleRate: Double + let outputChannels: AVAudioChannelCount + let presentationLatency: TimeInterval + let completionElapsed: TimeInterval +} + +private func defaultAudioOutput() throws -> AudioDeviceID { + var address = AudioObjectPropertyAddress( + mSelector: kAudioHardwarePropertyDefaultOutputDevice, + mScope: kAudioObjectPropertyScopeGlobal, + mElement: kAudioObjectPropertyElementMain + ) + var device = AudioDeviceID(kAudioObjectUnknown) + var size = UInt32(MemoryLayout.size) + let status = AudioObjectGetPropertyData( + AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &size, &device + ) + guard status == noErr, device != kAudioObjectUnknown else { + throw FixturePlaybackError.noDefaultOutput(status) + } + return device +} + +private func playFixturePCM(_ pcm: [UInt8]) throws -> FixturePlayback { // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1), @@ -191,6 +219,7 @@ private func playFixturePCM(_ pcm: [UInt8]) throws -> Int { let high = UInt16(pcm[frame * 2 + 1]) << 8 samples[frame] = Float(Int16(bitPattern: low | high)) / 32_768 } + let outputDevice = try defaultAudioOutput() let engine = AVAudioEngine() let player = AVAudioPlayerNode() let played = DispatchSemaphore(value: 0) @@ -202,14 +231,22 @@ private func playFixturePCM(_ pcm: [UInt8]) throws -> Int { engine.detach(player) } try engine.start() + let output = engine.outputNode.outputFormat(forBus: 0) + let presentationLatency = engine.outputNode.presentationLatency player.scheduleBuffer(buffer, completionCallbackType: .dataPlayedBack) { _ in played.signal() } + let start = DispatchTime.now() player.play() guard played.wait(timeout: .now() + .seconds(3)) == .success else { throw FixturePlaybackError.timedOut } - return Int(buffer.frameLength) + let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds) / 1e9 + return FixturePlayback( + frames: Int(buffer.frameLength), outputDevice: outputDevice, + outputSampleRate: output.sampleRate, outputChannels: output.channelCount, + presentationLatency: presentationLatency, completionElapsed: elapsed + ) } /// Owns the latest fixture run. A class with @Published avoids SwiftUI macros, @@ -649,8 +686,8 @@ if CommandLine.arguments.contains("--smoke-native-audio") { } do { let played = try playFixturePCM(frame.pcm) - print("smoke-native-audio: playedBackFrames=\(played)") - exit(played == Int(frame.samples) ? 0 : 1) + print("smoke-native-audio: playedBackFrames=\(played.frames) defaultDevice=\(played.outputDevice) outputRate=\(played.outputSampleRate) outputChannels=\(played.outputChannels) presentationLatencyMs=\(played.presentationLatency * 1000) completionElapsedMs=\(played.completionElapsed * 1000)") + exit(played.frames == Int(frame.samples) && played.outputSampleRate > 0 && played.outputChannels > 0 ? 0 : 1) } catch { print("smoke-native-audio: \(error)") exit(1) From 243a2d2c5852f893edec7363742f31cfd4e3c713 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:03:33 -0500 Subject: [PATCH 70/82] Discover host audio output devices through Core Audio Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 138c18ba..f11dc7ce 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -176,6 +176,7 @@ struct AudioVfsFrame { private enum FixturePlaybackError: Error { case invalidPCM case noDefaultOutput(OSStatus) + case deviceDiscovery(OSStatus) case timedOut } @@ -205,6 +206,40 @@ private func defaultAudioOutput() throws -> AudioDeviceID { return device } +private func audioOutputDevices() throws -> [AudioDeviceID] { + let system = AudioObjectID(kAudioObjectSystemObject) + var address = AudioObjectPropertyAddress( + mSelector: kAudioHardwarePropertyDevices, + mScope: kAudioObjectPropertyScopeGlobal, + mElement: kAudioObjectPropertyElementMain + ) + let stride = UInt32(MemoryLayout.stride) + var size: UInt32 = 0 + let sizeStatus = AudioObjectGetPropertyDataSize(system, &address, 0, nil, &size) + guard sizeStatus == noErr, size.isMultiple(of: stride) else { + throw FixturePlaybackError.deviceDiscovery(sizeStatus) + } + if size == 0 { return [] } + var devices = [AudioDeviceID](repeating: kAudioObjectUnknown, count: Int(size / stride)) + let readStatus = devices.withUnsafeMutableBytes { bytes in + AudioObjectGetPropertyData(system, &address, 0, nil, &size, bytes.baseAddress!) + } + guard readStatus == noErr, size.isMultiple(of: stride), Int(size / stride) <= devices.count else { + throw FixturePlaybackError.deviceDiscovery(readStatus) + } + return devices.prefix(Int(size / stride)).filter { device in + var streams = AudioObjectPropertyAddress( + mSelector: kAudioDevicePropertyStreams, + mScope: kAudioDevicePropertyScopeOutput, + mElement: kAudioObjectPropertyElementMain + ) + var bytes: UInt32 = 0 + return device != kAudioObjectUnknown + && AudioObjectGetPropertyDataSize(device, &streams, 0, nil, &bytes) == noErr + && bytes > 0 + }.sorted() +} + private func playFixturePCM(_ pcm: [UInt8]) throws -> FixturePlayback { // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), @@ -678,6 +713,21 @@ if CommandLine.arguments.contains("--smoke-resources") { } // `--smoke-audio-vfs` tests VFS asset loading, PCM audio streaming, and Metal texture presentation. +if CommandLine.arguments.contains("--list-audio-outputs") { + do { + let devices = try audioOutputDevices() + let defaultDevice = try? defaultAudioOutput() + print("audio-outputs: count=\(devices.count)") + for device in devices { + print("audio-output: id=\(device) default=\(device == defaultDevice)") + } + exit(0) + } catch { + print("audio-outputs: \(error)") + exit(1) + } +} + if CommandLine.arguments.contains("--smoke-native-audio") { let frame = AudioVfsFrame.run(captureAudio: true) guard frame.status == XENORA_OK, frame.samples == 256, frame.pcm.count == 512 else { From ccaa92ce3a2768a82ce86a91e5b2ae871030e72f Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:04:21 -0500 Subject: [PATCH 71/82] Verify sequential native PCM buffer playback Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 46 +++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index f11dc7ce..79609e56 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -182,6 +182,7 @@ private enum FixturePlaybackError: Error { private struct FixturePlayback { let frames: Int + let buffers: Int let outputDevice: AudioDeviceID let outputSampleRate: Double let outputChannels: AVAudioChannelCount @@ -243,17 +244,11 @@ private func audioOutputDevices() throws -> [AudioDeviceID] { private func playFixturePCM(_ pcm: [UInt8]) throws -> FixturePlayback { // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), - let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1), - let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(pcm.count / 2)), - let samples = buffer.floatChannelData?[0] else { + let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1) else { throw FixturePlaybackError.invalidPCM } - buffer.frameLength = buffer.frameCapacity - for frame in 0.. FixturePlayback { try engine.start() let output = engine.outputNode.outputFormat(forBus: 0) let presentationLatency = engine.outputNode.presentationLatency - player.scheduleBuffer(buffer, completionCallbackType: .dataPlayedBack) { _ in - played.signal() + var bufferCount = 0 + for first in stride(from: 0, to: frames, by: framesPerBuffer) { + let count = min(framesPerBuffer, frames - first) + guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)), + let samples = buffer.floatChannelData?[0] else { + throw FixturePlaybackError.invalidPCM + } + buffer.frameLength = AVAudioFrameCount(count) + for offset in 0.. 0 && played.outputChannels > 0 ? 0 : 1) + print("smoke-native-audio: playedBackFrames=\(played.frames) playedBackBuffers=\(played.buffers) defaultDevice=\(played.outputDevice) outputRate=\(played.outputSampleRate) outputChannels=\(played.outputChannels) presentationLatencyMs=\(played.presentationLatency * 1000) completionElapsedMs=\(played.completionElapsed * 1000)") + exit(played.frames == Int(frame.samples) && played.buffers == 2 && played.outputSampleRate > 0 && played.outputChannels > 0 ? 0 : 1) } catch { print("smoke-native-audio: \(error)") exit(1) From efe9fdeb8d6e37d2a5ce8ab4ad23f173982657b0 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:05:17 -0500 Subject: [PATCH 72/82] Select and verify the native playback output device Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 44 +++++++++++++++++++++++++++++++---- 1 file changed, 40 insertions(+), 4 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 79609e56..13fb085e 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -6,6 +6,7 @@ import AppKit import AVFoundation +import AudioToolbox import CoreAudio import CXenora import Foundation @@ -177,6 +178,10 @@ private enum FixturePlaybackError: Error { case invalidPCM case noDefaultOutput(OSStatus) case deviceDiscovery(OSStatus) + case unavailableOutput(AudioDeviceID) + case outputUnitUnavailable + case outputRouting(OSStatus) + case unexpectedOutput(AudioDeviceID) case timedOut } @@ -241,7 +246,7 @@ private func audioOutputDevices() throws -> [AudioDeviceID] { }.sorted() } -private func playFixturePCM(_ pcm: [UInt8]) throws -> FixturePlayback { +private func playFixturePCM(_ pcm: [UInt8], requestedOutput: AudioDeviceID? = nil) throws -> FixturePlayback { // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1) else { @@ -249,8 +254,20 @@ private func playFixturePCM(_ pcm: [UInt8]) throws -> FixturePlayback { } let frames = pcm.count / 2 let framesPerBuffer = 128 - let outputDevice = try defaultAudioOutput() let engine = AVAudioEngine() + guard let outputUnit = engine.outputNode.audioUnit else { + throw FixturePlaybackError.outputUnitUnavailable + } + if var device = requestedOutput { + guard try audioOutputDevices().contains(device) else { + throw FixturePlaybackError.unavailableOutput(device) + } + let status = AudioUnitSetProperty( + outputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, + &device, UInt32(MemoryLayout.size) + ) + guard status == noErr else { throw FixturePlaybackError.outputRouting(status) } + } let player = AVAudioPlayerNode() let played = DispatchSemaphore(value: 0) engine.attach(player) @@ -261,6 +278,16 @@ private func playFixturePCM(_ pcm: [UInt8]) throws -> FixturePlayback { engine.detach(player) } try engine.start() + var outputDevice = AudioDeviceID(kAudioObjectUnknown) + var outputIDSize = UInt32(MemoryLayout.size) + let routeStatus = AudioUnitGetProperty( + outputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, + &outputDevice, &outputIDSize + ) + guard routeStatus == noErr else { throw FixturePlaybackError.outputRouting(routeStatus) } + guard outputDevice != kAudioObjectUnknown, requestedOutput.map({ $0 == outputDevice }) ?? true else { + throw FixturePlaybackError.unexpectedOutput(outputDevice) + } let output = engine.outputNode.outputFormat(forBus: 0) let presentationLatency = engine.outputNode.presentationLatency var bufferCount = 0 @@ -743,14 +770,23 @@ if CommandLine.arguments.contains("--list-audio-outputs") { } if CommandLine.arguments.contains("--smoke-native-audio") { + var requestedOutput: AudioDeviceID? + if let index = CommandLine.arguments.firstIndex(of: "--audio-output") { + let values = CommandLine.arguments + guard index + 1 < values.count, let device = AudioDeviceID(values[index + 1]), device != 0 else { + print("smoke-native-audio: --audio-output requires a device ID") + exit(2) + } + requestedOutput = device + } let frame = AudioVfsFrame.run(captureAudio: true) guard frame.status == XENORA_OK, frame.samples == 256, frame.pcm.count == 512 else { print("smoke-native-audio: fixture PCM unavailable") exit(1) } do { - let played = try playFixturePCM(frame.pcm) - print("smoke-native-audio: playedBackFrames=\(played.frames) playedBackBuffers=\(played.buffers) defaultDevice=\(played.outputDevice) outputRate=\(played.outputSampleRate) outputChannels=\(played.outputChannels) presentationLatencyMs=\(played.presentationLatency * 1000) completionElapsedMs=\(played.completionElapsed * 1000)") + let played = try playFixturePCM(frame.pcm, requestedOutput: requestedOutput) + print("smoke-native-audio: playedBackFrames=\(played.frames) playedBackBuffers=\(played.buffers) outputDevice=\(played.outputDevice) outputRate=\(played.outputSampleRate) outputChannels=\(played.outputChannels) presentationLatencyMs=\(played.presentationLatency * 1000) completionElapsedMs=\(played.completionElapsed * 1000)") exit(played.frames == Int(frame.samples) && played.buffers == 2 && played.outputSampleRate > 0 && played.outputChannels > 0 ? 0 : 1) } catch { print("smoke-native-audio: \(error)") From 1edcbb651dd0b6f00b9c4473701008e03f9c5e1b Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:06:17 -0500 Subject: [PATCH 73/82] Verify native audio mixing and sample-rate conversion offline Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/AudioMixFixture.swift | 84 ++++++++++++++++++++++++ app/Sources/Xenora/main.swift | 12 ++++ 2 files changed, 96 insertions(+) create mode 100644 app/Sources/Xenora/AudioMixFixture.swift diff --git a/app/Sources/Xenora/AudioMixFixture.swift b/app/Sources/Xenora/AudioMixFixture.swift new file mode 100644 index 00000000..e81a0249 --- /dev/null +++ b/app/Sources/Xenora/AudioMixFixture.swift @@ -0,0 +1,84 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +import AVFoundation +import Foundation + +struct AudioMixMeasurement { + let frames: Int + let mean: Double + let toneAmplitude: Double +} + +enum AudioMixFixtureError: Error { + case bufferAllocation + case renderFailure(AVAudioEngineManualRenderingStatus) + case shortRender +} + +func measureAudioMixFixture() throws -> AudioMixMeasurement { + let outputRate = 48_000.0 + let toneRate = 44_100.0 + let toneFrequency = 1_000.0 + let blockSize: AVAudioFrameCount = 480 + let totalFrames = 4_800 + guard let outputFormat = AVAudioFormat(standardFormatWithSampleRate: outputRate, channels: 1), + let toneFormat = AVAudioFormat(standardFormatWithSampleRate: toneRate, channels: 1), + let constant = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: 4_800), + let tone = AVAudioPCMBuffer(pcmFormat: toneFormat, frameCapacity: 4_410), + let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: blockSize), + let constantSamples = constant.floatChannelData?[0], + let toneSamples = tone.floatChannelData?[0], + let outputSamples = output.floatChannelData?[0] else { + throw AudioMixFixtureError.bufferAllocation + } + constant.frameLength = constant.frameCapacity + tone.frameLength = tone.frameCapacity + for index in 0.. Date: Tue, 24 Nov 2026 09:07:08 -0500 Subject: [PATCH 74/82] Refill a bounded native audio playback window Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 44 ++++++++++++++++++++++++++--------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index b569e2ca..72ff97a4 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -188,6 +188,7 @@ private enum FixturePlaybackError: Error { private struct FixturePlayback { let frames: Int let buffers: Int + let refills: Int let outputDevice: AudioDeviceID let outputSampleRate: Double let outputChannels: AVAudioChannelCount @@ -246,14 +247,18 @@ private func audioOutputDevices() throws -> [AudioDeviceID] { }.sorted() } -private func playFixturePCM(_ pcm: [UInt8], requestedOutput: AudioDeviceID? = nil) throws -> FixturePlayback { +private func playFixturePCM( + _ pcm: [UInt8], requestedOutput: AudioDeviceID? = nil, streamingFixture: Bool = false +) throws -> FixturePlayback { // The embedded audio/VFS fixture submits mono 48 kHz S16LE frames. guard !pcm.isEmpty, pcm.count.isMultiple(of: 2), let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1) else { throw FixturePlaybackError.invalidPCM } - let frames = pcm.count / 2 - let framesPerBuffer = 128 + let sourceFrames = pcm.count / 2 + let frames = sourceFrames * (streamingFixture ? 32 : 1) + let framesPerBuffer = streamingFixture ? 1024 : 128 + let bufferWindow = 3 let engine = AVAudioEngine() guard let outputUnit = engine.outputNode.audioUnit else { throw FixturePlaybackError.outputUnitUnavailable @@ -290,8 +295,10 @@ private func playFixturePCM(_ pcm: [UInt8], requestedOutput: AudioDeviceID? = ni } let output = engine.outputNode.outputFormat(forBus: 0) let presentationLatency = engine.outputNode.presentationLatency + var nextFrame = 0 var bufferCount = 0 - for first in stride(from: 0, to: frames, by: framesPerBuffer) { + func scheduleNextBuffer() throws { + let first = nextFrame let count = min(framesPerBuffer, frames - first) guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)), let samples = buffer.floatChannelData?[0] else { @@ -299,7 +306,7 @@ private func playFixturePCM(_ pcm: [UInt8], requestedOutput: AudioDeviceID? = ni } buffer.frameLength = AVAudioFrameCount(count) for offset in 0.. 0 && played.outputChannels > 0 ? 0 : 1) + let played = try playFixturePCM( + frame.pcm, requestedOutput: requestedOutput, streamingFixture: nativeAudioStreamSmoke + ) + print("smoke-native-audio: playedBackFrames=\(played.frames) playedBackBuffers=\(played.buffers) refills=\(played.refills) outputDevice=\(played.outputDevice) outputRate=\(played.outputSampleRate) outputChannels=\(played.outputChannels) presentationLatencyMs=\(played.presentationLatency * 1000) completionElapsedMs=\(played.completionElapsed * 1000)") + let expected = nativeAudioStreamSmoke ? (8192, 8, 5) : (256, 2, 0) + exit((played.frames, played.buffers, played.refills) == expected + && played.outputSampleRate > 0 && played.outputChannels > 0 ? 0 : 1) } catch { print("smoke-native-audio: \(error)") exit(1) From 3ca4c8586cdc2b1cce26d19dd35f649ea4264964 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:08:10 -0500 Subject: [PATCH 75/82] Render PCM playback blocks with silence and accurate underrun counts Signed-off-by: Adeeb Rahman --- crates/ffi/include/xenora.h | 13 ++++- crates/ffi/src/lib.rs | 98 ++++++++++++++++++++++++++++++++++++- 2 files changed, 109 insertions(+), 2 deletions(-) diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index da6ff23d..85fe0bf6 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -267,7 +267,18 @@ xenora_status xenora_session_audio_read( ); /* - * Query current audio queue status: queued bytes, underruns, total submitted. + * Fill one playback block with whole frames, padding a shortfall with silence. + * out_source_bytes reports how much PCM was supplied before padding. + */ +xenora_status xenora_session_audio_render( + xenora_session session, + uint8_t *out_pcm, + uint64_t byte_count, + uint64_t *out_source_bytes +); + +/* + * Query queued bytes, render calls that ran short, and total bytes submitted. */ xenora_status xenora_session_audio_status( xenora_session session, diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index b78ff58f..775ad5ab 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -143,7 +143,6 @@ impl AudioSubsystem { for b in processed_bytes { if self.queue.len() >= self.max_capacity_bytes { self.queue.pop_front(); - self.underruns = self.underruns.saturating_add(1); } self.queue.push_back(b); } @@ -157,6 +156,15 @@ impl AudioSubsystem { } count } + + fn render(&mut self, out: &mut [u8]) -> usize { + let supplied = self.read(out); + if supplied < out.len() { + out[supplied..].fill(0); + self.underruns = self.underruns.saturating_add(1); + } + supplied + } } pub const XENORA_NO_FILE: u64 = 0; @@ -1395,6 +1403,42 @@ pub unsafe extern "C" fn xenora_session_audio_read( }) } +/// Fill an aligned PCM playback block. Missing frames are replaced with silence. +/// +/// # Safety +/// `out_pcm` must point to `byte_count` writable bytes and `out_source_bytes` +/// must be valid for one aligned `u64` write. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_audio_render( + session: u64, + out_pcm: *mut u8, + byte_count: u64, + out_source_bytes: *mut u64, +) -> i32 { + guarded(|| { + if out_pcm.is_null() + || out_source_bytes.is_null() + || !(1..=256 * 1024).contains(&byte_count) + { + return XENORA_INVALID_ARGUMENT; + } + let Ok(mut slots) = SESSIONS.lock() else { + return XENORA_INTERNAL_ERROR; + }; + if !is_live(&slots, session) { + return XENORA_INVALID_HANDLE; + } + let audio = &mut slots[split(session).0].audio; + if !(byte_count as usize).is_multiple_of(audio.frame_bytes()) { + return XENORA_INVALID_ARGUMENT; + } + let output = unsafe { std::slice::from_raw_parts_mut(out_pcm, byte_count as usize) }; + let supplied = audio.render(output); + unsafe { out_source_bytes.write(supplied as u64) }; + XENORA_OK + }) +} + /// # Safety /// Each output pointer must be non-null and valid for one aligned write. #[unsafe(no_mangle)] @@ -2539,6 +2583,58 @@ mod tests { xenora_session_destroy(session); } + #[test] + fn audio_render_pads_missing_frames_and_counts_only_render_shortfalls() { + let _guard = serial(); + let session = create(); + assert_eq!( + xenora_session_audio_init(session, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE), + XENORA_OK + ); + let frame = [1, 2, 3, 4]; + assert_eq!( + unsafe { xenora_session_audio_submit(session, frame.as_ptr(), 4) }, + XENORA_OK + ); + let mut output = [0xaa; 8]; + let mut supplied = 99; + assert_eq!( + unsafe { xenora_session_audio_render(session, output.as_mut_ptr(), 7, &mut supplied) }, + XENORA_INVALID_ARGUMENT + ); + assert_eq!(output, [0xaa; 8]); + assert_eq!(supplied, 99); + assert_eq!( + unsafe { xenora_session_audio_render(session, output.as_mut_ptr(), 8, &mut supplied) }, + XENORA_OK + ); + assert_eq!(supplied, 4); + assert_eq!(output, [1, 2, 3, 4, 0, 0, 0, 0]); + assert_eq!( + unsafe { xenora_session_audio_render(session, output.as_mut_ptr(), 8, &mut supplied) }, + XENORA_OK + ); + assert_eq!(supplied, 0); + assert_eq!(output, [0; 8]); + let overflow = vec![0; 256 * 1024 + 4]; + assert_eq!( + unsafe { + xenora_session_audio_submit(session, overflow.as_ptr(), overflow.len() as u64) + }, + XENORA_OK + ); + let (mut queued, mut underruns, mut total) = (0, 0, 0); + assert_eq!( + unsafe { + xenora_session_audio_status(session, &mut queued, &mut underruns, &mut total) + }, + XENORA_OK + ); + assert_eq!(queued, 256 * 1024); + assert_eq!(underruns, 2); + xenora_session_destroy(session); + } + #[test] fn float_pcm_applies_gain_and_preserves_stereo_frame_boundaries() { let _guard = serial(); From e984cfc0991281161d8c3a29ed8a565defb4952d Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:09:16 -0500 Subject: [PATCH 76/82] Feed native playback refills through the runtime PCM queue Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 71 ++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 6 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 72ff97a4..68e4277f 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -182,6 +182,8 @@ private enum FixturePlaybackError: Error { case outputUnitUnavailable case outputRouting(OSStatus) case unexpectedOutput(AudioDeviceID) + case queueFailure(Int32) + case queueShortfall(UInt64) case timedOut } @@ -189,6 +191,7 @@ private struct FixturePlayback { let frames: Int let buffers: Int let refills: Int + let underruns: UInt32 let outputDevice: AudioDeviceID let outputSampleRate: Double let outputChannels: AVAudioChannelCount @@ -259,6 +262,23 @@ private func playFixturePCM( let frames = sourceFrames * (streamingFixture ? 32 : 1) let framesPerBuffer = streamingFixture ? 1024 : 128 let bufferWindow = 3 + var streamSession: xenora_session = 0 + let producer = DispatchQueue(label: "xenora.fixture.pcm") + if streamingFixture { + let createStatus = xenora_session_create(XENORA_ABI_VERSION, &streamSession) + guard createStatus == XENORA_OK else { throw FixturePlaybackError.queueFailure(createStatus) } + } + let session = streamSession + defer { + if session != 0 { + producer.sync {} + _ = xenora_session_destroy(session) + } + } + if session != 0 { + let initStatus = xenora_session_audio_init(session, 48_000, 1, UInt32(XENORA_AUDIO_FORMAT_PCM_S16LE)) + guard initStatus == XENORA_OK else { throw FixturePlaybackError.queueFailure(initStatus) } + } let engine = AVAudioEngine() guard let outputUnit = engine.outputNode.audioUnit else { throw FixturePlaybackError.outputUnitUnavailable @@ -297,18 +317,46 @@ private func playFixturePCM( let presentationLatency = engine.outputNode.presentationLatency var nextFrame = 0 var bufferCount = 0 + func renderBlock(first: Int, count: Int) throws -> [UInt8] { + let firstByte = first * 2 + let byteCount = count * 2 + if session == 0 { + return Array(pcm[firstByte..<(firstByte + byteCount)]) + } + let submitted = DispatchSemaphore(value: 0) + producer.async { + let block = (0.. 0 && played.outputChannels > 0 ? 0 : 1) + && played.underruns == 0 && played.outputSampleRate > 0 && played.outputChannels > 0 ? 0 : 1) } catch { print("smoke-native-audio: \(error)") exit(1) From b8b42c73bf697d601313275bac13add19585614a Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:10:35 -0500 Subject: [PATCH 77/82] Feed macOS GameController snapshots to the interactive guest Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/ControllerInput.swift | 61 ++++++++++++++++++++++++ app/Sources/Xenora/main.swift | 37 ++++++++++++-- 2 files changed, 95 insertions(+), 3 deletions(-) create mode 100644 app/Sources/Xenora/ControllerInput.swift diff --git a/app/Sources/Xenora/ControllerInput.swift b/app/Sources/Xenora/ControllerInput.swift new file mode 100644 index 00000000..025c3c92 --- /dev/null +++ b/app/Sources/Xenora/ControllerInput.swift @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +import CXenora +import GameController + +struct ControllerSnapshot: Equatable { + let buttons: UInt32 + let x: Int16 + let y: Int16 + let leftTrigger: Float + let rightTrigger: Float + + init(buttons: UInt32, x: Float, y: Float, leftTrigger: Float, rightTrigger: Float) { + self.buttons = buttons + self.x = Self.axis(x) + self.y = Self.axis(y) + self.leftTrigger = Self.trigger(leftTrigger) + self.rightTrigger = Self.trigger(rightTrigger) + } + + private static func axis(_ value: Float) -> Int16 { + guard value.isFinite else { return 0 } + let deadZone: Float = 0.15 + let magnitude = max(0, min(1, abs(value)) - deadZone) / (1 - deadZone) + return Int16((magnitude * (value < 0 ? -32767 : 32767)).rounded()) + } + + private static func trigger(_ value: Float) -> Float { + value.isFinite ? min(1, max(0, value)) : 0 + } +} + +struct DetectedController: Equatable { + let identity: ObjectIdentifier + let name: String + let supportsHaptics: Bool + let snapshot: ControllerSnapshot +} + +@MainActor +func pollGameController() -> DetectedController? { + let controller = GCController.current.flatMap { $0.extendedGamepad == nil ? nil : $0 } + ?? GCController.controllers().first { $0.extendedGamepad != nil } + guard let controller, let pad = controller.capture().extendedGamepad else { return nil } + var buttons: UInt32 = 0 + if pad.dpad.right.isPressed { buttons |= UInt32(XENORA_INPUT_RIGHT) } + if pad.dpad.left.isPressed { buttons |= UInt32(XENORA_INPUT_LEFT) } + if pad.dpad.up.isPressed { buttons |= UInt32(XENORA_INPUT_UP) } + if pad.dpad.down.isPressed { buttons |= UInt32(XENORA_INPUT_DOWN) } + if pad.buttonA.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_A) } + if pad.buttonB.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_B) } + return DetectedController( + identity: ObjectIdentifier(controller), + name: controller.vendorName ?? controller.productCategory, + supportsHaptics: controller.haptics != nil, + snapshot: ControllerSnapshot( + buttons: buttons, x: pad.leftThumbstick.xAxis.value, y: pad.leftThumbstick.yAxis.value, + leftTrigger: pad.leftTrigger.value, rightTrigger: pad.rightTrigger.value + ) + ) +} diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 68e4277f..b61adc35 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -447,6 +447,7 @@ final class FrameLoopModel: ObservableObject { @Published var image: CGImage? @Published var errorMessage: String? @Published var isInteractive: Bool = false + @Published private(set) var controller: DetectedController? private var session: xenora_session = 0 private var pollTask: Task? @@ -526,6 +527,7 @@ final class FrameLoopModel: ObservableObject { return } isInteractive = true + controller = nil state = UInt32(XENORA_LOOP_RUNNING) completed = 0 frameId = XENORA_NO_FRAME @@ -534,20 +536,33 @@ final class FrameLoopModel: ObservableObject { } func sendInput(buttons: UInt32) { + sendInput(buttons: buttons, x: 0, y: 0, connected: true) + } + + private func sendInput(buttons: UInt32, x: Int16, y: Int16, connected: Bool) { guard session != 0 else { return } var input = xenora_input_state( buttons: buttons, - stick_x: 0, - stick_y: 0, + stick_x: x, + stick_y: y, mouse_dx: 0, mouse_dy: 0, mouse_buttons: 0, - connected: 1, + connected: connected ? 1 : 0, reserved: 0 ) _ = xenora_session_send_input(session, &input) } + private func updateGameController() { + let next = pollGameController() + guard next != controller else { return } + controller = next + let snapshot = next?.snapshot + sendInput(buttons: snapshot?.buttons ?? 0, x: snapshot?.x ?? 0, y: snapshot?.y ?? 0, + connected: next != nil) + } + func pause() { guard session != 0 else { return } _ = xenora_session_pause_frame_loop(session) @@ -569,6 +584,9 @@ final class FrameLoopModel: ObservableObject { while !Task.isCancelled { try? await Task.sleep(nanoseconds: 16_000_000) guard let self = self, self.session != 0 else { break } + if self.isInteractive { + self.updateGameController() + } var st: UInt32 = 0 var comp: UInt32 = 0 var fId: UInt32 = 0 @@ -773,6 +791,11 @@ struct ContentView: View { .disabled(!loop.isRunning && !loop.isPaused) } if loop.isInteractive && (loop.isRunning || loop.isPaused) { + if let controller = loop.controller { + Text("Controller: \(controller.name)") + .font(.caption) + .foregroundStyle(.secondary) + } HStack { Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) } Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) } @@ -830,6 +853,14 @@ if CommandLine.arguments.contains("--smoke-resources") { } // `--smoke-audio-vfs` tests VFS asset loading, PCM audio streaming, and Metal texture presentation. +if CommandLine.arguments.contains("--smoke-controller") { + let simulated = ControllerSnapshot(buttons: 1, x: 0.1, y: -1, leftTrigger: 1.2, rightTrigger: .nan) + let physical = pollGameController() + print("smoke-controller: simulatedAxis=\(simulated.x),\(simulated.y) triggers=\(simulated.leftTrigger),\(simulated.rightTrigger) detected=\(physical?.name ?? "none")") + exit(simulated.buttons == 1 && simulated.x == 0 && simulated.y == -32767 + && simulated.leftTrigger == 1 && simulated.rightTrigger == 0 ? 0 : 1) +} + if CommandLine.arguments.contains("--smoke-audio-mix") { do { let result = try measureAudioMixFixture() From 6b55d76a14a99f382a5da20c9a4a1e1552820e32 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:12:02 -0500 Subject: [PATCH 78/82] Carry analog triggers in extended guest controller snapshots Signed-off-by: Adeeb Rahman --- app/Sources/Xenora/main.swift | 16 +++++-- crates/ffi/include/xenora.h | 8 ++++ crates/ffi/src/frame_loop.rs | 79 ++++++++++++++++++++++++++++++++++- crates/ffi/src/lib.rs | 24 +++++++++++ 4 files changed, 121 insertions(+), 6 deletions(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index b61adc35..a3fb18f8 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -539,9 +539,12 @@ final class FrameLoopModel: ObservableObject { sendInput(buttons: buttons, x: 0, y: 0, connected: true) } - private func sendInput(buttons: UInt32, x: Int16, y: Int16, connected: Bool) { + private func sendInput( + buttons: UInt32, x: Int16, y: Int16, connected: Bool, + leftTrigger: Float = 0, rightTrigger: Float = 0 + ) { guard session != 0 else { return } - var input = xenora_input_state( + let state = xenora_input_state( buttons: buttons, stick_x: x, stick_y: y, @@ -551,7 +554,11 @@ final class FrameLoopModel: ObservableObject { connected: connected ? 1 : 0, reserved: 0 ) - _ = xenora_session_send_input(session, &input) + var input = xenora_controller_input( + state: state, left_trigger: UInt16((leftTrigger * 65535).rounded()), + right_trigger: UInt16((rightTrigger * 65535).rounded()) + ) + _ = xenora_session_send_controller_input(session, &input) } private func updateGameController() { @@ -560,7 +567,8 @@ final class FrameLoopModel: ObservableObject { controller = next let snapshot = next?.snapshot sendInput(buttons: snapshot?.buttons ?? 0, x: snapshot?.x ?? 0, y: snapshot?.y ?? 0, - connected: next != nil) + connected: next != nil, leftTrigger: snapshot?.leftTrigger ?? 0, + rightTrigger: snapshot?.rightTrigger ?? 0) } func pause() { diff --git a/crates/ffi/include/xenora.h b/crates/ffi/include/xenora.h index 85fe0bf6..7f508e3e 100644 --- a/crates/ffi/include/xenora.h +++ b/crates/ffi/include/xenora.h @@ -59,6 +59,13 @@ typedef struct { uint16_t reserved; } xenora_input_state; +/* Extended controller snapshot. Trigger values span 0 to 65535. */ +typedef struct { + xenora_input_state state; + uint16_t left_trigger; + uint16_t right_trigger; +} xenora_controller_input; + #define XENORA_INPUT_NONE 0u #define XENORA_INPUT_RIGHT (1u << 0) #define XENORA_INPUT_LEFT (1u << 1) @@ -116,6 +123,7 @@ xenora_status xenora_session_run_trusted_fixture( xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count); xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count); xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input); +xenora_status xenora_session_send_controller_input(xenora_session session, const xenora_controller_input *input); xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input); xenora_status xenora_session_pause_frame_loop(xenora_session session); xenora_status xenora_session_resume_frame_loop(xenora_session session); diff --git a/crates/ffi/src/frame_loop.rs b/crates/ffi/src/frame_loop.rs index 8357944c..1e5b3479 100644 --- a/crates/ffi/src/frame_loop.rs +++ b/crates/ffi/src/frame_loop.rs @@ -50,6 +50,34 @@ pub struct InputState { pub reserved: u16, } +#[derive(Default, Copy, Clone)] +#[repr(C)] +pub struct ControllerInput { + pub state: InputState, + pub left_trigger: u16, + pub right_trigger: u16, +} + +impl ControllerInput { + fn guest_bytes(self) -> [u8; 20] { + let mut bytes = [0; 20]; + bytes[..4].copy_from_slice(&self.state.buttons.to_le_bytes()); + for (slot, value) in bytes[4..12].as_chunks_mut::<2>().0.iter_mut().zip([ + self.state.stick_x, + self.state.stick_y, + self.state.mouse_dx, + self.state.mouse_dy, + ]) { + *slot = value.to_le_bytes(); + } + bytes[12] = self.state.mouse_buttons; + bytes[13] = self.state.connected; + bytes[16..18].copy_from_slice(&self.left_trigger.to_le_bytes()); + bytes[18..20].copy_from_slice(&self.right_trigger.to_le_bytes()); + bytes + } +} + #[derive(Default)] struct State { status: u32, @@ -58,7 +86,7 @@ struct State { interactive: bool, limit: u32, completed: u32, - input: InputState, + input: ControllerInput, input_queue: std::collections::VecDeque, recorded_frames: Vec<(u32, Vec)>, /// Every `frame_submit` call the guest made, including the one answered with 0. @@ -131,6 +159,13 @@ impl FrameLoop { } pub fn send_input(&self, input: InputState) { + self.send_controller_input(ControllerInput { + state: input, + ..ControllerInput::default() + }); + } + + pub fn send_controller_input(&self, input: ControllerInput) { let mut state = self.lock(); state.input = input; } @@ -187,7 +222,7 @@ impl FrameLoop { let shared_poll = Arc::clone(self); imports.register("xenora.dll", "input_poll", move |_args, _, _memory| { let mut state = shared_poll.lock(); - let input = state.input_queue.pop_front().unwrap_or(state.input); + let input = state.input_queue.pop_front().unwrap_or(state.input.state); let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 { 1u64 } else if input.buttons & crate::XENORA_INPUT_LEFT != 0 { @@ -197,6 +232,18 @@ impl FrameLoop { }; Ok(cmd) }); + let snapshot = Arc::clone(self); + imports.register( + "xenora.dll", + "input_poll_snapshot", + move |args, _, memory| { + let input = snapshot.lock().input; + memory + .write_bytes(args.rcx, &input.guest_bytes()) + .map_err(ExitReason::MemoryFault)?; + Ok(1) + }, + ); } let limit = self.lock().limit as usize; let is_interactive = self.lock().interactive; @@ -311,3 +358,31 @@ pub fn expected(index: u32) -> Vec { }) .collect() } + +#[cfg(test)] +#[test] +fn extended_controller_snapshot_retains_trigger_bytes_and_legacy_input_resets_them() { + let running = FrameLoop::default(); + running.send_controller_input(ControllerInput { + state: InputState { + buttons: 0x10, + stick_x: -32767, + stick_y: 9, + connected: 1, + reserved: u16::MAX, + ..InputState::default() + }, + left_trigger: 0x1234, + right_trigger: u16::MAX, + }); + let bytes = running.lock().input.guest_bytes(); + assert_eq!(std::mem::size_of::(), 20); + assert_eq!( + bytes, + [ + 16, 0, 0, 0, 1, 128, 9, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0x34, 0x12, 255, 255 + ] + ); + running.send_input(InputState::default()); + assert_eq!(running.lock().input.guest_bytes(), [0; 20]); +} diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 775ad5ab..6f8869e2 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -50,6 +50,7 @@ pub const XENORA_INPUT_DOWN: u32 = 1 << 3; pub const XENORA_INPUT_ACTION_A: u32 = 1 << 4; pub const XENORA_INPUT_ACTION_B: u32 = 1 << 5; +pub use frame_loop::ControllerInput as xenora_controller_input; pub use frame_loop::InputState as xenora_input_state; pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4; @@ -431,6 +432,29 @@ pub unsafe extern "C" fn xenora_session_send_input( }) } +/// # Safety +/// `input` must be a valid pointer to an initialized `xenora_controller_input`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn xenora_session_send_controller_input( + session: u64, + input: *const frame_loop::ControllerInput, +) -> i32 { + guarded(|| { + if input.is_null() { + return XENORA_INVALID_ARGUMENT; + } + let input = unsafe { *input }; + match session_loop(session) { + Ok(Some(running)) => { + running.send_controller_input(input); + XENORA_OK + } + Ok(None) => XENORA_INVALID_STATE, + Err(status) => status, + } + }) +} + /// # Safety /// `input` must be a valid pointer to an initialized `xenora_input_state`. #[unsafe(no_mangle)] From ac6f9daff3491820381c60aa7ae1e45fce408c05 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:33:07 -0500 Subject: [PATCH 79/82] Add guest mutexes, locks, one-time init, SLists and TLS slots Ownership is keyed by guest TEB. Operations that would block another guest thread stop with the runtime-limit fault because no guest scheduler exists. Also stop the import generator from overriding the semaphore handlers with stubs, and check every generator standard service against the loader registry. Signed-off-by: Adeeb Rahman Co-authored-by: Cursor --- CHANGELOG.md | 4 + crates/cli/tests/standard_services.rs | 57 ++ crates/import-gen/src/apiset.rs | 1 + crates/import-gen/src/classify.rs | 113 ++-- crates/loader/src/services.rs | 4 + crates/loader/src/services/events.rs | 117 +++- crates/loader/src/services/synch.rs | 866 ++++++++++++++++++++++++++ crates/loader/tests/runtime_synch.rs | 744 ++++++++++++++++++++++ docs/interfaces.md | 58 ++ 9 files changed, 1912 insertions(+), 52 deletions(-) create mode 100644 crates/cli/tests/standard_services.rs create mode 100644 crates/loader/src/services/synch.rs create mode 100644 crates/loader/tests/runtime_synch.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c799ecd..2a634291 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -39,6 +39,10 @@ remains unsupported. - Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215. - Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215. +- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`. + +- Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler. + - Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services. - Added same-process guest file handle duplication with a shared file position. diff --git a/crates/cli/tests/standard_services.rs b/crates/cli/tests/standard_services.rs new file mode 100644 index 00000000..c3d67dc9 --- /dev/null +++ b/crates/cli/tests/standard_services.rs @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! The import generator skips emitting an adapter for a symbol it classifies +//! as a standard service, so every such classification must name a handler +//! the standard loader registry actually provides. + +use std::sync::Arc; +use xenora_import_gen::{Classification, SymbolDb}; +use xenora_loader::import_table::ImportName; +use xenora_loader::imports::{ImportRegistry, ServiceStatus}; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; + +#[test] +fn every_standard_service_classification_resolves_to_a_registered_handler() { + let mut registry = ImportRegistry::new(); + let state = ServicesState::new(Arc::new(MockClock::new(0))); + register_standard_services(&mut registry, Arc::new(state)); + + let db = SymbolDb::builtin(); + let mut checked = 0; + let mut missing = Vec::new(); + for (module, symbol, class) in db.entries() { + if !matches!(class, Classification::StandardService) { + continue; + } + checked += 1; + match registry.resolve(module, &ImportName::Name(symbol.to_string())) { + Some(service) if service.status != ServiceStatus::Stub => {} + _ => missing.push(format!("{module}!{symbol}")), + } + } + assert!(missing.is_empty(), "unregistered: {missing:?}"); + assert!(checked > 100, "{checked}"); +} + +#[test] +fn registered_synchronization_services_are_not_classified_as_stubs() { + let db = SymbolDb::builtin(); + for module in ["api-ms-win-core-synch-l1-1-0.dll", "kernel32.dll"] { + for symbol in [ + "CreateSemaphoreW", + "ReleaseSemaphore", + "CreateMutexW", + "EnterCriticalSection", + "TryEnterCriticalSection", + "AcquireSRWLockExclusive", + ] { + assert!( + matches!( + db.get(module, symbol), + Some(Classification::StandardService) + ), + "{module}!{symbol}" + ); + } + } +} diff --git a/crates/import-gen/src/apiset.rs b/crates/import-gen/src/apiset.rs index 39264b8f..cfd4d888 100644 --- a/crates/import-gen/src/apiset.rs +++ b/crates/import-gen/src/apiset.rs @@ -53,6 +53,7 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] { "api-ms-win-core-debug-l1-1-0.dll", "api-ms-win-core-handle-l1-1-0.dll", "api-ms-win-core-interlocked-l1-1-0.dll", + "api-ms-win-core-fibers-l1-1-0.dll", "api-ms-win-core-datetime-l1-1-1.dll", "api-ms-win-core-timezone-l1-1-0.dll", "api-ms-win-core-memory-l1-1-0.dll", diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 9eff9e7f..24e4c8f9 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -77,6 +77,17 @@ impl SymbolDb { self.entries.get(&key) } + /// Every classified `(module, symbol)` pair, sorted, with modules in lowercase. + pub fn entries(&self) -> Vec<(&str, &str, &Classification)> { + let mut entries: Vec<_> = self + .entries + .iter() + .map(|((module, symbol), class)| (module.as_str(), symbol.as_str(), class)) + .collect(); + entries.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1))); + entries + } + /// Build the built-in database. Every entry here is derived exclusively from /// public Microsoft documentation and ISO/POSIX standards. pub fn builtin() -> Self { @@ -784,53 +795,66 @@ impl SymbolDb { "WaitForSingleObjectEx", "WaitForMultipleObjects", "WaitForMultipleObjectsEx", + "CreateMutexA", + "CreateMutexW", + "CreateMutexExA", + "CreateMutexExW", + "ReleaseMutex", + "InitializeCriticalSection", + "InitializeCriticalSectionAndSpinCount", + "InitializeCriticalSectionEx", + "EnterCriticalSection", + "TryEnterCriticalSection", + "LeaveCriticalSection", + "DeleteCriticalSection", + "SetCriticalSectionSpinCount", + "InitializeSRWLock", + "AcquireSRWLockExclusive", + "AcquireSRWLockShared", + "TryAcquireSRWLockExclusive", + "TryAcquireSRWLockShared", + "ReleaseSRWLockExclusive", + "ReleaseSRWLockShared", ] { self.ins(module, symbol, Classification::StandardService); } } - self.win32_stub(m, "CreateMutexA", true, "CreateMutex — stub"); - self.win32_stub(m, "CreateMutexW", true, "CreateMutex wide — stub"); - self.win32_stub(m, "ReleaseMutex", false, "ReleaseMutex — stub"); + for module in ["api-ms-win-core-synch-l1-2-0.dll", "kernel32.dll"] { + for symbol in [ + "InitializeConditionVariable", + "WakeConditionVariable", + "WakeAllConditionVariable", + "SleepConditionVariableCS", + "SleepConditionVariableSRW", + "InitOnceInitialize", + "InitOnceBeginInitialize", + "InitOnceComplete", + ] { + self.ins(module, symbol, Classification::StandardService); + } + } + for module in ["api-ms-win-core-interlocked-l1-1-0.dll", "kernel32.dll"] { + for symbol in [ + "InitializeSListHead", + "InterlockedPushEntrySList", + "InterlockedPopEntrySList", + "InterlockedFlushSList", + "QueryDepthSList", + ] { + self.ins(module, symbol, Classification::StandardService); + } + } + for module in ["api-ms-win-core-processthreads-l1-1-0.dll", "kernel32.dll"] { + for symbol in ["TlsAlloc", "TlsFree", "TlsGetValue", "TlsSetValue"] { + self.ins(module, symbol, Classification::StandardService); + } + } + for module in ["api-ms-win-core-fibers-l1-1-0.dll", "kernel32.dll"] { + for symbol in ["FlsAlloc", "FlsFree", "FlsGetValue", "FlsSetValue"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub"); - self.win32_stub( - m, - "InitializeCriticalSection", - false, - "InitializeCriticalSection — no-op", - ); - self.win32_stub( - m, - "InitializeCriticalSectionAndSpinCount", - false, - "CRIT_SECTION with spin — no-op", - ); - self.win32_stub( - m, - "EnterCriticalSection", - false, - "EnterCriticalSection — no-op", - ); - self.win32_stub( - m, - "LeaveCriticalSection", - false, - "LeaveCriticalSection — no-op", - ); - self.win32_stub( - m, - "DeleteCriticalSection", - false, - "DeleteCriticalSection — no-op", - ); - self.win32_stub( - m, - "TryEnterCriticalSection", - false, - "TryEnterCriticalSection — returns TRUE", - ); - self.win32_stub(m, "CreateSemaphoreA", true, "CreateSemaphore — stub"); - self.win32_stub(m, "CreateSemaphoreW", true, "CreateSemaphore wide — stub"); - self.win32_stub(m, "ReleaseSemaphore", false, "ReleaseSemaphore — stub"); self.win32_stub( m, "InterlockedIncrement", @@ -863,12 +887,11 @@ impl SymbolDb { Classification::StandardService, ); self.win32_stub( - m2, + "api-ms-win-core-synch-l1-2-0.dll", "InitOnceExecuteOnce", false, - "InitOnce — executes callback directly", + "needs a guest callback with three arguments and its result", ); - self.win32_stub(m2, "InitOnceInitialize", false, "InitOnce init — no-op"); } // ---- Win32 library loader ---------------------------------------------- diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index d955ed23..f917413e 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -16,6 +16,7 @@ mod gdk_queue; mod heap; mod modules; mod platform_fixture; +mod synch; mod task_fixture; mod winsock; @@ -174,6 +175,7 @@ pub struct ServicesState { pub thread_id: u32, objects: Mutex, last_errors: Mutex>, + synch: Mutex, winsock: Mutex, task_fixture: Mutex, platform_fixture: Mutex, @@ -194,6 +196,7 @@ impl ServicesState { thread_id: 0x4104, // Synthetic main thread ID objects: Mutex::new(ObjectState::default()), last_errors: Mutex::default(), + synch: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), platform_fixture: Mutex::default(), @@ -333,6 +336,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc, + recursion: u32, + }, } impl Waitable { - fn is_ready(&self) -> bool { + fn is_ready(&self, teb: u64) -> bool { match self { Self::Event { signaled, .. } => *signaled, Self::Semaphore { count, .. } => *count > 0, + Self::Mutex { owner, .. } => owner.is_none_or(|owner| owner == teb), } } - fn consume(&mut self) { + fn consume(&mut self, teb: u64) { match self { Self::Event { manual_reset, signaled, } => *signaled = *manual_reset, Self::Semaphore { count, .. } => *count -= 1, + Self::Mutex { owner, recursion } => { + *owner = Some(teb); + *recursion += 1; + } } } + + fn at_recursion_limit(&self) -> bool { + matches!(self, Self::Mutex { recursion, .. } if *recursion >= i32::MAX as u32) + } } fn insert_waitable( @@ -67,6 +91,19 @@ fn insert_waitable( Ok(handle) } +fn insert_mutex( + state: &ServicesState, + teb: u64, + initial_owner: bool, + access: u32, +) -> Result { + let object = Waitable::Mutex { + owner: initial_owner.then_some(teb), + recursion: u32::from(initial_owner), + }; + insert_waitable(state, teb, object, access) +} + pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { for symbol in ["CreateEventA", "CreateEventW"] { let state = Arc::clone(state); @@ -168,6 +205,58 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc Ok(1) }); + for symbol in ["CreateMutexA", "CreateMutexW"] { + let state = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, cpu, mem| { + let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let initial_owner = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32 != 0; + let name = args.get(2, mem).map_err(ExitReason::MemoryFault)?; + if attributes != 0 || name != 0 { + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); + } + insert_mutex(&state, cpu.gs_base, initial_owner, MUTEX_ALL_ACCESS) + }); + } + + for symbol in ["CreateMutexExA", "CreateMutexExW"] { + let state = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, cpu, mem| { + let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let name = args.get(1, mem).map_err(ExitReason::MemoryFault)?; + let flags = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32; + let access = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; + if attributes != 0 || name != 0 || access & !MUTEX_ALL_ACCESS != 0 { + return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0); + } + if flags & !CREATE_MUTEX_INITIAL_OWNER != 0 { + return state.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + let initial_owner = flags & CREATE_MUTEX_INITIAL_OWNER != 0; + insert_mutex(&state, cpu.gs_base, initial_owner, access) + }); + } + + let release = Arc::clone(state); + registry.register(KERNEL32, "ReleaseMutex", move |args, cpu, mem| { + let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let objects = release.objects.lock().expect("guest object state"); + let Some(GuestObject::Waitable { state, .. }) = objects.handles.get(&handle) else { + return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); + }; + let mut state = state.lock().expect("guest waitable state"); + let Waitable::Mutex { owner, recursion } = &mut *state else { + return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0); + }; + if *owner != Some(cpu.gs_base) { + return release.fail(cpu.gs_base, ERROR_NOT_OWNER, 0); + } + *recursion -= 1; + if *recursion == 0 { + *owner = None; + } + Ok(1) + }); + for (symbol, extended) in [ ("WaitForSingleObject", false), ("WaitForSingleObjectEx", true), @@ -218,6 +307,11 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc "CreateSemaphoreA", "CreateSemaphoreW", "ReleaseSemaphore", + "CreateMutexA", + "CreateMutexW", + "CreateMutexExA", + "CreateMutexExW", + "ReleaseMutex", "WaitForSingleObject", "WaitForSingleObjectEx", "WaitForMultipleObjects", @@ -271,7 +365,7 @@ fn wait_for_objects( } let mut ready = Vec::with_capacity(handles.len()); for (index, event) in waitables.into_iter().enumerate() { - if event.lock().expect("guest waitable state").is_ready() { + if event.lock().expect("guest waitable state").is_ready(teb) { ready.push((index, event)); if !all { break; @@ -285,9 +379,18 @@ fn wait_for_objects( state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED) }; } + if ready.iter().any(|(_, object)| { + object + .lock() + .expect("guest waitable state") + .at_recursion_limit() + }) { + // Windows raises STATUS_MUTANT_LIMIT_EXCEEDED; exceptions are unsupported. + return Err(ExitReason::IllegalInstruction(0xFE)); + } let first = ready[0].0; for (_, event) in ready { - event.lock().expect("guest waitable state").consume(); + event.lock().expect("guest waitable state").consume(teb); } Ok(WAIT_OBJECT_0 + first as u64) } diff --git a/crates/loader/src/services/synch.rs b/crates/loader/src/services/synch.rs new file mode 100644 index 00000000..72ad6950 --- /dev/null +++ b/crates/loader/src/services/synch.rs @@ -0,0 +1,866 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Critical sections, slim reader/writer locks, condition variables, one-time +//! initialization, interlocked singly linked lists and thread-local storage. +//! +//! Ownership is keyed by the calling guest TEB. No guest scheduler exists yet, +//! so an operation that would have to block another guest thread stops the +//! guest with the runtime-limit fault instead of pretending to synchronize. + +use super::{ + ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState, +}; +use crate::cpu::ExitReason; +use crate::imports::{ImportRegistry, ServiceStatus}; +use crate::memory::{GuestMemory, MemoryError}; +use std::collections::BTreeMap; +use std::sync::Arc; + +const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll"; +const SYNCH_API_2: &str = "api-ms-win-core-synch-l1-2-0.dll"; +const SLIST_API: &str = "api-ms-win-core-interlocked-l1-1-0.dll"; +const TLS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll"; +const FLS_API: &str = "api-ms-win-core-fibers-l1-1-0.dll"; + +const ERROR_GEN_FAILURE: u32 = 31; +const ERROR_TIMEOUT: u32 = 1460; + +/// `RTL_CRITICAL_SECTION` on x64 (winnt.h): DebugInfo, LockCount, +/// RecursionCount, OwningThread, LockSemaphore, SpinCount. +const CS_SIZE: usize = 40; +const CS_LOCK_COUNT: u64 = 8; +const CS_RECURSION: u64 = 12; +const CS_OWNER: u64 = 16; +const CS_SPIN: u64 = 32; +const CS_SPIN_MASK: u64 = 0x00ff_ffff; +const CRITICAL_SECTION_NO_DEBUG_INFO: u32 = 0x0100_0000; +const MAX_CRITICAL_SECTIONS: usize = 4096; + +const MAX_SRW_LOCKS: usize = 4096; +const CONDITION_VARIABLE_LOCKMODE_SHARED: u32 = 1; + +const INIT_ONCE_CHECK_ONLY: u32 = 1; +const INIT_ONCE_ASYNC: u32 = 2; +const INIT_ONCE_INIT_FAILED: u32 = 4; +const INIT_ONCE_CTX_RESERVED_MASK: u64 = 3; +/// Opaque `INIT_ONCE` values. Completion stores the context with this bit set, +/// as the context's two reserved low bits allow. +const INIT_ONCE_PENDING: u64 = 1; +const INIT_ONCE_COMPLETE: u64 = 2; + +/// `SLIST_HEADER` on x64 is 16 bytes: Depth:16, Sequence:48 in the first +/// quadword and Reserved:4, NextEntry:60 (address >> 4) in the second. +const SLIST_ALIGNMENT: u64 = 16; +const SLIST_MAX_DEPTH: u64 = 0xffff; + +/// TLS_MINIMUM_AVAILABLE (64) plus the documented expansion slots. +const TLS_MAX_INDEXES: u32 = 1088; +const TLS_OUT_OF_INDEXES: u64 = u32::MAX as u64; +/// FLS_MAXIMUM_AVAILABLE in the MinGW-w64 winnt.h. +const FLS_MAX_INDEXES: u32 = 128; +const FLS_OUT_OF_INDEXES: u64 = u32::MAX as u64; + +fn unsupported() -> Result { + Err(ExitReason::IllegalInstruction(0xFE)) +} + +fn fault(error: MemoryError) -> ExitReason { + ExitReason::MemoryFault(error) +} + +struct CriticalSection { + owner: Option, + recursion: u32, + spin: u64, +} + +#[derive(Default)] +struct SrwLock { + exclusive: Option, + shared: BTreeMap, +} + +impl SrwLock { + fn is_free(&self) -> bool { + self.exclusive.is_none() && self.shared.is_empty() + } +} + +struct FlsSlot { + callback: u64, +} + +#[derive(Default)] +pub(super) struct Synch { + sections: BTreeMap, + srw: BTreeMap, + init_once_pending: BTreeMap, + tls_allocated: BTreeMap, + tls_values: BTreeMap<(u64, u32), u64>, + fls_slots: BTreeMap, + fls_values: BTreeMap<(u64, u32), u64>, +} + +impl Synch { + fn section(&mut self, address: u64) -> Result<&mut CriticalSection, ExitReason> { + // Using an uninitialized critical section is undefined; report it. + self.sections.get_mut(&address).map_or_else(unsupported, Ok) + } +} + +/// Write the documented observable fields: LockCount is -1 when free and -2 +/// when held with no waiters, and OwningThread holds the owner's thread ID. +fn mirror_section( + memory: &mut GuestMemory, + address: u64, + section: &CriticalSection, + thread_id: u32, +) -> Result<(), ExitReason> { + let (lock_count, owner) = match section.owner { + Some(_) => (-2i32, u64::from(thread_id)), + None => (-1, 0), + }; + memory + .write_u32(address + CS_LOCK_COUNT, lock_count as u32) + .map_err(fault)?; + memory + .write_u32(address + CS_RECURSION, section.recursion) + .map_err(fault)?; + memory.write_u64(address + CS_OWNER, owner).map_err(fault) +} + +fn initialize_section( + state: &ServicesState, + memory: &mut GuestMemory, + address: u64, + spin: u64, +) -> Result { + if address == 0 { + return Err(fault(MemoryError::UnmappedAddress(0))); + } + address + .checked_add(CS_SIZE as u64) + .ok_or(fault(MemoryError::Overflow))?; + let mut synch = state.synch.lock().expect("guest synchronization state"); + match synch.sections.get(&address) { + Some(existing) if existing.owner.is_some() => return unsupported(), + None if synch.sections.len() >= MAX_CRITICAL_SECTIONS => return Ok(false), + _ => {} + } + let mut image = [0u8; CS_SIZE]; + image[CS_LOCK_COUNT as usize..CS_RECURSION as usize].copy_from_slice(&(-1i32).to_le_bytes()); + image[CS_SPIN as usize..].copy_from_slice(&(spin & CS_SPIN_MASK).to_le_bytes()); + memory.write_bytes(address, &image).map_err(fault)?; + synch.sections.insert( + address, + CriticalSection { + owner: None, + recursion: 0, + spin: spin & CS_SPIN_MASK, + }, + ); + Ok(true) +} + +/// Acquire for `teb`. Returns false when another guest thread owns it. +fn enter_section( + state: &ServicesState, + memory: &mut GuestMemory, + address: u64, + teb: u64, +) -> Result { + let mut synch = state.synch.lock().expect("guest synchronization state"); + let section = synch.section(address)?; + match section.owner { + Some(owner) if owner != teb => return Ok(false), + Some(_) if section.recursion >= i32::MAX as u32 => return unsupported(), + _ => {} + } + section.owner = Some(teb); + section.recursion += 1; + mirror_section(memory, address, section, state.thread_id)?; + Ok(true) +} + +fn leave_section( + state: &ServicesState, + memory: &mut GuestMemory, + address: u64, + teb: u64, +) -> Result<(), ExitReason> { + let mut synch = state.synch.lock().expect("guest synchronization state"); + let section = synch.section(address)?; + if section.owner != Some(teb) { + return unsupported(); + } + section.recursion -= 1; + if section.recursion == 0 { + section.owner = None; + } + mirror_section(memory, address, section, state.thread_id) +} + +/// Check that a pointer-sized synchronization object is readable and writable. +fn check_word(memory: &mut GuestMemory, address: u64) -> Result { + if address == 0 { + return Err(fault(MemoryError::UnmappedAddress(0))); + } + let value = memory.read_u64(address).map_err(fault)?; + memory.write_u64(address, value).map_err(fault)?; + Ok(value) +} + +#[derive(Clone, Copy, PartialEq)] +enum SrwMode { + Exclusive, + Shared, +} + +/// Acquire without blocking. Returns false when the lock is unavailable. +fn try_acquire_srw( + state: &ServicesState, + memory: &mut GuestMemory, + address: u64, + teb: u64, + mode: SrwMode, +) -> Result { + check_word(memory, address)?; + let mut synch = state.synch.lock().expect("guest synchronization state"); + if !synch.srw.contains_key(&address) && synch.srw.len() >= MAX_SRW_LOCKS { + return unsupported(); + } + let lock = synch.srw.entry(address).or_default(); + let acquired = match mode { + SrwMode::Exclusive if lock.is_free() => { + lock.exclusive = Some(teb); + true + } + SrwMode::Shared if lock.exclusive.is_none() => { + let count = lock.shared.entry(teb).or_default(); + if *count == u32::MAX { + return unsupported(); + } + *count += 1; + true + } + _ => false, + }; + if lock.is_free() { + synch.srw.remove(&address); + } + Ok(acquired) +} + +fn release_srw( + state: &ServicesState, + memory: &mut GuestMemory, + address: u64, + teb: u64, + mode: SrwMode, +) -> Result<(), ExitReason> { + check_word(memory, address)?; + let mut synch = state.synch.lock().expect("guest synchronization state"); + let Some(lock) = synch.srw.get_mut(&address) else { + return unsupported(); + }; + match mode { + SrwMode::Exclusive if lock.exclusive == Some(teb) => lock.exclusive = None, + SrwMode::Shared => match lock.shared.get_mut(&teb) { + Some(count) if *count > 1 => *count -= 1, + Some(_) => { + lock.shared.remove(&teb); + } + None => return unsupported(), + }, + SrwMode::Exclusive => return unsupported(), + } + if lock.is_free() { + synch.srw.remove(&address); + } + Ok(()) +} + +fn holds_srw(state: &ServicesState, address: u64, teb: u64, mode: SrwMode) -> bool { + let synch = state.synch.lock().expect("guest synchronization state"); + synch.srw.get(&address).is_some_and(|lock| match mode { + SrwMode::Exclusive => lock.exclusive == Some(teb), + SrwMode::Shared => lock.shared.contains_key(&teb), + }) +} + +/// Read an aligned `SLIST_HEADER` as (depth, sequence, first entry). +fn read_slist(memory: &GuestMemory, header: u64) -> Result<(u64, u64, u64), ExitReason> { + if header == 0 || !header.is_multiple_of(SLIST_ALIGNMENT) { + return unsupported(); + } + let low = memory.read_u64(header).map_err(fault)?; + let high = memory.read_u64(header + 8).map_err(fault)?; + Ok((low & 0xffff, low >> 16, (high >> 4) << 4)) +} + +fn write_slist( + memory: &mut GuestMemory, + header: u64, + depth: u64, + sequence: u64, + first: u64, +) -> Result<(), ExitReason> { + let low = (depth & 0xffff) | (sequence << 16); + let mut bytes = [0u8; 16]; + bytes[..8].copy_from_slice(&low.to_le_bytes()); + bytes[8..].copy_from_slice(&first.to_le_bytes()); + memory.write_bytes(header, &bytes).map_err(fault) +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + register_critical_sections(registry, state); + register_srw_and_conditions(registry, state); + register_init_once(registry, state); + register_slist(registry, state); + register_tls(registry, state); +} + +fn register_critical_sections(registry: &mut ImportRegistry, state: &Arc) { + let s = Arc::clone(state); + registry.register( + KERNEL32, + "InitializeCriticalSection", + move |args, _, mem| { + if !initialize_section(&s, mem, args.rcx, 0)? { + return unsupported(); + } + Ok(0) + }, + ); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "InitializeCriticalSectionAndSpinCount", + move |args, cpu, mem| { + if !initialize_section(&s, mem, args.rcx, args.rdx & 0xffff_ffff)? { + return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0); + } + Ok(1) + }, + ); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "InitializeCriticalSectionEx", + move |args, cpu, mem| { + let flags = args.r8 as u32; + if flags & !CRITICAL_SECTION_NO_DEBUG_INFO != 0 { + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + if !initialize_section(&s, mem, args.rcx, args.rdx & 0xffff_ffff)? { + return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0); + } + Ok(1) + }, + ); + + let s = Arc::clone(state); + registry.register(KERNEL32, "EnterCriticalSection", move |args, cpu, mem| { + if !enter_section(&s, mem, args.rcx, cpu.gs_base)? { + // Another guest thread owns it; waiting needs the guest scheduler. + return unsupported(); + } + Ok(0) + }); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "TryEnterCriticalSection", + move |args, cpu, mem| Ok(u64::from(enter_section(&s, mem, args.rcx, cpu.gs_base)?)), + ); + + let s = Arc::clone(state); + registry.register(KERNEL32, "LeaveCriticalSection", move |args, cpu, mem| { + leave_section(&s, mem, args.rcx, cpu.gs_base)?; + Ok(0) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "DeleteCriticalSection", move |args, _, _| { + let mut synch = s.synch.lock().expect("guest synchronization state"); + if synch.sections.remove(&args.rcx).is_none() { + return unsupported(); + } + Ok(0) + }); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "SetCriticalSectionSpinCount", + move |args, _, mem| { + let mut synch = s.synch.lock().expect("guest synchronization state"); + let section = synch.section(args.rcx)?; + let previous = section.spin; + section.spin = args.rdx & 0xffff_ffff & CS_SPIN_MASK; + mem.write_u64(args.rcx + CS_SPIN, section.spin) + .map_err(fault)?; + Ok(previous) + }, + ); + + for symbol in [ + "InitializeCriticalSection", + "InitializeCriticalSectionAndSpinCount", + "InitializeCriticalSectionEx", + "EnterCriticalSection", + "TryEnterCriticalSection", + "LeaveCriticalSection", + "DeleteCriticalSection", + "SetCriticalSectionSpinCount", + ] { + registry.alias(SYNCH_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} + +fn register_srw_and_conditions(registry: &mut ImportRegistry, state: &Arc) { + let s = Arc::clone(state); + registry.register(KERNEL32, "InitializeSRWLock", move |args, _, mem| { + check_word(mem, args.rcx)?; + let synch = s.synch.lock().expect("guest synchronization state"); + if synch.srw.get(&args.rcx).is_some_and(|lock| !lock.is_free()) { + return unsupported(); + } + mem.write_u64(args.rcx, 0).map_err(fault)?; + Ok(0) + }); + + for (acquire, try_acquire, release, mode) in [ + ( + "AcquireSRWLockExclusive", + "TryAcquireSRWLockExclusive", + "ReleaseSRWLockExclusive", + SrwMode::Exclusive, + ), + ( + "AcquireSRWLockShared", + "TryAcquireSRWLockShared", + "ReleaseSRWLockShared", + SrwMode::Shared, + ), + ] { + let s = Arc::clone(state); + registry.register(KERNEL32, acquire, move |args, cpu, mem| { + // SRW locks are not recursive, so a held lock would block or deadlock. + if !try_acquire_srw(&s, mem, args.rcx, cpu.gs_base, mode)? { + return unsupported(); + } + Ok(0) + }); + let s = Arc::clone(state); + registry.register(KERNEL32, try_acquire, move |args, cpu, mem| { + Ok(u64::from(try_acquire_srw( + &s, + mem, + args.rcx, + cpu.gs_base, + mode, + )?)) + }); + let s = Arc::clone(state); + registry.register(KERNEL32, release, move |args, cpu, mem| { + release_srw(&s, mem, args.rcx, cpu.gs_base, mode)?; + Ok(0) + }); + } + + registry.register(KERNEL32, "InitializeConditionVariable", |args, _, mem| { + check_word(mem, args.rcx)?; + mem.write_u64(args.rcx, 0).map_err(fault)?; + Ok(0) + }); + // No guest thread can be waiting, because a sleep never blocks. + for symbol in ["WakeConditionVariable", "WakeAllConditionVariable"] { + registry.register(KERNEL32, symbol, |args, _, mem| { + check_word(mem, args.rcx)?; + Ok(0) + }); + } + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "SleepConditionVariableCS", + move |args, cpu, mem| { + check_word(mem, args.rcx)?; + let owned = { + let synch = s.synch.lock().expect("guest synchronization state"); + synch + .sections + .get(&args.rdx) + .is_some_and(|section| section.owner == Some(cpu.gs_base)) + }; + if !owned { + return unsupported(); + } + sleep_result(&s, cpu.gs_base, args.r8 as u32) + }, + ); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "SleepConditionVariableSRW", + move |args, cpu, mem| { + check_word(mem, args.rcx)?; + let flags = args.r9 as u32; + if flags & !CONDITION_VARIABLE_LOCKMODE_SHARED != 0 { + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + let mode = if flags == 0 { + SrwMode::Exclusive + } else { + SrwMode::Shared + }; + if !holds_srw(&s, args.rdx, cpu.gs_base, mode) { + return unsupported(); + } + sleep_result(&s, cpu.gs_base, args.r8 as u32) + }, + ); + + for symbol in [ + "InitializeSRWLock", + "AcquireSRWLockExclusive", + "AcquireSRWLockShared", + "TryAcquireSRWLockExclusive", + "TryAcquireSRWLockShared", + "ReleaseSRWLockExclusive", + "ReleaseSRWLockShared", + ] { + registry.alias(SYNCH_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } + for symbol in [ + "InitializeConditionVariable", + "WakeConditionVariable", + "WakeAllConditionVariable", + "SleepConditionVariableCS", + "SleepConditionVariableSRW", + ] { + registry.alias(SYNCH_API_2, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} + +/// A zero timeout releases and reacquires the lock, which no other guest +/// thread can observe, then reports the timeout. Longer sleeps would block. +fn sleep_result(state: &ServicesState, teb: u64, timeout: u32) -> Result { + if timeout == 0 { + state.fail(teb, ERROR_TIMEOUT, 0) + } else { + state.fail(teb, ERROR_NOT_SUPPORTED, 0) + } +} + +fn register_init_once(registry: &mut ImportRegistry, state: &Arc) { + let s = Arc::clone(state); + registry.register(KERNEL32, "InitOnceInitialize", move |args, _, mem| { + check_word(mem, args.rcx)?; + let synch = s.synch.lock().expect("guest synchronization state"); + if synch.init_once_pending.contains_key(&args.rcx) { + return unsupported(); + } + mem.write_u64(args.rcx, 0).map_err(fault)?; + Ok(0) + }); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "InitOnceBeginInitialize", + move |args, cpu, mem| { + let (once, flags, pending, context) = (args.rcx, args.rdx as u32, args.r8, args.r9); + let teb = cpu.gs_base; + if flags & !(INIT_ONCE_CHECK_ONLY | INIT_ONCE_ASYNC) != 0 || pending == 0 { + return s.fail(teb, ERROR_INVALID_PARAMETER, 0); + } + if flags & INIT_ONCE_ASYNC != 0 { + return s.fail(teb, ERROR_NOT_SUPPORTED, 0); + } + let value = check_word(mem, once)?; + let mut synch = s.synch.lock().expect("guest synchronization state"); + let pending_here = synch.init_once_pending.contains_key(&once); + match value & INIT_ONCE_CTX_RESERVED_MASK { + INIT_ONCE_COMPLETE => { + mem.check_write(pending, 4).map_err(fault)?; + if context != 0 { + mem.check_write(context, 8).map_err(fault)?; + mem.write_u64(context, value & !INIT_ONCE_CTX_RESERVED_MASK) + .map_err(fault)?; + } + mem.write_u32(pending, 0).map_err(fault)?; + Ok(1) + } + _ if flags & INIT_ONCE_CHECK_ONLY != 0 + && (value == 0 || (value == INIT_ONCE_PENDING && pending_here)) => + { + s.fail(teb, ERROR_GEN_FAILURE, 0) + } + 0 if value == 0 => { + mem.write_u32(pending, 1).map_err(fault)?; + mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?; + synch.init_once_pending.insert(once, teb); + Ok(1) + } + // Pending in another thread would block; pending in this thread + // or an unrecognized value is a guest error. + _ => unsupported(), + } + }, + ); + + let s = Arc::clone(state); + registry.register(KERNEL32, "InitOnceComplete", move |args, cpu, mem| { + let (once, flags, context) = (args.rcx, args.rdx as u32, args.r8); + let teb = cpu.gs_base; + if flags & !(INIT_ONCE_ASYNC | INIT_ONCE_INIT_FAILED) != 0 { + return s.fail(teb, ERROR_INVALID_PARAMETER, 0); + } + if flags & INIT_ONCE_ASYNC != 0 { + return s.fail(teb, ERROR_NOT_SUPPORTED, 0); + } + let failed = flags & INIT_ONCE_INIT_FAILED != 0; + if context & INIT_ONCE_CTX_RESERVED_MASK != 0 || (failed && context != 0) { + return s.fail(teb, ERROR_INVALID_PARAMETER, 0); + } + let value = check_word(mem, once)?; + let mut synch = s.synch.lock().expect("guest synchronization state"); + if value != INIT_ONCE_PENDING || synch.init_once_pending.get(&once) != Some(&teb) { + return s.fail(teb, ERROR_GEN_FAILURE, 0); + } + let next = if failed { + 0 + } else { + context | INIT_ONCE_COMPLETE + }; + mem.write_u64(once, next).map_err(fault)?; + synch.init_once_pending.remove(&once); + Ok(1) + }); + + for symbol in [ + "InitOnceInitialize", + "InitOnceBeginInitialize", + "InitOnceComplete", + ] { + registry.alias(SYNCH_API_2, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} + +fn register_slist(registry: &mut ImportRegistry, state: &Arc) { + registry.register(KERNEL32, "InitializeSListHead", |args, _, mem| { + read_slist(mem, args.rcx)?; + write_slist(mem, args.rcx, 0, 0, 0)?; + Ok(0) + }); + + registry.register(KERNEL32, "QueryDepthSList", |args, _, mem| { + Ok(read_slist(mem, args.rcx)?.0) + }); + + // Services run one at a time, which makes each list update atomic with + // respect to other services. + let s = Arc::clone(state); + registry.register( + KERNEL32, + "InterlockedPushEntrySList", + move |args, _, mem| { + let _serial = s.synch.lock().expect("guest synchronization state"); + let (header, entry) = (args.rcx, args.rdx); + let (depth, sequence, first) = read_slist(mem, header)?; + if entry == 0 || !entry.is_multiple_of(SLIST_ALIGNMENT) || depth == SLIST_MAX_DEPTH { + return unsupported(); + } + mem.write_u64(entry, first).map_err(fault)?; + write_slist( + mem, + header, + depth + 1, + (sequence + 1) & 0xffff_ffff_ffff, + entry, + )?; + Ok(first) + }, + ); + + let s = Arc::clone(state); + registry.register(KERNEL32, "InterlockedPopEntrySList", move |args, _, mem| { + let _serial = s.synch.lock().expect("guest synchronization state"); + let (depth, sequence, first) = read_slist(mem, args.rcx)?; + if first == 0 { + return Ok(0); + } + let next = mem.read_u64(first).map_err(fault)?; + if !next.is_multiple_of(SLIST_ALIGNMENT) || depth == 0 { + return unsupported(); + } + write_slist(mem, args.rcx, depth - 1, sequence, next)?; + Ok(first) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "InterlockedFlushSList", move |args, _, mem| { + let _serial = s.synch.lock().expect("guest synchronization state"); + let (_, sequence, first) = read_slist(mem, args.rcx)?; + write_slist(mem, args.rcx, 0, sequence, 0)?; + Ok(first) + }); + + for symbol in [ + "InitializeSListHead", + "QueryDepthSList", + "InterlockedPushEntrySList", + "InterlockedPopEntrySList", + "InterlockedFlushSList", + ] { + registry.alias(SLIST_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} + +fn register_tls(registry: &mut ImportRegistry, state: &Arc) { + let s = Arc::clone(state); + registry.register(KERNEL32, "TlsAlloc", move |_, cpu, _| { + let mut synch = s.synch.lock().expect("guest synchronization state"); + let Some(index) = (0..TLS_MAX_INDEXES).find(|i| !synch.tls_allocated.contains_key(i)) + else { + drop(synch); + return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, TLS_OUT_OF_INDEXES); + }; + synch.tls_allocated.insert(index, ()); + synch.tls_values.retain(|&(_, slot), _| slot != index); + Ok(u64::from(index)) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "TlsFree", move |args, cpu, _| { + let index = args.rcx as u32; + let mut synch = s.synch.lock().expect("guest synchronization state"); + if synch.tls_allocated.remove(&index).is_none() { + drop(synch); + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + synch.tls_values.retain(|&(_, slot), _| slot != index); + Ok(1) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "TlsGetValue", move |args, cpu, _| { + let index = args.rcx as u32; + let synch = s.synch.lock().expect("guest synchronization state"); + if !synch.tls_allocated.contains_key(&index) { + drop(synch); + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + let value = synch + .tls_values + .get(&(cpu.gs_base, index)) + .copied() + .unwrap_or(0); + drop(synch); + // A successful call clears the last error, so zero is distinguishable. + s.set_last_error(cpu.gs_base, 0); + Ok(value) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "TlsSetValue", move |args, cpu, _| { + let index = args.rcx as u32; + let mut synch = s.synch.lock().expect("guest synchronization state"); + if !synch.tls_allocated.contains_key(&index) { + drop(synch); + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + if args.rdx == 0 { + synch.tls_values.remove(&(cpu.gs_base, index)); + } else { + synch.tls_values.insert((cpu.gs_base, index), args.rdx); + } + Ok(1) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "FlsAlloc", move |args, cpu, _| { + let callback = args.rcx; + let mut synch = s.synch.lock().expect("guest synchronization state"); + let Some(index) = (0..FLS_MAX_INDEXES).find(|i| !synch.fls_slots.contains_key(i)) else { + drop(synch); + return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, FLS_OUT_OF_INDEXES); + }; + synch.fls_slots.insert(index, FlsSlot { callback }); + synch.fls_values.retain(|&(_, slot), _| slot != index); + Ok(u64::from(index)) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "FlsFree", move |args, cpu, _| { + let index = args.rcx as u32; + let mut synch = s.synch.lock().expect("guest synchronization state"); + let Some(slot) = synch.fls_slots.get(&index) else { + drop(synch); + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + }; + let has_values = synch.fls_values.keys().any(|&(_, i)| i == index); + if slot.callback != 0 && has_values { + // FlsFree must run the guest callback for each nonnull value. + return unsupported(); + } + synch.fls_slots.remove(&index); + synch.fls_values.retain(|&(_, slot), _| slot != index); + Ok(1) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "FlsGetValue", move |args, cpu, _| { + let index = args.rcx as u32; + let synch = s.synch.lock().expect("guest synchronization state"); + if !synch.fls_slots.contains_key(&index) { + drop(synch); + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + let value = synch + .fls_values + .get(&(cpu.gs_base, index)) + .copied() + .unwrap_or(0); + drop(synch); + s.set_last_error(cpu.gs_base, 0); + Ok(value) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "FlsSetValue", move |args, cpu, _| { + let index = args.rcx as u32; + let mut synch = s.synch.lock().expect("guest synchronization state"); + if !synch.fls_slots.contains_key(&index) { + drop(synch); + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + if args.rdx == 0 { + synch.fls_values.remove(&(cpu.gs_base, index)); + } else { + synch.fls_values.insert((cpu.gs_base, index), args.rdx); + } + Ok(1) + }); + + for symbol in ["TlsAlloc", "TlsFree", "TlsGetValue", "TlsSetValue"] { + registry.alias(TLS_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } + for symbol in ["FlsAlloc", "FlsFree", "FlsGetValue", "FlsSetValue"] { + registry.alias(FLS_API, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} diff --git a/crates/loader/tests/runtime_synch.rs b/crates/loader/tests/runtime_synch.rs new file mode 100644 index 00000000..6de20fd0 --- /dev/null +++ b/crates/loader/tests/runtime_synch.rs @@ -0,0 +1,744 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Mutexes, critical sections, SRW locks, condition variables, one-time +//! initialization, SLists and thread-local storage, called by translated guest +//! code through a bound import table. +//! +//! Two guest threads are modelled by switching the TEB address in GS between +//! calls. Expected values come from the public Win32 synchprocess and +//! processthreadsapi documentation and the x64 layouts in winnt.h, not from +//! the handlers. + +use std::sync::Arc; +use xenora_loader::cpu::{CpuState, ExitReason, Register}; +use xenora_loader::dbt::DbtEngine; +use xenora_loader::imports::ImportRegistry; +use xenora_loader::memory::{GuestMemory, MemoryPermissions}; +use xenora_loader::pe::ParsedPe; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; + +const BASE: u64 = 0x1_4000_0000; +const CODE_RVA: u32 = 0x1000; +const IDATA_RVA: u32 = 0x10000; +const IDATA_RAW: usize = 0x2200; +const IDATA_LEN: usize = 0x4000; +const SCRATCH: u64 = 0x5_0000; +const STACK: u64 = 0x8_0000; +const STACK_TOP: u64 = STACK + 0x800; +const THREAD_A: u64 = 0x7_0000; +const THREAD_B: u64 = 0x7_2000; + +const KERNEL32: &str = "kernel32.dll"; +const SYNCH: &str = "api-ms-win-core-synch-l1-1-0.dll"; +const SYNCH_2: &str = "api-ms-win-core-synch-l1-2-0.dll"; +const SLIST: &str = "api-ms-win-core-interlocked-l1-1-0.dll"; +const THREADS: &str = "api-ms-win-core-processthreads-l1-1-0.dll"; +const FIBERS: &str = "api-ms-win-core-fibers-l1-1-0.dll"; + +const IMPORTS: &[(&str, &str)] = &[ + (KERNEL32, "GetLastError"), + (KERNEL32, "SetLastError"), + (KERNEL32, "GetCurrentThreadId"), + (KERNEL32, "CloseHandle"), + (KERNEL32, "DuplicateHandle"), + (KERNEL32, "SetEvent"), + (KERNEL32, "CreateEventW"), + (KERNEL32, "WaitForSingleObject"), + (KERNEL32, "WaitForMultipleObjects"), + (KERNEL32, "CreateMutexW"), + (SYNCH, "CreateMutexExW"), + (SYNCH, "ReleaseMutex"), + (KERNEL32, "InitializeCriticalSection"), + (KERNEL32, "InitializeCriticalSectionAndSpinCount"), + (SYNCH, "InitializeCriticalSectionEx"), + (KERNEL32, "EnterCriticalSection"), + (SYNCH, "TryEnterCriticalSection"), + (KERNEL32, "LeaveCriticalSection"), + (KERNEL32, "DeleteCriticalSection"), + (KERNEL32, "SetCriticalSectionSpinCount"), + (SYNCH, "InitializeSRWLock"), + (KERNEL32, "AcquireSRWLockExclusive"), + (SYNCH, "AcquireSRWLockShared"), + (KERNEL32, "TryAcquireSRWLockExclusive"), + (KERNEL32, "TryAcquireSRWLockShared"), + (KERNEL32, "ReleaseSRWLockExclusive"), + (SYNCH, "ReleaseSRWLockShared"), + (KERNEL32, "InitializeConditionVariable"), + (KERNEL32, "WakeAllConditionVariable"), + (SYNCH_2, "WakeConditionVariable"), + (KERNEL32, "SleepConditionVariableCS"), + (SYNCH_2, "SleepConditionVariableSRW"), + (SYNCH_2, "InitOnceInitialize"), + (KERNEL32, "InitOnceBeginInitialize"), + (SYNCH_2, "InitOnceComplete"), + (KERNEL32, "InitializeSListHead"), + (SLIST, "InterlockedPushEntrySList"), + (KERNEL32, "InterlockedPopEntrySList"), + (SLIST, "InterlockedFlushSList"), + (SLIST, "QueryDepthSList"), + (KERNEL32, "TlsAlloc"), + (THREADS, "TlsGetValue"), + (THREADS, "TlsSetValue"), + (KERNEL32, "TlsFree"), + (FIBERS, "FlsAlloc"), + (KERNEL32, "FlsGetValue"), + (FIBERS, "FlsSetValue"), + (FIBERS, "FlsFree"), +]; + +const WAIT_TIMEOUT: u64 = 258; +const ERROR_INVALID_HANDLE: u64 = 6; +const ERROR_GEN_FAILURE: u64 = 31; +const ERROR_NOT_SUPPORTED: u64 = 50; +const ERROR_INVALID_PARAMETER: u64 = 87; +const ERROR_NOT_OWNER: u64 = 288; +const ERROR_TIMEOUT: u64 = 1460; +const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE); + +/// Original PE32+ image importing each entry of `IMPORTS` from its own +/// descriptor. The code for import `n`, at RVA 0x1000 + 16n, is +/// `call [its slot]; hlt`. +fn build() -> Vec { + let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN]; + fn put(pe: &mut [u8], at: usize, bytes: &[u8]) { + pe[at..at + bytes.len()].copy_from_slice(bytes); + } + put(&mut pe, 0, b"MZ"); + put(&mut pe, 0x3C, &0x80u32.to_le_bytes()); + put(&mut pe, 0x80, b"PE\0\0"); + put(&mut pe, 0x84, &0x8664u16.to_le_bytes()); + put(&mut pe, 0x86, &2u16.to_le_bytes()); + put(&mut pe, 0x94, &240u16.to_le_bytes()); + let optional = 0x98; + put(&mut pe, optional, &0x20Bu16.to_le_bytes()); + put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes()); + put(&mut pe, optional + 24, &BASE.to_le_bytes()); + put(&mut pe, optional + 32, &0x1000u32.to_le_bytes()); + put(&mut pe, optional + 36, &0x200u32.to_le_bytes()); + put(&mut pe, optional + 56, &0x20000u32.to_le_bytes()); + put(&mut pe, optional + 60, &0x200u32.to_le_bytes()); + put(&mut pe, optional + 108, &16u32.to_le_bytes()); + put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes()); + put(&mut pe, optional + 124, &0x100u32.to_le_bytes()); + for (index, (name, rva, raw, len, flags)) in [ + (b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32), + (b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040), + ] + .into_iter() + .enumerate() + { + let section = optional + 240 + 40 * index; + put(&mut pe, section, name); + put(&mut pe, section + 8, &(len as u32).to_le_bytes()); + put(&mut pe, section + 12, &rva.to_le_bytes()); + put(&mut pe, section + 16, &(len as u32).to_le_bytes()); + put(&mut pe, section + 20, &(raw as u32).to_le_bytes()); + put(&mut pe, section + 36, &flags.to_le_bytes()); + } + + let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize; + let mut next = IDATA_RVA + 20 * (IMPORTS.len() as u32 + 1); + let mut take = |len: usize| { + let rva = next; + next = (next + len as u32 + 7) & !7; + rva + }; + for (index, (module, symbol)) in IMPORTS.iter().enumerate() { + let module_rva = take(module.len() + 1); + put(&mut pe, file(module_rva), module.as_bytes()); + let hint = take(symbol.len() + 3); + put(&mut pe, file(hint) + 2, symbol.as_bytes()); + let (lookup, slot) = (take(16), take(16)); + put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes()); + put(&mut pe, file(slot), &u64::from(hint).to_le_bytes()); + let descriptor = file(IDATA_RVA) + 20 * index; + put(&mut pe, descriptor, &lookup.to_le_bytes()); + put(&mut pe, descriptor + 12, &module_rva.to_le_bytes()); + put(&mut pe, descriptor + 16, &slot.to_le_bytes()); + + let code_rva = CODE_RVA + 16 * index as u32; + let displacement = slot.wrapping_sub(code_rva + 6); + let at = 0x200 + 16 * index; + put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement] + put(&mut pe, at + 2, &displacement.to_le_bytes()); + put(&mut pe, at + 6, &[0xF4]); // hlt + } + pe +} + +struct Guest { + engine: DbtEngine, + memory: GuestMemory, + teb: u64, +} + +impl Guest { + fn new() -> Self { + let bytes = build(); + let pe = ParsedPe::parse(&bytes).unwrap(); + let mut memory = pe.load_into_memory(&bytes).unwrap().memory; + memory + .map_region(SCRATCH, 0x1000, MemoryPermissions::READ_WRITE) + .unwrap(); + memory + .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) + .unwrap(); + let mut registry = ImportRegistry::new(); + let state = ServicesState::new(Arc::new(MockClock::new(0))); + register_standard_services(&mut registry, Arc::new(state)); + let bound = registry + .bind_imports(&pe, &bytes, BASE, &mut memory) + .unwrap(); + assert_eq!(bound, IMPORTS.len()); + let mut engine = DbtEngine::new(256 * 1024).unwrap(); + engine.set_import_registry(registry); + Self { + engine, + memory, + teb: THREAD_A, + } + } + + fn on(&mut self, teb: u64) -> &mut Self { + self.teb = teb; + self + } + + fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) { + let index = IMPORTS + .iter() + .position(|(_, name)| *name == symbol) + .unwrap_or_else(|| panic!("{symbol} is not imported")); + let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); + cpu.gs_base = self.teb; + for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(register, *value); + } + // Stack arguments start after the return address and the home area. + for (slot, value) in args.iter().skip(4).enumerate() { + let address = STACK_TOP - 8 + 8 + 32 + 8 * slot as u64; + self.memory.write_u64(address, *value).unwrap(); + } + let result = self.engine.run(&mut cpu, &mut self.memory, 8); + (cpu.get(Register::Rax), result.exit_reason) + } + + fn call(&mut self, symbol: &str, args: &[u64]) -> u64 { + let (rax, exit) = self.run(symbol, args); + assert_eq!(exit, ExitReason::Halt, "{symbol}"); + rax + } + + fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason { + let (_, exit) = self.run(symbol, args); + assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest"); + exit + } + + fn error(&mut self) -> u64 { + self.call("GetLastError", &[]) + } + + fn u32_at(&self, address: u64) -> u32 { + self.memory.read_u32(address).unwrap() + } + + fn u64_at(&self, address: u64) -> u64 { + self.memory.read_u64(address).unwrap() + } +} + +#[test] +fn mutexes_are_recursive_for_their_owner_and_exclusive_across_threads() { + let mut guest = Guest::new(); + let mutex = guest.on(THREAD_A).call("CreateMutexW", &[0, 1, 0]); + assert_ne!(mutex, 0); + + // A held mutex is not signaled for another thread, but its owner may + // acquire it again; each acquisition needs a matching release. + assert_eq!( + guest.on(THREAD_B).call("WaitForSingleObject", &[mutex, 0]), + WAIT_TIMEOUT + ); + assert_eq!( + guest.on(THREAD_A).call("WaitForSingleObject", &[mutex, 0]), + 0 + ); + assert_eq!(guest.on(THREAD_B).call("ReleaseMutex", &[mutex]), 0); + assert_eq!(guest.error(), ERROR_NOT_OWNER); + assert_eq!(guest.on(THREAD_A).call("ReleaseMutex", &[mutex]), 1); + assert_eq!( + guest.on(THREAD_B).call("WaitForSingleObject", &[mutex, 0]), + WAIT_TIMEOUT + ); + assert_eq!(guest.on(THREAD_A).call("ReleaseMutex", &[mutex]), 1); + assert_eq!(guest.call("ReleaseMutex", &[mutex]), 0); + assert_eq!(guest.error(), ERROR_NOT_OWNER); + + // Once released, the next waiter acquires ownership. + assert_eq!( + guest.on(THREAD_B).call("WaitForSingleObject", &[mutex, 0]), + 0 + ); + assert_eq!( + guest.on(THREAD_A).call("WaitForSingleObject", &[mutex, 0]), + WAIT_TIMEOUT + ); + // A wait that would block needs the guest scheduler. + assert_eq!( + guest.call("WaitForSingleObject", &[mutex, 10]), + u64::from(u32::MAX) + ); + assert_eq!(guest.error(), ERROR_NOT_SUPPORTED); + + // A duplicate refers to the same mutex, so it shares ownership. + let output = SCRATCH + 0x800; + let duplicate = guest.on(THREAD_B).call( + "DuplicateHandle", + &[u64::MAX, mutex, u64::MAX, output, 0, 0, 2], + ); + assert_eq!(duplicate, 1); + let duplicate = guest.u64_at(output); + assert_eq!(guest.call("CloseHandle", &[mutex]), 1); + assert_eq!( + guest + .on(THREAD_A) + .call("WaitForSingleObject", &[duplicate, 0]), + WAIT_TIMEOUT + ); + assert_eq!(guest.on(THREAD_B).call("ReleaseMutex", &[duplicate]), 1); + assert_eq!( + guest + .on(THREAD_A) + .call("WaitForSingleObject", &[duplicate, 0]), + 0 + ); + + // Mutexes are not events. + assert_eq!(guest.call("SetEvent", &[duplicate]), 0); + assert_eq!(guest.error(), ERROR_INVALID_HANDLE); + + // CREATE_MUTEX_INITIAL_OWNER is the only defined flag. + let owned = guest.call("CreateMutexExW", &[0, 0, 1, 0x001f_0001]); + assert_ne!(owned, 0); + assert_eq!( + guest.on(THREAD_B).call("WaitForSingleObject", &[owned, 0]), + WAIT_TIMEOUT + ); + assert_eq!(guest.call("CreateMutexExW", &[0, 0, 2, 0x001f_0001]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + + // Wait-all acquires the mutex and consumes the event together, or neither. + let event = guest.call("CreateEventW", &[0, 0, 1, 0]); + let unowned = guest.call("CreateMutexW", &[0, 0, 0]); + let handles = SCRATCH + 0x900; + for (index, handle) in [unowned, event, owned].into_iter().enumerate() { + guest + .memory + .write_u64(handles + 8 * index as u64, handle) + .unwrap(); + } + assert_eq!( + guest + .on(THREAD_B) + .call("WaitForMultipleObjects", &[3, handles, 1, 0]), + WAIT_TIMEOUT + ); + assert_eq!(guest.call("WaitForSingleObject", &[event, 0]), 0); + assert_eq!(guest.call("SetEvent", &[event]), 1); + assert_eq!( + guest + .on(THREAD_A) + .call("WaitForMultipleObjects", &[3, handles, 1, 0]), + 0 + ); + assert_eq!( + guest + .on(THREAD_B) + .call("WaitForSingleObject", &[unowned, 0]), + WAIT_TIMEOUT + ); + assert_eq!(guest.call("WaitForSingleObject", &[event, 0]), WAIT_TIMEOUT); +} + +#[test] +fn critical_sections_track_owner_and_recursion_in_the_guest_structure() { + let mut guest = Guest::new(); + let section = SCRATCH; + guest.memory.write_bytes(section, &[0xAA; 48]).unwrap(); + assert_eq!(guest.call("InitializeCriticalSection", &[section]), 0); + // winnt.h RTL_CRITICAL_SECTION: LockCount at 8 is -1 when free, + // RecursionCount at 12, OwningThread at 16, SpinCount at 32. + assert_eq!(guest.u32_at(section + 8), u32::MAX); + assert_eq!(guest.u32_at(section + 12), 0); + assert_eq!(guest.u64_at(section + 16), 0); + assert_eq!(guest.u64_at(section + 32), 0); + assert_eq!(guest.u64_at(section + 40), 0xAAAA_AAAA_AAAA_AAAA); + + let thread_id = guest.on(THREAD_A).call("GetCurrentThreadId", &[]); + assert_eq!(guest.call("EnterCriticalSection", &[section]), 0); + assert_eq!(guest.call("TryEnterCriticalSection", &[section]), 1); + assert_eq!(guest.u32_at(section + 12), 2); + assert_eq!(guest.u64_at(section + 16), thread_id); + assert_ne!(guest.u32_at(section + 8), u32::MAX); + + assert_eq!( + guest + .on(THREAD_B) + .call("TryEnterCriticalSection", &[section]), + 0 + ); + assert_eq!( + guest.fails("EnterCriticalSection", &[section]), + RUNTIME_LIMIT + ); + assert_eq!( + guest.fails("LeaveCriticalSection", &[section]), + RUNTIME_LIMIT + ); + assert_eq!(guest.u32_at(section + 12), 2); + + assert_eq!( + guest.on(THREAD_A).call("LeaveCriticalSection", &[section]), + 0 + ); + assert_eq!(guest.u32_at(section + 12), 1); + assert_eq!(guest.call("LeaveCriticalSection", &[section]), 0); + assert_eq!(guest.u32_at(section + 8), u32::MAX); + assert_eq!(guest.u64_at(section + 16), 0); + assert_eq!( + guest + .on(THREAD_B) + .call("TryEnterCriticalSection", &[section]), + 1 + ); + assert_eq!(guest.call("LeaveCriticalSection", &[section]), 0); + assert_eq!(guest.call("DeleteCriticalSection", &[section]), 0); + assert_eq!( + guest.fails("EnterCriticalSection", &[section]), + RUNTIME_LIMIT + ); + + let spinning = SCRATCH + 0x40; + assert_eq!( + guest.call("InitializeCriticalSectionAndSpinCount", &[spinning, 4000]), + 1 + ); + assert_eq!(guest.u64_at(spinning + 32), 4000); + assert_eq!( + guest.call("SetCriticalSectionSpinCount", &[spinning, 100]), + 4000 + ); + assert_eq!(guest.u64_at(spinning + 32), 100); + + let extended = SCRATCH + 0x80; + // CRITICAL_SECTION_NO_DEBUG_INFO is accepted; other flag bits are reserved. + assert_eq!( + guest.call("InitializeCriticalSectionEx", &[extended, 0, 0x0100_0000]), + 1 + ); + assert_eq!( + guest.call( + "InitializeCriticalSectionEx", + &[extended + 0x40, 0, 0x0200_0000] + ), + 0 + ); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + + // The structure lives in guest memory, so it must be writable. + let text = BASE + u64::from(CODE_RVA); + assert!(matches!( + guest.fails("InitializeCriticalSection", &[text]), + ExitReason::MemoryFault(_) + )); +} + +#[test] +fn srw_locks_allow_shared_readers_or_one_writer_and_condition_sleeps_time_out() { + let mut guest = Guest::new(); + let lock = SCRATCH; + let condition = SCRATCH + 8; + let section = SCRATCH + 0x40; + guest.memory.write_u64(lock, u64::MAX).unwrap(); + assert_eq!(guest.call("InitializeSRWLock", &[lock]), 0); + assert_eq!(guest.u64_at(lock), 0); // SRWLOCK_INIT + + assert_eq!(guest.on(THREAD_A).call("AcquireSRWLockShared", &[lock]), 0); + assert_eq!( + guest.on(THREAD_B).call("TryAcquireSRWLockShared", &[lock]) & 0xff, + 1 + ); + assert_eq!(guest.call("TryAcquireSRWLockExclusive", &[lock]) & 0xff, 0); + assert_eq!( + guest.fails("ReleaseSRWLockExclusive", &[lock]), + RUNTIME_LIMIT + ); + assert_eq!(guest.call("ReleaseSRWLockShared", &[lock]), 0); + assert_eq!(guest.call("TryAcquireSRWLockExclusive", &[lock]) & 0xff, 0); + assert_eq!(guest.on(THREAD_A).call("ReleaseSRWLockShared", &[lock]), 0); + + assert_eq!( + guest + .on(THREAD_B) + .call("TryAcquireSRWLockExclusive", &[lock]) + & 0xff, + 1 + ); + assert_eq!( + guest.on(THREAD_A).call("TryAcquireSRWLockShared", &[lock]) & 0xff, + 0 + ); + assert_eq!( + guest.fails("AcquireSRWLockExclusive", &[lock]), + RUNTIME_LIMIT + ); + assert_eq!( + guest.fails("ReleaseSRWLockExclusive", &[lock]), + RUNTIME_LIMIT + ); + // Exclusive SRW locks are not recursive. + assert_eq!( + guest.on(THREAD_B).fails("AcquireSRWLockExclusive", &[lock]), + RUNTIME_LIMIT + ); + + guest.memory.write_u64(condition, u64::MAX).unwrap(); + assert_eq!(guest.call("InitializeConditionVariable", &[condition]), 0); + assert_eq!(guest.u64_at(condition), 0); // CONDITION_VARIABLE_INIT + assert_eq!(guest.call("WakeConditionVariable", &[condition]), 0); + assert_eq!(guest.call("WakeAllConditionVariable", &[condition]), 0); + + // A zero-timeout sleep returns FALSE with ERROR_TIMEOUT and still holds + // the lock in its original mode. + assert_eq!( + guest.call("SleepConditionVariableSRW", &[condition, lock, 0, 0]), + 0 + ); + assert_eq!(guest.error(), ERROR_TIMEOUT); + assert_eq!( + guest.on(THREAD_A).call("TryAcquireSRWLockShared", &[lock]) & 0xff, + 0 + ); + assert_eq!( + guest + .on(THREAD_B) + .call("SleepConditionVariableSRW", &[condition, lock, 10, 0]), + 0 + ); + assert_eq!(guest.error(), ERROR_NOT_SUPPORTED); + assert_eq!( + guest.call("SleepConditionVariableSRW", &[condition, lock, 0, 2]), + 0 + ); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + // Shared mode does not match the exclusive hold; the caller must own the lock. + assert_eq!( + guest.fails("SleepConditionVariableSRW", &[condition, lock, 0, 1]), + RUNTIME_LIMIT + ); + assert_eq!(guest.call("ReleaseSRWLockExclusive", &[lock]), 0); + assert_eq!( + guest.fails("SleepConditionVariableSRW", &[condition, lock, 0, 0]), + RUNTIME_LIMIT + ); + + assert_eq!(guest.call("InitializeCriticalSection", &[section]), 0); + assert_eq!( + guest.fails("SleepConditionVariableCS", &[condition, section, 0]), + RUNTIME_LIMIT + ); + assert_eq!(guest.call("EnterCriticalSection", &[section]), 0); + assert_eq!(guest.call("EnterCriticalSection", &[section]), 0); + assert_eq!( + guest.call("SleepConditionVariableCS", &[condition, section, 0]), + 0 + ); + assert_eq!(guest.error(), ERROR_TIMEOUT); + assert_eq!(guest.u32_at(section + 12), 2); + assert_eq!( + guest + .on(THREAD_A) + .call("TryEnterCriticalSection", &[section]), + 0 + ); +} + +#[test] +fn init_once_runs_one_initializer_and_publishes_its_context() { + let mut guest = Guest::new(); + let once = SCRATCH; + let pending = SCRATCH + 0x10; + let context = SCRATCH + 0x18; + let begin = |guest: &mut Guest, flags: u64| { + guest.memory.write_u64(pending, u64::MAX).unwrap(); + guest.memory.write_u64(context, u64::MAX).unwrap(); + guest.call("InitOnceBeginInitialize", &[once, flags, pending, context]) + }; + guest.memory.write_u64(once, u64::MAX).unwrap(); + assert_eq!(guest.call("InitOnceInitialize", &[once]), 0); + assert_eq!(guest.u64_at(once), 0); // INIT_ONCE_STATIC_INIT + + // INIT_ONCE_CHECK_ONLY reports incomplete initialization as a failure. + assert_eq!(begin(&mut guest, 1), 0); + assert_eq!(guest.error(), ERROR_GEN_FAILURE); + assert_eq!(guest.u64_at(pending), u64::MAX); + + assert_eq!(begin(&mut guest, 0), 1); + // fPending is a 4-byte BOOL. + assert_eq!(guest.u64_at(pending), 0xffff_ffff_0000_0001); + assert_eq!(begin(&mut guest, 1), 0); + + // Context values must leave INIT_ONCE_CTX_RESERVED_BITS (2) clear. + assert_eq!(guest.call("InitOnceComplete", &[once, 0, 0x1003]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + // Only the thread that began initialization may complete it. + assert_eq!( + guest + .on(THREAD_B) + .call("InitOnceComplete", &[once, 0, 0x1000]), + 0 + ); + assert_eq!(guest.error(), ERROR_GEN_FAILURE); + assert_eq!( + guest + .on(THREAD_A) + .call("InitOnceComplete", &[once, 0, 0x1000]), + 1 + ); + + for flags in [0, 1] { + assert_eq!(begin(guest.on(THREAD_B), flags), 1); + assert_eq!(guest.u64_at(pending), 0xffff_ffff_0000_0000); + assert_eq!(guest.u64_at(context), 0x1000); + } + assert_eq!(guest.call("InitOnceComplete", &[once, 0, 0x1000]), 0); + assert_eq!(guest.error(), ERROR_GEN_FAILURE); + + // INIT_ONCE_INIT_FAILED returns the object to its initial state. + let retry = SCRATCH + 0x40; + assert_eq!( + guest.call("InitOnceBeginInitialize", &[retry, 0, pending, 0]), + 1 + ); + assert_eq!(guest.call("InitOnceComplete", &[retry, 4, 8]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + assert_eq!(guest.call("InitOnceComplete", &[retry, 4, 0]), 1); + assert_eq!( + guest.call("InitOnceBeginInitialize", &[retry, 0, pending, 0]), + 1 + ); + assert_eq!(guest.u32_at(pending), 1); + + // A second thread would have to wait for the pending initializer. + assert_eq!( + guest + .on(THREAD_A) + .fails("InitOnceBeginInitialize", &[retry, 0, pending, 0]), + RUNTIME_LIMIT + ); + + assert_eq!( + guest.call("InitOnceBeginInitialize", &[once, 2, pending, 0]), + 0 + ); + assert_eq!(guest.error(), ERROR_NOT_SUPPORTED); + assert_eq!(guest.call("InitOnceBeginInitialize", &[once, 0, 0, 0]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); +} + +#[test] +fn slists_push_and_pop_in_lifo_order_using_the_x64_header_layout() { + let mut guest = Guest::new(); + let header = SCRATCH; + let (first, second) = (SCRATCH + 0x100, SCRATCH + 0x200); + guest.memory.write_bytes(header, &[0xCC; 16]).unwrap(); + assert_eq!(guest.call("InitializeSListHead", &[header]), 0); + assert_eq!((guest.u64_at(header), guest.u64_at(header + 8)), (0, 0)); + assert_eq!(guest.call("QueryDepthSList", &[header]), 0); + + assert_eq!(guest.call("InterlockedPushEntrySList", &[header, first]), 0); + assert_eq!( + guest.call("InterlockedPushEntrySList", &[header, second]), + first + ); + assert_eq!(guest.call("QueryDepthSList", &[header]), 2); + // Depth is the low 16 bits; NextEntry holds the first entry's address + // shifted right by four in bits 4..63 of the second quadword. + assert_eq!(guest.u64_at(header) & 0xffff, 2); + assert_eq!(guest.u64_at(header + 8), second); + assert_eq!(guest.u64_at(second), first); + assert_eq!(guest.u64_at(first), 0); + + assert_eq!(guest.call("InterlockedPopEntrySList", &[header]), second); + assert_eq!(guest.call("QueryDepthSList", &[header]), 1); + assert_eq!( + guest.call("InterlockedPushEntrySList", &[header, second]), + first + ); + assert_eq!(guest.call("InterlockedFlushSList", &[header]), second); + assert_eq!(guest.call("QueryDepthSList", &[header]), 0); + assert_eq!(guest.call("InterlockedPopEntrySList", &[header]), 0); + + // Entries and headers require MEMORY_ALLOCATION_ALIGNMENT (16 bytes). + assert_eq!( + guest.fails("InterlockedPushEntrySList", &[header, first + 8]), + RUNTIME_LIMIT + ); + assert_eq!(guest.fails("QueryDepthSList", &[header + 8]), RUNTIME_LIMIT); +} + +#[test] +fn tls_and_fls_values_are_per_thread_and_cleared_on_reallocation() { + let mut guest = Guest::new(); + let index = guest.call("TlsAlloc", &[]); + assert!(index < 1088, "{index}"); + guest.call("SetLastError", &[5]); + // TlsGetValue clears the last error on success so zero is unambiguous. + assert_eq!(guest.call("TlsGetValue", &[index]), 0); + assert_eq!(guest.error(), 0); + assert_eq!(guest.on(THREAD_A).call("TlsSetValue", &[index, 0xABC0]), 1); + assert_eq!(guest.on(THREAD_B).call("TlsGetValue", &[index]), 0); + assert_eq!(guest.call("TlsSetValue", &[index, 0xDEF0]), 1); + assert_eq!(guest.on(THREAD_A).call("TlsGetValue", &[index]), 0xABC0); + assert_eq!(guest.on(THREAD_B).call("TlsGetValue", &[index]), 0xDEF0); + + assert_eq!(guest.call("TlsFree", &[index]), 1); + assert_eq!(guest.call("TlsGetValue", &[index]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + assert_eq!(guest.call("TlsFree", &[index]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + // A newly allocated index reads as zero in every thread. + let again = guest.call("TlsAlloc", &[]); + assert_eq!(guest.on(THREAD_A).call("TlsGetValue", &[again]), 0); + assert_eq!(guest.on(THREAD_B).call("TlsGetValue", &[again]), 0); + + // The documented process limit is 1,088 TLS indexes. + let mut allocated = 1; + while guest.call("TlsAlloc", &[]) != u64::from(u32::MAX) { + allocated += 1; + assert!(allocated <= 1088); + } + assert_eq!(allocated, 1088); + + let plain = guest.call("FlsAlloc", &[0]); + assert_ne!(plain, u64::from(u32::MAX)); + assert_eq!(guest.call("FlsSetValue", &[plain, 7]), 1); + assert_eq!(guest.on(THREAD_A).call("FlsGetValue", &[plain]), 0); + assert_eq!(guest.on(THREAD_B).call("FlsGetValue", &[plain]), 7); + assert_eq!(guest.call("FlsFree", &[plain]), 1); + assert_eq!(guest.call("FlsGetValue", &[plain]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + + // FlsFree must run the callback for each nonnull value, which needs guest + // callback execution; a slot without values can be released. + let callback = BASE + u64::from(CODE_RVA); + let with_callback = guest.call("FlsAlloc", &[callback]); + assert_eq!(guest.call("FlsSetValue", &[with_callback, 9]), 1); + assert_eq!(guest.fails("FlsFree", &[with_callback]), RUNTIME_LIMIT); + assert_eq!(guest.call("FlsSetValue", &[with_callback, 0]), 1); + assert_eq!(guest.call("FlsFree", &[with_callback]), 1); +} diff --git a/docs/interfaces.md b/docs/interfaces.md index f3e29579..7f23a53f 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -252,8 +252,66 @@ with default security attributes. A successful wait consumes one permit. that exceeds the maximum without changing the count. Duplicates share the same permit count. +`CreateMutexA`, `CreateMutexW` and their `Ex` forms create unnamed mutexes, +optionally owned by the caller. Ownership belongs to the calling guest +thread, identified by its TEB. The owner can acquire the mutex again, and +each acquisition needs a matching `ReleaseMutex`. Another thread sees the +mutex as unsignaled. A release by a thread that is not the owner fails with +`ERROR_NOT_OWNER`. Waits, duplicates and wait-all treat mutexes like the +other waitable objects. Abandonment on thread exit is not modeled, because +guest threads do not exit yet. + See Microsoft's [event object documentation](https://learn.microsoft.com/windows/win32/sync/event-objects). +### Locks, one-time initialization and thread-local storage + +These services keep their state in the runtime and key ownership by guest +TEB. There is no guest scheduler, so any call that would block stops the +guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) rather than +reporting success. Guest code reaches that fault by entering a critical +section owned by another thread, acquiring a held SRW lock, or beginning a +one-time initialization that another thread has pending. + +- Critical sections use the x64 `RTL_CRITICAL_SECTION` layout from + `winnt.h`. Initialization writes the 40-byte structure. `LockCount` is -1 + when free and -2 when held; the runtime also updates `RecursionCount` and + `OwningThread`. The owner may enter recursively. `TryEnterCriticalSection` + returns FALSE when another thread owns it. Leaving a section the caller + does not own, or using one that was never initialized, stops the guest. + The runtime holds up to 4,096 sections. +- SRW locks allow any number of shared holders or one exclusive holder. The + try forms return FALSE instead of waiting. Exclusive acquisition is not + recursive. Releasing a mode the caller does not hold stops the guest. +- Condition variables check that the caller holds the named lock. A + zero-timeout sleep returns FALSE with `ERROR_TIMEOUT` and leaves the lock + held in its original mode. Longer sleeps return `ERROR_NOT_SUPPORTED`. + Wake calls do nothing, because no thread can be sleeping. +- `InitOnceBeginInitialize` and `InitOnceComplete` support the synchronous + mode, `INIT_ONCE_CHECK_ONLY` and `INIT_ONCE_INIT_FAILED`. The completed + context is stored in the `INIT_ONCE` word, so later calls read it back. + Asynchronous mode returns `ERROR_NOT_SUPPORTED`. `InitOnceExecuteOnce` + needs a three-argument guest callback and is not registered. +- Interlocked SLists use the x64 `SLIST_HEADER` layout. The low 16 bits hold + the depth, and bits 4 to 63 of the second quadword hold the first entry. + Headers and entries must be 16-byte aligned. Updates are atomic with + respect to other services. They are not atomic with respect to guest + instructions that modify the header directly on another host thread. +- TLS provides the documented 1,088 indexes. FLS provides the 128 + `FLS_MAXIMUM_AVAILABLE` slots defined in the MinGW-w64 headers. Values are + per guest thread, new indexes read as zero everywhere, and successful get + calls clear the last error. Values live in the runtime, not in the TEB + `TlsSlots` array, so guest code that reads the TEB directly does not see + them. `FlsFree` stops the guest if it would have to run a cleanup callback. + +API-set aliases follow Microsoft's +[Win32 APIs for UWP apps](https://learn.microsoft.com/uwp/win32-and-com/win32-apis) +listing: critical sections, SRW locks and mutexes use +`api-ms-win-core-synch-l1-1-0`; condition variables and one-time +initialization use `api-ms-win-core-synch-l1-2-0`; SLists use +`api-ms-win-core-interlocked-l1-1-0`; TLS uses +`api-ms-win-core-processthreads-l1-1-0`; and FLS uses +`api-ms-win-core-fibers-l1-1-0`. + ## Synthetic tiled textures The texture crate reads original fixtures in an array-layer-major layout. Each From 1eae910ce1e576fd53c000bfb49de99a11cc43f7 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:41:39 -0500 Subject: [PATCH 80/82] Let services call guest code and continue after it returns Add callback tasks to the import dispatcher. A task runs guest callbacks on a reserved stack frame, checks the nonvolatile registers after each, and returns to the original caller. Use it for qsort, qsort_s, bsearch, bsearch_s, _initterm, _initterm_e, InitOnceExecuteOnce and FlsFree cleanup callbacks. Signed-off-by: Adeeb Rahman Co-authored-by: Cursor --- CHANGELOG.md | 2 + crates/import-gen/src/classify.rs | 32 +- crates/loader/src/imports.rs | 161 ++++++++- crates/loader/src/services.rs | 2 + crates/loader/src/services/crt_callbacks.rs | 363 +++++++++++++++++++ crates/loader/src/services/synch.rs | 149 +++++++- crates/loader/tests/runtime_synch.rs | 378 +++++++++++++++++++- docs/interfaces.md | 38 +- 8 files changed, 1069 insertions(+), 56 deletions(-) create mode 100644 crates/loader/src/services/crt_callbacks.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index cfd9c909..240c06f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,8 @@ remains unsupported. - Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`. +- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm` and `_initterm_e`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation. + - Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler. - Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 24e4c8f9..03590a21 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -425,18 +425,11 @@ impl SymbolDb { "CRT invalid param abort", ); self.win32_stub(m, "_purecall", false, "pure virtual call trap"); - self.win32_stub( - m, - "_initterm", - false, - "CRT ctor table init — no-op for guest image", - ); - self.win32_stub( - m, - "_initterm_e", - false, - "CRT ctor table init with error — no-op", - ); + for module in [m, "ucrtbase.dll"] { + for symbol in ["_initterm", "_initterm_e"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.win32_stub( m, "_initialize_onexit_table", @@ -582,8 +575,12 @@ impl SymbolDb { self.crt_native(m, "div", "div", "ISO C div"); self.crt_native(m, "ldiv", "ldiv", "ISO C ldiv"); self.crt_native(m, "lldiv", "lldiv", "ISO C lldiv"); - self.crt_native(m, "bsearch", "bsearch", "ISO C bsearch"); - self.crt_native(m, "qsort", "qsort", "ISO C qsort"); + // The comparators are guest code, so these cannot use host libc. + for module in [m, "ucrtbase.dll"] { + for symbol in ["qsort", "qsort_s", "bsearch", "bsearch_s"] { + self.ins(module, symbol, Classification::StandardService); + } + } self.crt_native(m, "rand", "rand", "ISO C rand"); self.crt_native(m, "srand", "srand", "ISO C srand"); } @@ -829,6 +826,7 @@ impl SymbolDb { "InitOnceInitialize", "InitOnceBeginInitialize", "InitOnceComplete", + "InitOnceExecuteOnce", ] { self.ins(module, symbol, Classification::StandardService); } @@ -886,12 +884,6 @@ impl SymbolDb { "WaitForMultipleObjects", Classification::StandardService, ); - self.win32_stub( - "api-ms-win-core-synch-l1-2-0.dll", - "InitOnceExecuteOnce", - false, - "needs a guest callback with three arguments and its result", - ); } // ---- Win32 library loader ---------------------------------------------- diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index f81b624e..dafa7a93 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -12,7 +12,7 @@ use crate::memory::{GuestMemory, MemoryError}; use crate::pe::ParsedPe; use std::collections::HashMap; use std::fmt; -use std::sync::{Arc, RwLock}; +use std::sync::{Arc, Mutex, RwLock}; /// Base virtual address range reserved for synthetic guest import dispatch trampolines. pub const IMPORT_TRAMPOLINE_BASE_VA: u64 = 0x0000_0007_F000_0000; @@ -208,10 +208,58 @@ type CallbackDispatch = Box< dyn Fn(&Win64Args, &GuestMemory) -> Result, ExitReason> + Send + Sync, >; +/// What a callback-driven service does next. +pub(crate) enum CallbackStep { + /// Call guest code at `entry` with the four Win64 integer register arguments. + Call { entry: u64, args: [u64; 4] }, + /// Return `value` in RAX to the service's caller. + Return(u64), +} + +/// A service that calls guest code one or more times before it returns. +pub(crate) trait CallbackTask: Send { + /// Continue after the previous guest callback returned `result` in RAX. + fn resume( + &mut self, + result: u64, + teb: u64, + memory: &mut GuestMemory, + ) -> Result; +} + +/// How a callback-driven service begins: return at once, or call guest code +/// and continue in a task. +pub(crate) enum CallbackStart { + Return(u64), + Call { + task: Box, + entry: u64, + args: [u64; 4], + }, +} + +/// Starts a callback service. The last argument is the address of 16 bytes of +/// guest stack the service owns until it returns. +type TaskStart = Box< + dyn Fn(&Win64Args, u64, &mut GuestMemory, u64) -> Result + + Send + + Sync, +>; + +/// Stack the dispatcher reserves below the caller's return address for a +/// callback frame: the callback's return address, its 32-byte home area, +/// 16 bytes of service scratch and alignment padding. 72 keeps the callback +/// entry RSP at 8 modulo 16, as after a CALL. +const TASK_FRAME: u64 = 72; +const TASK_SCRATCH: u64 = 40; + #[derive(Clone)] pub(crate) struct CallbackFrame { resume: u64, preserved: Nonvolatile, + task: Option>>>, + /// RSP to restore when a task returns to its caller. + after: u64, } /// Registry for resolving and binding import symbols to guest trampoline VAs. @@ -220,6 +268,7 @@ pub struct ImportRegistry { services: HashMap<(String, ImportName), usize>, handlers: Vec, callback_dispatchers: HashMap, + callback_tasks: HashMap, dynamic_trampolines: DynamicTrampolines, trampoline_to_service: HashMap, // Trampoline VA -> service_index } @@ -236,6 +285,7 @@ impl ImportRegistry { services: HashMap::new(), handlers: Vec::new(), callback_dispatchers: HashMap::new(), + callback_tasks: HashMap::new(), trampoline_to_service: HashMap::new(), dynamic_trampolines: DynamicTrampolines::default(), } @@ -527,6 +577,61 @@ impl ImportRegistry { self.callback_dispatchers.insert(index, Box::new(handler)); } + /// Register a service that may call guest code before returning. `start` + /// receives the arguments, the caller's TEB, guest memory and the address + /// of the service's 16-byte stack scratch area. + pub(crate) fn register_callback_task( + &mut self, + module: &str, + symbol: &str, + status: ServiceStatus, + start: impl Fn(&Win64Args, u64, &mut GuestMemory, u64) -> Result + + Send + + Sync + + 'static, + ) { + self.register_with_status(module, symbol, status, |_, _, _| { + Err(ExitReason::IllegalInstruction(0xff)) + }); + let index = self + .service_index(module, symbol) + .expect("registered callback task"); + self.callback_tasks.insert(index, Box::new(start)); + } + + /// Enter a guest callback from the task frame whose return slot is `slot`. + fn enter_task_callback( + cpu: &mut CpuState, + memory: &mut GuestMemory, + frame: CallbackFrame, + slot: u64, + entry: u64, + args: [u64; 4], + ) -> Result<(), ExitReason> { + let key = (cpu.gs_base, slot + 8); + if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH + || memory.callback_frames.contains_key(&key) + { + return Err(ExitReason::ServiceAbiViolation); + } + memory + .fetch_instruction_byte(entry) + .map_err(ExitReason::MemoryFault)?; + memory + .write_u64(slot, CALLBACK_RETURN) + .map_err(ExitReason::MemoryFault)?; + memory.callback_frames.insert(key, frame); + for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(register, value); + } + cpu.set(Register::Rsp, slot); + cpu.rip = entry; + Ok(()) + } + /// Check if target RIP matches a synthetic service trampoline. pub fn is_service_trampoline(&self, rip: u64) -> bool { rip == CALLBACK_RETURN @@ -550,9 +655,28 @@ impl ImportRegistry { if Nonvolatile::of(cpu) != frame.preserved { return Err(ExitReason::ServiceAbiViolation); } - cpu.set(Register::Rax, 1); - cpu.rip = frame.resume; - return Ok(()); + let Some(task) = frame.task.clone() else { + cpu.set(Register::Rax, 1); + cpu.rip = frame.resume; + return Ok(()); + }; + let result = cpu.get(Register::Rax); + let step = + task.lock() + .expect("guest callback task") + .resume(result, cpu.gs_base, memory)?; + return match step { + CallbackStep::Call { entry, args } => { + let slot = key.1 - 8; + Self::enter_task_callback(cpu, memory, frame, slot, entry, args) + } + CallbackStep::Return(value) => { + cpu.set(Register::Rax, value); + cpu.set(Register::Rsp, frame.after); + cpu.rip = frame.resume; + Ok(()) + } + }; } let service_idx = self .trampoline_to_service @@ -572,6 +696,33 @@ impl ImportRegistry { let args = Win64Args::new(cpu); let preserved = Nonvolatile::of(cpu); + if let Some(start) = self.callback_tasks.get(&service_idx) { + let slot = after + .checked_sub(TASK_FRAME) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + memory + .check_write(slot, (TASK_FRAME - 8) as usize) + .map_err(ExitReason::MemoryFault)?; + match start(&args, cpu.gs_base, memory, slot + TASK_SCRATCH)? { + CallbackStart::Return(value) => { + cpu.set(Register::Rax, value); + cpu.set(Register::Rsp, after); + cpu.rip = ret_addr; + } + CallbackStart::Call { task, entry, args } => { + let mut preserved = preserved; + preserved.gpr[4] = slot + 8; + let frame = CallbackFrame { + resume: ret_addr, + preserved, + task: Some(Arc::new(Mutex::new(task))), + after, + }; + Self::enter_task_callback(cpu, memory, frame, slot, entry, args)?; + } + } + return Ok(()); + } if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) { let key = (cpu.gs_base, after); if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH @@ -593,6 +744,8 @@ impl ImportRegistry { CallbackFrame { resume: ret_addr, preserved, + task: None, + after, }, ); cpu.set(Register::Rcx, callback.context); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index f917413e..4ff943e1 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -10,6 +10,7 @@ //! - Xbox physical memory: `XMemAlloc`, `XMemFree` mod crt; +mod crt_callbacks; mod events; mod files; mod gdk_queue; @@ -342,6 +343,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc() -> Result { + Err(ExitReason::IllegalInstruction(0xFE)) +} + +fn fault(error: MemoryError) -> ExitReason { + ExitReason::MemoryFault(error) +} + +/// The comparator's `int` result. +fn ordering(result: u64) -> i32 { + result as u32 as i32 +} + +/// Comparator arguments. The secure variants pass the caller's context first. +#[derive(Clone, Copy)] +struct Comparator { + entry: u64, + context: Option, +} + +impl Comparator { + fn call(self, left: u64, right: u64) -> CallbackStep { + let args = match self.context { + Some(context) => [context, left, right, 0], + None => [left, right, 0, 0], + }; + CallbackStep::Call { + entry: self.entry, + args, + } + } +} + +/// Binary insertion sort over element indices. Elements stay in place while +/// the comparator runs and are permuted once at the end. +struct Sort { + base: u64, + width: u64, + count: u64, + compare: Comparator, + sorted: Vec, + next: u64, + low: usize, + high: usize, +} + +impl Sort { + fn element(&self, index: u64) -> u64 { + self.base + index * self.width + } + + fn probe(&self) -> CallbackStep { + let middle = (self.low + self.high) / 2; + self.compare + .call(self.element(self.next), self.element(self.sorted[middle])) + } + + fn permute(&self, memory: &mut GuestMemory) -> Result<(), ExitReason> { + let mut original = vec![0; (self.count * self.width) as usize]; + memory.read_bytes(self.base, &mut original).map_err(fault)?; + let width = self.width as usize; + let mut ordered = Vec::with_capacity(original.len()); + for &index in &self.sorted { + let start = index as usize * width; + ordered.extend_from_slice(&original[start..start + width]); + } + memory.write_bytes(self.base, &ordered).map_err(fault) + } +} + +impl CallbackTask for Sort { + fn resume( + &mut self, + result: u64, + _: u64, + memory: &mut GuestMemory, + ) -> Result { + let middle = (self.low + self.high) / 2; + // Inserting after equal elements keeps equal keys in input order. + if ordering(result) < 0 { + self.high = middle; + } else { + self.low = middle + 1; + } + if self.low < self.high { + return Ok(self.probe()); + } + self.sorted.insert(self.low, self.next); + self.next += 1; + if self.next == self.count { + self.permute(memory)?; + return Ok(CallbackStep::Return(0)); + } + self.low = 0; + self.high = self.sorted.len(); + Ok(self.probe()) + } +} + +fn start_sort( + memory: &mut GuestMemory, + base: u64, + count: u64, + width: u64, + compare: Comparator, +) -> Result { + if count > 0 && (base == 0 || width == 0) || compare.entry == 0 { + return unsupported(); + } + if count < 2 { + return Ok(CallbackStart::Return(0)); + } + let Some(bytes) = count + .checked_mul(width) + .filter(|&bytes| bytes <= SORT_BUDGET) + else { + return unsupported(); + }; + base.checked_add(bytes) + .ok_or(fault(MemoryError::Overflow))?; + memory.check_write(base, bytes as usize).map_err(fault)?; + let sort = Sort { + base, + width, + count, + compare, + sorted: vec![0], + next: 1, + low: 0, + high: 1, + }; + let CallbackStep::Call { entry, args } = sort.probe() else { + unreachable!("a probe always calls the comparator"); + }; + Ok(CallbackStart::Call { + task: Box::new(sort), + entry, + args, + }) +} + +struct Search { + key: u64, + base: u64, + width: u64, + compare: Comparator, + low: u64, + high: u64, +} + +impl Search { + fn middle(&self) -> u64 { + self.low + (self.high - self.low) / 2 + } + + fn probe(&self) -> CallbackStep { + self.compare + .call(self.key, self.base + self.middle() * self.width) + } +} + +impl CallbackTask for Search { + fn resume( + &mut self, + result: u64, + _: u64, + _: &mut GuestMemory, + ) -> Result { + let middle = self.middle(); + match ordering(result) { + 0 => return Ok(CallbackStep::Return(self.base + middle * self.width)), + order if order < 0 => self.high = middle, + _ => self.low = middle + 1, + } + if self.low < self.high { + Ok(self.probe()) + } else { + Ok(CallbackStep::Return(0)) + } + } +} + +fn start_search( + key: u64, + base: u64, + count: u64, + width: u64, + compare: Comparator, +) -> Result { + if compare.entry == 0 || count > 0 && (base == 0 || width == 0) { + return unsupported(); + } + if count == 0 { + return Ok(CallbackStart::Return(0)); + } + count + .checked_mul(width) + .and_then(|bytes| base.checked_add(bytes)) + .ok_or(fault(MemoryError::Overflow))?; + let search = Search { + key, + base, + width, + compare, + low: 0, + high: count, + }; + let CallbackStep::Call { entry, args } = search.probe() else { + unreachable!("a probe always calls the comparator"); + }; + Ok(CallbackStart::Call { + task: Box::new(search), + entry, + args, + }) +} + +/// Calls each nonnull function pointer in `[cursor, end)` in order. +/// `_initterm_e` stops at the first initializer that returns nonzero. +struct Initializers { + cursor: u64, + end: u64, + stop_on_error: bool, +} + +impl Initializers { + fn next(&mut self, memory: &GuestMemory) -> Result { + while self.cursor < self.end { + let entry = memory.read_u64(self.cursor).map_err(fault)?; + self.cursor += 8; + if entry != 0 { + return Ok(CallbackStep::Call { + entry, + args: [0; 4], + }); + } + } + Ok(CallbackStep::Return(0)) + } +} + +impl CallbackTask for Initializers { + fn resume( + &mut self, + result: u64, + _: u64, + memory: &mut GuestMemory, + ) -> Result { + let status = result as u32; + if self.stop_on_error && status != 0 { + return Ok(CallbackStep::Return(u64::from(status))); + } + self.next(memory) + } +} + +fn start_initializers( + memory: &mut GuestMemory, + first: u64, + last: u64, + stop_on_error: bool, +) -> Result { + let Some(span) = last.checked_sub(first) else { + return unsupported(); + }; + if !span.is_multiple_of(8) || span / 8 > MAX_INITIALIZERS { + return unsupported(); + } + let mut table = Initializers { + cursor: first, + end: last, + stop_on_error, + }; + Ok(match table.next(memory)? { + CallbackStep::Call { entry, args } => CallbackStart::Call { + task: Box::new(table), + entry, + args, + }, + CallbackStep::Return(value) => CallbackStart::Return(value), + }) +} + +pub(super) fn register(registry: &mut ImportRegistry) { + registry.register_callback_task(UCRT, "qsort", ServiceStatus::Partial, |args, _, mem, _| { + let compare = Comparator { + entry: args.r9, + context: None, + }; + start_sort(mem, args.rcx, args.rdx, args.r8, compare) + }); + registry.register_callback_task( + UCRT, + "qsort_s", + ServiceStatus::Partial, + |args, _, mem, _| { + let context = args.get(4, mem).map_err(fault)?; + let compare = Comparator { + entry: args.r9, + context: Some(context), + }; + start_sort(mem, args.rcx, args.rdx, args.r8, compare) + }, + ); + registry.register_callback_task( + UCRT, + "bsearch", + ServiceStatus::Partial, + |args, _, mem, _| { + let compare = Comparator { + entry: args.get(4, mem).map_err(fault)?, + context: None, + }; + start_search(args.rcx, args.rdx, args.r8, args.r9, compare) + }, + ); + registry.register_callback_task( + UCRT, + "bsearch_s", + ServiceStatus::Partial, + |args, _, mem, _| { + let compare = Comparator { + entry: args.get(4, mem).map_err(fault)?, + context: Some(args.get(5, mem).map_err(fault)?), + }; + start_search(args.rcx, args.rdx, args.r8, args.r9, compare) + }, + ); + for (symbol, stop_on_error) in [("_initterm", false), ("_initterm_e", true)] { + registry.register_callback_task( + UCRT, + symbol, + ServiceStatus::Partial, + move |args, _, mem, _| start_initializers(mem, args.rcx, args.rdx, stop_on_error), + ); + registry.alias(CRT_RUNTIME_API, UCRT, symbol); + } + for symbol in ["qsort", "qsort_s", "bsearch", "bsearch_s"] { + registry.alias(CRT_UTILITY_API, UCRT, symbol); + } +} diff --git a/crates/loader/src/services/synch.rs b/crates/loader/src/services/synch.rs index 72ad6950..d3690d62 100644 --- a/crates/loader/src/services/synch.rs +++ b/crates/loader/src/services/synch.rs @@ -11,7 +11,7 @@ use super::{ ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState, }; use crate::cpu::ExitReason; -use crate::imports::{ImportRegistry, ServiceStatus}; +use crate::imports::{CallbackStart, CallbackStep, CallbackTask, ImportRegistry, ServiceStatus}; use crate::memory::{GuestMemory, MemoryError}; use std::collections::BTreeMap; use std::sync::Arc; @@ -90,6 +90,65 @@ struct FlsSlot { callback: u64, } +struct FlsCleanup { + callback: u64, + values: std::vec::IntoIter, +} + +impl CallbackTask for FlsCleanup { + fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result { + Ok(match self.values.next() { + Some(value) => CallbackStep::Call { + entry: self.callback, + args: [value, 0, 0, 0], + }, + None => CallbackStep::Return(1), + }) + } +} + +/// `InitOnceExecuteOnce` after its initializer returns. The initializer wrote +/// its context to the service's scratch word. +struct InitOnceExecution { + state: Arc, + once: u64, + context: u64, + scratch: u64, +} + +impl CallbackTask for InitOnceExecution { + fn resume( + &mut self, + result: u64, + teb: u64, + memory: &mut GuestMemory, + ) -> Result { + let succeeded = result as u32 != 0; + let produced = memory.read_u64(self.scratch).map_err(fault)?; + let mut synch = self + .state + .synch + .lock() + .expect("guest synchronization state"); + synch.init_once_pending.remove(&self.once); + if !succeeded || produced & INIT_ONCE_CTX_RESERVED_MASK != 0 { + memory.write_u64(self.once, 0).map_err(fault)?; + drop(synch); + if succeeded { + self.state.set_last_error(teb, ERROR_INVALID_PARAMETER); + } + return Ok(CallbackStep::Return(0)); + } + memory + .write_u64(self.once, produced | INIT_ONCE_COMPLETE) + .map_err(fault)?; + if self.context != 0 { + memory.write_u64(self.context, produced).map_err(fault)?; + } + Ok(CallbackStep::Return(1)) + } +} + #[derive(Default)] pub(super) struct Synch { sections: BTreeMap, @@ -648,10 +707,47 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc) Ok(1) }); + let s = Arc::clone(state); + registry.register_callback_task( + KERNEL32, + "InitOnceExecuteOnce", + ServiceStatus::Partial, + move |args, teb, mem, scratch| { + let (once, initializer, parameter, context) = (args.rcx, args.rdx, args.r8, args.r9); + let value = check_word(mem, once)?; + if value & INIT_ONCE_CTX_RESERVED_MASK == INIT_ONCE_COMPLETE { + if context != 0 { + mem.write_u64(context, value & !INIT_ONCE_CTX_RESERVED_MASK) + .map_err(fault)?; + } + return Ok(CallbackStart::Return(1)); + } + if value != 0 { + // Another thread's pending initialization would block. + return unsupported(); + } + let mut synch = s.synch.lock().expect("guest synchronization state"); + mem.write_u64(scratch, 0).map_err(fault)?; + mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?; + synch.init_once_pending.insert(once, teb); + Ok(CallbackStart::Call { + task: Box::new(InitOnceExecution { + state: Arc::clone(&s), + once, + context, + scratch, + }), + entry: initializer, + args: [once, parameter, scratch, 0], + }) + }, + ); + for symbol in [ "InitOnceInitialize", "InitOnceBeginInitialize", "InitOnceComplete", + "InitOnceExecuteOnce", ] { registry.alias(SYNCH_API_2, KERNEL32, symbol); registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); @@ -804,22 +900,41 @@ fn register_tls(registry: &mut ImportRegistry, state: &Arc) { }); let s = Arc::clone(state); - registry.register(KERNEL32, "FlsFree", move |args, cpu, _| { - let index = args.rcx as u32; - let mut synch = s.synch.lock().expect("guest synchronization state"); - let Some(slot) = synch.fls_slots.get(&index) else { - drop(synch); - return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); - }; - let has_values = synch.fls_values.keys().any(|&(_, i)| i == index); - if slot.callback != 0 && has_values { - // FlsFree must run the guest callback for each nonnull value. - return unsupported(); - } - synch.fls_slots.remove(&index); - synch.fls_values.retain(|&(_, slot), _| slot != index); - Ok(1) - }); + registry.register_callback_task( + KERNEL32, + "FlsFree", + ServiceStatus::Partial, + move |args, teb, _, _| { + let index = args.rcx as u32; + let mut synch = s.synch.lock().expect("guest synchronization state"); + let Some(slot) = synch.fls_slots.remove(&index) else { + drop(synch); + s.fail(teb, ERROR_INVALID_PARAMETER, 0)?; + return Ok(CallbackStart::Return(0)); + }; + // The slot is released first; its callback then receives each + // thread's nonnull value, in TEB order, on the calling thread. + let mut values = Vec::new(); + synch.fls_values.retain(|&(_, slot), value| { + if slot == index { + values.push(*value); + } + slot != index + }); + if slot.callback == 0 || values.is_empty() { + return Ok(CallbackStart::Return(1)); + } + let first = values.remove(0); + Ok(CallbackStart::Call { + task: Box::new(FlsCleanup { + callback: slot.callback, + values: values.into_iter(), + }), + entry: slot.callback, + args: [first, 0, 0, 0], + }) + }, + ); let s = Arc::clone(state); registry.register(KERNEL32, "FlsGetValue", move |args, cpu, _| { diff --git a/crates/loader/tests/runtime_synch.rs b/crates/loader/tests/runtime_synch.rs index 6de20fd0..5d7769ee 100644 --- a/crates/loader/tests/runtime_synch.rs +++ b/crates/loader/tests/runtime_synch.rs @@ -1,13 +1,15 @@ // SPDX-License-Identifier: GPL-3.0-or-later //! Mutexes, critical sections, SRW locks, condition variables, one-time -//! initialization, SLists and thread-local storage, called by translated guest -//! code through a bound import table. +//! initialization, SLists, thread-local storage and the CRT services that call +//! guest functions, called by translated guest code through a bound import +//! table. //! //! Two guest threads are modelled by switching the TEB address in GS between -//! calls. Expected values come from the public Win32 synchprocess and -//! processthreadsapi documentation and the x64 layouts in winnt.h, not from -//! the handlers. +//! calls. Guest comparators and initializers are original x86-64 routines in +//! the image's text section. Expected values come from the public Win32 +//! synchapi and processthreadsapi documentation, the C standard, the Microsoft +//! CRT reference and the x64 layouts in winnt.h, not from the handlers. use std::sync::Arc; use xenora_loader::cpu::{CpuState, ExitReason, Register}; @@ -84,8 +86,124 @@ const IMPORTS: &[(&str, &str)] = &[ (KERNEL32, "FlsGetValue"), (FIBERS, "FlsSetValue"), (FIBERS, "FlsFree"), + (SYNCH_2, "InitOnceExecuteOnce"), + (UCRT, "qsort"), + (CRT_UTILITY, "qsort_s"), + (CRT_UTILITY, "bsearch"), + (UCRT, "bsearch_s"), + (CRT_RUNTIME, "_initterm"), + (UCRT, "_initterm_e"), ]; +const UCRT: &str = "ucrtbase.dll"; +const CRT_UTILITY: &str = "api-ms-win-crt-utility-l1-1-0.dll"; +const CRT_RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll"; + +/// Guest routines, placed at RVA 0x1800 in the text section. +const ROUTINES_RVA: u32 = 0x1800; +/// Written by the initializer and cleanup routines. +const LOG: u64 = SCRATCH + 0xF00; +const COUNTER: u64 = SCRATCH + 0xF08; + +#[derive(Clone, Copy)] +enum Routine { + /// `int compare(const int *a, const int *b)`: `*a - *b`. + Compare, + /// `int compare_s(int64_t *calls, const int *a, const int *b)`: counts calls. + CompareCounting, + /// `void init(void)` appending `n` as a decimal digit of LOG. + Append(u8), + /// `int init(void)` returning 7 without touching LOG. + Fail, + /// Clobbers nonvolatile RBX. + ClobberRbx, + /// `BOOL init(INIT_ONCE *, void *parameter, void **context)`: stores the + /// parameter as the context, increments COUNTER and returns TRUE. + InitOnceStore, + /// `BOOL init(...)` returning FALSE. + InitOnceFail, + /// `void cleanup(void *value)` adding the value to LOG. + FlsAdd, +} + +const ROUTINES: [Routine; 10] = [ + Routine::Compare, + Routine::CompareCounting, + Routine::Append(1), + Routine::Append(2), + Routine::Append(3), + Routine::Fail, + Routine::ClobberRbx, + Routine::InitOnceStore, + Routine::InitOnceFail, + Routine::FlsAdd, +]; + +impl Routine { + fn code(self) -> Vec { + let mov_rax = |address: u64| { + let mut code = vec![0x48, 0xB8]; // mov rax, imm64 + code.extend_from_slice(&address.to_le_bytes()); + code + }; + match self { + // mov eax, [rcx]; sub eax, [rdx]; ret + Self::Compare => vec![0x8B, 0x01, 0x2B, 0x02, 0xC3], + // inc qword [rcx]; mov eax, [rdx]; sub eax, [r8]; ret + Self::CompareCounting => vec![0x48, 0xFF, 0x01, 0x8B, 0x02, 0x41, 0x2B, 0x00, 0xC3], + Self::Append(digit) => { + let mut code = mov_rax(LOG); + code.extend_from_slice(&[ + 0x48, 0x8B, 0x08, // mov rcx, [rax] + 0x48, 0x6B, 0xC9, 0x0A, // imul rcx, rcx, 10 + 0x48, 0x83, 0xC1, digit, // add rcx, digit + 0x48, 0x89, 0x08, // mov [rax], rcx + 0x31, 0xC0, // xor eax, eax + 0xC3, + ]); + code + } + // mov eax, 7; ret + Self::Fail => vec![0xB8, 7, 0, 0, 0, 0xC3], + // mov rbx, 1; ret + Self::ClobberRbx => vec![0x48, 0xC7, 0xC3, 1, 0, 0, 0, 0xC3], + Self::InitOnceStore => { + let mut code = mov_rax(COUNTER); + code.extend_from_slice(&[ + 0x48, 0xFF, 0x00, // inc qword [rax] + 0x49, 0x89, 0x10, // mov [r8], rdx + 0xB8, 1, 0, 0, 0, // mov eax, 1 + 0xC3, + ]); + code + } + // xor eax, eax; ret + Self::InitOnceFail => vec![0x31, 0xC0, 0xC3], + Self::FlsAdd => { + let mut code = mov_rax(LOG); + code.extend_from_slice(&[0x48, 0x01, 0x08, 0xC3]); // add [rax], rcx; ret + code + } + } + } +} + +/// Guest address of a routine. Each routine occupies a 32-byte slot. +fn routine(which: usize) -> u64 { + BASE + u64::from(ROUTINES_RVA) + 32 * which as u64 +} + +const COMPARE: usize = 0; +const COMPARE_COUNTING: usize = 1; +const APPEND_1: usize = 2; +const APPEND_2: usize = 3; +const APPEND_3: usize = 4; +const FAIL: usize = 5; +const CLOBBER_RBX: usize = 6; +const INIT_ONCE_STORE: usize = 7; +const INIT_ONCE_FAIL: usize = 8; +const FLS_ADD: usize = 9; + const WAIT_TIMEOUT: u64 = 258; const ERROR_INVALID_HANDLE: u64 = 6; const ERROR_GEN_FAILURE: u64 = 31; @@ -163,6 +281,12 @@ fn build() -> Vec { put(&mut pe, at + 2, &displacement.to_le_bytes()); put(&mut pe, at + 6, &[0xF4]); // hlt } + for (index, routine) in ROUTINES.iter().enumerate() { + let code = routine.code(); + assert!(code.len() <= 32); + let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + 32 * index; + put(&mut pe, at, &code); + } pe } @@ -222,7 +346,19 @@ impl Guest { let address = STACK_TOP - 8 + 8 + 32 + 8 * slot as u64; self.memory.write_u64(address, *value).unwrap(); } - let result = self.engine.run(&mut cpu, &mut self.memory, 8); + use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi}; + let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15]; + for (index, register) in nonvolatile.into_iter().enumerate() { + cpu.set(register, 0x5EED_0000 + index as u64); + } + let result = self.engine.run(&mut cpu, &mut self.memory, 100_000); + if result.exit_reason == ExitReason::Halt { + // The service returned to the instruction after its CALL. + assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}"); + for (index, register) in nonvolatile.into_iter().enumerate() { + assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}"); + } + } (cpu.get(Register::Rax), result.exit_reason) } @@ -733,12 +869,228 @@ fn tls_and_fls_values_are_per_thread_and_cleared_on_reallocation() { assert_eq!(guest.call("FlsGetValue", &[plain]), 0); assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); - // FlsFree must run the callback for each nonnull value, which needs guest - // callback execution; a slot without values can be released. - let callback = BASE + u64::from(CODE_RVA); - let with_callback = guest.call("FlsAlloc", &[callback]); - assert_eq!(guest.call("FlsSetValue", &[with_callback, 9]), 1); - assert_eq!(guest.fails("FlsFree", &[with_callback]), RUNTIME_LIMIT); - assert_eq!(guest.call("FlsSetValue", &[with_callback, 0]), 1); + // FlsFree runs the slot's callback once for each nonnull value. + let with_callback = guest.call("FlsAlloc", &[routine(FLS_ADD)]); + assert_eq!( + guest.on(THREAD_A).call("FlsSetValue", &[with_callback, 5]), + 1 + ); + assert_eq!( + guest.on(THREAD_B).call("FlsSetValue", &[with_callback, 30]), + 1 + ); + let unset = guest.call("FlsAlloc", &[routine(FLS_ADD)]); + guest.memory.write_u64(LOG, 0).unwrap(); assert_eq!(guest.call("FlsFree", &[with_callback]), 1); + assert_eq!(guest.u64_at(LOG), 35); + assert_eq!(guest.call("FlsGetValue", &[with_callback]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + assert_eq!(guest.call("FlsFree", &[unset]), 1); + assert_eq!(guest.u64_at(LOG), 35); +} + +fn write_i32s(guest: &mut Guest, address: u64, values: &[i32]) { + for (index, value) in values.iter().enumerate() { + guest + .memory + .write_u32(address + 4 * index as u64, *value as u32) + .unwrap(); + } +} + +fn read_i32s(guest: &Guest, address: u64, count: usize) -> Vec { + (0..count) + .map(|index| guest.u32_at(address + 4 * index as u64) as i32) + .collect() +} + +#[test] +fn qsort_orders_elements_with_a_guest_comparator() { + let mut guest = Guest::new(); + let array = SCRATCH + 0x100; + let input = [5, -3, 9, 0, 5, 2, -8, 7, 1, 4, -1]; + write_i32s(&mut guest, array, &input); + let mut expected = input; + expected.sort(); + let count = input.len() as u64; + assert_eq!(guest.call("qsort", &[array, count, 4, routine(COMPARE)]), 0); + assert_eq!(read_i32s(&guest, array, input.len()), expected); + + // Eight-byte records keyed by their first int: the records move intact. + let records = SCRATCH + 0x200; + let keyed = [(3, 30), (1, 10), (2, 20), (0, 0)]; + for (index, (key, tag)) in keyed.iter().enumerate() { + write_i32s(&mut guest, records + 8 * index as u64, &[*key, *tag]); + } + assert_eq!(guest.call("qsort", &[records, 4, 8, routine(COMPARE)]), 0); + assert_eq!(read_i32s(&guest, records, 8), [0, 0, 1, 10, 2, 20, 3, 30]); + + // qsort_s passes its context as the comparator's first argument. + write_i32s(&mut guest, array, &input); + guest.memory.write_u64(COUNTER, 0).unwrap(); + assert_eq!( + guest.call( + "qsort_s", + &[array, count, 4, routine(COMPARE_COUNTING), COUNTER] + ), + 0 + ); + assert_eq!(read_i32s(&guest, array, input.len()), expected); + // Any comparison sort of n distinct-enough keys needs at least n - 1 calls. + let calls = guest.u64_at(COUNTER); + assert!(calls >= count - 1 && calls <= count * count, "{calls}"); + + // Fewer than two elements need no comparison. + guest.memory.write_u64(COUNTER, 0).unwrap(); + assert_eq!( + guest.call( + "qsort_s", + &[array, 1, 4, routine(COMPARE_COUNTING), COUNTER] + ), + 0 + ); + assert_eq!(guest.u64_at(COUNTER), 0); + // A read-only array cannot be sorted in place. + let text = BASE + u64::from(CODE_RVA); + assert!(matches!( + guest.fails("qsort", &[text, 4, 4, routine(COMPARE)]), + ExitReason::MemoryFault(_) + )); + assert_eq!(guest.fails("qsort", &[array, 4, 4, 0]), RUNTIME_LIMIT); +} + +#[test] +fn bsearch_returns_the_matching_element_or_null() { + let mut guest = Guest::new(); + let array = SCRATCH + 0x100; + let key = SCRATCH + 0x80; + let sorted = [-8, -3, 0, 2, 5, 9, 14]; + write_i32s(&mut guest, array, &sorted); + let count = sorted.len() as u64; + for (index, value) in sorted.iter().enumerate() { + write_i32s(&mut guest, key, &[*value]); + assert_eq!( + guest.call("bsearch", &[key, array, count, 4, routine(COMPARE)]), + array + 4 * index as u64 + ); + } + for missing in [-9, 1, 15] { + write_i32s(&mut guest, key, &[missing]); + assert_eq!( + guest.call("bsearch", &[key, array, count, 4, routine(COMPARE)]), + 0 + ); + } + assert_eq!( + guest.call("bsearch", &[key, array, 0, 4, routine(COMPARE)]), + 0 + ); + + write_i32s(&mut guest, key, &[14]); + guest.memory.write_u64(COUNTER, 0).unwrap(); + assert_eq!( + guest.call( + "bsearch_s", + &[key, array, count, 4, routine(COMPARE_COUNTING), COUNTER] + ), + array + 24 + ); + // A binary search of seven elements needs at most three comparisons. + let calls = guest.u64_at(COUNTER); + assert!((1..=3).contains(&calls), "{calls}"); +} + +#[test] +fn initializer_tables_run_in_order_and_stop_on_failure() { + let mut guest = Guest::new(); + let table = SCRATCH + 0x300; + let write_table = |guest: &mut Guest, entries: &[u64]| { + for (index, entry) in entries.iter().enumerate() { + guest + .memory + .write_u64(table + 8 * index as u64, *entry) + .unwrap(); + } + table + 8 * entries.len() as u64 + }; + + // Null entries are skipped. + let end = write_table( + &mut guest, + &[routine(APPEND_1), 0, routine(APPEND_2), routine(APPEND_3)], + ); + guest.memory.write_u64(LOG, 0).unwrap(); + assert_eq!(guest.call("_initterm", &[table, end]), 0); + assert_eq!(guest.u64_at(LOG), 123); + assert_eq!(guest.call("_initterm", &[table, table]), 0); + assert_eq!(guest.u64_at(LOG), 123); + + // _initterm_e returns the first nonzero result and runs nothing after it. + let end = write_table( + &mut guest, + &[routine(APPEND_2), routine(FAIL), routine(APPEND_3)], + ); + guest.memory.write_u64(LOG, 0).unwrap(); + assert_eq!(guest.call("_initterm_e", &[table, end]), 7); + assert_eq!(guest.u64_at(LOG), 2); + let end = write_table(&mut guest, &[routine(APPEND_3), routine(APPEND_1)]); + guest.memory.write_u64(LOG, 0).unwrap(); + assert_eq!(guest.call("_initterm_e", &[table, end]), 0); + assert_eq!(guest.u64_at(LOG), 31); + + // An initializer that does not preserve RBX breaks the Win64 contract. + let end = write_table(&mut guest, &[routine(CLOBBER_RBX)]); + assert_eq!( + guest.fails("_initterm", &[table, end]), + ExitReason::ServiceAbiViolation + ); + // Reversed and misaligned tables are rejected. + assert_eq!(guest.fails("_initterm", &[end, table]), RUNTIME_LIMIT); + assert_eq!(guest.fails("_initterm", &[table, table + 4]), RUNTIME_LIMIT); +} + +#[test] +fn init_once_execute_once_runs_the_initializer_exactly_once() { + let mut guest = Guest::new(); + let once = SCRATCH; + let context = SCRATCH + 0x10; + guest.memory.write_u64(COUNTER, 0).unwrap(); + let execute = |guest: &mut Guest, once: u64, initializer: usize, parameter: u64| { + guest.call( + "InitOnceExecuteOnce", + &[once, routine(initializer), parameter, context], + ) + }; + assert_eq!(execute(&mut guest, once, INIT_ONCE_STORE, 0x5000), 1); + assert_eq!(guest.u64_at(context), 0x5000); + assert_eq!(guest.u64_at(COUNTER), 1); + guest.memory.write_u64(context, 0).unwrap(); + assert_eq!( + execute(guest.on(THREAD_B), once, INIT_ONCE_STORE, 0x6000), + 1 + ); + assert_eq!(guest.u64_at(context), 0x5000); + assert_eq!(guest.u64_at(COUNTER), 1); + + // The completed context is visible through InitOnceBeginInitialize. + let pending = SCRATCH + 0x18; + assert_eq!( + guest.call("InitOnceBeginInitialize", &[once, 1, pending, context]), + 1 + ); + assert_eq!(guest.u32_at(pending), 0); + + // A failed initializer leaves the object uninitialized for a retry. + let retry = SCRATCH + 0x40; + assert_eq!(execute(&mut guest, retry, INIT_ONCE_FAIL, 0), 0); + assert_eq!(guest.u64_at(retry), 0); + assert_eq!(execute(&mut guest, retry, INIT_ONCE_STORE, 0x7000), 1); + assert_eq!(guest.u64_at(context), 0x7000); + assert_eq!(guest.u64_at(COUNTER), 2); + + // A context using the reserved low bits cannot be stored. + let reserved = SCRATCH + 0x60; + assert_eq!(execute(&mut guest, reserved, INIT_ONCE_STORE, 0x7001), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + assert_eq!(guest.u64_at(reserved), 0); } diff --git a/docs/interfaces.md b/docs/interfaces.md index 7f23a53f..97797f4c 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -290,7 +290,9 @@ one-time initialization that another thread has pending. mode, `INIT_ONCE_CHECK_ONLY` and `INIT_ONCE_INIT_FAILED`. The completed context is stored in the `INIT_ONCE` word, so later calls read it back. Asynchronous mode returns `ERROR_NOT_SUPPORTED`. `InitOnceExecuteOnce` - needs a three-argument guest callback and is not registered. + calls the guest initializer once with the object, the parameter and a + context pointer. A FALSE result, or a context that uses the two reserved + low bits, leaves the object uninitialized so a later call can retry. - Interlocked SLists use the x64 `SLIST_HEADER` layout. The low 16 bits hold the depth, and bits 4 to 63 of the second quadword hold the first entry. Headers and entries must be 16-byte aligned. Updates are atomic with @@ -301,7 +303,39 @@ one-time initialization that another thread has pending. per guest thread, new indexes read as zero everywhere, and successful get calls clear the last error. Values live in the runtime, not in the TEB `TlsSlots` array, so guest code that reads the TEB directly does not see - them. `FlsFree` stops the guest if it would have to run a cleanup callback. + them. `FlsFree` releases the slot, then calls its cleanup callback on the + calling thread for each thread's nonnull value, in TEB order. + +### Services that call guest code + +A service registered as a callback task can call guest functions before it +returns. The dispatcher reserves 72 bytes of guest stack below the caller's +return address. That space holds the callback's return address, its 32-byte +home area and 16 bytes of scratch owned by the service, and it keeps RSP at 8 +modulo 16 on entry, as after a CALL. Each callback receives up to four +integer register arguments and must preserve the Win64 nonvolatile +registers, or the guest stops with `ServiceAbiViolation`. The callback's RAX +is passed to the task, which either calls guest code again or returns a value +to the original caller with its RSP restored. Up to 32 callback frames may be +active. Callback entry points must be executable. The earlier one-shot +dispatch used by the GDK task queue is unchanged. + +The CRT uses this for: + +- `qsort` and `qsort_s`, which sort up to 1 MiB in place with a guest + comparator. Elements stay in place while the comparator runs and are + permuted once at the end. `qsort_s` passes its context as the first + comparator argument. +- `bsearch` and `bsearch_s`, which return a pointer to a matching element + or null. +- `_initterm` and `_initterm_e`, which call each nonnull entry of an + initializer table in order. `_initterm_e` stops at the first nonzero + result and returns it. Tables hold at most 65,536 entries. + +Null comparators, null arrays with a nonzero count, and reversed or +misaligned tables would reach the CRT invalid-parameter handler. That +handler is not modeled, so these inputs stop the guest with the +runtime-limit fault. API-set aliases follow Microsoft's [Win32 APIs for UWP apps](https://learn.microsoft.com/uwp/win32-and-com/win32-apis) From 8d7f7fadb4e88e1fa4feb3fefa5245f15bfa5625 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:48:16 -0500 Subject: [PATCH 81/82] Add guest system information, calendar time and sleeping The guest sees a configurable simulated machine, kept separate from the detected host hardware. Sleeping goes through the injectable clock. Move the PE fixture harness into a shared test support module. Signed-off-by: Adeeb Rahman Co-authored-by: Cursor --- CHANGELOG.md | 2 + crates/import-gen/src/apiset.rs | 1 + crates/import-gen/src/classify.rs | 69 +++-- crates/loader/src/memory.rs | 15 + crates/loader/src/services.rs | 18 ++ crates/loader/src/services/sysinfo.rs | 402 +++++++++++++++++++++++++ crates/loader/tests/runtime_synch.rs | 223 +------------- crates/loader/tests/runtime_sysinfo.rs | 252 ++++++++++++++++ crates/loader/tests/support/mod.rs | 227 ++++++++++++++ docs/interfaces.md | 31 ++ 10 files changed, 1012 insertions(+), 228 deletions(-) create mode 100644 crates/loader/src/services/sysinfo.rs create mode 100644 crates/loader/tests/runtime_sysinfo.rs create mode 100644 crates/loader/tests/support/mod.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index aee46b37..c2995db0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,6 +44,8 @@ remains unsupported. - Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`. +- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently. + - Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm` and `_initterm_e`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation. - Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler. diff --git a/crates/import-gen/src/apiset.rs b/crates/import-gen/src/apiset.rs index cfd4d888..d28dfc63 100644 --- a/crates/import-gen/src/apiset.rs +++ b/crates/import-gen/src/apiset.rs @@ -56,6 +56,7 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] { "api-ms-win-core-fibers-l1-1-0.dll", "api-ms-win-core-datetime-l1-1-1.dll", "api-ms-win-core-timezone-l1-1-0.dll", + "api-ms-win-core-realtime-l1-1-0.dll", "api-ms-win-core-memory-l1-1-0.dll", ], "ucrtbase.dll" => &[ diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index 03590a21..abb5591f 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -936,30 +936,57 @@ impl SymbolDb { fn populate_win32_sysinfo(&mut self) { let m = "api-ms-win-core-sysinfo-l1-1-0.dll"; - self.win32_stub( - m, - "GetSystemTimeAsFileTime", - false, - "returns current UTC as FILETIME", - ); - for module in [m, "kernel32.dll"] { - for symbol in ["GetTickCount", "GetTickCount64"] { + for (module, symbols) in [ + ( + m, + &[ + "GetSystemTimeAsFileTime", + "GetTickCount", + "GetTickCount64", + "GetSystemInfo", + "GlobalMemoryStatusEx", + "GetSystemTime", + "GetLocalTime", + ][..], + ), + ( + "api-ms-win-core-sysinfo-l1-2-0.dll", + &["GetNativeSystemInfo", "GetSystemTimePreciseAsFileTime"], + ), + ( + "api-ms-win-core-timezone-l1-1-0.dll", + &["FileTimeToSystemTime", "SystemTimeToFileTime"], + ), + ( + "api-ms-win-core-realtime-l1-1-0.dll", + &["QueryUnbiasedInterruptTime"], + ), + ("api-ms-win-core-synch-l1-2-0.dll", &["Sleep"]), + ("api-ms-win-core-synch-l1-1-0.dll", &["SleepEx"]), + ( + "kernel32.dll", + &[ + "GetSystemTimeAsFileTime", + "GetTickCount", + "GetTickCount64", + "GetSystemInfo", + "GetNativeSystemInfo", + "GlobalMemoryStatusEx", + "GetSystemTime", + "GetLocalTime", + "GetSystemTimePreciseAsFileTime", + "FileTimeToSystemTime", + "SystemTimeToFileTime", + "QueryUnbiasedInterruptTime", + "Sleep", + "SleepEx", + ], + ), + ] { + for symbol in symbols { self.ins(module, symbol, Classification::StandardService); } } - self.win32_stub( - m, - "GetSystemInfo", - false, - "fills SYSTEM_INFO with synthetic values", - ); - self.win32_stub( - m, - "GetLocalTime", - false, - "fills SYSTEMTIME with host local time", - ); - self.win32_stub(m, "GetSystemTime", false, "fills SYSTEMTIME with host UTC"); self.win32_stub( m, "GetProcessorCount", diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index cdf81246..77eb168d 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -87,6 +87,8 @@ impl std::error::Error for MemoryError {} pub(crate) const PROCESS_HEAP: u64 = u64::MAX - 2; const MAX_DYNAMIC_BYTES: usize = 64 * 1024 * 1024; +/// Host storage bound for each dynamic allocation kind. +pub(crate) const DYNAMIC_BUDGET: u64 = MAX_DYNAMIC_BYTES as u64; #[derive(Clone, Copy, PartialEq, Eq)] enum AllocationKind { @@ -205,6 +207,19 @@ impl GuestMemory { self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual) } + /// Bytes mapped in total, held by virtual allocations, and held by heap + /// blocks. Each of the last two kinds is bounded by [`DYNAMIC_BUDGET`]. + pub(crate) fn usage(&self) -> (u64, u64, u64) { + let mapped = self + .regions + .iter() + .map(|region| region.data.len()) + .sum::(); + let virtual_bytes = self.dynamic_bytes(AllocationKind::Virtual); + let heap_bytes = self.dynamic_bytes(AllocationKind::Heap(PROCESS_HEAP)); + (mapped as u64, virtual_bytes as u64, heap_bytes as u64) + } + pub(crate) fn crt_errno_address(&mut self, teb: u64) -> Result { if let Some(&address) = self.crt_errno.get(&teb) { return Ok(address); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 4ff943e1..cb51720f 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -18,6 +18,7 @@ mod heap; mod modules; mod platform_fixture; mod synch; +pub mod sysinfo; mod task_fixture; mod winsock; @@ -68,6 +69,13 @@ pub trait Clock: Send + Sync { let ticks = ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() / 100; ticks.min(u128::from(MAX_PERFORMANCE_COUNT)) as u64 } + + /// Suspend the calling guest thread for `intervals` 100-nanosecond ticks. + fn sleep(&self, intervals: u64) { + std::thread::sleep(std::time::Duration::from_nanos( + intervals.saturating_mul(100), + )); + } } /// Deterministic test clock. @@ -102,6 +110,11 @@ impl Clock for MockClock { fn performance_count(&self) -> u64 { self.performance_count.load(Ordering::SeqCst) } + + /// Sleeping advances the mock clock instead of waiting. + fn sleep(&self, intervals: u64) { + self.advance(intervals); + } } /// Host system UTC clock. @@ -174,6 +187,9 @@ pub struct ServicesState { pub process_id: u32, priority_boost_disabled: AtomicBool, pub thread_id: u32, + /// Characteristics the guest is told it runs on. These are simulated and + /// independent of the host; see [`sysinfo::HostCapabilities`] for the host. + pub guest_profile: sysinfo::GuestSystemProfile, objects: Mutex, last_errors: Mutex>, synch: Mutex, @@ -195,6 +211,7 @@ impl ServicesState { priority_boost_disabled: AtomicBool::new(false), process_id: 0x4100, // Synthetic process ID thread_id: 0x4104, // Synthetic main thread ID + guest_profile: sysinfo::GuestSystemProfile::default(), objects: Mutex::new(ObjectState::default()), last_errors: Mutex::default(), synch: Mutex::default(), @@ -338,6 +355,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Self { + Self { processors: 1 } + } +} + +/// Hardware detected on the host Mac. Never reported to the guest. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HostCapabilities { + pub logical_processors: Option, + pub physical_memory: Option, + pub page_size: Option, +} + +impl HostCapabilities { + pub fn detect() -> Self { + let logical_processors = std::thread::available_parallelism() + .ok() + .map(|count| count.get() as u64); + // SAFETY: sysconf takes no pointers. + let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; + Self { + logical_processors, + physical_memory: physical_memory(), + page_size: u64::try_from(page_size).ok().filter(|&size| size > 0), + } + } +} + +#[cfg(target_os = "macos")] +fn physical_memory() -> Option { + let mut bytes = 0u64; + let mut size = std::mem::size_of::(); + // SAFETY: the name is NUL-terminated and the output buffer is a u64 whose + // size is passed in `size`; no new value is written. + let status = unsafe { + libc::sysctlbyname( + c"hw.memsize".as_ptr(), + (&raw mut bytes).cast(), + &raw mut size, + std::ptr::null_mut(), + 0, + ) + }; + (status == 0 && size == std::mem::size_of::()).then_some(bytes) +} + +#[cfg(not(target_os = "macos"))] +fn physical_memory() -> Option { + None +} + +/// A Windows `SYSTEMTIME`, in field order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct SystemTime { + year: u16, + month: u16, + day_of_week: u16, + day: u16, + hour: u16, + minute: u16, + second: u16, + milliseconds: u16, +} + +impl SystemTime { + fn to_bytes(self) -> [u8; 16] { + let fields = [ + self.year, + self.month, + self.day_of_week, + self.day, + self.hour, + self.minute, + self.second, + self.milliseconds, + ]; + let mut bytes = [0; 16]; + for (chunk, field) in bytes.as_chunks_mut::<2>().0.iter_mut().zip(fields) { + *chunk = field.to_le_bytes(); + } + bytes + } + + fn from_bytes(bytes: [u8; 16]) -> Self { + let field = |index: usize| u16::from_le_bytes([bytes[2 * index], bytes[2 * index + 1]]); + Self { + year: field(0), + month: field(1), + day_of_week: field(2), + day: field(3), + hour: field(4), + minute: field(5), + second: field(6), + milliseconds: field(7), + } + } +} + +/// Proleptic Gregorian date for a day count relative to 1970-01-01. +fn civil_from_days(days: i64) -> (i64, u16, u16) { + let shifted = days + 719_468; + let era = shifted.div_euclid(146_097); + let day_of_era = shifted.rem_euclid(146_097); + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let month_index = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * month_index + 2) / 5 + 1; + let month = if month_index < 10 { + month_index + 3 + } else { + month_index - 9 + }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + (year, month as u16, day as u16) +} + +fn days_from_civil(year: i64, month: u16, day: u16) -> i64 { + let year = year - i64::from(month <= 2); + let era = year.div_euclid(400); + let year_of_era = year - era * 400; + let month_index = (i64::from(month) + 9) % 12; + let day_of_year = (153 * month_index + 2) / 5 + i64::from(day) - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + era * 146_097 + day_of_era - 719_468 +} + +fn is_leap(year: u16) -> bool { + year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) +} + +fn days_in_month(year: u16, month: u16) -> u16 { + match month { + 2 if is_leap(year) => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + } +} + +fn filetime_to_system_time(filetime: u64) -> Option { + if filetime >= MAX_FILETIME { + return None; + } + let millis = filetime / TICKS_PER_MILLI; + let days = (millis / MILLIS_PER_DAY) as i64; + let of_day = millis % MILLIS_PER_DAY; + let (year, month, day) = civil_from_days(days - DAYS_1601_TO_1970); + Some(SystemTime { + year: year as u16, + month, + // 1601-01-01 was a Monday, and Sunday is zero. + day_of_week: ((days + 1) % 7) as u16, + day, + hour: (of_day / 3_600_000) as u16, + minute: (of_day / 60_000 % 60) as u16, + second: (of_day / 1000 % 60) as u16, + milliseconds: (of_day % 1000) as u16, + }) +} + +/// The day of week is ignored, as documented for SystemTimeToFileTime. +fn system_time_to_filetime(time: SystemTime) -> Option { + let valid = (1601..=30827).contains(&time.year) + && (1..=12).contains(&time.month) + && (1..=days_in_month(time.year, time.month)).contains(&time.day) + && time.hour < 24 + && time.minute < 60 + && time.second < 60 + && time.milliseconds < 1000; + if !valid { + return None; + } + let days = days_from_civil(i64::from(time.year), time.month, time.day) + DAYS_1601_TO_1970; + let millis = days as u64 * MILLIS_PER_DAY + + u64::from(time.hour) * 3_600_000 + + u64::from(time.minute) * 60_000 + + u64::from(time.second) * 1000 + + u64::from(time.milliseconds); + Some(millis * TICKS_PER_MILLI) +} + +fn fault(error: MemoryError) -> ExitReason { + ExitReason::MemoryFault(error) +} + +fn write_system_info( + state: &ServicesState, + memory: &mut GuestMemory, + address: u64, +) -> Result<(), ExitReason> { + let processors = state.guest_profile.processors.clamp(1, 64); + let mask = u64::MAX >> (64 - processors); + let mut info = [0u8; 48]; + info[0..2].copy_from_slice(&PROCESSOR_ARCHITECTURE_AMD64.to_le_bytes()); + info[4..8].copy_from_slice(&GUEST_PAGE_SIZE.to_le_bytes()); + info[8..16].copy_from_slice(&MINIMUM_APPLICATION_ADDRESS.to_le_bytes()); + info[16..24].copy_from_slice(&MAXIMUM_APPLICATION_ADDRESS.to_le_bytes()); + info[24..32].copy_from_slice(&mask.to_le_bytes()); + info[32..36].copy_from_slice(&processors.to_le_bytes()); + info[36..40].copy_from_slice(&PROCESSOR_AMD_X8664.to_le_bytes()); + info[40..44].copy_from_slice(&(ALLOCATION_GRANULARITY as u32).to_le_bytes()); + // wProcessorLevel and wProcessorRevision stay zero: no CPU model is simulated. + memory.write_bytes(address, &info).map_err(fault) +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + for symbol in ["GetSystemInfo", "GetNativeSystemInfo"] { + let s = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + write_system_info(&s, mem, args.rcx)?; + Ok(0) + }); + } + + let s = Arc::clone(state); + registry.register(KERNEL32, "GlobalMemoryStatusEx", move |args, cpu, mem| { + let address = args.rcx; + if mem.read_u32(address).map_err(fault)? != MEMORYSTATUSEX_SIZE { + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + } + let (mapped, virtual_bytes, heap_bytes) = mem.usage(); + // Guest physical memory is the virtual-allocation and heap budgets; + // there is no paging file. + let total = 2 * DYNAMIC_BUDGET; + let used = (virtual_bytes + heap_bytes).min(total); + let total_virtual = MAXIMUM_APPLICATION_ADDRESS - MINIMUM_APPLICATION_ADDRESS + 1; + let mut status = [0u8; 64]; + status[0..4].copy_from_slice(&MEMORYSTATUSEX_SIZE.to_le_bytes()); + status[4..8].copy_from_slice(&((used * 100 / total) as u32).to_le_bytes()); + for (offset, value) in [ + (8, total), + (16, total - used), + (24, total), + (32, total - used), + (40, total_virtual), + (48, total_virtual.saturating_sub(mapped)), + ] { + status[offset..offset + 8].copy_from_slice(&value.to_le_bytes()); + } + mem.write_bytes(address, &status).map_err(fault)?; + Ok(1) + }); + + // The guest time zone is UTC, so local time equals system time. + for symbol in ["GetSystemTime", "GetLocalTime"] { + let s = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, mem| { + let time = filetime_to_system_time(s.clock.now_filetime()) + .ok_or(ExitReason::IllegalInstruction(0xFE))?; + mem.write_bytes(args.rcx, &time.to_bytes()).map_err(fault)?; + Ok(0) + }); + } + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "GetSystemTimePreciseAsFileTime", + move |args, _, mem| { + mem.write_u64(args.rcx, s.clock.now_filetime()) + .map_err(fault)?; + Ok(0) + }, + ); + + let s = Arc::clone(state); + registry.register(KERNEL32, "FileTimeToSystemTime", move |args, cpu, mem| { + let filetime = mem.read_u64(args.rcx).map_err(fault)?; + let Some(time) = filetime_to_system_time(filetime) else { + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + }; + mem.write_bytes(args.rdx, &time.to_bytes()).map_err(fault)?; + Ok(1) + }); + + let s = Arc::clone(state); + registry.register(KERNEL32, "SystemTimeToFileTime", move |args, cpu, mem| { + let mut bytes = [0; 16]; + mem.read_bytes(args.rcx, &mut bytes).map_err(fault)?; + let Some(filetime) = system_time_to_filetime(SystemTime::from_bytes(bytes)) else { + return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0); + }; + mem.write_u64(args.rdx, filetime).map_err(fault)?; + Ok(1) + }); + + let s = Arc::clone(state); + registry.register( + KERNEL32, + "QueryUnbiasedInterruptTime", + move |args, _, mem| { + let elapsed = s.clock.performance_count().saturating_sub(s.clock_origin); + mem.write_u64(args.rcx, elapsed).map_err(fault)?; + Ok(1) + }, + ); + + // No APCs can be queued, so an alertable SleepEx always runs to completion + // and returns zero rather than WAIT_IO_COMPLETION. + for symbol in ["Sleep", "SleepEx"] { + let s = Arc::clone(state); + registry.register(KERNEL32, symbol, move |args, _, _| { + let millis = args.rcx as u32; + if millis == INFINITE || millis > MAX_SLEEP_MILLIS { + return Err(ExitReason::IllegalInstruction(0xFE)); + } + s.clock.sleep(u64::from(millis) * TICKS_PER_MILLI); + Ok(0) + }); + } + + for (symbol, api_set) in [ + ("GetSystemInfo", SYSINFO_API), + ("GetNativeSystemInfo", SYSINFO_API_2), + ("GlobalMemoryStatusEx", SYSINFO_API), + ("GetSystemTime", SYSINFO_API), + ("GetLocalTime", SYSINFO_API), + ("GetSystemTimePreciseAsFileTime", SYSINFO_API_2), + ("FileTimeToSystemTime", TIMEZONE_API), + ("SystemTimeToFileTime", TIMEZONE_API), + ("QueryUnbiasedInterruptTime", REALTIME_API), + ("Sleep", SYNCH_API_2), + ("SleepEx", SYNCH_API), + ] { + registry.alias(api_set, KERNEL32, symbol); + registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn calendar_conversion_round_trips_across_leap_and_century_boundaries() { + for days in (-DAYS_1601_TO_1970..2_000_000).step_by(997) { + let (year, month, day) = civil_from_days(days); + assert_eq!(days_from_civil(year, month, day), days); + } + assert!(is_leap(2000) && is_leap(2024) && !is_leap(1900) && !is_leap(2100)); + } + + #[test] + fn host_capabilities_are_detected_on_this_mac() { + let host = HostCapabilities::detect(); + assert!(host.logical_processors.unwrap() >= 1); + assert!(host.page_size.unwrap() >= 4096); + #[cfg(target_os = "macos")] + assert!(host.physical_memory.unwrap() >= 1 << 30); + } +} diff --git a/crates/loader/tests/runtime_synch.rs b/crates/loader/tests/runtime_synch.rs index 5d7769ee..12a1c3e6 100644 --- a/crates/loader/tests/runtime_synch.rs +++ b/crates/loader/tests/runtime_synch.rs @@ -11,24 +11,10 @@ //! synchapi and processthreadsapi documentation, the C standard, the Microsoft //! CRT reference and the x64 layouts in winnt.h, not from the handlers. -use std::sync::Arc; -use xenora_loader::cpu::{CpuState, ExitReason, Register}; -use xenora_loader::dbt::DbtEngine; -use xenora_loader::imports::ImportRegistry; -use xenora_loader::memory::{GuestMemory, MemoryPermissions}; -use xenora_loader::pe::ParsedPe; -use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; +mod support; -const BASE: u64 = 0x1_4000_0000; -const CODE_RVA: u32 = 0x1000; -const IDATA_RVA: u32 = 0x10000; -const IDATA_RAW: usize = 0x2200; -const IDATA_LEN: usize = 0x4000; -const SCRATCH: u64 = 0x5_0000; -const STACK: u64 = 0x8_0000; -const STACK_TOP: u64 = STACK + 0x800; -const THREAD_A: u64 = 0x7_0000; -const THREAD_B: u64 = 0x7_2000; +use support::*; +use xenora_loader::cpu::ExitReason; const KERNEL32: &str = "kernel32.dll"; const SYNCH: &str = "api-ms-win-core-synch-l1-1-0.dll"; @@ -99,8 +85,6 @@ const UCRT: &str = "ucrtbase.dll"; const CRT_UTILITY: &str = "api-ms-win-crt-utility-l1-1-0.dll"; const CRT_RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll"; -/// Guest routines, placed at RVA 0x1800 in the text section. -const ROUTINES_RVA: u32 = 0x1800; /// Written by the initializer and cleanup routines. const LOG: u64 = SCRATCH + 0xF00; const COUNTER: u64 = SCRATCH + 0xF08; @@ -188,11 +172,6 @@ impl Routine { } } -/// Guest address of a routine. Each routine occupies a 32-byte slot. -fn routine(which: usize) -> u64 { - BASE + u64::from(ROUTINES_RVA) + 32 * which as u64 -} - const COMPARE: usize = 0; const COMPARE_COUNTING: usize = 1; const APPEND_1: usize = 2; @@ -211,185 +190,15 @@ const ERROR_NOT_SUPPORTED: u64 = 50; const ERROR_INVALID_PARAMETER: u64 = 87; const ERROR_NOT_OWNER: u64 = 288; const ERROR_TIMEOUT: u64 = 1460; -const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE); -/// Original PE32+ image importing each entry of `IMPORTS` from its own -/// descriptor. The code for import `n`, at RVA 0x1000 + 16n, is -/// `call [its slot]; hlt`. -fn build() -> Vec { - let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN]; - fn put(pe: &mut [u8], at: usize, bytes: &[u8]) { - pe[at..at + bytes.len()].copy_from_slice(bytes); - } - put(&mut pe, 0, b"MZ"); - put(&mut pe, 0x3C, &0x80u32.to_le_bytes()); - put(&mut pe, 0x80, b"PE\0\0"); - put(&mut pe, 0x84, &0x8664u16.to_le_bytes()); - put(&mut pe, 0x86, &2u16.to_le_bytes()); - put(&mut pe, 0x94, &240u16.to_le_bytes()); - let optional = 0x98; - put(&mut pe, optional, &0x20Bu16.to_le_bytes()); - put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes()); - put(&mut pe, optional + 24, &BASE.to_le_bytes()); - put(&mut pe, optional + 32, &0x1000u32.to_le_bytes()); - put(&mut pe, optional + 36, &0x200u32.to_le_bytes()); - put(&mut pe, optional + 56, &0x20000u32.to_le_bytes()); - put(&mut pe, optional + 60, &0x200u32.to_le_bytes()); - put(&mut pe, optional + 108, &16u32.to_le_bytes()); - put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes()); - put(&mut pe, optional + 124, &0x100u32.to_le_bytes()); - for (index, (name, rva, raw, len, flags)) in [ - (b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32), - (b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040), - ] - .into_iter() - .enumerate() - { - let section = optional + 240 + 40 * index; - put(&mut pe, section, name); - put(&mut pe, section + 8, &(len as u32).to_le_bytes()); - put(&mut pe, section + 12, &rva.to_le_bytes()); - put(&mut pe, section + 16, &(len as u32).to_le_bytes()); - put(&mut pe, section + 20, &(raw as u32).to_le_bytes()); - put(&mut pe, section + 36, &flags.to_le_bytes()); - } - - let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize; - let mut next = IDATA_RVA + 20 * (IMPORTS.len() as u32 + 1); - let mut take = |len: usize| { - let rva = next; - next = (next + len as u32 + 7) & !7; - rva - }; - for (index, (module, symbol)) in IMPORTS.iter().enumerate() { - let module_rva = take(module.len() + 1); - put(&mut pe, file(module_rva), module.as_bytes()); - let hint = take(symbol.len() + 3); - put(&mut pe, file(hint) + 2, symbol.as_bytes()); - let (lookup, slot) = (take(16), take(16)); - put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes()); - put(&mut pe, file(slot), &u64::from(hint).to_le_bytes()); - let descriptor = file(IDATA_RVA) + 20 * index; - put(&mut pe, descriptor, &lookup.to_le_bytes()); - put(&mut pe, descriptor + 12, &module_rva.to_le_bytes()); - put(&mut pe, descriptor + 16, &slot.to_le_bytes()); - - let code_rva = CODE_RVA + 16 * index as u32; - let displacement = slot.wrapping_sub(code_rva + 6); - let at = 0x200 + 16 * index; - put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement] - put(&mut pe, at + 2, &displacement.to_le_bytes()); - put(&mut pe, at + 6, &[0xF4]); // hlt - } - for (index, routine) in ROUTINES.iter().enumerate() { - let code = routine.code(); - assert!(code.len() <= 32); - let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + 32 * index; - put(&mut pe, at, &code); - } - pe -} - -struct Guest { - engine: DbtEngine, - memory: GuestMemory, - teb: u64, -} - -impl Guest { - fn new() -> Self { - let bytes = build(); - let pe = ParsedPe::parse(&bytes).unwrap(); - let mut memory = pe.load_into_memory(&bytes).unwrap().memory; - memory - .map_region(SCRATCH, 0x1000, MemoryPermissions::READ_WRITE) - .unwrap(); - memory - .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) - .unwrap(); - let mut registry = ImportRegistry::new(); - let state = ServicesState::new(Arc::new(MockClock::new(0))); - register_standard_services(&mut registry, Arc::new(state)); - let bound = registry - .bind_imports(&pe, &bytes, BASE, &mut memory) - .unwrap(); - assert_eq!(bound, IMPORTS.len()); - let mut engine = DbtEngine::new(256 * 1024).unwrap(); - engine.set_import_registry(registry); - Self { - engine, - memory, - teb: THREAD_A, - } - } - - fn on(&mut self, teb: u64) -> &mut Self { - self.teb = teb; - self - } - - fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) { - let index = IMPORTS - .iter() - .position(|(_, name)| *name == symbol) - .unwrap_or_else(|| panic!("{symbol} is not imported")); - let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); - cpu.gs_base = self.teb; - for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] - .into_iter() - .zip(args) - { - cpu.set(register, *value); - } - // Stack arguments start after the return address and the home area. - for (slot, value) in args.iter().skip(4).enumerate() { - let address = STACK_TOP - 8 + 8 + 32 + 8 * slot as u64; - self.memory.write_u64(address, *value).unwrap(); - } - use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi}; - let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15]; - for (index, register) in nonvolatile.into_iter().enumerate() { - cpu.set(register, 0x5EED_0000 + index as u64); - } - let result = self.engine.run(&mut cpu, &mut self.memory, 100_000); - if result.exit_reason == ExitReason::Halt { - // The service returned to the instruction after its CALL. - assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}"); - for (index, register) in nonvolatile.into_iter().enumerate() { - assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}"); - } - } - (cpu.get(Register::Rax), result.exit_reason) - } - - fn call(&mut self, symbol: &str, args: &[u64]) -> u64 { - let (rax, exit) = self.run(symbol, args); - assert_eq!(exit, ExitReason::Halt, "{symbol}"); - rax - } - - fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason { - let (_, exit) = self.run(symbol, args); - assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest"); - exit - } - - fn error(&mut self) -> u64 { - self.call("GetLastError", &[]) - } - - fn u32_at(&self, address: u64) -> u32 { - self.memory.read_u32(address).unwrap() - } - - fn u64_at(&self, address: u64) -> u64 { - self.memory.read_u64(address).unwrap() - } +fn new_guest() -> Guest { + let routines: Vec> = ROUTINES.iter().map(|routine| routine.code()).collect(); + Guest::new(IMPORTS, &routines) } #[test] fn mutexes_are_recursive_for_their_owner_and_exclusive_across_threads() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let mutex = guest.on(THREAD_A).call("CreateMutexW", &[0, 1, 0]); assert_ne!(mutex, 0); @@ -502,7 +311,7 @@ fn mutexes_are_recursive_for_their_owner_and_exclusive_across_threads() { #[test] fn critical_sections_track_owner_and_recursion_in_the_guest_structure() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let section = SCRATCH; guest.memory.write_bytes(section, &[0xAA; 48]).unwrap(); assert_eq!(guest.call("InitializeCriticalSection", &[section]), 0); @@ -595,7 +404,7 @@ fn critical_sections_track_owner_and_recursion_in_the_guest_structure() { #[test] fn srw_locks_allow_shared_readers_or_one_writer_and_condition_sleeps_time_out() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let lock = SCRATCH; let condition = SCRATCH + 8; let section = SCRATCH + 0x40; @@ -705,7 +514,7 @@ fn srw_locks_allow_shared_readers_or_one_writer_and_condition_sleeps_time_out() #[test] fn init_once_runs_one_initializer_and_publishes_its_context() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let once = SCRATCH; let pending = SCRATCH + 0x10; let context = SCRATCH + 0x18; @@ -788,7 +597,7 @@ fn init_once_runs_one_initializer_and_publishes_its_context() { #[test] fn slists_push_and_pop_in_lifo_order_using_the_x64_header_layout() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let header = SCRATCH; let (first, second) = (SCRATCH + 0x100, SCRATCH + 0x200); guest.memory.write_bytes(header, &[0xCC; 16]).unwrap(); @@ -829,7 +638,7 @@ fn slists_push_and_pop_in_lifo_order_using_the_x64_header_layout() { #[test] fn tls_and_fls_values_are_per_thread_and_cleared_on_reallocation() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let index = guest.call("TlsAlloc", &[]); assert!(index < 1088, "{index}"); guest.call("SetLastError", &[5]); @@ -906,7 +715,7 @@ fn read_i32s(guest: &Guest, address: u64, count: usize) -> Vec { #[test] fn qsort_orders_elements_with_a_guest_comparator() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let array = SCRATCH + 0x100; let input = [5, -3, 9, 0, 5, 2, -8, 7, 1, 4, -1]; write_i32s(&mut guest, array, &input); @@ -961,7 +770,7 @@ fn qsort_orders_elements_with_a_guest_comparator() { #[test] fn bsearch_returns_the_matching_element_or_null() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let array = SCRATCH + 0x100; let key = SCRATCH + 0x80; let sorted = [-8, -3, 0, 2, 5, 9, 14]; @@ -1002,7 +811,7 @@ fn bsearch_returns_the_matching_element_or_null() { #[test] fn initializer_tables_run_in_order_and_stop_on_failure() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let table = SCRATCH + 0x300; let write_table = |guest: &mut Guest, entries: &[u64]| { for (index, entry) in entries.iter().enumerate() { @@ -1051,7 +860,7 @@ fn initializer_tables_run_in_order_and_stop_on_failure() { #[test] fn init_once_execute_once_runs_the_initializer_exactly_once() { - let mut guest = Guest::new(); + let mut guest = new_guest(); let once = SCRATCH; let context = SCRATCH + 0x10; guest.memory.write_u64(COUNTER, 0).unwrap(); diff --git a/crates/loader/tests/runtime_sysinfo.rs b/crates/loader/tests/runtime_sysinfo.rs new file mode 100644 index 00000000..72743382 --- /dev/null +++ b/crates/loader/tests/runtime_sysinfo.rs @@ -0,0 +1,252 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! System information, calendar conversion and sleeping through the guest +//! import table. +//! +//! Layouts and constants come from the public `SYSTEM_INFO`, `MEMORYSTATUSEX` +//! and `SYSTEMTIME` documentation and winnt.h. Calendar expectations come from +//! the FILETIME epoch (1601-01-01 UTC) and dates computed independently with +//! the host `date` utility, not from the conversion code. + +mod support; + +use std::sync::Arc; +use support::*; +use xenora_loader::services::sysinfo::{GuestSystemProfile, HostCapabilities}; +use xenora_loader::services::{MockClock, ServicesState}; + +const KERNEL32: &str = "kernel32.dll"; +const SYSINFO: &str = "api-ms-win-core-sysinfo-l1-1-0.dll"; + +const IMPORTS: &[(&str, &str)] = &[ + (KERNEL32, "GetLastError"), + (SYSINFO, "GetSystemInfo"), + ("api-ms-win-core-sysinfo-l1-2-0.dll", "GetNativeSystemInfo"), + (SYSINFO, "GlobalMemoryStatusEx"), + (SYSINFO, "GetSystemTime"), + (KERNEL32, "GetLocalTime"), + (KERNEL32, "GetSystemTimeAsFileTime"), + ( + "api-ms-win-core-sysinfo-l1-2-0.dll", + "GetSystemTimePreciseAsFileTime", + ), + ( + "api-ms-win-core-timezone-l1-1-0.dll", + "FileTimeToSystemTime", + ), + (KERNEL32, "SystemTimeToFileTime"), + ( + "api-ms-win-core-realtime-l1-1-0.dll", + "QueryUnbiasedInterruptTime", + ), + ("api-ms-win-core-synch-l1-2-0.dll", "Sleep"), + (KERNEL32, "SleepEx"), + (KERNEL32, "GetTickCount64"), + (KERNEL32, "VirtualAlloc"), + (KERNEL32, "GetProcessHeap"), + (KERNEL32, "HeapAlloc"), +]; + +const ERROR_INVALID_PARAMETER: u64 = 87; +const UNIX_EPOCH_FILETIME: u64 = 116_444_736_000_000_000; +const TICKS_PER_SECOND: u64 = 10_000_000; +/// `date -u -j -f "%Y-%m-%d %H:%M:%S" "2026-11-24 12:34:56" +%s`, a Tuesday. +const NOV_24_2026: u64 = 1_795_523_696; +/// `date -u -j -f "%Y-%m-%d %H:%M:%S" "2024-02-29 23:59:59" +%s`, a Thursday. +const FEB_29_2024: u64 = 1_709_251_199; + +fn filetime(unix_seconds: u64, millis: u64) -> u64 { + UNIX_EPOCH_FILETIME + unix_seconds * TICKS_PER_SECOND + millis * 10_000 +} + +/// SYSTEMTIME fields: year, month, day of week, day, hour, minute, second, ms. +fn system_time(guest: &Guest, address: u64) -> [u16; 8] { + std::array::from_fn(|index| guest.u16_at(address + 2 * index as u64)) +} + +fn write_system_time(guest: &mut Guest, address: u64, fields: [u16; 8]) { + for (index, field) in fields.into_iter().enumerate() { + guest + .memory + .write_u16(address + 2 * index as u64, field) + .unwrap(); + } +} + +#[test] +fn system_info_reports_the_simulated_guest_machine() { + let mut guest = Guest::new(IMPORTS, &[]); + let info = SCRATCH; + for symbol in ["GetSystemInfo", "GetNativeSystemInfo"] { + guest.memory.write_bytes(info, &[0xAA; 56]).unwrap(); + assert_eq!(guest.call(symbol, &[info]), 0); + assert_eq!(guest.u16_at(info), 9); // PROCESSOR_ARCHITECTURE_AMD64 + assert_eq!(guest.u32_at(info + 4), 4096); // dwPageSize + assert_eq!(guest.u64_at(info + 8), 0x1_0000); + assert_eq!(guest.u64_at(info + 16), 0x7fff_fffe_ffff); + assert_eq!(guest.u64_at(info + 24), 1); // dwActiveProcessorMask + assert_eq!(guest.u32_at(info + 32), 1); // dwNumberOfProcessors + assert_eq!(guest.u32_at(info + 36), 8664); // PROCESSOR_AMD_X8664 + assert_eq!(guest.u32_at(info + 40), 65_536); // dwAllocationGranularity + assert_eq!(guest.u32_at(info + 44), 0); // no simulated CPU model + assert_eq!(guest.u64_at(info + 48), 0xAAAA_AAAA_AAAA_AAAA); + } + + let mut state = ServicesState::new(Arc::new(MockClock::new(0))); + state.guest_profile = GuestSystemProfile { processors: 4 }; + let mut guest = Guest::with_state(IMPORTS, &[], state); + assert_eq!(guest.call("GetSystemInfo", &[info]), 0); + assert_eq!(guest.u64_at(info + 24), 0b1111); + assert_eq!(guest.u32_at(info + 32), 4); + + // The guest page size does not follow the host's. + let host = HostCapabilities::detect(); + assert!(host.page_size.is_some() && host.logical_processors.is_some()); + assert_eq!(guest.u32_at(info + 4), 4096); +} + +#[test] +fn memory_status_tracks_guest_allocations_against_the_budget() { + let mut guest = Guest::new(IMPORTS, &[]); + let status = SCRATCH; + // dwLength must hold sizeof(MEMORYSTATUSEX). + guest.memory.write_u32(status, 0).unwrap(); + assert_eq!(guest.call("GlobalMemoryStatusEx", &[status]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + + let query = |guest: &mut Guest| { + guest.memory.write_u32(status, 64).unwrap(); + assert_eq!(guest.call("GlobalMemoryStatusEx", &[status]), 1); + let load = guest.u32_at(status + 4); + let fields: [u64; 7] = + std::array::from_fn(|index| guest.u64_at(status + 8 + 8 * index as u64)); + (load, fields) + }; + const MIB: u64 = 1 << 20; + let ( + load, + [ + total, + available, + page_total, + page_available, + total_virtual, + _, + extended, + ], + ) = query(&mut guest); + assert_eq!((load, total, available), (0, 128 * MIB, 128 * MIB)); + assert_eq!((page_total, page_available), (total, available)); + assert_eq!(total_virtual, 0x7fff_fffe_0000); + assert_eq!(extended, 0); + + let region = guest.call("VirtualAlloc", &[0, MIB, 0x3000, 4]); + assert_ne!(region, 0); + let heap = guest.call("GetProcessHeap", &[]); + assert_ne!(guest.call("HeapAlloc", &[heap, 0, 32 * MIB]), 0); + let (load, [_, available, ..]) = query(&mut guest); + assert_eq!(available, 128 * MIB - 33 * MIB); + assert_eq!(load, 25); // 33 of 128 MiB in use, rounded down +} + +#[test] +fn calendar_time_comes_from_the_injected_clock() { + let clock = Arc::new(MockClock::new(filetime(NOV_24_2026, 789))); + let state = ServicesState::new(clock.clone()); + let mut guest = Guest::with_state(IMPORTS, &[], state); + let time = SCRATCH; + for symbol in ["GetSystemTime", "GetLocalTime"] { + assert_eq!(guest.call(symbol, &[time]), 0); + assert_eq!( + system_time(&guest, time), + [2026, 11, 2, 24, 12, 34, 56, 789] + ); + } + let precise = SCRATCH + 0x20; + assert_eq!(guest.call("GetSystemTimePreciseAsFileTime", &[precise]), 0); + assert_eq!(guest.u64_at(precise), filetime(NOV_24_2026, 789)); + clock.advance(TICKS_PER_SECOND); + assert_eq!(guest.call("GetSystemTimeAsFileTime", &[precise]), 0); + assert_eq!(guest.u64_at(precise), filetime(NOV_24_2026 + 1, 789)); +} + +#[test] +fn filetime_and_system_time_convert_in_both_directions() { + let mut guest = Guest::new(IMPORTS, &[]); + let (input, output, back) = (SCRATCH, SCRATCH + 0x20, SCRATCH + 0x40); + for (value, expected) in [ + (0, [1601, 1, 1, 1, 0, 0, 0, 0]), // a Monday + (UNIX_EPOCH_FILETIME, [1970, 1, 4, 1, 0, 0, 0, 0]), // a Thursday + ( + filetime(FEB_29_2024, 999), + [2024, 2, 4, 29, 23, 59, 59, 999], + ), + ( + filetime(NOV_24_2026, 789), + [2026, 11, 2, 24, 12, 34, 56, 789], + ), + ] { + guest.memory.write_u64(input, value).unwrap(); + assert_eq!(guest.call("FileTimeToSystemTime", &[input, output]), 1); + assert_eq!(system_time(&guest, output), expected); + // The day of week is ignored on the way back. + let mut fields = expected; + fields[2] = 6; + write_system_time(&mut guest, output, fields); + assert_eq!(guest.call("SystemTimeToFileTime", &[output, back]), 1); + assert_eq!(guest.u64_at(back), value - value % 10_000); + } + + guest + .memory + .write_u64(input, 0x8000_0000_0000_0000) + .unwrap(); + guest.memory.write_u64(output, u64::MAX).unwrap(); + assert_eq!(guest.call("FileTimeToSystemTime", &[input, output]), 0); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + assert_eq!(guest.u64_at(output), u64::MAX); + + for invalid in [ + [2023, 2, 0, 29, 0, 0, 0, 0], // not a leap year + [1900, 2, 0, 29, 0, 0, 0, 0], // century, not a leap year + [2026, 13, 0, 1, 0, 0, 0, 0], + [2026, 4, 0, 31, 0, 0, 0, 0], + [2026, 1, 0, 1, 24, 0, 0, 0], + [2026, 1, 0, 1, 0, 0, 0, 1000], + [1600, 12, 0, 31, 0, 0, 0, 0], + ] { + write_system_time(&mut guest, output, invalid); + guest.memory.write_u64(back, 7).unwrap(); + assert_eq!( + guest.call("SystemTimeToFileTime", &[output, back]), + 0, + "{invalid:?}" + ); + assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); + assert_eq!(guest.u64_at(back), 7); + } + write_system_time(&mut guest, output, [2000, 2, 0, 29, 0, 0, 0, 0]); + assert_eq!(guest.call("SystemTimeToFileTime", &[output, back]), 1); + write_system_time(&mut guest, output, [30827, 12, 0, 31, 23, 59, 59, 999]); + assert_eq!(guest.call("SystemTimeToFileTime", &[output, back]), 1); +} + +#[test] +fn sleeping_advances_the_injected_clock() { + let clock = Arc::new(MockClock::new(0)); + let state = ServicesState::new(clock.clone()); + let mut guest = Guest::with_state(IMPORTS, &[], state); + let interrupt = SCRATCH; + assert_eq!(guest.call("GetTickCount64", &[]), 0); + assert_eq!(guest.call("Sleep", &[250]), 0); + assert_eq!(guest.call("GetTickCount64", &[]), 250); + assert_eq!(guest.call("SleepEx", &[5, 1]), 0); + assert_eq!(guest.call("Sleep", &[0]), 0); + assert_eq!(guest.call("GetTickCount64", &[]), 255); + assert_eq!(guest.call("QueryUnbiasedInterruptTime", &[interrupt]), 1); + assert_eq!(guest.u64_at(interrupt), 2_550_000); + // A single guest thread sleeping forever can never wake. + assert_eq!(guest.fails("Sleep", &[u64::from(u32::MAX)]), RUNTIME_LIMIT); + assert_eq!(guest.fails("SleepEx", &[60_000, 0]), RUNTIME_LIMIT); + assert_eq!(guest.call("GetTickCount64", &[]), 255); +} diff --git a/crates/loader/tests/support/mod.rs b/crates/loader/tests/support/mod.rs new file mode 100644 index 00000000..eaa3edd6 --- /dev/null +++ b/crates/loader/tests/support/mod.rs @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Shared harness for runtime service tests: an original PE32+ image whose +//! imports are bound to the standard service registry and called from +//! translated guest code. + +#![allow(dead_code)] + +use std::sync::Arc; +use xenora_loader::cpu::{CpuState, ExitReason, Register}; +use xenora_loader::dbt::DbtEngine; +use xenora_loader::imports::ImportRegistry; +use xenora_loader::memory::{GuestMemory, MemoryPermissions}; +use xenora_loader::pe::ParsedPe; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; + +pub const BASE: u64 = 0x1_4000_0000; +pub const CODE_RVA: u32 = 0x1000; +const IDATA_RVA: u32 = 0x10000; +const IDATA_RAW: usize = 0x2200; +const IDATA_LEN: usize = 0x4000; +pub const SCRATCH: u64 = 0x5_0000; +pub const SCRATCH_LEN: u64 = 0x1000; +pub const STACK: u64 = 0x8_0000; +pub const STACK_TOP: u64 = STACK + 0x800; +pub const THREAD_A: u64 = 0x7_0000; +pub const THREAD_B: u64 = 0x7_2000; +/// Guest routines start at this RVA in the text section, 32 bytes apart. +pub const ROUTINES_RVA: u32 = 0x1800; +pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE); + +/// Guest address of routine `index`. +pub fn routine(index: usize) -> u64 { + BASE + u64::from(ROUTINES_RVA) + 32 * index as u64 +} + +/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`. +/// Each import has its own descriptor. +fn build(imports: &[(&str, &str)], routines: &[Vec]) -> Vec { + let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN]; + fn put(pe: &mut [u8], at: usize, bytes: &[u8]) { + pe[at..at + bytes.len()].copy_from_slice(bytes); + } + put(&mut pe, 0, b"MZ"); + put(&mut pe, 0x3C, &0x80u32.to_le_bytes()); + put(&mut pe, 0x80, b"PE\0\0"); + put(&mut pe, 0x84, &0x8664u16.to_le_bytes()); + put(&mut pe, 0x86, &2u16.to_le_bytes()); + put(&mut pe, 0x94, &240u16.to_le_bytes()); + let optional = 0x98; + put(&mut pe, optional, &0x20Bu16.to_le_bytes()); + put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes()); + put(&mut pe, optional + 24, &BASE.to_le_bytes()); + put(&mut pe, optional + 32, &0x1000u32.to_le_bytes()); + put(&mut pe, optional + 36, &0x200u32.to_le_bytes()); + put(&mut pe, optional + 56, &0x20000u32.to_le_bytes()); + put(&mut pe, optional + 60, &0x200u32.to_le_bytes()); + put(&mut pe, optional + 108, &16u32.to_le_bytes()); + put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes()); + put(&mut pe, optional + 124, &0x100u32.to_le_bytes()); + for (index, (name, rva, raw, len, flags)) in [ + (b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32), + (b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040), + ] + .into_iter() + .enumerate() + { + let section = optional + 240 + 40 * index; + put(&mut pe, section, name); + put(&mut pe, section + 8, &(len as u32).to_le_bytes()); + put(&mut pe, section + 12, &rva.to_le_bytes()); + put(&mut pe, section + 16, &(len as u32).to_le_bytes()); + put(&mut pe, section + 20, &(raw as u32).to_le_bytes()); + put(&mut pe, section + 36, &flags.to_le_bytes()); + } + + assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize); + let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize; + let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1); + let mut take = |len: usize| { + let rva = next; + next = (next + len as u32 + 7) & !7; + rva + }; + for (index, (module, symbol)) in imports.iter().enumerate() { + let module_rva = take(module.len() + 1); + put(&mut pe, file(module_rva), module.as_bytes()); + let hint = take(symbol.len() + 3); + put(&mut pe, file(hint) + 2, symbol.as_bytes()); + let (lookup, slot) = (take(16), take(16)); + put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes()); + put(&mut pe, file(slot), &u64::from(hint).to_le_bytes()); + let descriptor = file(IDATA_RVA) + 20 * index; + put(&mut pe, descriptor, &lookup.to_le_bytes()); + put(&mut pe, descriptor + 12, &module_rva.to_le_bytes()); + put(&mut pe, descriptor + 16, &slot.to_le_bytes()); + + let code_rva = CODE_RVA + 16 * index as u32; + let displacement = slot.wrapping_sub(code_rva + 6); + let at = 0x200 + 16 * index; + put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement] + put(&mut pe, at + 2, &displacement.to_le_bytes()); + put(&mut pe, at + 6, &[0xF4]); // hlt + } + for (index, code) in routines.iter().enumerate() { + assert!(code.len() <= 32); + let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + 32 * index; + put(&mut pe, at, code); + } + pe +} + +pub struct Guest { + engine: DbtEngine, + pub memory: GuestMemory, + pub state: Arc, + imports: &'static [(&'static str, &'static str)], + teb: u64, +} + +impl Guest { + pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec]) -> Self { + let state = ServicesState::new(Arc::new(MockClock::new(0))); + Self::with_state(imports, routines, state) + } + + pub fn with_state( + imports: &'static [(&'static str, &'static str)], + routines: &[Vec], + state: ServicesState, + ) -> Self { + let bytes = build(imports, routines); + let pe = ParsedPe::parse(&bytes).unwrap(); + let mut memory = pe.load_into_memory(&bytes).unwrap().memory; + memory + .map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE) + .unwrap(); + memory + .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) + .unwrap(); + let state = Arc::new(state); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + let bound = registry + .bind_imports(&pe, &bytes, BASE, &mut memory) + .unwrap(); + assert_eq!(bound, imports.len()); + let mut engine = DbtEngine::new(256 * 1024).unwrap(); + engine.set_import_registry(registry); + Self { + engine, + memory, + state, + imports, + teb: THREAD_A, + } + } + + pub fn on(&mut self, teb: u64) -> &mut Self { + self.teb = teb; + self + } + + /// Call an import with Win64 arguments. Arguments after the fourth go on + /// the stack after the return address and the home area. + pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) { + let index = self + .imports + .iter() + .position(|(_, name)| *name == symbol) + .unwrap_or_else(|| panic!("{symbol} is not imported")); + let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); + cpu.gs_base = self.teb; + for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(register, *value); + } + for (slot, value) in args.iter().skip(4).enumerate() { + let address = STACK_TOP + 32 + 8 * slot as u64; + self.memory.write_u64(address, *value).unwrap(); + } + use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi}; + let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15]; + for (index, register) in nonvolatile.into_iter().enumerate() { + cpu.set(register, 0x5EED_0000 + index as u64); + } + let result = self.engine.run(&mut cpu, &mut self.memory, 100_000); + if result.exit_reason == ExitReason::Halt { + // The service returned to the instruction after its CALL. + assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}"); + for (index, register) in nonvolatile.into_iter().enumerate() { + assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}"); + } + } + (cpu.get(Register::Rax), result.exit_reason) + } + + pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 { + let (rax, exit) = self.run(symbol, args); + assert_eq!(exit, ExitReason::Halt, "{symbol}"); + rax + } + + pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason { + let (_, exit) = self.run(symbol, args); + assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest"); + exit + } + + pub fn error(&mut self) -> u64 { + self.call("GetLastError", &[]) + } + + pub fn u16_at(&self, address: u64) -> u16 { + self.memory.read_u16(address).unwrap() + } + + pub fn u32_at(&self, address: u64) -> u32 { + self.memory.read_u32(address).unwrap() + } + + pub fn u64_at(&self, address: u64) -> u64 { + self.memory.read_u64(address).unwrap() + } +} diff --git a/docs/interfaces.md b/docs/interfaces.md index 97797f4c..3542c7ad 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -306,6 +306,37 @@ one-time initialization that another thread has pending. them. `FlsFree` releases the slot, then calls its cleanup callback on the calling thread for each thread's nonnull value, in TEB order. +### System information, calendar time and sleeping + +The guest sees a simulated machine described by `GuestSystemProfile` on +`ServicesState`, and never the host's hardware. `HostCapabilities::detect` +reports the Mac's logical processors, physical memory and page size +separately, for diagnostics. + +- `GetSystemInfo` and `GetNativeSystemInfo` report an AMD64 processor + (`PROCESSOR_ARCHITECTURE_AMD64`, `PROCESSOR_AMD_X8664`), 4 KiB pages, + 64 KiB allocation granularity and the x64 user address range + `0x10000`–`0x7FFFFFFEFFFF`. The processor count comes from the profile and + defaults to one, because guest code runs on one thread at a time. The + processor level and revision are zero, because no CPU model is simulated. +- `GlobalMemoryStatusEx` requires `dwLength` to be 64. Guest physical memory is + the virtual-allocation and heap budgets together, 128 MiB. Available memory + and `dwMemoryLoad` reflect current guest allocations. There is no paging + file, and the virtual totals cover the x64 user range. +- `GetSystemTime`, `GetLocalTime` and `GetSystemTimePreciseAsFileTime` read + the injected clock. The guest time zone is UTC, so local time equals system + time. `FileTimeToSystemTime` and `SystemTimeToFileTime` convert using the + proleptic Gregorian calendar. They reject FILETIME values with the top bit + set and invalid dates (years outside 1601–30827), ignore the day of week on + input, and return `ERROR_INVALID_PARAMETER` without writing output. +- `QueryUnbiasedInterruptTime` reports 100 ns ticks since the service state + was created. +- `Sleep` and `SleepEx` suspend the calling thread through the clock, so the + mock clock advances instead of waiting. No APCs exist, so an alertable sleep + always returns zero. `INFINITE` and sleeps longer than 10 seconds stop the + guest with the runtime-limit fault, because a single guest thread could not + be woken. + ### Services that call guest code A service registered as a callback task can call guest functions before it From 17fa47f0589ddb813a702b6d26197705d000ede0 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:52:50 -0500 Subject: [PATCH 82/82] Add CRT onexit tables, atexit and _cexit Exit functions are guest code run through callback tasks in reverse registration order. Table storage lives on the default guest heap. Signed-off-by: Adeeb Rahman Co-authored-by: Cursor --- CHANGELOG.md | 2 +- crates/import-gen/src/classify.rs | 28 ++- crates/loader/src/services.rs | 5 +- crates/loader/src/services/crt_callbacks.rs | 195 +++++++++++++++++++- crates/loader/tests/runtime_synch.rs | 79 +++++++- docs/interfaces.md | 8 + 6 files changed, 295 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 210a9a9c..7fc06c18 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,7 +48,7 @@ remains unsupported. - Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently. -- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm` and `_initterm_e`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation. +- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation. - Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index abb5591f..5126df0c 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -381,9 +381,6 @@ impl SymbolDb { ("abort", "abort"), ("exit", "exit"), ("_exit", "_exit"), - ("atexit", "atexit"), - ("bsearch", "bsearch"), - ("qsort", "qsort"), ("rand", "rand"), ("srand", "srand"), ("atoi", "atoi"), @@ -425,24 +422,21 @@ impl SymbolDb { "CRT invalid param abort", ); self.win32_stub(m, "_purecall", false, "pure virtual call trap"); + // Initializer and exit functions are guest code. for module in [m, "ucrtbase.dll"] { - for symbol in ["_initterm", "_initterm_e"] { + for symbol in [ + "_initterm", + "_initterm_e", + "_initialize_onexit_table", + "_register_onexit_function", + "_execute_onexit_table", + "atexit", + "_crt_atexit", + "_cexit", + ] { self.ins(module, symbol, Classification::StandardService); } } - self.win32_stub( - m, - "_initialize_onexit_table", - false, - "CRT onexit table init — no-op", - ); - self.win32_stub( - m, - "_register_onexit_function", - false, - "CRT onexit register — no-op", - ); - self.win32_stub(m, "_crt_atexit", false, "CRT atexit variant — no-op"); self.win32_stub( m, "_register_thread_local_exe_atexit_callback", diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index cb51720f..e3a39c66 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -193,6 +193,8 @@ pub struct ServicesState { objects: Mutex, last_errors: Mutex>, synch: Mutex, + /// Functions registered with `atexit`, run in reverse order by `_cexit`. + atexit: Mutex>, winsock: Mutex, task_fixture: Mutex, platform_fixture: Mutex, @@ -215,6 +217,7 @@ impl ServicesState { objects: Mutex::new(ObjectState::default()), last_errors: Mutex::default(), synch: Mutex::default(), + atexit: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), platform_fixture: Mutex::default(), @@ -361,7 +364,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc Result<[u64; 3], ExitReason> { + let mut bytes = [0; ONEXIT_TABLE_SIZE]; + memory.read_bytes(table, &mut bytes).map_err(fault)?; + Ok(std::array::from_fn(|index| { + u64::from_le_bytes(bytes[8 * index..8 * index + 8].try_into().unwrap()) + })) +} + +fn write_onexit_table( + memory: &mut GuestMemory, + table: u64, + pointers: [u64; 3], +) -> Result<(), ExitReason> { + let mut bytes = [0; ONEXIT_TABLE_SIZE]; + for (chunk, pointer) in bytes.as_chunks_mut::<8>().0.iter_mut().zip(pointers) { + *chunk = pointer.to_le_bytes(); + } + memory.write_bytes(table, &bytes).map_err(fault) +} + +/// Append `function`, growing the table's storage on the default process heap. +/// Returns false when the storage cannot grow. +fn register_onexit( + memory: &mut GuestMemory, + table: u64, + function: u64, +) -> Result { + let [mut first, mut last, mut end] = read_onexit_table(memory, table)?; + if first == 0 { + let bytes = (ONEXIT_INITIAL_ENTRIES * 8) as usize; + let Ok(storage) = memory.map_heap_allocation(PROCESS_HEAP, bytes) else { + return Ok(false); + }; + (first, last, end) = (storage, storage, storage + bytes as u64); + } + if last < first || end < last || !(end - first).is_multiple_of(8) { + return unsupported(); + } + if last == end { + let capacity = (end - first) / 8; + if capacity >= MAX_ONEXIT_ENTRIES { + return Ok(false); + } + let bytes = (capacity * 2 * 8) as usize; + let Ok(storage) = memory.resize_heap_allocation(PROCESS_HEAP, first, bytes, false) else { + return Ok(false); + }; + (first, last, end) = (storage, storage + capacity * 8, storage + bytes as u64); + } + memory.write_u64(last, function).map_err(fault)?; + write_onexit_table(memory, table, [first, last + 8, end])?; + Ok(true) +} + +/// Runs registered functions in reverse order of registration. +struct ExitFunctions { + pending: Vec, +} + +impl ExitFunctions { + fn next(&mut self) -> CallbackStep { + match self.pending.pop() { + Some(entry) => CallbackStep::Call { + entry, + args: [0; 4], + }, + None => CallbackStep::Return(0), + } + } + + fn start(mut self) -> CallbackStart { + match self.next() { + CallbackStep::Call { entry, args } => CallbackStart::Call { + task: Box::new(self), + entry, + args, + }, + CallbackStep::Return(value) => CallbackStart::Return(value), + } + } +} + +impl CallbackTask for ExitFunctions { + fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result { + Ok(self.next()) + } +} + +fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc) { + registry.register(UCRT, "_initialize_onexit_table", |args, _, mem| { + let table = args.rcx; + if table == 0 { + return Ok(CRT_FAILURE); + } + // An initialized table keeps its registrations. + if read_onexit_table(mem, table)?[0] == 0 { + write_onexit_table(mem, table, [0; 3])?; + } + Ok(0) + }); + + registry.register(UCRT, "_register_onexit_function", |args, _, mem| { + if args.rcx == 0 { + return Ok(CRT_FAILURE); + } + Ok(if register_onexit(mem, args.rcx, args.rdx)? { + 0 + } else { + CRT_FAILURE + }) + }); + + registry.register_callback_task( + UCRT, + "_execute_onexit_table", + ServiceStatus::Partial, + |args, _, mem, _| { + let table = args.rcx; + if table == 0 { + return Ok(CallbackStart::Return(CRT_FAILURE)); + } + let [first, last, _] = read_onexit_table(mem, table)?; + if first == 0 { + return Ok(CallbackStart::Return(0)); + } + if last < first || !(last - first).is_multiple_of(8) { + return unsupported(); + } + let mut pending = Vec::with_capacity(((last - first) / 8) as usize); + for slot in (first..last).step_by(8) { + let entry = mem.read_u64(slot).map_err(fault)?; + if entry != 0 { + pending.push(entry); + } + } + // The table is reset before the functions run, so a function + // registered while they run starts a new table. + write_onexit_table(mem, table, [0; 3])?; + mem.release_heap_allocation(PROCESS_HEAP, first); + Ok(ExitFunctions { pending }.start()) + }, + ); + + for symbol in ["atexit", "_crt_atexit"] { + let s = Arc::clone(state); + registry.register(UCRT, symbol, move |args, _, _| { + let mut functions = s.atexit.lock().expect("guest atexit functions"); + if args.rcx == 0 || functions.len() as u64 >= MAX_ONEXIT_ENTRIES { + return Ok(CRT_FAILURE); + } + functions.push(args.rcx); + Ok(0) + }); + } + + let s = Arc::clone(state); + registry.register_callback_task(UCRT, "_cexit", ServiceStatus::Partial, move |_, _, _, _| { + let pending = std::mem::take(&mut *s.atexit.lock().expect("guest atexit functions")); + Ok(ExitFunctions { pending }.start()) + }); + + for symbol in [ + "_initialize_onexit_table", + "_register_onexit_function", + "atexit", + "_crt_atexit", + ] { + registry.set_status(UCRT, symbol, ServiceStatus::Partial); + } + for symbol in [ + "_initialize_onexit_table", + "_register_onexit_function", + "_execute_onexit_table", + "_crt_atexit", + "_cexit", + ] { + registry.alias(CRT_RUNTIME_API, UCRT, symbol); + } + registry.alias(CRT_RUNTIME_API, UCRT, "atexit"); +} + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + register_exit_tables(registry, state); registry.register_callback_task(UCRT, "qsort", ServiceStatus::Partial, |args, _, mem, _| { let compare = Comparator { entry: args.r9, diff --git a/crates/loader/tests/runtime_synch.rs b/crates/loader/tests/runtime_synch.rs index 12a1c3e6..f58432fe 100644 --- a/crates/loader/tests/runtime_synch.rs +++ b/crates/loader/tests/runtime_synch.rs @@ -79,6 +79,12 @@ const IMPORTS: &[(&str, &str)] = &[ (UCRT, "bsearch_s"), (CRT_RUNTIME, "_initterm"), (UCRT, "_initterm_e"), + (CRT_RUNTIME, "_initialize_onexit_table"), + (UCRT, "_register_onexit_function"), + (CRT_RUNTIME, "_execute_onexit_table"), + (UCRT, "atexit"), + (CRT_RUNTIME, "_crt_atexit"), + (CRT_RUNTIME, "_cexit"), ]; const UCRT: &str = "ucrtbase.dll"; @@ -108,9 +114,11 @@ enum Routine { InitOnceFail, /// `void cleanup(void *value)` adding the value to LOG. FlsAdd, + /// `void count(void)` incrementing COUNTER. + Count, } -const ROUTINES: [Routine; 10] = [ +const ROUTINES: [Routine; 11] = [ Routine::Compare, Routine::CompareCounting, Routine::Append(1), @@ -121,6 +129,7 @@ const ROUTINES: [Routine; 10] = [ Routine::InitOnceStore, Routine::InitOnceFail, Routine::FlsAdd, + Routine::Count, ]; impl Routine { @@ -168,6 +177,11 @@ impl Routine { code.extend_from_slice(&[0x48, 0x01, 0x08, 0xC3]); // add [rax], rcx; ret code } + Self::Count => { + let mut code = mov_rax(COUNTER); + code.extend_from_slice(&[0x48, 0xFF, 0x00, 0xC3]); // inc qword [rax]; ret + code + } } } } @@ -182,6 +196,7 @@ const CLOBBER_RBX: usize = 6; const INIT_ONCE_STORE: usize = 7; const INIT_ONCE_FAIL: usize = 8; const FLS_ADD: usize = 9; +const COUNT: usize = 10; const WAIT_TIMEOUT: u64 = 258; const ERROR_INVALID_HANDLE: u64 = 6; @@ -903,3 +918,65 @@ fn init_once_execute_once_runs_the_initializer_exactly_once() { assert_eq!(guest.error(), ERROR_INVALID_PARAMETER); assert_eq!(guest.u64_at(reserved), 0); } + +#[test] +fn onexit_tables_run_registered_functions_in_reverse_order() { + let mut guest = new_guest(); + let table = SCRATCH + 0x400; + let pointers = |guest: &Guest| [0, 8, 16].map(|offset| guest.u64_at(table + offset)); + let status = |value: u64| value as u32; + assert_eq!(guest.call("_initialize_onexit_table", &[table]), 0); + assert_eq!(pointers(&guest), [0; 3]); + assert_eq!( + status(guest.call("_initialize_onexit_table", &[0])), + u32::MAX + ); + assert_eq!( + status(guest.call("_register_onexit_function", &[0, routine(APPEND_1)])), + u32::MAX + ); + + for digit in [APPEND_1, APPEND_2, APPEND_3] { + assert_eq!( + guest.call("_register_onexit_function", &[table, routine(digit)]), + 0 + ); + } + let [first, last, end] = pointers(&guest); + assert_ne!(first, 0); + assert_eq!(last - first, 24); + assert!(end >= last); + // Reinitializing a table keeps its registrations. + assert_eq!(guest.call("_initialize_onexit_table", &[table]), 0); + assert_eq!(pointers(&guest), [first, last, end]); + + guest.memory.write_u64(LOG, 0).unwrap(); + assert_eq!(guest.call("_execute_onexit_table", &[table]), 0); + assert_eq!(guest.u64_at(LOG), 321); + assert_eq!(pointers(&guest), [0; 3]); + assert_eq!(guest.call("_execute_onexit_table", &[table]), 0); + assert_eq!(guest.u64_at(LOG), 321); + + // The table grows past its initial storage. + for _ in 0..100 { + assert_eq!( + guest.call("_register_onexit_function", &[table, routine(COUNT)]), + 0 + ); + } + let [first, last, _] = pointers(&guest); + assert_eq!(last - first, 800); + guest.memory.write_u64(COUNTER, 0).unwrap(); + assert_eq!(guest.call("_execute_onexit_table", &[table]), 0); + assert_eq!(guest.u64_at(COUNTER), 100); + + // atexit functions run in reverse order when the CRT is shut down. + assert_eq!(guest.call("atexit", &[routine(APPEND_1)]), 0); + assert_eq!(guest.call("_crt_atexit", &[routine(APPEND_2)]), 0); + assert_eq!(status(guest.call("atexit", &[0])), u32::MAX); + guest.memory.write_u64(LOG, 0).unwrap(); + assert_eq!(guest.call("_cexit", &[]), 0); + assert_eq!(guest.u64_at(LOG), 21); + assert_eq!(guest.call("_cexit", &[]), 0); + assert_eq!(guest.u64_at(LOG), 21); +} diff --git a/docs/interfaces.md b/docs/interfaces.md index 3542c7ad..417b08f7 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -363,6 +363,14 @@ The CRT uses this for: initializer table in order. `_initterm_e` stops at the first nonzero result and returns it. Tables hold at most 65,536 entries. +- `_initialize_onexit_table`, `_register_onexit_function` and + `_execute_onexit_table` manage `_onexit_table_t` tables. Their storage is + on the default guest heap, and they hold at most 65,536 entries. Execution + resets the table first, then calls the functions in reverse order of + registration. `atexit` and `_crt_atexit` record process exit functions, + which `_cexit` runs in reverse order. Process termination through `exit` is + not modeled. + Null comparators, null arrays with a nonzero count, and reversed or misaligned tables would reach the CRT invalid-parameter handler. That handler is not modeled, so these inputs stop the guest with the