diff --git a/CHANGELOG.md b/CHANGELOG.md index aee46b3..c2995db 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 cfd4d88..d28dfc6 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 03590a2..abb5591 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 cdf8124..77eb168 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 4ff943e..cb51720 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 5d7769e..12a1c3e 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 0000000..7274338 --- /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 0000000..eaa3edd --- /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 97797f4..3542c7a 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