From 6e6473702159f58a649889738752b4332ec6b8c2 Mon Sep 17 00:00:00 2001 From: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:41:04 -0300 Subject: [PATCH 1/2] loader: keep a guest last error per modeled thread context (#202) ServicesState held one process-wide last-error value, so every modeled guest thread would have read and overwritten the same slot. The running context now owns the live slot and the others are parked by identifier, bounded at 1,024. No guest thread is scheduled: the embedder switches contexts between service calls. Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/src/services.rs | 70 ++++++++++++- crates/loader/tests/runtime_services.rs | 129 +++++++++++++++++++++++- 3 files changed, 194 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ada8094..cddb4e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added a separate guest last-error value for each modeled thread context (#202; awaiting independent review). `ServicesState::switch_thread_context` selects the running context and `retire_thread_context` drops one that has ended, with at most 1,024 parked contexts. `GetLastError`, `SetLastError` and failing services now act on the running context only, so one context no longer overwrites another's error. No guest thread is scheduled yet: contexts are switched by the embedder, and `GetCurrentThreadId` and `OpenThread` still describe the single synthetic thread. Covered through translated guest calls in `crates/loader/tests/runtime_services.rs`. - Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215). - Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`. - Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`. diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 5e3723b..69915c2 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -29,6 +29,9 @@ const THREAD_SET_RIGHTS: u32 = 0x0020 | 0x0400; const THREAD_SUPPORTED_RIGHTS: u32 = THREAD_QUERY_RIGHTS | THREAD_SET_RIGHTS | 0x0010_0000; const THREAD_PRIORITY_ERROR_RETURN: u64 = 0x7fff_ffff; const MAX_THREAD_HANDLES: usize = 1024; +const MAIN_THREAD_ID: u32 = 0x4104; // Synthetic main thread ID +/// Most modeled thread contexts that may hold a parked last-error slot. +pub const MAX_THREAD_CONTEXTS: usize = 1024; const PAGE_SIZE: u64 = 4096; const MEM_COMMIT_RESERVE: u32 = 0x3000; const MEM_RELEASE: u32 = 0x8000; @@ -103,6 +106,25 @@ impl ThreadState { } } +/// Last-error slots of the modeled guest thread contexts that are not running. +/// +/// `ServicesState::last_error` is the slot of the running context; this holds +/// every other one. No scheduler exists yet: a context is only an identifier +/// with its own slot, and the embedder says which one is running. +struct ThreadContexts { + current: u32, + parked: BTreeMap, +} + +/// Why a modeled thread context was refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ThreadContextError { + /// `MAX_THREAD_CONTEXTS` other contexts already hold a slot. + TooManyContexts, + /// The running context cannot be retired. + Running, +} + /// State container for runtime services. pub struct ServicesState { pub clock: Arc, @@ -110,7 +132,9 @@ pub struct ServicesState { priority_boost_disabled: AtomicBool, pub thread_id: u32, thread: Mutex, + /// Last error of the running thread context. pub last_error: AtomicU32, + contexts: Mutex, pub next_alloc_addr: AtomicU64, pub graphics: Arc>, } @@ -121,9 +145,13 @@ impl ServicesState { clock, priority_boost_disabled: AtomicBool::new(false), process_id: 0x4100, // Synthetic process ID - thread_id: 0x4104, // Synthetic main thread ID + thread_id: MAIN_THREAD_ID, thread: Mutex::new(ThreadState::default()), last_error: AtomicU32::new(0), + contexts: Mutex::new(ThreadContexts { + current: MAIN_THREAD_ID, + parked: BTreeMap::new(), + }), next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())), } @@ -133,6 +161,46 @@ impl ServicesState { self.priority_boost_disabled.load(Ordering::SeqCst) } + /// Identifier of the modeled thread context whose last error is live. + /// It starts as `thread_id`. + pub fn current_thread_context(&self) -> u32 { + self.contexts.lock().expect("guest thread contexts").current + } + + /// Make `id` the running thread context. The outgoing context keeps its + /// last error; a context seen for the first time starts at zero, and one + /// seen before gets back the value it left with. + /// + /// Call this between service calls only: a service that is still running + /// would report its failure to the context that replaced it. + pub fn switch_thread_context(&self, id: u32) -> Result<(), ThreadContextError> { + let mut contexts = self.contexts.lock().expect("guest thread contexts"); + if id == contexts.current { + return Ok(()); + } + let incoming = contexts.parked.remove(&id); + if incoming.is_none() && contexts.parked.len() >= MAX_THREAD_CONTEXTS { + return Err(ThreadContextError::TooManyContexts); + } + let outgoing = self + .last_error + .swap(incoming.unwrap_or(0), Ordering::SeqCst); + let previous = std::mem::replace(&mut contexts.current, id); + contexts.parked.insert(previous, outgoing); + Ok(()) + } + + /// Drop the slot of a context that is not running, as when its thread + /// ends. Returns whether it held one; the identifier starts at zero if it + /// is used again. + pub fn retire_thread_context(&self, id: u32) -> Result { + let mut contexts = self.contexts.lock().expect("guest thread contexts"); + if id == contexts.current { + return Err(ThreadContextError::Running); + } + Ok(contexts.parked.remove(&id).is_some()) + } + /// Record a guest error and return the documented failure value. fn fail(&self, error: u32, value: T) -> Result { self.last_error.store(error, Ordering::SeqCst); diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index f8417d4..f6132a7 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -19,7 +19,9 @@ use xenora_loader::pe::ParsedPe; use xenora_loader::probe::{ProbeConfig, ProbeReport, probe_pe_bytes}; use xenora_loader::runtime::{Call, Float32, Float64}; use xenora_loader::runtime_table::SERVICES; -use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; +use xenora_loader::services::{ + MAX_THREAD_CONTEXTS, MockClock, ServicesState, ThreadContextError, register_standard_services, +}; const BASE: u64 = 0x1_4000_0000; const CODE_RVA: u32 = 0x1000; @@ -120,17 +122,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image { } fn standard(clock: u64) -> (ImportRegistry, Arc) { - let clock = Arc::new(MockClock::new(clock)); - let mut registry = ImportRegistry::new(); - register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone()))); + let (registry, clock, _) = standard_with_state(clock); (registry, clock) } +fn standard_with_state(clock: u64) -> (ImportRegistry, Arc, Arc) { + let clock = Arc::new(MockClock::new(clock)); + let state = Arc::new(ServicesState::new(clock.clone())); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, state.clone()); + (registry, clock, state) +} + /// A guest whose image imports every generated service from its own library. struct Guest { engine: DbtEngine, memory: GuestMemory, clock: Arc, + state: Arc, /// Upper halves and XMM lanes of unrelated arguments hold this pattern. xmm: [u128; 4], } @@ -150,7 +159,7 @@ impl Guest { memory .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) .unwrap(); - let (mut registry, clock) = standard(0x01DA_0000_1234_5678); + let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678); let bound = registry .bind_imports(&pe, &image.bytes, BASE, &mut memory) .unwrap(); @@ -161,6 +170,7 @@ impl Guest { engine, memory, clock, + state, xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4], } } @@ -339,6 +349,115 @@ fn last_error_is_set_by_failures_and_by_the_guest() { assert_eq!(guest.last_error(), 6); } +/// GetLastError is documented as the calling thread's value, kept per thread +/// so that threads do not overwrite each other's (errhandlingapi.h). These are +/// modeled contexts switched by the test: no guest thread is scheduled. +const MAIN_THREAD: u32 = 0x4104; +const WORKER: u32 = 0x5000; +const OTHER_WORKER: u32 = 0x5004; + +#[test] +fn last_error_belongs_to_the_thread_context_that_set_it() { + let mut guest = Guest::new(); + assert_eq!(guest.state.current_thread_context(), MAIN_THREAD); + guest.call("CloseHandle", &[0x1234]); + assert_eq!(guest.last_error(), 6); // ERROR_INVALID_HANDLE + + guest.state.switch_thread_context(WORKER).unwrap(); + assert_eq!(guest.state.current_thread_context(), WORKER); + assert_eq!(guest.last_error(), 0, "a new context starts clean"); + assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS); + assert_eq!(guest.last_error(), 0, "success leaves it unchanged"); + assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0); + assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER + + guest.state.switch_thread_context(OTHER_WORKER).unwrap(); + assert_eq!(guest.last_error(), 0); + guest.call("SetLastError", &[0xFFFF_FFFF]); + assert_eq!(guest.last_error(), 0xFFFF_FFFF); + guest.call("SetLastError", &[0]); + assert_eq!(guest.last_error(), 0); + + guest.state.switch_thread_context(MAIN_THREAD).unwrap(); + assert_eq!(guest.last_error(), 6, "untouched by the other contexts"); + assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104); + assert_eq!(guest.last_error(), 6); + guest.state.switch_thread_context(WORKER).unwrap(); + assert_eq!(guest.last_error(), 87); + guest.state.switch_thread_context(OTHER_WORKER).unwrap(); + assert_eq!(guest.last_error(), 0, "an explicit zero is kept as set"); +} + +#[test] +fn switching_to_the_running_context_keeps_its_last_error() { + let mut guest = Guest::new(); + guest.call("SetLastError", &[5]); + guest.state.switch_thread_context(MAIN_THREAD).unwrap(); + assert_eq!(guest.last_error(), 5); + guest.state.switch_thread_context(WORKER).unwrap(); + guest.call("SetLastError", &[50]); + guest.state.switch_thread_context(WORKER).unwrap(); + assert_eq!(guest.last_error(), 50); + guest.state.switch_thread_context(MAIN_THREAD).unwrap(); + assert_eq!(guest.last_error(), 5); +} + +#[test] +fn a_retired_thread_context_starts_clean_when_its_id_is_reused() { + let mut guest = Guest::new(); + guest.state.switch_thread_context(WORKER).unwrap(); + guest.call("SetLastError", &[998]); + assert_eq!( + guest.state.retire_thread_context(WORKER), + Err(ThreadContextError::Running) + ); + assert_eq!( + guest.last_error(), + 998, + "a refused retirement changes nothing" + ); + + guest.state.switch_thread_context(MAIN_THREAD).unwrap(); + assert_eq!(guest.state.retire_thread_context(WORKER), Ok(true)); + assert_eq!(guest.state.retire_thread_context(WORKER), Ok(false)); + assert_eq!(guest.state.retire_thread_context(OTHER_WORKER), Ok(false)); + guest.state.switch_thread_context(WORKER).unwrap(); + assert_eq!(guest.last_error(), 0); +} + +#[test] +fn thread_contexts_are_bounded_and_a_refused_switch_changes_nothing() { + let mut guest = Guest::new(); + guest.call("SetLastError", &[1]); + // The running context holds no parked slot, so the limit is reached once + // MAX_THREAD_CONTEXTS others are parked. + let first = 0x1_0000; + for index in 0..MAX_THREAD_CONTEXTS as u32 { + guest.state.switch_thread_context(first + index).unwrap(); + guest.call("SetLastError", &[u64::from(index) + 2]); + } + let running = first + MAX_THREAD_CONTEXTS as u32 - 1; + assert_eq!( + guest.state.switch_thread_context(0x9_0000), + Err(ThreadContextError::TooManyContexts) + ); + assert_eq!(guest.state.current_thread_context(), running); + assert_eq!(guest.last_error(), MAX_THREAD_CONTEXTS as u64 + 1); + + // A parked context is still reachable, and retiring one frees a slot. + guest.state.switch_thread_context(MAIN_THREAD).unwrap(); + assert_eq!(guest.last_error(), 1); + assert_eq!( + guest.state.switch_thread_context(0x9_0000), + Err(ThreadContextError::TooManyContexts) + ); + assert_eq!(guest.state.retire_thread_context(first), Ok(true)); + guest.state.switch_thread_context(0x9_0000).unwrap(); + assert_eq!(guest.last_error(), 0); + guest.state.switch_thread_context(first + 1).unwrap(); + assert_eq!(guest.last_error(), 3); +} + #[test] fn virtual_memory_is_mapped_released_and_bounded() { let mut guest = Guest::new(); From 7623fde0e77ae4ed24c06ff9e95058bd3a2dee7a Mon Sep 17 00:00:00 2001 From: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:10:20 -0300 Subject: [PATCH 2/2] loader: retire a guest thread's last error and test the per-TEB contract (#202) main keeps the last error per TEB since #310. This adds the missing retirement step, so a reused TEB address starts at zero, and two conformance tests: a successful call keeps a nonzero error, and one thread's failure does not reach another. Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/src/services.rs | 15 +++++++ crates/loader/tests/runtime_services.rs | 58 +++++++++++++++++++++++-- 3 files changed, 70 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d35d637..a6b2d5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Added +- Added `ServicesState::retire_thread_last_error`, which drops the last-error value of a guest thread that has ended so a reused TEB address starts at zero, and two conformance tests for the per-TEB last error from #310: a successful call keeps a nonzero error, and one thread's failure does not reach another (#202; awaiting independent review). No guest thread is scheduled yet, and the number of TEBs holding a value is not bounded. - Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215. - Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215). - Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`. diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index e3a39c6..1f588ae 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -251,6 +251,21 @@ impl ServicesState { .unwrap_or(0) } + /// Forget the last-error value of a guest thread that has ended, so a + /// later thread given the same TEB address starts at zero. Returns + /// whether a nonzero value was dropped. + /// + /// Each service call names its own TEB and the values sit behind one + /// lock, so calls for different threads may run concurrently. Retire a + /// TEB only once no service call for that thread is still running. + pub fn retire_thread_last_error(&self, teb: u64) -> bool { + self.last_errors + .lock() + .expect("guest last-error state") + .remove(&teb) + .is_some() + } + fn set_last_error(&self, teb: u64, error: u32) { let mut errors = self.last_errors.lock().expect("guest last-error state"); if error == 0 { diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 8616549..5d5d2fa 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -120,17 +120,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image { } fn standard(clock: u64) -> (ImportRegistry, Arc) { - let clock = Arc::new(MockClock::new(clock)); - let mut registry = ImportRegistry::new(); - register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone()))); + let (registry, clock, _) = standard_with_state(clock); (registry, clock) } +fn standard_with_state(clock: u64) -> (ImportRegistry, Arc, Arc) { + let clock = Arc::new(MockClock::new(clock)); + let state = Arc::new(ServicesState::new(clock.clone())); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, state.clone()); + (registry, clock, state) +} + /// A guest whose image imports every generated service from its own library. struct Guest { engine: DbtEngine, memory: GuestMemory, clock: Arc, + state: Arc, teb: u64, /// Upper halves and XMM lanes of unrelated arguments hold this pattern. xmm: [u128; 4], @@ -151,7 +158,7 @@ impl Guest { memory .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) .unwrap(); - let (mut registry, clock) = standard(0x01DA_0000_1234_5678); + let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678); let bound = registry .bind_imports(&pe, &image.bytes, BASE, &mut memory) .unwrap(); @@ -162,6 +169,7 @@ impl Guest { engine, memory, clock, + state, teb: 0, xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4], } @@ -554,6 +562,48 @@ fn last_error_isolated_across_guest_thread_switches() { assert_eq!(guest.last_error(), 6); } +/// The last-error code is documented as kept per thread, and most functions +/// set it only when they fail (errhandlingapi.h GetLastError). +#[test] +fn a_successful_call_keeps_another_threads_error_and_its_own() { + let mut guest = Guest::new(); + guest.teb = 0x10000; + assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0); + assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER + guest.teb = 0x20000; + guest.call("SetLastError", &[0xFFFF_FFFF]); + assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS); + assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104); + assert_eq!( + guest.last_error(), + 0xFFFF_FFFF, + "success keeps a nonzero error" + ); + guest.teb = 0x10000; + assert_eq!(guest.last_error(), 87); +} + +#[test] +fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() { + let mut guest = Guest::new(); + guest.teb = 0x10000; + guest.call("SetLastError", &[998]); + guest.teb = 0x20000; + guest.call("CloseHandle", &[0x1234]); + + assert!(guest.state.retire_thread_last_error(0x10000)); + assert!(!guest.state.retire_thread_last_error(0x10000)); + assert!( + !guest.state.retire_thread_last_error(0x30000), + "a thread that never failed holds no value" + ); + assert_eq!(guest.last_error(), 6, "the other thread is untouched"); + guest.teb = 0x10000; + assert_eq!(guest.last_error(), 0); + guest.call("SetLastError", &[5]); + assert_eq!(guest.last_error(), 5); +} + #[test] fn last_error_is_set_by_failures_and_by_the_guest() { let mut guest = Guest::new();