From e856f080d16325543cc1b4473930c6a0a842207e Mon Sep 17 00:00:00 2001 From: Arths17 Date: Tue, 24 Nov 2026 14:17:40 -0600 Subject: [PATCH] dbt: retranslate cached blocks when guest code changes (#84) Each cached block keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup. Signed-off-by: Arths17 --- CHANGELOG.md | 1 + crates/loader/src/dbt.rs | 158 ++++++++++++++++++++--- crates/loader/tests/cpu_known_answers.rs | 5 +- 3 files changed, 145 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2efe1e..37beee7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,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. ### Fixed +- The DBT no longer runs a stale translation after the guest rewrites its own code or runs against a different address space (#84). Each cached block now keeps the guest bytes it was translated from and is compared with the current executable bytes on every lookup; a mismatch, or bytes that are no longer readable, discards the block and translates it again, counted in the new `DbtMetrics::blocks_invalidated`. This makes the `cpu_known_answers` self-modifying-code case pass for the DBT, so it is no longer ignored as a known defect, and regression tests cover a rewritten block, a rewritten final byte, a budget-limited block and a second address space. The discarded native code stays in the JIT cache until cache reclamation exists (#99), and a store into a block's own later instructions during the same dispatch is not detected. Local verification only; not independently reviewed. - Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing. ### Added diff --git a/crates/loader/src/dbt.rs b/crates/loader/src/dbt.rs index 8a9fa93..657bc7d 100644 --- a/crates/loader/src/dbt.rs +++ b/crates/loader/src/dbt.rs @@ -29,6 +29,9 @@ pub struct DbtMetrics { pub blocks_compiled: usize, pub cache_hits: usize, pub cache_misses: usize, + /// Cached blocks discarded because the guest bytes they were translated + /// from changed or became unreadable. Each also counts as a cache miss. + pub blocks_invalidated: usize, pub native_bytes_emitted: usize, pub dbt_dispatches: usize, pub instructions_executed: usize, @@ -37,11 +40,31 @@ pub struct DbtMetrics { pub service_calls: usize, } +/// A translated block and the guest bytes it was translated from. +/// +/// A cached block is only valid while those bytes are still executable at the +/// same address. Guest stores into code (Intel SDM Vol. 3A 11.6) and a different +/// address space at the same address both change them. +struct CachedBlock { + code: *const u8, + start: u64, + source: Box<[u8]>, +} + +impl CachedBlock { + fn is_current(&self, memory: &GuestMemory) -> bool { + self.source.iter().enumerate().all(|(offset, &byte)| { + let address = self.start.wrapping_add(offset as u64); + matches!(memory.fetch_instruction_byte(address), Ok(current) if current == byte) + }) + } +} + /// Dynamic Binary Translator and native execution runtime. pub struct DbtEngine { jit: JitMemory, - block_cache: HashMap, - limited_block_cache: HashMap<(u64, usize), *const u8>, + block_cache: HashMap, + limited_block_cache: HashMap<(u64, usize), CachedBlock>, assembler: Arm64Assembler, /// Decoded instructions that emitted helper calls point into. decoded_blocks: Vec>, @@ -186,26 +209,34 @@ impl DbtEngine { block_limit: usize, ) -> Result<*const u8, ExitReason> { if block_limit == MAX_BLOCK_INSTRUCTIONS { - if let Some(&fn_ptr) = self.block_cache.get(&rip) { - self.metrics.cache_hits += 1; - return Ok(fn_ptr); + if let Some(cached) = self.block_cache.get(&rip) { + if cached.is_current(memory) { + self.metrics.cache_hits += 1; + return Ok(cached.code); + } + self.metrics.blocks_invalidated += 1; } self.metrics.cache_misses += 1; - let compiled_ptr = self.compile_block(rip, memory, block_limit)?; - self.block_cache.insert(rip, compiled_ptr); - return Ok(compiled_ptr); + let compiled = self.compile_block(rip, memory, block_limit)?; + let code = compiled.code; + self.block_cache.insert(rip, compiled); + return Ok(code); } // Keep budget-limited blocks separate so they cannot shorten a later run. let key = (rip, block_limit); - if let Some(&fn_ptr) = self.limited_block_cache.get(&key) { - self.metrics.cache_hits += 1; - return Ok(fn_ptr); + if let Some(cached) = self.limited_block_cache.get(&key) { + if cached.is_current(memory) { + self.metrics.cache_hits += 1; + return Ok(cached.code); + } + self.metrics.blocks_invalidated += 1; } self.metrics.cache_misses += 1; - let compiled_ptr = self.compile_block(rip, memory, block_limit)?; - self.limited_block_cache.insert(key, compiled_ptr); - Ok(compiled_ptr) + let compiled = self.compile_block(rip, memory, block_limit)?; + let code = compiled.code; + self.limited_block_cache.insert(key, compiled); + Ok(code) } fn compile_block( @@ -213,7 +244,7 @@ impl DbtEngine { start_rip: u64, memory: &GuestMemory, block_limit: usize, - ) -> Result<*const u8, ExitReason> { + ) -> Result { // Decode the whole block first: lowering needs to know whether a later // instruction observes the flags an earlier one produces. let mut decoded = Vec::with_capacity(block_limit); @@ -292,8 +323,17 @@ impl DbtEngine { .map_err(|_| ExitReason::JitCacheExhausted)?; self.metrics.blocks_compiled += 1; self.metrics.native_bytes_emitted += asm.instructions().len() * 4; + // Decoding just read every one of these bytes, so they are readable. + let source = (0..rip.wrapping_sub(start_rip)) + .map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset))) + .collect::, _>>() + .map_err(ExitReason::MemoryFault)?; self.decoded_blocks.push(insns); - Ok(emitted) + Ok(CachedBlock { + code: emitted, + start: start_rip, + source, + }) } } @@ -1452,6 +1492,92 @@ mod tests { ) } + /// `mov eax, imm32; hlt`, with the immediate at `ENTRY + 1`. + fn mov_eax(imm: u8) -> [u8; 6] { + [0xB8, imm, 0x00, 0x00, 0x00, 0xF4] + } + + fn writable_fixture(code: &[u8]) -> (DbtEngine, GuestMemory) { + let mut memory = GuestMemory::new(); + memory + .map_region_with_data( + ENTRY, + code.len(), + MemoryPermissions::READ_WRITE_EXECUTE, + code, + ) + .unwrap(); + (DbtEngine::new(64 * 1024).unwrap(), memory) + } + + fn rax_after_run(engine: &mut DbtEngine, memory: &mut GuestMemory, limit: usize) -> u64 { + let mut cpu = CpuState::new(ENTRY, 0); + let result = engine.run(&mut cpu, memory, limit); + assert_eq!(result.exit_reason, ExitReason::Halt); + cpu.get(Register::Rax) + } + + #[test] + fn unchanged_code_stays_cached() { + let (mut engine, mut memory) = writable_fixture(&mov_eax(1)); + assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1); + assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1); + assert_eq!(engine.metrics.blocks_compiled, 1); + assert_eq!(engine.metrics.cache_hits, 1); + assert_eq!(engine.metrics.blocks_invalidated, 0); + } + + #[test] + fn rewritten_code_is_translated_again() { + let (mut engine, mut memory) = writable_fixture(&mov_eax(1)); + assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1); + memory.write_bytes(ENTRY + 1, &[2]).unwrap(); + assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2); + assert_eq!(engine.metrics.blocks_compiled, 2); + assert_eq!(engine.metrics.blocks_invalidated, 1); + // The new translation is cached in turn. + assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2); + assert_eq!(engine.metrics.blocks_compiled, 2); + } + + #[test] + fn rewriting_the_last_byte_of_a_block_is_detected() { + let (mut engine, mut memory) = writable_fixture(&mov_eax(1)); + assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1); + // HLT becomes NOP, so the block now runs off the end of the mapping. + memory.write_bytes(ENTRY + 5, &[0x90]).unwrap(); + let mut cpu = CpuState::new(ENTRY, 0); + let result = engine.run(&mut cpu, &mut memory, 16); + assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_))); + assert_eq!(engine.metrics.blocks_invalidated, 1); + } + + #[test] + fn budget_limited_block_is_checked_against_current_bytes() { + let (mut engine, mut memory) = writable_fixture(&mov_eax(1)); + for expected in [1, 3] { + let mut cpu = CpuState::new(ENTRY, 0); + let result = engine.run(&mut cpu, &mut memory, 1); + assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded); + assert_eq!(cpu.get(Register::Rax), expected); + memory.write_bytes(ENTRY + 1, &[3]).unwrap(); + } + assert_eq!(engine.metrics.blocks_invalidated, 1); + } + + #[test] + fn another_address_space_does_not_reuse_a_block() { + let (mut engine, mut first) = writable_fixture(&mov_eax(1)); + let (_, mut second) = writable_fixture(&mov_eax(7)); + assert_eq!(rax_after_run(&mut engine, &mut first, 16), 1); + assert_eq!(rax_after_run(&mut engine, &mut second, 16), 7); + + let mut unmapped = GuestMemory::new(); + let mut cpu = CpuState::new(ENTRY, 0); + let result = engine.run(&mut cpu, &mut unmapped, 16); + assert!(matches!(result.exit_reason, ExitReason::MemoryFault(_))); + } + #[test] fn cached_block_obeys_remaining_budget() { let code = [ diff --git a/crates/loader/tests/cpu_known_answers.rs b/crates/loader/tests/cpu_known_answers.rs index 16a517e..90ca173 100644 --- a/crates/loader/tests/cpu_known_answers.rs +++ b/crates/loader/tests/cpu_known_answers.rs @@ -5404,10 +5404,9 @@ fn interpreter_executes_modified_code_after_a_jump() { assert_eq!(self_modified_result(Engine::Interpreter), wanted); } -/// Known defect: the DBT keeps running the block it translated before the store. +/// The DBT must not keep running the block it translated before the store (#84). #[test] -#[ignore = "known defect (#155): the DBT keeps translated blocks after the guest rewrites their code"] -fn defect_dbt_executes_modified_code_after_a_jump() { +fn dbt_executes_modified_code_after_a_jump() { for engine in [Engine::Dbt, Engine::DbtStepped] { let wanted = (1, 2, ExitReason::Halt); assert_eq!(self_modified_result(engine), wanted, "{engine:?}");