From 1eae910ce1e576fd53c000bfb49de99a11cc43f7 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 09:41:39 -0500 Subject: [PATCH] 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 cfd9c90..240c06f 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 24e4c8f..03590a2 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 f81b624..dafa7a9 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 f917413..4ff943e 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 72ad695..d3690d6 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 6de20fd..5d7769e 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 7f23a53..97797f4 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)