From c4ce9a4e38d279214823949a94c1c2408dfd7eaa Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:53:16 -0500 Subject: [PATCH] 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 c814631..ee84a82 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 e44e2c9..09b9bb8 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 3eb15c7..835b5b9 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 7b86c54..b9a38c4 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 56c2614..57b443b 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 5c1db9b..f2e9cd0 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,