Compare commits

...
Author SHA1 Message Date
atharvranjan e50268d872 Add isolated Remill AOT evaluation and adapter design
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-25 02:54:32 -06:00
atharvranjan b2654e93a4 Merge pull request #292 from MacosPorters/fix/migration-benchmark-checks
Run benchmark report tests in CI and record migration integration
2026-11-24 22:52:27 -06:00
atharvranjan 146d2dd467 Correct Win64 call-entry alignment wording
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:46:05 -06:00
atharvranjan a0d9b85dbf Run benchmark report tests in workspace CI and record migration review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:42:19 -06:00
atharvranjan 5366b93986 Merge pull request #269 from MacosPorters/archive/pull/371/head
Validate DBT caches with executable generations and source revalidation
2026-11-24 22:31:00 -06:00
atharvranjan 50c392111d Merge pull request #266 from MacosPorters/archive/pull/352/head
bench: measure Metal startup in fresh processes and repeated runs (#178)
2026-11-24 22:26:04 -06:00
atharvranjan f43a07ce31 Synchronize cache generation fix with the integrated hosted C runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:25:18 -06:00
atharvranjan 10fd1cd4be Merge pull request #265 from MacosPorters/archive/pull/346/head
metal: budgeted staged RGBA8 texture upload into Private storage (#144)
2026-11-24 22:24:24 -06:00
atharvranjan 95aa10c60f Merge pull request #278 from MacosPorters/archive/pull/394/head
Pack block-compressed texture mip chains by subresource
2026-11-24 22:24:17 -06:00
atharvranjan d26af53cef Merge pull request #283 from MacosPorters/archive/pull/420/head
loader: add the Gate A2 hosted C program and its test (#419)
2026-11-24 22:15:23 -06:00
atharvranjan b6ebaaad5e Merge pull request #282 from MacosPorters/archive/pull/418/head
loader: add files for a hosted C program: fopen, fclose, fgets and perror (#402)
2026-11-24 22:11:50 -06:00
atharvranjan 44ac976291 Retain cache-hit assertions with generation-triggered source revalidation
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:10:24 -06:00
atharvranjan 0bd8e19aac Merge pull request #281 from MacosPorters/archive/pull/401/head
loader: add standard output and printf formatting for a hosted C program (#400)
2026-11-24 22:08:23 -06:00
atharvranjan e93509ef5b Merge pull request #280 from MacosPorters/archive/pull/399/head
loader: add exit, _exit and abort for a hosted C program (#395)
2026-11-24 22:04:34 -06:00
atharvranjan 8344e299c9 Merge pull request #277 from MacosPorters/archive/pull/393/head
loader: add program arguments for a hosted C program (#392)
2026-11-24 22:04:27 -06:00
atharvranjan 433dc43695 Merge pull request #273 from MacosPorters/archive/pull/385/head
loader: add nine C runtime startup services a hosted C program imports (#382)
2026-11-24 22:04:19 -06:00
atharvranjan a0f2d833aa Merge pull request #276 from MacosPorters/archive/pull/390/head
loader: add VirtualProtect, VirtualQuery and __C_specific_handler as stubs (#388)
2026-11-24 22:04:10 -06:00
atharvranjan 61afca42c9 Merge pull request #279 from MacosPorters/archive/pull/397/head
loader: run LOOP, LOOPE, LOOPNE and JRCXZ (#396)
2026-11-24 22:04:02 -06:00
atharvranjan be19e4e28f Merge pull request #275 from MacosPorters/archive/pull/389/head
loader: run LAHF and SAHF and report them in CPUID (#387)
2026-11-24 22:03:56 -06:00
atharvranjan 33ccf7fd55 Merge pull request #271 from MacosPorters/archive/pull/381/head
loader: add FNINIT and the x87 control, status and tag words (#378)
2026-11-24 22:03:49 -06:00
atharvranjan bb62353cfe Merge pull request #274 from MacosPorters/archive/pull/386/head
loader: raise #GP for instructions longer than 15 bytes (#384)
2026-11-24 22:03:42 -06:00
atharvranjan 1f2e7d3bb6 Merge pull request #272 from MacosPorters/archive/pull/383/head
bench: compare two dbt_bench JSON results (#114)
2026-11-24 22:03:34 -06:00
atharvranjan b5b646a58d Warm differential-test caches within the same guest address space
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 22:02:34 -06:00
atharvranjan 4314071ac7 Validate DBT cache identity with executable generations instead of byte scans
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:59:14 -06:00
atharvranjan 4e15e5f43b Synchronize PR #275 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:16 -06:00
atharvranjan cf4010ba94 Synchronize PR #271 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:14 -06:00
atharvranjan b9e6a9d365 Synchronize PR #274 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:12 -06:00
atharvranjan a1a1020ebd Synchronize PR #272 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:10 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
Ranveer Soni 4cc703d566 Merge branch 'main' into fix/84-dbt-stale-code-cache 2026-11-25 07:02:16 +05:30
atharvranjan e856f080d1 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 <Atharvranjan8@gmail.com>
2026-11-24 14:17:40 -06:00
20 changed files with 2409 additions and 26 deletions

No files matched your search

+6 -1
View File
@@ -33,6 +33,8 @@ 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
- Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command.
- DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported.
- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version.
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
@@ -40,6 +42,9 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Documented proposed Remill numerical and per-instruction execution adapters, including explicit ABI/state ownership, exception commits, exact budget exits and regression requirements. This is a design only; the recorded numerical and budget failures remain open.
- Added an isolated Remill native ARM64 experiment with original x86-64 fixtures, a bridge to checked guest memory, and comparisons against the existing interpreter and DBT. The local Apple M4 run passed 32 case/path checks; a wrong-answer control fails explicitly. The extended evaluation retains eight failing floating-point cases and a missing guest-budget exit, alongside narrow vector/control results and exploratory toy-workload timings. Production CPU behavior is unchanged; adoption and independent acceptance remain open.
- Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation.
- Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated
submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline,
submission, GPU, readback), with median, p90, p99 and maximum. Every sample must produce the fixture's
@@ -66,7 +71,7 @@ remains unsupported.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify stack alignment before CALL and at callee entry (`RSP % 16 == 8`), accessibility of the caller-allocated 32-byte shadow space, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- LAHF and SAHF run in both engines, and guest CPUID reports them in leaf `8000_0001h`, ECX bit 0 (#387; Intel SDM Vol. 2A LAHF, Vol. 2B SAHF). The DBT runs them through the shared semantics. The four known answers from #155 that both engines refused are now verified, with twelve more cases, and the independent reference in `tests/x86_integer.rs` covers both instructions.
- LOOP, LOOPE, LOOPNE and JRCXZ run in both engines (#396; Intel SDM Vol. 2A, LOOP/LOOPcc and Jcc). The count is RCX; the address-size prefix stays rejected, so JECXZ and the ECX-counted forms are still refused. The DBT runs them through the shared semantics and ends its block at each. The three known answers from #155 that both engines refused are now verified, with eleven more cases, and `tests/cpu_loop.rs` checks a loop that spans translated blocks against a step-by-step model for every count, ZF match point and step budget.
+4 -2
View File
@@ -14,8 +14,9 @@
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! Report, comparison and percentile tests run in ordinary workspace tests
//! through `tests/dbt_benchmark_report.rs`. The benchmark target itself disables
//! Cargo's test harness. To run its tests directly, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
//! and run the executable named by the benchmark's compiler-artifact message.
@@ -982,6 +983,7 @@ mod tests {
blocks_compiled: 626,
cache_hits: 0,
cache_misses: 626,
blocks_invalidated: 0,
native_bytes_emitted: 245_168,
dbt_dispatches: 626,
instructions_executed: 10_002,
+278 -17
View File
@@ -15,7 +15,7 @@ use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment, decode};
use crate::x86_exec;
use crate::x86_table::{FORMS, Op};
use std::collections::HashMap;
use std::{collections::HashMap, sync::Arc};
const MAX_BLOCK_INSTRUCTIONS: usize = 16;
@@ -29,6 +29,9 @@ pub struct DbtMetrics {
pub blocks_compiled: usize,
pub cache_hits: usize,
pub cache_misses: usize,
/// Cached blocks discarded because their guest bytes or executable mappings
/// changed. 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,42 @@ pub struct DbtMetrics {
pub service_calls: usize,
}
/// A translated block and its executable-memory generation.
///
/// Guest stores into executable memory (Intel SDM Vol. 3A 11.6), executable
/// mapping changes and another address space invalidate the retained token.
/// An unchanged token takes a constant-time check. After a generation or address
/// space change, bytes and execute permissions are revalidated once before an
/// identical translation may be reused in that generation.
/// Validation occurs at dispatch boundaries: a store into the currently running
/// block's later instructions still needs a separate dispatch-boundary design.
struct CachedBlock {
code: *const u8,
generation: Arc<()>,
start: u64,
source: Box<[u8]>,
}
impl CachedBlock {
fn is_current(&mut self, memory: &GuestMemory) -> bool {
if memory.code_is_current(&self.generation) {
return true;
}
if !self.source.iter().enumerate().all(|(offset, &byte)| {
matches!(memory.fetch_instruction_byte(self.start.wrapping_add(offset as u64)), Ok(current) if current == byte)
}) {
return false;
}
self.generation = memory.code_generation();
true
}
}
/// Dynamic Binary Translator and native execution runtime.
pub struct DbtEngine {
jit: JitMemory,
block_cache: HashMap<u64, *const u8>,
limited_block_cache: HashMap<(u64, usize), *const u8>,
block_cache: HashMap<u64, CachedBlock>,
limited_block_cache: HashMap<(u64, usize), CachedBlock>,
assembler: Arm64Assembler,
/// Decoded instructions that emitted helper calls point into.
decoded_blocks: Vec<Box<[Insn]>>,
@@ -245,26 +279,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_mut(&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_mut(&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(
@@ -272,7 +314,7 @@ impl DbtEngine {
start_rip: u64,
memory: &GuestMemory,
block_limit: usize,
) -> Result<*const u8, ExitReason> {
) -> Result<CachedBlock, ExitReason> {
// 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);
@@ -351,8 +393,17 @@ impl DbtEngine {
.map_err(|_| ExitReason::JitCacheExhausted)?;
self.metrics.blocks_compiled += 1;
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
let source = (0..rip.wrapping_sub(start_rip))
.map(|offset| memory.fetch_instruction_byte(start_rip.wrapping_add(offset)))
.collect::<Result<Box<[u8]>, _>>()
.map_err(ExitReason::MemoryFault)?;
self.decoded_blocks.push(insns);
Ok(emitted)
Ok(CachedBlock {
code: emitted,
generation: memory.code_generation(),
start: start_rip,
source,
})
}
}
@@ -1569,6 +1620,216 @@ 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 data_writes_and_allocations_do_not_invalidate_executable_code() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
memory
.map_region(ENTRY + 0x1000, 8, MemoryPermissions::READ_WRITE)
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
for value in 0..64 {
memory.write_u64(ENTRY + 0x1000, value).unwrap();
let allocation = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE)
.unwrap();
assert!(memory.release_virtual_allocation(allocation));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
}
assert_eq!(engine.metrics.blocks_compiled, 1);
assert_eq!(engine.metrics.cache_hits, 64);
assert_eq!(engine.metrics.blocks_invalidated, 0);
}
#[test]
fn cloned_address_spaces_diverge_when_executable_code_changes() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
let mut cloned = memory.clone();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
memory.write_u8(ENTRY + 1, 7).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut cloned, 16), 1);
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 7);
// A deep clone shares the proven identical executable snapshot. The
// write in the original space must still force retranslation there.
assert_eq!(engine.metrics.blocks_compiled, 2);
assert_eq!(engine.metrics.cache_hits, 2);
}
#[test]
fn executable_bypass_writes_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
ENTRY,
8,
MemoryPermissions::READ_EXECUTE,
&[0xB8, 1, 0, 0, 0, 0xF4, 0, 0],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert!(memory.write_u32(ENTRY + 1, 9).is_err());
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
assert_eq!(engine.metrics.blocks_invalidated, 0);
memory
.write_u64_bypass(ENTRY, u64::from_le_bytes([0xB8, 2, 0, 0, 0, 0xF4, 0, 0]))
.unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 2);
memory.write_u32_bypass(ENTRY + 1, 3).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 3);
assert_eq!(engine.metrics.blocks_invalidated, 2);
}
#[test]
fn executable_writes_crossing_regions_invalidate_cached_translations() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, 2, MemoryPermissions::READ_WRITE_EXECUTE, &[0xB8, 1])
.unwrap();
memory
.map_region_with_data(
ENTRY + 2,
4,
MemoryPermissions::READ_WRITE_EXECUTE,
&[0, 0, 0, 0xF4],
)
.unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 1);
memory.write_u32(ENTRY + 1, 9).unwrap();
assert_eq!(rax_after_run(&mut engine, &mut memory, 16), 9);
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn remapped_non_executable_memory_cannot_reuse_a_translation() {
let mut memory = GuestMemory::new();
let base = memory
.map_virtual_allocation(0, 4096, MemoryPermissions::READ_WRITE_EXECUTE)
.unwrap();
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut cpu = CpuState::new(base, 0);
assert_eq!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::Halt
);
assert!(memory.release_virtual_allocation(base));
assert_eq!(
memory.map_virtual_allocation(base, 4096, MemoryPermissions::READ_WRITE),
Ok(base)
);
memory.write_bytes(base, &mov_eax(1)).unwrap();
let mut cpu = CpuState::new(base, 0);
assert!(matches!(
engine.run(&mut cpu, &mut memory, 16).exit_reason,
ExitReason::MemoryFault(_)
));
assert_eq!(engine.metrics.blocks_invalidated, 1);
}
#[test]
fn repeated_code_rewrites_report_bounded_jit_cache_exhaustion() {
let (mut engine, mut memory) = writable_fixture(&mov_eax(1));
for value in 0..16_384u32 {
memory.write_u32(ENTRY + 1, value).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = engine.run(&mut cpu, &mut memory, 16);
if result.exit_reason == ExitReason::JitCacheExhausted {
return;
}
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(cpu.get(Register::Rax), u64::from(value));
}
panic!("rewritten blocks unexpectedly avoided the bounded JIT capacity");
}
#[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 = [
+57 -3
View File
@@ -5,7 +5,7 @@
//! Provides isolated, page-aligned guest virtual memory with permission checking
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
use std::{fmt, ops::Range};
use std::{fmt, ops::Range, sync::Arc};
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
@@ -119,8 +119,13 @@ impl MappedRegion {
}
/// Guest virtual memory address space.
#[derive(Default, Clone)]
#[derive(Default)]
pub struct GuestMemory {
// A retained token identifies a validated executable snapshot. Independent
// address spaces get distinct tokens. A deep clone may share its identical
// snapshot; an executable mutation detaches only the changed address space.
// Cached translations retain tokens, preventing allocator-address reuse.
executable_generation: Arc<()>,
regions: Vec<MappedRegion>,
private_heaps: std::collections::BTreeSet<u64>,
private_heap_serial: u64,
@@ -130,7 +135,32 @@ pub struct GuestMemory {
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
}
impl Clone for GuestMemory {
fn clone(&self) -> Self {
Self {
executable_generation: Arc::clone(&self.executable_generation),
regions: self.regions.clone(),
private_heaps: self.private_heaps.clone(),
private_heap_serial: self.private_heap_serial,
crt_errno: self.crt_errno.clone(),
callback_frames: self.callback_frames.clone(),
}
}
}
impl GuestMemory {
pub(crate) fn code_generation(&self) -> Arc<()> {
Arc::clone(&self.executable_generation)
}
pub(crate) fn code_is_current(&self, generation: &Arc<()>) -> bool {
Arc::ptr_eq(&self.executable_generation, generation)
}
fn invalidate_executable_code(&mut self) {
self.executable_generation = Arc::new(());
}
/// Create a new empty guest address space.
pub fn new() -> Self {
Self::default()
@@ -197,6 +227,9 @@ impl GuestMemory {
allocation,
});
self.regions.sort_by_key(|r| r.base);
if permissions.execute && size != 0 {
self.invalidate_executable_code();
}
Ok(())
}
@@ -256,8 +289,14 @@ impl GuestMemory {
if !self.private_heaps.remove(&heap) {
return false;
}
let executable = self.regions.iter().any(|region| {
region.allocation == AllocationKind::Heap(heap) && region.permissions.execute
});
self.regions
.retain(|region| region.allocation != AllocationKind::Heap(heap));
if executable {
self.invalidate_executable_code();
}
true
}
@@ -377,10 +416,14 @@ impl GuestMemory {
if size < previous {
region.data.shrink_to_fit();
}
let executable = region.permissions.execute;
if destination != base {
region.base = destination;
self.regions.sort_by_key(|region| region.base);
}
if executable && (size != previous || destination != base) {
self.invalidate_executable_code();
}
Ok(destination)
}
@@ -420,7 +463,10 @@ impl GuestMemory {
else {
return false;
};
self.regions.remove(index);
let removed = self.regions.remove(index);
if removed.permissions.execute && !removed.data.is_empty() {
self.invalidate_executable_code();
}
true
}
@@ -510,11 +556,16 @@ impl GuestMemory {
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
let mut executable = false;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
executable |= take != 0 && self.regions[index].permissions.execute;
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
if executable {
self.invalidate_executable_code();
}
Ok(())
}
@@ -524,6 +575,9 @@ impl GuestMemory {
&& self.regions[index].permissions.write
{
self.regions[index].data[range].copy_from_slice(src);
if !src.is_empty() && self.regions[index].permissions.execute {
self.invalidate_executable_code();
}
return Ok(());
}
self.write_checked(address, src, Some("write"))
+2 -3
View File
@@ -5723,10 +5723,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:?}");
@@ -0,0 +1,8 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Run the benchmark's report, comparison and percentile tests in normal CI.
//! Timing runs remain confined to the standalone benchmark entry point.
#[allow(dead_code)]
#[path = "../benches/dbt_bench.rs"]
mod benchmark;
+4
View File
@@ -36,6 +36,9 @@ Historical phase checkpoints retain their original evidence scope.
## Guest CPU and runtime experiments
- [Remill adapter design](../experiments/remill/adapter-design.md) — Proposed numerical and instruction-budget contracts, state/result ownership and planned regression gates; not implemented.
- [Isolated Remill evaluation](../experiments/remill/README.md) — Native ARM64 prototype, checked-memory comparison, floating-point/budget blockers, exploratory measurements and adoption requirements; local evidence only.
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
@@ -45,6 +48,7 @@ Historical phase checkpoints retain their original evidence scope.
## Testing, validation, and benchmarks
- [Migrated pull-request integration review](testing/migration-pr-review.md) — Merge decisions, integration fixes, native verification and excluded concurrent work.
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
+1
View File
@@ -1,5 +1,6 @@
# Testing and acceptance
- [Migrated pull-request integration review](migration-pr-review.md) — Merge decisions, fixes, native verification and remaining scope limits.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
+96
View File
@@ -0,0 +1,96 @@
# Migrated pull-request integration review
Reviewed on November 24, 2026 (America/Chicago). The initial inventory contained
23 open pull requests under `Arths17`, including the development-plan PR.
Twenty-two were merged after their updated heads passed the applicable GitHub
checks. Imported records retain their original author attribution and commits.
The maintainer authorized per-merge admin overrides for the review restriction.
The ARM64 build/test requirement, one-approval rule, code-owner review requirement
and enforcement for admins remain configured. Failed or pending checks were
resolved before merging. The conditional `verify` comment job is normally skipped;
that skip is not independent semantic verification.
## Results
All links below refer to the BetterXen repository.
| PR | Result | Integration work |
| --- | --- | --- |
| [#263](https://github.com/MacosPorters/betterxen/pull/263) | Pending | Pending: overlaps the contributor's live PR #290, excluded by the maintainer. |
| [#264](https://github.com/MacosPorters/betterxen/pull/264) | Merged; checks passed | Identification fixture runs in ordinary tests; benchmark-harness lint fixed. |
| [#265](https://github.com/MacosPorters/betterxen/pull/265) | Merged; checks passed | Bounded native texture staging; planner and Metal readback tests. |
| [#266](https://github.com/MacosPorters/betterxen/pull/266) | Merged; checks passed | Startup measurement harness; unit tests and correctness smoke run. |
| [#267](https://github.com/MacosPorters/betterxen/pull/267) | Merged; checks passed | Bounded flat draws and repeated-frame regressions. |
| [#268](https://github.com/MacosPorters/betterxen/pull/268) | Merged; checks passed | Windows x64 calling conventions; writable-home-slot regression and nonvolatile vector-register negative controls. |
| [#269](https://github.com/MacosPorters/betterxen/pull/269) | Merged; checks passed | Executable generations with source revalidation; original cache assertions preserved. |
| [#270](https://github.com/MacosPorters/betterxen/pull/270) | Merged; checks passed | ARM64 shift encoding and operand checks; draft marked ready. |
| [#271](https://github.com/MacosPorters/betterxen/pull/271) | Merged; checks passed | Floating-point unit initialization, combined decoder generation and preserved tests. |
| [#272](https://github.com/MacosPorters/betterxen/pull/272) | Merged; checks passed | Dynamic binary translation (DBT) report comparison and input validation. |
| [#273](https://github.com/MacosPorters/betterxen/pull/273) | Merged; checks passed | C startup service integration and registry regeneration. |
| [#274](https://github.com/MacosPorters/betterxen/pull/274) | Merged; checks passed | Instruction-length faults and precise retirement. |
| [#275](https://github.com/MacosPorters/betterxen/pull/275) | Merged; checks passed | Flag-transfer instructions; combined fixtures and supported-case expectations retained. |
| [#276](https://github.com/MacosPorters/betterxen/pull/276) | Merged; checks passed | Explicitly unsupported service stubs and combined registry. |
| [#277](https://github.com/MacosPorters/betterxen/pull/277) | Merged; checks passed | Guest arguments and environment with combined services. |
| [#278](https://github.com/MacosPorters/betterxen/pull/278) | Merged; checks passed | Packed texture footprints; CPU and native GPU checks. |
| [#279](https://github.com/MacosPorters/betterxen/pull/279) | Merged; checks passed | Loop instructions; regenerated tables and corrected description to 3,600 comparisons. |
| [#280](https://github.com/MacosPorters/betterxen/pull/280) | Merged; checks passed | Process termination and exit callbacks. |
| [#281](https://github.com/MacosPorters/betterxen/pull/281) | Merged; checks passed | Formatted output integrated with startup and arguments. |
| [#282](https://github.com/MacosPorters/betterxen/pull/282) | Merged; checks passed | File streams; combined registry and dependency readiness. |
| [#283](https://github.com/MacosPorters/betterxen/pull/283) | Merged; checks passed | Hosted C fixture; driver architecture checked before execution. |
| [#284](https://github.com/MacosPorters/betterxen/pull/284) | Merged; checks passed | Thread-local storage (TLS) template-copy integration and preserved changelog entries. |
| [#288](https://github.com/MacosPorters/betterxen/pull/288) | Merged; checks passed | Development phases, README and migration-check record. |
PR #263 remains open to avoid competing with the contributor's live PR #290.
PR #290 was excluded from branch edits, reviews and merge operations as requested.
Its filesystem security and integration acceptance are left to that workstream.
## Verification and evidence scope
The integrated runtime candidate was
`5366b9398668128fdbb0b0879840dfa072bfa352`. Its GitHub native Rust workflow passed,
including workspace formatting, strict Clippy, tests and the hosted C fixture.
Local native results below concern the reported Apple M4 host running macOS 27.0
(class A host observations); they establish no Xbox-hardware or commercial-game
execution result.
| Check | Observed result |
| --- | --- |
| `scripts/test-gpu.sh` | 124 passed, 0 failed; 2 manual timing tests ignored. Metal API and GPU validation enabled. |
| Packed block-compressed texture GPU target | 1 passed, 0 failed, 0 ignored, with both validation layers enabled. |
| `scripts/demo.sh` | All three original fixtures matched Metal, reference and known-answer outputs. |
| `scripts/audit/native.sh` | 110 executables/loadable dependencies checked with `file`, `lipo` and `otool`; ARM64 architecture and permitted linkage checks passed. |
| Status, claims and dependency audits | Passed. |
The cache fix also passed an isolated local workspace run at `44ac976`: 917
passed, 0 failed, 35 ignored, plus strict Clippy. Its three alternating CPU
benchmark pairs used native release executables and identical original inputs:
per-run warm medians were 87.334–88.333 microseconds with per-byte validation and
15.625–18.791 microseconds with generation validation. Machine idleness was not
controlled. These measurements do not close the formal performance gate; their
candidate scope and cold results are recorded in PR #269.
A supplemental benchmark test-harness command exposed a missing initialization
for the newly added cache-invalidation counter. The follow-up initializes that
fixture and runs the existing report, JSON, comparison and percentile tests via
an ordinary integration-test target, preserving their assertions. This lets
workspace CI detect future benchmark-test compilation failures. All 14 existing
tests passed through both the ordinary integration target and the documented
manual harness command; strict workspace Clippy passed as well.
Raw final native logs, cache benchmark JSON and the PR-state inventory are kept
under ignored `artifacts/pr-integration/` in the lead checkout. PR checks and merge
records remain linked from each GitHub record.
## Remaining acceptance
This is an integration and execution record. Independent semantic and security
acceptance remains separate from implementer-run checks and administrative merge
permission. No release gates were redefined or releases created. Commercial Xbox
game execution remains unsupported.
Active-block self-modifying code is tracked separately in
[issue #291](https://github.com/MacosPorters/betterxen/issues/291); native-code cache
reclamation remains [issue #95](https://github.com/MacosPorters/betterxen/issues/95).
The source fixture programs, desktop instruction evidence and native Mac results
retain their existing boundaries.
+140
View File
@@ -0,0 +1,140 @@
# Remill native ARM64 experiment
Issue [#324](https://github.com/MacosPorters/betterxen/issues/324). This is an
isolated evaluation, with no production CPU or workspace dependency changes.
It uses original fixture bytes and harness code. Remill and its dependencies
remain external under ignored `artifacts/`; their notices are retained there.
## Decision and local result
**Keep the existing translator. The extended Remill adapter fails tested
floating-point and instruction-budget requirements.** See the
[extended evaluation](evaluation-2.md) for the failing cases, vector/control
results and exploratory measurements.
Remill built natively and the small lifted integer workload executed correctly
on this host. This establishes a usable experiment, not a production backend.
Broader instruction semantics, representative performance and runtime
integration remain unestablished.
Commercial Xbox execution remains unsupported.
The experiment also passed Rust formatting, strict Clippy for the standalone
bridge and its targets, C++ compilation with `-Wall -Wextra -Werror`, Python
syntax checks, local documentation-link checks and `git diff --check`. Full
workspace/GPU suites, fuzzing, mutation campaigns and the production benchmark
suite were not run. The extended report records separate toy-workload timings.
The initial November 25, 2026 prototype on Apple M4/macOS 27.0 (26A428) completed:
| Check | Local result |
| --- | --- |
| Dependencies and Remill | Native ARM64 builds succeeded with LLVM 17.0.6; upstream build warnings remain in the logs. Upstream tests were disabled; the result below comes from the original experiment harness. |
| Original AMD64 fixtures | Five traces lifted to LLVM IR, then compiled to ARM64 Mach-O objects with LLVM. Guest x86 bytes were never executed as host code. |
| Arithmetic | Six ADD/store/return cases passed through Remill, BetterXen's interpreter and its ARM64 dynamic binary translator (DBT). All three matched hand-derived RAX, carry/parity/auxiliary-carry/zero/sign/overflow flags, stored data and stack movement. |
| Checked memory | Four cases passed through all three paths: unmapped read, unmapped write, read-only write and an eight-byte write crossing the end of a mapping. Each stopped at guest RIP `0x1000`, preserved the checked registers and flags, and left both data words and the read-only sentinel unchanged. |
| Unsupported control | Remill's UD2 and indirect jump traces stopped explicitly in the harness. This does not implement guest exception delivery or indirect dispatch. |
| Wrong-answer control | Changing the first expected sum makes the harness fail with exit 1, as required. |
| Aggregate | 32 case/path checks passed: `(6 arithmetic + 4 memory) × 3 engines + 2 Remill control rejections`. |
| Native audit | `file`, `lipo -archs` and `otool -L` receipts cover the native tools, linked non-system dylibs, dependency archives, generated objects and final executable. macOS shared-cache libraries are identified separately. |
Host execution evidence above is **class A: direct local observation on this
Apple M4**. It is not Xbox hardware evidence, independent R1/R2 acceptance,
an M1–M5 compatibility result or a performance result. No GPU tests were run;
this is a CPU experiment. The author of this harness does not certify it.
The default Rust 1.94.1 build was refused by BetterXen's Rust 1.100 requirement;
an exploratory `--ignore-rust-version` attempt also failed on `atomic_try_update`.
The successful run uses the separately installed native Rust 1.100.0, without
changing BetterXen's requirement or implementation. Both failures remain logged.
## What the prototype does
`evaluate.py` checks the pinned Remill source, audits native inputs, optionally
builds dependencies/Remill, lifts five explicit byte strings and lowers the
resulting IR to ARM64. Only entry symbol names and x86 code-generation attributes
are adjusted; instruction bodies are retained. The original IR and adjusted IR
are both kept for inspection. LLVM receives the native host target explicitly.
`prototype.cpp` supplies the checked 64-bit memory intrinsics, a validated return
sentinel and explicit rejection hooks. Its flag annotation functions return the
predicate already computed by the lifted semantics. Unimplemented intrinsic
symbols cause a link failure. No generic no-op fallback is supplied.
`bridge/` is a separate, non-publishable Rust crate. It calls the real
`xenora_loader::memory::GuestMemory` methods and runs the same bytes through
BetterXen's existing interpreter and DBT. It is not a second memory mock. Its C
ABI accepts trusted harness pointers only, and is not a public guest interface.
The C++ error escape happens after a Rust memory call has returned; it does not
unwind through a Rust frame. This single-threaded harness cannot be used as a
general runtime error adapter.
The arithmetic program is `add rax, rcx; mov [rbx], rax; ret`. The six input pairs
cover an ordinary sum, unsigned wraparound, positive signed overflow, two
negative operands overflowing to zero, an auxiliary carry and zero. Expected
values are literal, hand-derived constants in the harness, independent of the
three execution paths. The Intel instruction reference is the semantic source:
[Intel Software Developer's Manuals](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html),
Volume 2, ADD/MOV/RET/UD2. These expectations still require independent review.
## Reproduce
Use native ARM64 macOS, Rust 1.100.0, CMake, Ninja, Git, Python 3 and native
Homebrew LLVM 17. Keep all source/build products beneath an ignored artifact
directory. The dependency builds can download a substantial Ghidra source tree.
The driver bounds each build to 1,800 seconds and limits parallel builds to two
jobs. It does not install system packages or change shell configuration.
From this worktree's root:
```sh
TASK_ROOT="$PWD/artifacts/remill-evaluation"
mkdir -p "$TASK_ROOT"
git clone https://github.com/lifting-bits/remill.git "$TASK_ROOT/upstream"
git -C "$TASK_ROOT/upstream" checkout --detach 66c488c9911fd9b368e4d0c9647d74239f8bba8b
python3 experiments/remill/evaluate.py --root "$TASK_ROOT" --build
```
For an already built artifact directory, omit `--build`. The `--llvm` argument
can select another installation of LLVM 17. Commands, exit statuses, native
architecture/linkage checks, source hashes and the actual harness output go to
`receipt.json` and individual logs in that directory. A failed stage leaves a
failed receipt and raises an error; absent prerequisites never count as a pass.
Raw receipts and generated files remain in the ignored artifact directory
selected with `--root`. The full build-driver receipt is `receipt-build.json`;
`receipt.json` records the initial prototype and `receipt-extended.json` records
the failing extended evaluation. This review branch includes source, reproduction
instructions and scoped findings; it does not include upstream build trees,
executables, raw gate logs or machine-specific paths. Recorded results are local
evidence, not independent acceptance.
## Adapter design
[Proposed correctness adapters](adapter-design.md) specify exact numerical-helper
commit rules, per-instruction dispatch, a versioned result layout and regression
gates. This is a design deliverable; the adapters are not implemented and the
existing extended gate still fails.
## Requirements before adoption
1. **State and faults:** define conversions for all CPU state, precise memory
fault metadata, partial/restartable instructions, exceptions and budget exits.
This harness checks only a small integer state slice and four memory faults.
2. **Execution:** supply bounded block dispatch, indirect calls/returns, service
interception, cache invalidation, code lifetime and scheduler transitions.
Ahead-of-time compilation of these five traces establishes none of those.
3. **Instruction coverage:** independently test the actual SSE/AVX forms needed
by admitted workloads. Validate rounding, MXCSR, NaNs and x87 behavior against
BetterXen's documented contract; advertised lifting coverage is insufficient.
4. **Memory ordering:** derive atomic/barrier semantics and fault atomicity for
ARM64 explicitly. No atomics, concurrency or host TSO assumptions were tested.
5. **Measurements:** compare matched workloads, cold compilation, warm execution,
memory use and code size with the current DBT. The harness recreates engines
for correctness cases; its elapsed time is not a meaningful speed comparison.
6. **Review and licensing:** obtain independent R1/R2 review and a complete
file/dependency attribution audit for the precise integration. See
[the preliminary license record](licenses.md). No release artifact is cleared.
Primary upstream design references:
[Remill README](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/README.md),
[architecture and memory intrinsics](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/docs/DESIGN.md),
[runtime intrinsic declarations](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/Arch/Runtime/Intrinsics.h).
+297
View File
@@ -0,0 +1,297 @@
# Proposed Remill correctness adapters
**Design only. No adapter described here is implemented or independently
accepted.** The [extended evaluation](evaluation-2.md) still has eight numerical
mismatches and a missing guest-budget exit. Keep the current production CPU
path. This design is the next bounded experiment under issue #324; it does not
authorize changes to production admission, CPUID or the AVX work in #299.
The candidate remains BetterXen `b2654e93a42e74e29570183da1f31bb8cdc6f721`
and Remill `66c488c9911fd9b368e4d0c9647d74239f8bba8b`. All initial implementation
files belong under `experiments/remill/`; generated code and logs stay under
ignored `artifacts/`. Upstream code remains external with its notices intact.
## Architecture decision
Build a consumer of Remill's **single-instruction** lifting interface. Return
from each admitted instruction to a dispatcher that owns budgets, faults and
canonical guest state. Initially reuse BetterXen's exact integer-based numerical
implementation for legacy register-to-register `ADDSS`. Handle the small admitted
control-transfer subset explicitly in the adapter, and report that work in its
own counters. Do not pass arbitrary floating-point instructions to an unguarded
LLVM floating-point operation.
The existing `remill-lift-17` command optimizes whole traces before exporting
them. Its output is useful evidence but has already lost dependable instruction
boundaries. Do not recover a budget contract by counting optimized IR operations,
searching textual IR labels, charging only backward branches, or relying on the
external timeout. Each guest instruction can produce many IR operations, and
optimization can merge or remove them.
The pinned upstream interfaces actually inspected are:
- `Arch::DecodeInstruction` in `include/remill/Arch/Arch.h`.
- `InstructionLifterIntf::LiftIntoBlock` and `LiftStatus` in
`include/remill/BC/InstructionLifter.h`.
- `Instruction::bytes`, `pc`, `next_pc`, `branch_taken_pc`,
`branch_not_taken_pc` and `category` in `include/remill/Arch/Instruction.h`.
Upstream warns that decoding a larger byte stream can fuse idioms. Supply exactly
one independently bounded instruction and reject a disagreement in length,
operands or category. The actual consumer and its LLVM wrapper still need to be
written and tested; these interfaces do not supply the proposed dispatcher.
```mermaid
flowchart TD
A[Dispatcher: remaining budget] -->|zero| B[StepLimitExceeded: no fetch]
A -->|positive| C[Checked fetch and single-instruction admission]
C --> D[Execute into temporary state]
D --> E{Outcome}
E -->|ordinary fault| F[Discard temporary changes; preserve fault details]
E -->|unmasked SIMD exception| G[Commit permitted MXCSR flags only]
E -->|completed instruction| H[Commit state and permitted memory write]
H --> I[Increment retired count; decrement remaining budget]
I -->|continue| A
I -->|guest stop| J[Return guest stop and completed count]
```
## First admission profile
The first adapter is for trusted original fixtures, not a general executable
loader. Every admitted form is listed explicitly; other forms return an
unsupported result with their guest PC and bytes.
| Forms | Proposed execution route | Initial boundary |
| --- | --- | --- |
| 64-bit register ADD, INC and DEC | Remill single-instruction thunk | Explicit fixture registers; defined arithmetic flags only |
| Legacy `ADDSS xmm0, xmm1` | Exact numerical helper | Register sources only; preserve the upper 96 destination bits and all source bits |
| JNE with a direct relative target | Adapter reads committed ZF and chooses the checked decoded target | Count as an adapter control step; no native jump directly to another guest thunk |
| HLT | Adapter guest stop | Completes one instruction and advances RIP, matching the existing synthetic CPU policy |
| 64-bit MOV through RBX and RET | Checked adapter memory/transfer operations in a later increment | One eight-byte span; authenticated fixture return sentinel; no general services or arbitrary host calls |
Using the numerical helper or explicit control adapter is visible routing,
not additional Remill-native instruction coverage. Preserve separate attempted
and retired counters for Remill thunks, numerical helpers and adapter controls.
There is no generic interpreter fallback and no implicit no-op.
VEX/EVEX, packed floating point, x87 operations, atomics, REP/string operations,
guest services and concurrent guest execution remain outside this profile. The
earlier vector probes remain separate research fixtures; their passing results
do not admit them into this adapter or establish production AVX state support.
## Numerical helper and state commit
The existing public Rust numerical surface is `softfloat::arithmetic`, using
`Arithmetic::Add`, `F32`, `Control::from_mxcsr` and `Outcome { bits, flags }`.
The private `x86_float::Raised::commit` cannot be called from the experiment.
The adapter must implement and independently test its exception-commit contract;
making private production handlers public is outside this work's scope.
The **proposed** helper ABI accepts two raw binary32 bit patterns and a guest
MXCSR value, and returns result bits, newly raised exception bits, the resulting
MXCSR and a normal/exception status through trusted host-owned storage. These are
new adapter fields, not existing Remill APIs. The proposed `AddssResultV1` has
four consecutive `uint32_t` fields: `result_bits`, `new_flags`, `mxcsr_after` and
`outcome`, with size 16 and alignment 4. `outcome` is 0 for completion or 4 for
SIMD exception; `result_bits` is consumed only on completion. A trusted wrapper
checks an explicit output-buffer size before writing, and distinguishes an ABI
error from a guest exception. These names and layouts are design proposals, not
functions already supplied by Remill or BetterXen.
Do not expose a Rust enum or cast either CPU structure across the C boundary.
No host float argument, floating-point return, `fesetround`, host FPCR change or
host exception flag is involved.
For each admitted ADDSS:
1. Snapshot the destination, source and guest MXCSR. The current guest instruction
PC remains authoritative until the instruction completes.
2. Ask the exact helper to compute the low lane and newly raised flags. The
high 96 destination bits, every source bit and integer flags are unchanged.
3. Decode exception masks from MXCSR bits 7–12. Newly raised pre-computation
exceptions are considered before post-computation exceptions. An old sticky
flag by itself must not cause a new trap.
4. If an unmasked pre-computation exception exists, commit the applicable new
pre-computation flags to MXCSR and return `SimdException`. Otherwise OR the
newly raised flags into MXCSR, and return `SimdException` if one is unmasked.
Preserve existing sticky flags and all MXCSR control bits.
5. On an exception, leave the entire destination, source, integer flags, memory
and RIP unchanged. MXCSR's permitted exception flags are the sole change.
The faulting instruction does not increment the completed-instruction count.
6. Otherwise merge the computed low lane, advance RIP and retire one instruction.
This describes the intended compatibility contract for the first scalar form.
Packed-lane exception priority needs its own specification before packed forms
are admitted. Nonzero reserved bits in an externally seeded initial MXCSR are
an admission error, not a fabricated ADDSS exception. LDMXCSR is not admitted by
this initial helper profile.
Intercept the identified ADDSS **before** general semantic lifting/optimization.
Emit its helper call and checked status branches as an instruction operation.
Do not globally replace every LLVM `fadd`, infer x86 semantics from optimized
floating-point IR, or let a helper exception continue into a destination write.
Do not mark the helper pure or speculate it across an instruction boundary.
Expected outputs must remain independent. Reusing `softfloat` means agreement
between this route and the current CPU engines is a consistency check, not a
second numerical oracle. Keep the nine literal ADDSS cases and independently
derived fraction/manual cases as the acceptance expectations. Never generate
those expectations by calling this helper or reading its actual output.
## Budget, state and memory protocol
The **proposed** per-step result distinguishes completion, completion with guest
stop, unsupported form, ordinary fault and SIMD exception. It carries the current
PC, successor PC when applicable, and typed fault information. The proposed
`StepResultV1` layout is:
| Offset | Field | C type | Meaning |
| ---: | --- | --- | --- |
| 0 | abi_version | uint32_t | Exactly 1 |
| 4 | outcome | uint32_t | 0 complete, 1 completed guest stop, 2 ordinary fault, 3 unsupported, 4 SIMD exception, 5 host failure |
| 8 | instruction_pc | uint64_t | Guest PC admitted for this step |
| 16 | successor_pc | uint64_t | Valid only for outcomes 0 and 1 |
| 24 | detail | uint32_t | Outcome-specific tag; guest stop 1 is HLT; fault 1 is unmapped, 2 protection, 3 general protection |
| 28 | access | uint32_t | 0 none, 1 read, 2 write, 3 execute |
| 32 | fault_address | uint64_t | Valid only for a memory/fetch fault carrying an address; never a fabricated CR2 value for a general-protection fault |
| 40 | access_width | uint32_t | Requested byte width for the reported memory operation; otherwise zero |
| 44 | mxcsr_after | uint32_t | Guest MXCSR following the permitted commit rule |
Size is 48 bytes, alignment 8. Future implementation must assert every offset
and size independently in Rust and C++. All fields are initialized on every
return, but callers must branch on `outcome` and `detail` before consuming
conditional fields. A trusted entry takes an opaque adapter-context handle,
requested ABI version, output pointer and explicit output size; it rejects a wrong size/version without
writing beyond that buffer. Contexts are created and destroyed by their owner,
are not reentrant, and are never guest addresses. Temporary Remill state remains
C++-owned, canonical CPU/memory state remains Rust-owned, and conversions use
explicit fields. No whole-state structure is passed by value across the ABI.
Host failure is an experiment failure, not a guest trap or success. Unmapped,
permission, execute-fetch and canonical-address/general-protection failures stay
distinct; unsupported decode/lifting details retain the actual bytes in the host
diagnostic record. An execute-fetch fault uses `access = 3` and retains its
unmapped/protection detail. Unsupported details are 1 for an unadmitted form,
2 for decode disagreement and 3 for an unadmitted transfer. Host-failure details
are 1 for ABI mismatch, 2 for lifting/verification failure, 3 for state conversion
failure and 4 for an internal memory error. Unrecognized tags fail as host errors.
This is an experiment ABI proposal, not a stable production interface.
Budget behavior follows the existing interpreter's public `ExecutionResult`:
- Check remaining budget before fetch, decoding, compilation or operand access.
A zero budget returns `StepLimitExceeded`, count zero and unchanged state even
when the current PC is unmapped.
- Fetch only bytes required for the current instruction through execute-checked
guest memory. Do not read a speculative fifteen-byte span or decode the next
instruction just because it shares a trace. An earlier data fault must win
over an unsupported or inaccessible following instruction.
- Reserve a step without retiring it. Execute into temporary state; retire only
after its permitted effects commit. Decode failures, operand faults, unsupported
forms and unmasked SIMD exceptions do not retire an instruction. A completed
HLT does. Do not underflow remaining budget or wrap the retired counter.
- Every taken or untaken branch returns to dispatch. There is no direct thunk
recursion or native backedge bypassing the budget check. Returning to the same
PC still requires another budget admission.
- At exhaustion, RIP names the next instruction that would execute. A later call
with a fresh budget resumes from that exact state and never replays a completed
store or instruction. This is the exact-budget API, not the current scheduler's
separately documented block-boundary slicing behavior.
Canonical CPU state remains owned by the dispatcher. A temporary Remill state
requires explicit conversion of each admitted register, arithmetic flag, RIP,
XMM and MXCSR field; never `memcpy` a Rust `CpuState` into a Remill `State`.
Validate the pinned Remill structure sizes and offsets at build time. Modelled
state outside the initial profile must be initialized and preserved under an
explicit admission rule, not silently discarded. Live YMM/AVX state integration
waits for the contract in #299.
Memory faults need more than the current experiment's boolean read/write result.
Carry operation kind, guest address, width and the actual memory/protection fault
back to the dispatcher. GuestMemory's mapping checks do not replace architectural
canonical-address and alignment checks. Ordinary faults must preserve all guest
state, including flags; earlier completed instructions remain committed.
For the first eight-byte store form, validate the whole span and retain one
pending write until instruction commit. No other form with multiple writes is
admitted. End validation and commit on the same single-threaded memory owner;
do not allow a callback to remap the span between them. The initial RET subset
reads through checked memory and admits only the authenticated fixture return
sentinel. Other transfers are explicitly unsupported by this profile. Do not
infer a general x86 RET policy from that restriction: a future admitted guest
return retires before an instruction-fetch fault at its successor, whose execute
check belongs to the next dispatcher turn.
Do not unwind a C++ exception or longjmp across a Rust frame or assume LLVM
`nounwind` code can carry a foreign exception. The current harness escape is not
the new protocol. Checked operations return explicit status, and generated IR
branches to the fault exit **before** any consumer uses an invalid result. There
is no zero/dummy read value followed by continued guest execution. A lifting or
verification failure stops compilation; it is not a guest success.
Initially compile fixed fixture instructions ahead of time; no general cache is
admitted. Keep guest code read/execute-only and reject self-modification in this
profile. Any later reusable cache must respect executable-generation and address-
space identity checks, checked fetch on revalidation, and in-flight code lifetime.
That integration requires the production CPU owner's review.
## Regression and review gates
These are **planned tests**, not results of this design task.
| Gate | Required observation |
| --- | --- |
| Existing numerical failures | All nine ADDSS cases retain their original bit/MXCSR/exit expectations; all destination/source preservation checks remain |
| Sticky flag handling | An exact operation with pre-existing PE set completes without a new precision trap; unrelated MXCSR bits remain unchanged |
| Fault atomicity | Invalid memory or an unmasked SIMD exception preserves destination and current RIP; only explicitly permitted MXCSR flags may change |
| No speculative execution | A faulting MOV followed by UD2 or an inaccessible instruction reports the MOV fault first |
| Zero budget | No instruction fetch or state/memory change, including an unmapped initial PC |
| Exact boundary | `inc rax; inc rax; hlt`, initially RAX 5 at `0x1000`: budgets 0/1/2/3 yield RAX 5/6/7/7, RIP `1000/1003/1006/1007`, counts 0/1/2/3; only budget 3 yields Halt |
| Resume | Running that program with budgets 1, then 1, then 1 matches one budget-3 run, including flags, memory and terminal status |
| Fault after progress | An instruction fault after two completions reports count two and leaves earlier effects intact; retry never double-retires them |
| Loops | Counts 1/3/7 still match; count zero and larger finite counts return exact guest-budget exits without supervisor termination |
| Decode agreement | Current-instruction length/category disagreement and a fused idiom are refused explicitly; no change to production decoder coverage |
| Compiler preservation | Optimized and unoptimized adapter runs obey the same counts, side-effect order and fault PCs; IR/control-flow inspection finds no edge bypassing dispatch |
| Wrong-answer controls | Incorrect result, missing MXCSR update, missing budget check and premature store each cause their intended failure |
Run native ARM64 correctness and provenance checks on the named candidate before
comparing performance. Keep the old unadapted route as a separately labelled
baseline with its failures; do not overwrite its receipts or redefine its gates.
Retain the supervisor timeout as a containment check, reported separately from
guest budget behavior. R1 reviews provenance, claims and native execution; R2
independently derives semantic expectations and reviews fault/count behavior.
The implementer cannot promote its own work to independent acceptance.
## Implementation order and exit decision
1. Specify the versioned status/state ABI and implement exact single-instruction
dispatch for INC/DEC/JNE/HLT. Close zero-budget, boundary, resume and runaway
regressions without numerical or memory operations.
2. Add the original ADDSS bit-pattern helper and transactional register/MXCSR
commit. Close the unchanged nine-case numerical gate and sticky-flag controls.
3. Add the checked MOV/RET subset, typed memory faults and one-write commit.
Close fault precedence, mapping-boundary and preservation tests.
4. Review the admitted profile independently. Only then measure matched release
workloads on an idle native host with equivalent budget/fault guarantees,
separating helper, dispatch, compilation, memory and code-size costs.
Stay isolated if any required semantic or budget gate fails, or if the combined
adapter adds complexity without a demonstrated workload benefit. Production
adoption is a separate decision after reviewed correctness, attributable
dependencies and representative measurements. This design adds no new hardware,
execution, benchmark or compatibility claim.
## Sources
- [Extended local findings](evaluation-2.md), including the retained failure receipts.
- [Current CPU contract](../../docs/cpu/instruction-registry.md),
[CPU state/counting](../../crates/loader/src/cpu.rs),
[exact numerical implementation](../../crates/loader/src/softfloat.rs), and
[current numerical commit behavior](../../crates/loader/src/x86_float.rs).
- [Pinned Remill instruction lifter](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/BC/InstructionLifter.h),
[decoder interface and idiom warning](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/Arch/Arch.h),
[instruction metadata](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/include/remill/Arch/Instruction.h), and
[CLI optimization order](https://github.com/lifting-bits/remill/blob/66c488c9911fd9b368e4d0c9647d74239f8bba8b/bin/lift/Lift.cpp).
- [Intel SDM Volume 1](https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf),
sections 10.2.3 and 11.5; Volume 2 instruction entries for each admitted form.
Architectural expectations and project budget policy are separate contracts.
+106
View File
@@ -0,0 +1,106 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "betterxen-remill-experiment"
version = "0.0.0"
dependencies = [
"xenora-loader",
]
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "xenora-loader"
version = "0.1.0"
dependencies = [
"libc",
"sha2",
"xenora-texture",
]
[[package]]
name = "xenora-texture"
version = "0.1.0"
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "betterxen-remill-experiment"
version = "0.0.0"
edition = "2024"
license = "GPL-3.0-or-later"
publish = false
[workspace]
[lib]
crate-type = ["staticlib"]
[dependencies]
xenora-loader = { path = "../../../crates/loader" }
[profile.release]
lto = "fat"
codegen-units = 1
+331
View File
@@ -0,0 +1,331 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Trusted experiment-only C ABI; never accepts an untrusted host pointer.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
#[repr(C)]
pub struct ResultState {
rax: u64,
rsp: u64,
rip: u64,
flags: u64,
data: u64,
data_hi: u64,
read_only: u64,
exit: u64,
}
#[unsafe(no_mangle)]
pub extern "C" fn bx_memory_new() -> *mut GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region(0x2000, 16, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region_with_data(
0x3000,
16,
MemoryPermissions::READ_WRITE,
&0x4000u64.to_le_bytes(),
)
.unwrap();
memory
.map_region_with_data(0x6000, 16, MemoryPermissions::READ_ONLY, &[0xa5; 16])
.unwrap();
Box::into_raw(Box::new(memory))
}
/// # Safety
/// `memory` must be a live pointer returned by bx_memory_new, freed once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_memory_free(memory: *mut GuestMemory) {
unsafe {
drop(Box::from_raw(memory));
}
}
/// # Safety
/// Pointers must reference a live memory object and an eight-byte output cell.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_read(memory: *const GuestMemory, address: u64, value: *mut u64) -> u8 {
match unsafe { &*memory }.read_u64(address) {
Ok(result) => {
unsafe {
*value = result;
}
1
}
Err(_) => 0,
}
}
/// # Safety
/// `memory` must exclusively reference a live bx_memory_new allocation.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_write(memory: *mut GuestMemory, address: u64, value: u64) -> u8 {
u8::from(unsafe { &mut *memory }.write_u64(address, value).is_ok())
}
/// # Safety
/// The byte span and output pointer must be valid for this call. Engine is 0 or 1.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_run(
engine: u32,
code: *const u8,
len: usize,
a: u64,
b: u64,
address: u64,
output: *mut ResultState,
) -> u8 {
let code = unsafe { std::slice::from_raw_parts(code, len) };
let raw = bx_memory_new();
let memory = unsafe { &mut *raw };
memory
.map_region_with_data(0x1000, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region_with_data(0x4000, 1, MemoryPermissions::READ_EXECUTE, &[0xf4])
.unwrap();
let mut cpu = CpuState::new(0x1000, 0x3000);
cpu.set(Register::Rax, a);
cpu.set(Register::Rcx, b);
cpu.set(Register::Rbx, address);
let result = match engine {
0 => Interpreter::new(cpu, memory, 32).run(),
1 => match DbtEngine::new(1024 * 1024) {
Ok(mut dbt) => dbt.run(&mut cpu, memory, 32),
Err(_) => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
},
_ => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
};
let state = result.final_state;
let flags = state.flags;
let exit = match result.exit_reason {
ExitReason::Halt => 0,
ExitReason::MemoryFault(_) => 1,
ExitReason::StepLimitExceeded => 4,
_ => 2,
};
unsafe {
*output = ResultState {
rax: state.get(Register::Rax),
rsp: state.get(Register::Rsp),
rip: state.rip,
flags: u64::from(flags.cf)
| u64::from(flags.pf) << 2
| u64::from(flags.af) << 4
| u64::from(flags.zf) << 6
| u64::from(flags.sf) << 7
| u64::from(flags.of) << 11,
data: memory.read_u64(0x2000).unwrap(),
data_hi: memory.read_u64(0x2008).unwrap(),
read_only: memory.read_u64(0x6000).unwrap(),
exit,
};
bx_memory_free(raw);
}
1
}
#[repr(C)]
pub struct SimdResult {
xmm0: [u64; 2],
xmm1: [u64; 2],
mxcsr: u64,
exit: u64,
}
/// # Safety
/// All pointers refer to trusted harness storage with the indicated lengths.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_simd_run(
engine: u32,
code: *const u8,
len: usize,
inputs: *const u64,
mxcsr: u32,
output: *mut SimdResult,
) -> u8 {
let code = unsafe { std::slice::from_raw_parts(code, len) };
let inputs = unsafe { std::slice::from_raw_parts(inputs, 4) };
let raw = bx_memory_new();
let memory = unsafe { &mut *raw };
memory
.map_region_with_data(0x1000, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region_with_data(0x4000, 1, MemoryPermissions::READ_EXECUTE, &[0xf4])
.unwrap();
let mut cpu = CpuState::new(0x1000, 0x3000);
cpu.xmm[0] = u128::from(inputs[0]) | u128::from(inputs[1]) << 64;
cpu.xmm[1] = u128::from(inputs[2]) | u128::from(inputs[3]) << 64;
cpu.mxcsr.0 = mxcsr;
let result = match engine {
0 => Interpreter::new(cpu, memory, 32).run(),
1 => match DbtEngine::new(1024 * 1024) {
Ok(mut dbt) => dbt.run(&mut cpu, memory, 32),
Err(_) => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
},
_ => {
unsafe {
bx_memory_free(raw);
}
return 0;
}
};
let state = result.final_state;
unsafe {
*output = SimdResult {
xmm0: [state.xmm[0] as u64, (state.xmm[0] >> 64) as u64],
xmm1: [state.xmm[1] as u64, (state.xmm[1] >> 64) as u64],
mxcsr: u64::from(state.mxcsr.0),
exit: match result.exit_reason {
ExitReason::Halt => 0,
ExitReason::MemoryFault(_) => 1,
ExitReason::SimdException => 3,
ExitReason::IllegalInstruction(_) => 5,
_ => 2,
},
};
bx_memory_free(raw);
}
1
}
pub struct Bench {
memory: GuestMemory,
dbt: Option<DbtEngine>,
engine: u32,
}
#[repr(C)]
#[derive(Default)]
pub struct BenchResult {
ns: u64,
compiled: u64,
cache_hits: u64,
fallbacks: u64,
native_bytes: u64,
}
/// # Safety
/// The code span is valid trusted straight-line fixture code, ending with RET.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_bench_new(engine: u32, code: *const u8, len: usize) -> *mut Bench {
if engine > 2 {
return std::ptr::null_mut();
}
let mut memory = unsafe { *Box::from_raw(bx_memory_new()) };
let code = unsafe { std::slice::from_raw_parts(code, len) };
memory
.map_region_with_data(0x1000, len, MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region_with_data(0x4000, 1, MemoryPermissions::READ_EXECUTE, &[0xf4])
.unwrap();
let dbt = if engine == 1 {
match DbtEngine::new(1024 * 1024) {
Ok(dbt) => Some(dbt),
Err(_) => return std::ptr::null_mut(),
}
} else {
None
};
Box::into_raw(Box::new(Bench {
memory,
dbt,
engine,
}))
}
/// # Safety
/// Bench is a live exclusive allocation returned by bx_bench_new; output is valid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_bench_run(
bench: *mut Bench,
repetitions: u32,
output: *mut BenchResult,
) -> u8 {
let bench = unsafe { &mut *bench };
if repetitions == 0 || repetitions > 10_000 {
return 0;
}
let mut stats = BenchResult::default();
let before = bench
.dbt
.as_ref()
.map(|dbt| dbt.metrics)
.unwrap_or_default();
let start = std::time::Instant::now();
for _ in 0..repetitions {
bench.memory.write_u64(0x2000, 0).unwrap();
let mut cpu = CpuState::new(0x1000, 0x3000);
cpu.set(Register::Rax, 1);
cpu.set(Register::Rcx, 1);
cpu.set(Register::Rbx, 0x2000);
let result = if let Some(dbt) = &mut bench.dbt {
dbt.run(&mut cpu, &mut bench.memory, 1024)
} else if bench.engine == 0 {
Interpreter::new(cpu, &mut bench.memory, 1024).run()
} else {
let Ok(mut dbt) = DbtEngine::new(1024 * 1024) else {
return 0;
};
let result = dbt.run(&mut cpu, &mut bench.memory, 1024);
stats.compiled += dbt.metrics.blocks_compiled as u64;
stats.cache_hits += dbt.metrics.cache_hits as u64;
stats.fallbacks += dbt.metrics.interpreter_fallbacks as u64;
stats.native_bytes += dbt.metrics.native_bytes_emitted as u64;
result
};
let state = result.final_state;
if result.exit_reason != ExitReason::Halt
|| state.get(Register::Rax) != 257
|| state.get(Register::Rsp) != 0x3008
|| state.flags != Default::default()
|| bench.memory.read_u64(0x2000).unwrap() != 257
|| bench.memory.read_u64(0x2008).unwrap() != 0
|| bench.memory.read_u64(0x6000).unwrap() != 0xa5a5_a5a5_a5a5_a5a5
{
return 0;
}
}
stats.ns = start.elapsed().as_nanos() as u64;
if let Some(dbt) = &bench.dbt {
stats.compiled = (dbt.metrics.blocks_compiled - before.blocks_compiled) as u64;
stats.cache_hits = (dbt.metrics.cache_hits - before.cache_hits) as u64;
stats.fallbacks = (dbt.metrics.interpreter_fallbacks - before.interpreter_fallbacks) as u64;
stats.native_bytes =
(dbt.metrics.native_bytes_emitted - before.native_bytes_emitted) as u64;
}
unsafe {
*output = stats;
}
1
}
/// # Safety
/// Bench is a live allocation returned by bx_bench_new and is freed exactly once.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn bx_bench_free(bench: *mut Bench) {
unsafe {
drop(Box::from_raw(bench));
}
}
+295
View File
@@ -0,0 +1,295 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Build/run the trusted, isolated Remill experiment; write receipts under artifacts/."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import shutil
import signal
import statistics
import subprocess
import time
PIN = "66c488c9911fd9b368e4d0c9647d74239f8bba8b"
HERE = Path(__file__).resolve().parent
FIXTURES = {
"add": "4801c8488903c3", # add rax,rcx; mov [rbx],rax; ret
"load": "488b03c3", # mov rax,[rbx]; ret
"store": "488903c3", # mov [rbx],rax; ret
"ud2": "0f0b", # deliberately invalid guest instruction
"jump": "ffe0", # indirect jmp rax; unsupported by our dispatcher
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, required=True,
help="artifact directory containing upstream/ at the pinned revision")
parser.add_argument("--llvm", type=Path, default=Path("/opt/homebrew/opt/llvm@17"))
parser.add_argument("--extended", action="store_true", help="run SIMD/control probes and matched integer measurements")
parser.add_argument("--build", action="store_true", help="configure/build dependencies and Remill first")
args = parser.parse_args()
root, llvm = args.root.resolve(), args.llvm.absolute()
if platform.system() != "Darwin" or platform.machine() != "arm64":
parser.error("this experiment requires native arm64 macOS")
# Never place generated source or receipts in a tracked directory.
root.mkdir(parents=True, exist_ok=True)
check = subprocess.run(["git", "check-ignore", str(root / "receipt.json")],
cwd=root, capture_output=True)
if check.returncode:
parser.error("--root must be inside an ignored artifacts/ directory")
host_version = platform.mac_ver()[0]
receipt = {"remill_revision": PIN, "platform": platform.platform(),
"commands": [], "native": [], "outcome": "incomplete"}
env = dict(os.environ, CMAKE_BUILD_PARALLEL_LEVEL="2", CARGO_BUILD_JOBS="2",
CARGO_TARGET_DIR=str(root / "bridge-target"))
def run(name, argv, timeout=180, cwd=root, expected_exit=0):
if args.extended:
name = "extended-" + name
argv = list(map(str, argv))
start = time.monotonic()
record = {"name": name, "argv": argv, "cwd": str(cwd)}
receipt["commands"].append(record)
try:
proc = subprocess.Popen(argv, cwd=cwd, env=env, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, start_new_session=True)
try:
output, _ = proc.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
# Bound the entire build process group, including nested Ninja jobs.
os.killpg(proc.pid, signal.SIGTERM)
try:
output, _ = proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
output, _ = proc.communicate()
(root / (name + ".log")).write_bytes(output)
record.update(exit="timeout", seconds=time.monotonic() - start)
raise RuntimeError(f"{name} exceeded {timeout} seconds")
(root / (name + ".log")).write_bytes(output)
record.update(exit=proc.returncode, seconds=time.monotonic() - start)
record["expected_exit"] = expected_exit
if proc.returncode != expected_exit:
raise RuntimeError(f"{name} failed ({proc.returncode}); see {root / (name + '.log')}")
return output.decode(errors="replace")
except OSError:
record.update(exit="could not execute", seconds=time.monotonic() - start)
raise
audited = set()
def audit(path):
path = Path(path).resolve()
if path in audited:
return
audited.add(path)
name = "native-" + hashlib.sha256(str(path).encode()).hexdigest()[:12]
description = run(name + "-file", ["/usr/bin/file", path])
archs = run(name + "-archs", ["/usr/bin/lipo", "-archs", path]).strip()
if not any(a.startswith("arm64") for a in archs.split()):
raise RuntimeError(f"refusing non-ARM64 native input: {path}")
item = {"path": str(path), "archs": archs, "file": description.strip()}
receipt["native"].append(item)
# Archives have no dynamic load commands. Check their ARM64 slice above.
if path.suffix == ".a":
return
links = run(name + "-links", ["/usr/bin/otool", "-L", path])
commands = run(name + "-load", ["/usr/bin/otool", "-l", path])
rpaths = re.findall(r"cmd LC_RPATH\s+cmdsize \d+\s+path (.*?) \(offset", commands)
def expand(value):
return value.replace("@loader_path", str(path.parent)).replace("@executable_path", str(path.parent))
dependencies = []
for line in links.splitlines()[1:]:
if " (compatibility version" not in line:
continue
lib = line.strip().split(" (compatibility")[0]
if lib.startswith(("/usr/lib/", "/System/Library/")):
dependencies.append({"install_name": lib, "system_shared_cache": True})
continue
candidates = [Path(expand(lib))]
if lib.startswith("@rpath/"):
candidates = [Path(expand(r)) / lib[7:] for r in rpaths]
candidates += [llvm / "lib" / lib[7:]]
resolved = next((p for p in candidates if p.exists()), None)
if resolved is None:
raise RuntimeError(f"unresolved native dependency: {path}: {lib}")
dependencies.append({"install_name": lib, "resolved": str(resolved.resolve())})
audit(resolved)
item["dependencies"] = dependencies
try:
upstream = root / "upstream"
revision = run("upstream-revision", ["git", "rev-parse", "HEAD"], cwd=upstream).strip()
if revision != PIN or run("upstream-status", ["git", "status", "--porcelain"], cwd=upstream).strip():
raise RuntimeError("upstream must be clean and match PIN")
receipt["project_revision"] = run("project-revision", ["git", "rev-parse", "HEAD"], cwd=HERE).strip()
receipt["fixture_bytes"] = FIXTURES
receipt["source_sha256"] = {str(p.relative_to(HERE)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in [Path(__file__), HERE / "prototype.cpp", HERE / "bridge/src/lib.rs", HERE / "bridge/Cargo.lock"]}
for tool in ["cmake", "ninja", "git", "make", "rustup"]:
audit(shutil.which(tool))
for tool in ["clang", "clang++", "llvm-ar", "llvm-link", "llc", "opt", "llvm-mc", "llvm-nm", "llvm-objcopy", "llvm-objdump"]:
audit(llvm / "bin" / tool)
# Check real toolchain executables, not only the rustup proxy.
for tool in ["cargo", "rustc"]:
path = run("which-" + tool, ["rustup", "which", "--toolchain", "1.100.0", tool]).strip()
audit(path)
audit(shutil.which("python3"))
if args.build:
common = [f"-DCMAKE_C_COMPILER={llvm}/bin/clang",
f"-DCMAKE_CXX_COMPILER={llvm}/bin/clang++", "-DCMAKE_OSX_ARCHITECTURES=arm64"]
run("deps-configure", ["cmake", "-G", "Ninja", "-S", upstream / "dependencies", "-B", root / "deps-build",
"-DUSE_EXTERNAL_LLVM=ON", "-DENABLE_SLEIGH=ON", f"-DCMAKE_PREFIX_PATH={llvm}",
f"-DCMAKE_INSTALL_PREFIX={root}/deps-install", *common])
run("deps-build", ["cmake", "--build", root / "deps-build", "--parallel", "2"], timeout=1800)
run("remill-configure", ["cmake", "-G", "Ninja", "-S", upstream, "-B", root / "remill-build",
f"-DCMAKE_PREFIX_PATH={root}/deps-install;{llvm}",
f"-DCMAKE_INSTALL_PREFIX={root}/remill-install", "-DCMAKE_BUILD_TYPE=Release",
"-DREMILL_FETCH_SLEIGH=OFF", "-DREMILL_ENABLE_TESTING=OFF", *common])
run("remill-build", ["cmake", "--build", root / "remill-build", "--parallel", "2"], timeout=1800)
dependency_sources = {
"gflags": ("gflags-prefix/src/gflags", "52e94563eba1968783864942fedf6e87e3c611f4"),
"glog": ("glog-prefix/src/glog", "7b134a5c82c0c0b5698bb6bf7a835b230c5638e4"),
"googletest": ("googletest-prefix/src/googletest", "52eb8108c5bdec04579160ae17225d66034bd723"),
"xed": ("xed-prefix/src/xed", "dc6bdbe036515c7ef55d3b2d50bafc5232bfe534"),
"mbuild": ("xed-prefix/src/mbuild", "7c4497f41f576b43a80bb0f8d8452bbcfd58b6e2"),
"sleigh": ("sleigh-prefix/src/sleigh", "7c6b7424467d0382a1303c278633e99b0d094d5b"),
}
receipt["dependency_revisions"] = {}
for name, (relative, expected) in dependency_sources.items():
path = root / "deps-build" / relative
actual = run("revision-" + name, ["git", "rev-parse", "HEAD"], cwd=path).strip()
if actual != expected:
raise RuntimeError(f"dependency revision mismatch: {name}: {actual}")
receipt["dependency_revisions"][name] = actual
ghidra = root / "deps-build/sleigh-prefix/src/sleigh-build/_deps/ghidrasource-src"
base = "80ccdadeba79cd42fb0b85796b55952e0f79f323"
run("ghidra-base", ["git", "merge-base", "--is-ancestor", base, "HEAD"], cwd=ghidra)
receipt["dependency_revisions"]["ghidra_base"] = base
receipt["ghidra_patch_commits"] = run("ghidra-patches", ["git", "log", "--format=%H %s", base + "..HEAD"], cwd=ghidra)
receipt["upstream_patch_sha256"] = {str(p.relative_to(upstream)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in (upstream / "dependencies/sleigh_patches").glob("*.patch")}
cache = (root / "deps-build/CMakeCache.txt").read_text()
python_path = re.search(r"^_Python3_EXECUTABLE:INTERNAL=(.+)$", cache, re.MULTILINE)
if python_path:
audit(python_path.group(1))
run("remill-install", ["cmake", "--install", root / "remill-build"])
lifter = root / "remill-install/bin/remill-lift-17"
audit(lifter)
for binary in (root / "deps-install/bin").iterdir():
if binary.is_file() and binary.open("rb").read(4) in (b"\xcf\xfa\xed\xfe", b"\xca\xfe\xba\xbe"):
audit(binary)
for archive in (root / "deps-install/lib").glob("*.a"):
audit(archive)
release = ["--release"] if args.extended else []
run("bridge-build", ["cargo", "+1.100.0", "build", *release, "--locked", "--manifest-path", HERE / "bridge/Cargo.toml",
"--target", "aarch64-apple-darwin"], timeout=300, cwd=HERE)
profile = "release" if args.extended else "debug"
bridge = root / f"bridge-target/aarch64-apple-darwin/{profile}/libbetterxen_remill_experiment.a"
audit(bridge)
fixtures = dict(FIXTURES)
if args.extended:
fixtures.update(addss="f30f58c1c3", paddd="660ffec1c3", vpaddd="c5fdfec1c3", vpxor="c5f9efc0c3",
loop="48ffc048ffc975f8488903c3", register256="4801c8" * 256 + "488903c3",
memory256="4801c8488903" * 256 + "c3")
run("fixture-assemble", [llvm / "bin/llvm-mc", "-triple=x86_64-unknown-linux-gnu", "-filetype=obj",
HERE / "fixtures.s", "-o", root / "extended-fixtures.o"])
run("fixture-extract", [llvm / "bin/llvm-objcopy", "--only-section=.text", "-O", "binary",
root / "extended-fixtures.o", root / "extended-fixtures.bin"])
symbols = run("fixture-symbols", [llvm / "bin/llvm-nm", "--numeric-sort", "--defined-only", root / "extended-fixtures.o"])
offsets = [(int(line.split()[0], 16), line.split()[-1]) for line in symbols.splitlines()]
raw = (root / "extended-fixtures.bin").read_bytes()
aliases = {"bench_register": "register256", "bench_memory": "memory256"}
for index, (offset, symbol) in enumerate(offsets):
name = aliases.get(symbol, symbol.removesuffix("_probe"))
end = offsets[index+1][0] if index+1 < len(offsets) else len(raw)
if raw[offset:end].hex() != fixtures[name]:
raise RuntimeError(f"original fixture assembler mismatch: {name}")
receipt["source_sha256"].update({name: hashlib.sha256((HERE / name).read_bytes()).hexdigest()
for name in ["probes.cpp", "fixtures.s", "bridge/Cargo.toml"]})
receipt["fixture_bytes"] = fixtures
objects = []
for name, code in fixtures.items():
ir = root / (name + ".ll")
run("lift-" + name, [lifter, "--arch", "amd64_avx" if name in {"addss", "paddd", "vpaddd", "vpxor"} else "amd64", "--os", "linux", "--address", "4096",
"--bytes", code, "--ir_out", ir])
source = ir.read_text()
if "@sub_1000(" not in source:
raise RuntimeError("entry symbol missing from lifted output")
# Preserve the lifted body. Override only the entry name and host codegen attributes.
# Guest x86 target-features must not be handed to the ARM64 backend.
source = source.replace("@sub_1000(", "@lifted_" + name + "(")
source = re.sub(r' "target-(?:cpu|features|tune-cpu)"="[^"]*"', "", source)
native_ir = root / (name + "-arm64.ll")
native_ir.write_text(source)
obj = root / (name + ".o")
run("lower-" + name, [llvm / "bin/llc", f"-mtriple=arm64-apple-macosx{host_version}", "-filetype=obj", "-O2", native_ir, "-o", obj])
audit(obj)
if args.extended and name in {"register256", "memory256"}:
sections = run("sections-" + name, [llvm / "bin/llvm-objdump", "--section-headers", obj])
match = re.search(r"^\s*\d+ __text\s+([0-9a-fA-F]+)\s", sections, re.MULTILINE)
if not match:
raise RuntimeError("native text section missing")
receipt.setdefault("remill_text_bytes", {})[name] = int(match.group(1), 16)
objects.append(obj)
executable = root / ("prototype-extended" if args.extended else "prototype")
run("prototype-link", [llvm / "bin/clang++", "-std=c++17", "-O2", f"-mmacosx-version-min={host_version}", "-Wall", "-Wextra", "-Werror", "-arch", "arm64", "-DADDRESS_SIZE_BITS=64",
f"-DHAS_FEATURE_AVX={int(args.extended)}", "-DHAS_FEATURE_AVX512=0", "-I", upstream / "include",
HERE / ("probes.cpp" if args.extended else "prototype.cpp"), *objects, bridge, "-framework", "Security", "-framework", "CoreFoundation",
"-liconv", "-lresolv", "-o", executable])
audit(executable)
semantic_error = None
try:
output = run("prototype-run", [executable], timeout=30)
except RuntimeError as error:
if not args.extended:
raise
semantic_error = str(error)
output = (root / "extended-prototype-run.log").read_text()
if args.extended:
# Integer measurements have their own per-run correctness gate. A failed SIMD
# contract remains a failed gate even if these separate measurements succeed.
receipt["measurement_limits"] = "Exploratory active-desktop run; not an idle-machine benchmark. Includes reset/check/return glue."
measurements = run("benchmark", [executable, "--benchmark"], timeout=120)
receipt["measurements"] = [json.loads(line) for line in measurements.splitlines()]
receipt["measurement_summary"] = {}
for workload in ["register256", "memory256"]:
receipt["measurement_summary"][workload] = {}
for engine in range(4):
rows = [r for r in receipt["measurements"] if r["kind"] == "sample" and r["workload"] == workload and r["engine"] == engine]
if len(rows) != 9:
raise RuntimeError("incomplete timing sample set")
values = [r["ns"] / r["repetitions"] / 1000 for r in rows]
receipt["measurement_summary"][workload][engine] = {"median_us": statistics.median(values), "min_us": min(values), "max_us": max(values)}
try:
run("runaway-budget", [executable, "--runaway"], timeout=1)
receipt["runaway_budget"] = "returned; inspect exit/log"
except RuntimeError as error:
receipt["runaway_budget"] = str(error)
semantic_error = (semantic_error + "; " if semantic_error else "") + str(error)
receipt["semantic_observations"] = [json.loads(line) for line in output.splitlines() if line.startswith("{")]
run("wrong-answer-control", [executable, "--wrong-answer"], timeout=30, expected_exit=1)
receipt["outcome"] = "local prototype passed; independent acceptance pending"
receipt["output"] = output.strip()
receipt["executable_sha256"] = hashlib.sha256(executable.read_bytes()).hexdigest()
print(output, end="")
if semantic_error:
raise RuntimeError(semantic_error)
except Exception as error:
receipt["outcome"] = "failed"
receipt["error"] = str(error)
raise
finally:
(root / ("receipt-extended.json" if args.extended else "receipt.json")).write_text(json.dumps(receipt, indent=2) + "\n")
if __name__ == "__main__":
main()
+154
View File
@@ -0,0 +1,154 @@
# Extended Remill evaluation
**Decision: retain BetterXen's current CPU path. The tested Remill adapter fails
floating-point and instruction-budget requirements needed before adoption.**
This is a local research result from November 25, 2026, not independent acceptance
or a verdict on every possible Remill integration. The original native prototype
remains usable; its 32 checks also passed inside this extended run.
## Candidate and evidence
- BetterXen worktree: `b2654e93a42e74e29570183da1f31bb8cdc6f721`, with local files
restricted to the experiment, documentation index and changelog.
- Remill: `66c488c9911fd9b368e4d0c9647d74239f8bba8b`, unchanged upstream source.
- Apple M4, native ARM64, macOS 27.0 (26A428), LLVM/Clang 17.0.6 and Rust 1.100.0.
- Native tool/object/archive/linkage receipts cover 59 inputs. Guest x86-64
ELF objects are assembler data and were never executed as host binaries.
- Evidence class A applies to the observed execution on this particular host.
Expected CPU behavior is spec-derived, not compared with physical x86 or Xbox.
Independent reviewers have not accepted these results.
`fixtures.s` contains seven additional original programs. LLVM assembles them,
and the driver compares the extracted bytes against the separately declared
fixture bytes before lifting. Remill's SSE/AVX probes use `amd64_avx`; the bridge
keeps the same explicitly sized state layout. The production CPU registry,
CPUID and AVX contracts are unchanged. The related design scope remains #299.
The extended executable exits **1**, and the driver records **failed**. It does
not turn mismatches into successful tests. There are **48 additional semantic
observations, with eight mismatches**, all in the Remill floating-point route.
Explicit VEX rejection checks on the existing engines are rejection evidence,
not AVX support. The runaway-budget failure is recorded separately.
## Floating-point findings
Nine `ADDSS xmm0, xmm1` cases check binary32 result bits, preservation of the
other vector lanes and source register, guest MXCSR, and the execution exit.
Both existing BetterXen engines match all nine expectations; Remill matches the
exact `1 + 2` case and fails the other eight through this adapter.
Expected values were specified as literal constants before the lifted code ran.
The midpoint cases use `1 + 2^-24` or `-1 + -2^-24`. Positive round-up must choose
`3f800001`; negative round-down must choose `bf800001`. Inexact results set the
precision flag, and enabling denormals-are-zeros changes a subnormal input to
zero. MXCSR was initialized in Remill's `state.x87.fxsave64` model for each case.
The host rounding mode was checked as round-to-nearest.
| Case | Expected low 32 bits / MXCSR | Remill low 32 bits / MXCSR | Comparison |
| --- | --- | --- | --- |
| exact | `40400000` / `1f80` | `40400000` / `1f80` | match |
| tie-nearest | `3f800000` / `1fa0` | `3f800000` / `1f80` | mismatch |
| tie-down | `3f800000` / `3fa0` | `3f800000` / `3f80` | mismatch |
| tie-up | `3f800001` / `5fa0` | `3f800000` / `5f80` | mismatch |
| tie-zero | `3f800000` / `7fa0` | `3f800000` / `7f80` | mismatch |
| negative-down | `bf800001` / `3fa0` | `bf800000` / `3f80` | mismatch |
| denormal | `00000001` / `1f82` | `00000001` / `1f80` | mismatch |
| denormal-daz | `00000000` / `1fc0` | `00000001` / `1fc0` | mismatch |
| precision-unmasked | `3f800000` / `0fa0` | `3f800000` / `0f80` | mismatch |
The unmasked-precision case must also stop with the guest SIMD exception, leaving
the destination unchanged. BetterXen reports that exit; the Remill trace returns
normally. The sticky-flag failures matter even when result bits happen to agree.
The primary reference is [Intel SDM Volume 1, December 2024](https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf),
sections 10.2.3.1–10.2.3.4 and 11.5.2.6, plus Volume 2's ADDSS entry. The generated
`addss.ll` contains a plain LLVM `fadd` and no guest MXCSR update. That supports
the inference that this route needs additional guest floating-point modeling;
merely lowering the current lifted IR to ARM64 is insufficient. This experiment
did not test other floating-point instructions, NaNs, flush-to-zero or x87.
## Vector and execution findings
- `PADDD xmm0, xmm1` matches four independently calculated wrapping integer lanes
in all three paths, preserves the source, and leaves MXCSR unchanged.
- Remill's legacy PADD preserves the tested YMM upper half; `VPADDD ymm0, ymm0,
ymm1` matches eight lanes; VEX.128 `VPXOR xmm0, xmm0, xmm0` zeroes the tested full
YMM destination. These are three narrow Remill state checks, not AVX2 coverage.
- The existing interpreter and DBT explicitly reject both VEX fixtures without
changing the checked XMM state. No production AVX support was added.
- A backward `INC/DEC/JNE` loop terminates with the hand-derived result and flags
for counts 1, 3 and 7 in all three paths.
- For the same loop starting at count zero, both existing engines return their
32-instruction budget exit. The Remill route does not yield a guest budget
exit; the supervisor terminates its process group after one second. A process
timeout does not satisfy the guest instruction-budget contract.
## Exploratory measurements
**The desktop was active. These are diagnostic toy-workload measurements, not
an idle-machine benchmark campaign, acceptance gate G10 or a general speedup.**
The earlier exploratory receipt is retained rather than selecting a favorable
run. No production optimization was made.
Both workloads start RAX and RCX at one, execute 256 additions, store the final
value and return. `register256` stores once; `memory256` stores after every add.
The same guest bytes are used by every path. All timed repetitions check RAX
257, the stored value, six arithmetic flags, stack movement and memory sentinels.
Each path performs one untimed correctness/warmup run, then nine batches of
200 repetitions, rotating engine order between batches. Warm DBT samples assert
zero new translations and positive cache hits.
Values below are microseconds per guest invocation: median, with minimum and
maximum batch averages in parentheses. They describe the final recorded run.
| Workload | Interpreter | Warm DBT | Cold DBT | Remill AOT |
| --- | ---: | ---: | ---: | ---: |
| register256 | 4.531 (3.907–11.857) | 0.552 (0.481–0.977) | 19.482 (17.350–44.555) | 0.959 (0.824–1.774) |
| memory256 | 8.310 (8.057–14.108) | 2.716 (2.639–4.356) | 47.383 (45.075–51.644) | 1.862 (1.796–3.760) |
Cold DBT creates an engine and translates each invocation. Remill is compiled
before these samples; its lift/lower process durations are separate receipt
entries, so the cold-DBT column must not be compared as equal preparation work.
The bridge uses release mode, fat LTO and one codegen unit, matching the project's
release profile; Remill objects use LLVM `llc -O2`, and the harness uses C++ `-O2`.
The interpreter and DBT also execute a terminal sentinel HLT after RET; the Remill
harness validates the return sentinel directly.
These timings include resetting CPU state, checked-memory access and validation.
State sizes, return plumbing and per-instruction budget checks differ, and Remill
still calls predicate-annotation helpers. They are not isolated instruction
throughput or equally featured production runtimes. Background activity and
these adapter costs limit any performance conclusion. Warm DBT is faster on
this register trace; Remill is faster on this store-heavy trace in the recorded
run. There is no demonstrated overall performance winner.
Remill object text is 48,288 bytes for `register256`
and 58,488 for `memory256`; warmed DBT reports
6,396 and 38,852 emitted native bytes respectively. These are code-size counters
for different glue/dispatch strategies, not full process memory or cache-use
measurements. Full-workload memory consumption remains unmeasured.
## Reproduce and next decision
```sh
python3 experiments/remill/evaluate.py --root /path/to/ignored/artifacts/remill-evaluation --extended
```
This command currently returns nonzero because the semantic and budget gates
fail. It still records the separately correctness-gated integer measurements.
`receipt-extended.json` contains command exit statuses, source hashes, assembled
bytes, observations, raw timing samples, summaries and the executable hash.
`extended-prototype-run.log`, `extended-benchmark.log` and
`extended-runaway-budget.log` retain the actual outcomes. The first extended
receipt and the intermediate exit-mapping diagnostic receipt are also retained.
The latter exposed a harness status-mapping omission; a distinct illegal-opcode
status fixed the reporting without altering either existing CPU engine or the
rejection expectations.
Before considering production use, implement and independently review a guest
floating-point contract and instruction-budget/dispatch adapter. Preserve the
known failing inputs as regressions. Then expand the workload corpus and run
matched, idle-host performance/memory measurements with equivalent guarantees.
No engine replacement, guest API change, game execution, GPU verification or
independent sign-off follows from these results. This review branch publishes
the isolated experiment sources and reports; raw artifacts remain local.
+34
View File
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# Original guest instructions. Assembled for inspection only; never a host executable.
.intel_syntax noprefix
.text
addss_probe:
addss xmm0, xmm1
ret
paddd_probe:
paddd xmm0, xmm1
ret
vpaddd_probe:
vpaddd ymm0, ymm0, ymm1
ret
vpxor_probe:
vpxor xmm0, xmm0, xmm0
ret
loop_probe:
inc rax
dec rcx
jne loop_probe
mov [rbx], rax
ret
bench_register:
.rept 256
add rax, rcx
.endr
mov [rbx], rax
ret
bench_memory:
.rept 256
add rax, rcx
mov [rbx], rax
.endr
ret
+40
View File
@@ -0,0 +1,40 @@
# Remill experiment provenance and preliminary license review
This records a local research build, not redistribution clearance. Original
BetterXen fixture/harness code is GPL-3.0-or-later. No upstream emulator source
was copied or adapted into the experiment. Remill code is compiled externally;
the harness includes its external state headers and links generated semantics.
Keep all upstream notices and source with any future redistributed derivative.
| Component | Exact source revision | Reviewed license/notice |
| --- | --- | --- |
| lifting-bits/remill | `66c488c9911fd9b368e4d0c9647d74239f8bba8b` | Apache-2.0, root `LICENSE`; file notices in `include/remill/Arch/X86/Runtime/State.h`, the included runtime headers, `lib/Arch/X86/Semantics/BINARY.cpp`, `DATAXFER.cpp`, `CALL_RET.cpp`, `MISC.cpp`, `MMX.cpp`, `LOGICAL.cpp`, and `CMakeLists.txt`. Trail of Bits copyright notices remain intact. |
| gflags/gflags | `52e94563eba1968783864942fedf6e87e3c611f4` | BSD-3-Clause, `COPYING.txt`. |
| google/glog (v0.7.1) | `7b134a5c82c0c0b5698bb6bf7a835b230c5638e4` | BSD-3-Clause, `COPYING`. |
| google/googletest (v1.17.0) | `52eb8108c5bdec04579160ae17225d66034bd723` | BSD-3-Clause, `LICENSE`; built as part of upstream's dependency superbuild. |
| intelxed/xed (v2025.06.08) | `dc6bdbe036515c7ef55d3b2d50bafc5232bfe534` | Apache-2.0, `LICENSE`. |
| intelxed/mbuild (v2024.11.04) | `7c4497f41f576b43a80bb0f8d8452bbcfd58b6e2` | Apache-2.0, `LICENSE`; build tool. |
| lifting-bits/sleigh | `7c6b7424467d0382a1303c278633e99b0d094d5b` | Apache-2.0, `LICENSE`. |
| NationalSecurityAgency/ghidra | `80ccdadeba79cd42fb0b85796b55952e0f79f323` before upstream Sleigh patches | `LICENSE` and `NOTICE`; sampled decompiler source headers carry Apache-2.0. Generated `xml.cc` also contains the FSF GPL-3.0-or-later Bison skeleton notice and its larger-work exception. Do not describe every Ghidra file as solely Apache-2.0. |
| LLVM/Clang | Homebrew LLVM 17.0.6 | Apache-2.0 WITH LLVM-exception; native external build/lifting tools. |
The Remill checkout is unchanged. Sleigh's superbuild applies its published
Ghidra patches and Remill's `dependencies/sleigh_patches/*.patch`; no experiment
patch was added to these upstream trees. The locally patched Ghidra checkout
initially ended at `9660b9036d4247eed1e572486db3ad1f839b763d`; the full driver
rebuild ended at `6a53bbfaa98fe272d12d7ba38b2e7ef96355e30f`. Patch-generated commit IDs
can depend on the build environment; the source base and patch content are the
reproducibility inputs. Git identities in the BetterXen checkout were not changed.
Apache-2.0 and BSD-3-Clause are compatible in principle with GPL-3.0-or-later;
the Bison notice must also be retained where applicable. This preliminary review
does not clear all transitive source files, generated language specifications,
system SDK terms or future binary packaging. Before adoption/distribution,
audit the actual linked files, preserve required license/copyright/NOTICE text,
record every modification and satisfy GPL corresponding-source requirements.
The bridge's locked Cargo dependencies are separate from the production lockfile;
their redistribution notices also require review for any shipped artifact.
No foreign source is vendored by this task. Machine-specific dependency revisions
are recorded in `artifacts/remill-evaluation/dependency-revisions.json`; original
licenses, notices, patches and source stay in the ignored upstream build trees.
+319
View File
@@ -0,0 +1,319 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#define REMILL_EXTENDED_PROBES
#include "prototype.cpp"
#include <array>
#include <cfenv>
#include <chrono>
#include <vector>
struct SimdResult {
uint64_t xmm0[2], xmm1[2], mxcsr, exit;
};
struct BenchResult {
uint64_t ns, compiled, cache_hits, fallbacks, native_bytes;
};
struct Bench;
extern "C" {
uint8_t bx_simd_run(uint32_t, const uint8_t *, size_t, const uint64_t *,
uint32_t, SimdResult *);
Bench *bx_bench_new(uint32_t, const uint8_t *, size_t);
uint8_t bx_bench_run(Bench *, uint32_t, BenchResult *);
void bx_bench_free(Bench *);
Memory *lifted_addss(State &, uint64_t, Memory *);
Memory *lifted_paddd(State &, uint64_t, Memory *);
Memory *lifted_vpaddd(State &, uint64_t, Memory *);
Memory *lifted_vpxor(State &, uint64_t, Memory *);
Memory *lifted_loop(State &, uint64_t, Memory *);
Memory *lifted_register256(State &, uint64_t, Memory *);
Memory *lifted_memory256(State &, uint64_t, Memory *);
// This intrinsic is a predicate annotation, just like the flag annotations.
bool __remill_compare_neq(bool value) { return value; }
}
static unsigned observations, mismatches;
static void observe(const char *name, unsigned engine, bool match,
uint64_t bits, uint64_t expected, uint64_t mxcsr,
uint64_t expected_mxcsr, uint64_t exit) {
++observations;
if (!match)
++mismatches;
std::printf(
"{\"kind\":\"semantic\",\"name\":\"%s\",\"engine\":%u,\"match\":%s,"
"\"bits\":%llu,\"expected\":%llu,\"mxcsr\":%llu,\"expected_mxcsr\":%llu,"
"\"exit\":%llu}\n",
name, engine, match ? "true" : "false", (unsigned long long)bits,
(unsigned long long)expected, (unsigned long long)mxcsr,
(unsigned long long)expected_mxcsr, (unsigned long long)exit);
}
static SimdResult remill_simd(Trace trace, const uint64_t *inputs,
uint32_t mxcsr) {
std::memset(&state, 0, sizeof(state));
std::memcpy(&state.vec[0], inputs, 16);
std::memcpy(&state.vec[1], inputs + 2, 16);
state.x87.fxsave.mxcsr.flat = mxcsr;
state.gpr.rsp.qword = 0x3000;
Memory *memory = bx_memory_new();
returned = false;
int status = setjmp(escape);
if (!status) {
trace(state, 0x1000, memory);
if (!returned)
stop(3);
}
SimdResult result{};
std::memcpy(result.xmm0, &state.vec[0], 16);
std::memcpy(result.xmm1, &state.vec[1], 16);
result.mxcsr = state.x87.fxsave.mxcsr.flat;
result.exit = status;
bx_memory_free(memory);
return result;
}
static void floating_point() {
// Literal IEEE binary32 answers, derived before executing the lifted code.
// 1 + 2^-24 is halfway between adjacent floats; PE is bit 5 of MXCSR.
struct Case {
const char *name;
uint32_t a, b, mxcsr, bits, after;
unsigned exit;
};
const Case cases[] = {
{"exact", 0x3f800000, 0x40000000, 0x1f80, 0x40400000, 0x1f80, 0},
{"tie-nearest", 0x3f800000, 0x33800000, 0x1f80, 0x3f800000, 0x1fa0, 0},
{"tie-down", 0x3f800000, 0x33800000, 0x3f80, 0x3f800000, 0x3fa0, 0},
{"tie-up", 0x3f800000, 0x33800000, 0x5f80, 0x3f800001, 0x5fa0, 0},
{"tie-zero", 0x3f800000, 0x33800000, 0x7f80, 0x3f800000, 0x7fa0, 0},
{"negative-down", 0xbf800000, 0xb3800000, 0x3f80, 0xbf800001, 0x3fa0, 0},
{"denormal", 0x00000001, 0x00000000, 0x1f80, 0x00000001, 0x1f82, 0},
{"denormal-daz", 0x00000001, 0x00000000, 0x1fc0, 0x00000000, 0x1fc0, 0},
{"precision-unmasked", 0x3f800000, 0x33800000, 0x0f80, 0x3f800000, 0x0fa0,
3},
};
const uint8_t code[] = {0xf3, 0x0f, 0x58, 0xc1, 0xc3};
for (const auto &c : cases) {
const uint64_t inputs[] = {
0x1122334400000000ULL | c.a, 0x5566778899aabbccULL,
0xaabbccdd00000000ULL | c.b, 0x0123456789abcdefULL};
for (unsigned engine = 0; engine < 3; ++engine) {
SimdResult actual{};
if (engine == 2)
actual = remill_simd(lifted_addss, inputs, c.mxcsr);
else
require(
bx_simd_run(engine, code, sizeof(code), inputs, c.mxcsr, &actual),
"SIMD baseline available");
const uint64_t expected = 0x1122334400000000ULL | c.bits;
bool match = actual.xmm0[0] == expected && actual.xmm0[1] == inputs[1] &&
actual.xmm1[0] == inputs[2] && actual.xmm1[1] == inputs[3] &&
actual.mxcsr == c.after && actual.exit == c.exit;
observe(c.name, engine, match, actual.xmm0[0], expected, actual.mxcsr,
c.after, actual.exit);
}
}
}
static void vectors() {
const uint32_t left[8] = {0xffffffff, 0x7fffffff, 10, 0x80000000, 3, 5, 7, 9};
const uint32_t right[8] = {1, 1, 20, 0x80000000, 4, 6, 8, 10};
const uint32_t expected[8] = {0, 0x80000000, 30, 0, 7, 11, 15, 19};
uint64_t inputs[4];
std::memcpy(inputs, left, 16);
std::memcpy(inputs + 2, right, 16);
const uint8_t code[] = {0x66, 0x0f, 0xfe, 0xc1, 0xc3};
for (unsigned engine = 0; engine < 3; ++engine) {
SimdResult actual{};
if (engine == 2)
actual = remill_simd(lifted_paddd, inputs, 0x1f80);
else
require(bx_simd_run(engine, code, sizeof(code), inputs, 0x1f80, &actual),
"PADD baseline available");
observe("paddd128", engine,
std::memcmp(actual.xmm0, expected, 16) == 0 &&
std::memcmp(actual.xmm1, inputs + 2, 16) == 0 &&
actual.mxcsr == 0x1f80 && actual.exit == 0,
actual.xmm0[0], uint64_t(expected[0]) | uint64_t(expected[1]) << 32,
actual.mxcsr, 0x1f80, actual.exit);
}
const uint8_t vex[2][5] = {{0xc5, 0xfd, 0xfe, 0xc1, 0xc3},
{0xc5, 0xf9, 0xef, 0xc0, 0xc3}};
for (unsigned form = 0; form < 2; ++form)
for (unsigned engine = 0; engine < 2; ++engine) {
SimdResult actual{};
require(bx_simd_run(engine, vex[form], 5, inputs, 0x1f80, &actual),
"VEX rejection baseline available");
observe("baseline-vex-rejection", engine,
actual.exit == 5 && actual.mxcsr == 0x1f80 &&
std::memcmp(actual.xmm0, inputs, 16) == 0 &&
std::memcmp(actual.xmm1, inputs + 2, 16) == 0,
actual.xmm0[0], inputs[0], actual.mxcsr, 0x1f80, actual.exit);
}
const Trace traces[] = {lifted_paddd, lifted_vpaddd, lifted_vpxor};
const char *names[] = {"legacy-upper-preserved", "vpaddd256",
"vpxor128-upper-zero"};
for (unsigned i = 0; i < 3; ++i) {
std::memset(&state, 0, sizeof(state));
std::memcpy(&state.vec[0], left, 32);
std::memcpy(&state.vec[1], right, 32);
state.gpr.rsp.qword = 0x3000;
Memory *memory = bx_memory_new();
returned = false;
int status = setjmp(escape);
if (!status) {
traces[i](state, 0x1000, memory);
if (!returned)
stop(3);
}
uint32_t result[8];
std::memcpy(result, &state.vec[0], 32);
const uint32_t zero[8] = {};
bool match = status == 0 && std::memcmp(&state.vec[1], right, 32) == 0;
if (i == 0)
match = match && std::memcmp(result, expected, 16) == 0 &&
std::memcmp(result + 4, left + 4, 16) == 0;
else
match = match && std::memcmp(result, i == 1 ? expected : zero, 32) == 0;
observe(names[i], 2, match, result[0], i == 2 ? 0 : expected[0], 0, 0,
status);
bx_memory_free(memory);
}
}
static void control_flow() {
const uint8_t code[] = {0x48, 0xff, 0xc0, 0x48, 0xff, 0xc9,
0x75, 0xf8, 0x48, 0x89, 0x03, 0xc3};
for (unsigned count : {1, 3, 7}) {
const auto actual = run(lifted_loop, 5, count, 0x2000);
observe("finite-loop", 2,
actual.exit == 0 && actual.rax == 5 + count &&
actual.data == 5 + count && actual.flags == 0x44,
actual.rax, 5 + count, 0, 0, actual.exit);
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState baseline{};
require(bx_run(engine, code, sizeof(code), 5, count, 0x2000, &baseline),
"loop baseline available");
observe("finite-loop", engine,
baseline.exit == 0 && baseline.rax == 5 + count &&
baseline.data == 5 + count && baseline.flags == 0x44,
baseline.rax, 5 + count, 0, 0, baseline.exit);
}
}
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState actual{};
require(bx_run(engine, code, sizeof(code), 5, 0, 0x2000, &actual),
"budget baseline available");
observe("baseline-step-budget", engine, actual.exit == 4, actual.rax, 0, 0,
0, actual.exit);
}
}
static uint64_t remill_batch(Trace trace, Memory *memory,
unsigned repetitions) {
const auto start = std::chrono::steady_clock::now();
for (unsigned i = 0; i < repetitions; ++i) {
std::memset(&state, 0, sizeof(state));
state.gpr.rax.qword = 1;
state.gpr.rcx.qword = 1;
state.gpr.rbx.qword = 0x2000;
state.gpr.rsp.qword = 0x3000;
require(bx_write(memory, 0x2000, 0), "benchmark reset");
returned = false;
int status = setjmp(escape);
if (!status)
trace(state, 0x1000, memory);
uint64_t data = 0, hi = 0, ro = 0;
require(!status && returned && state.gpr.rax.qword == 257 &&
state.gpr.rsp.qword == 0x3008 && state.aflag.cf == 0 &&
state.aflag.pf == 0 && state.aflag.af == 0 &&
state.aflag.zf == 0 && state.aflag.sf == 0 &&
state.aflag.of == 0 && bx_read(memory, 0x2000, &data) &&
data == 257 && bx_read(memory, 0x2008, &hi) && hi == 0 &&
bx_read(memory, 0x6000, &ro) && ro == 0xa5a5a5a5a5a5a5a5ULL,
"benchmark Remill correctness");
}
return std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now() - start)
.count();
}
static void benchmark() {
constexpr unsigned repetitions = 200, samples = 9;
const Trace traces[] = {lifted_register256, lifted_memory256};
const char *names[] = {"register256", "memory256"};
for (unsigned work = 0; work < 2; ++work) {
std::vector<uint8_t> code;
for (unsigned i = 0; i < 256; ++i) {
code.insert(code.end(), {0x48, 0x01, 0xc8});
if (work)
code.insert(code.end(), {0x48, 0x89, 0x03});
}
if (!work) {
code.insert(code.end(), {0x48, 0x89, 0x03});
}
code.push_back(0xc3);
Bench *benches[3];
for (unsigned engine = 0; engine < 3; ++engine) {
benches[engine] = bx_bench_new(engine, code.data(), code.size());
require(benches[engine], "benchmark context");
BenchResult warm{};
require(bx_bench_run(benches[engine], 1, &warm),
"benchmark warmup correctness");
std::printf("{\"kind\":\"warmup\",\"workload\":\"%s\",\"engine\":%u,"
"\"native_bytes\":%llu,\"compiled\":%llu}\n",
names[work], engine, (unsigned long long)warm.native_bytes,
(unsigned long long)warm.compiled);
}
Memory *memory = bx_memory_new();
remill_batch(traces[work], memory, 1);
for (unsigned sample = 0; sample < samples; ++sample)
for (unsigned turn = 0; turn < 4; ++turn) {
const unsigned engine = (sample + turn) % 4;
BenchResult result{};
if (engine == 3)
result.ns = remill_batch(traces[work], memory, repetitions);
else {
require(bx_bench_run(benches[engine], repetitions, &result),
"benchmark baseline correctness");
if (engine == 1)
require(result.compiled == 0 && result.cache_hits > 0,
"warm DBT must reuse its cache");
}
std::printf("{\"kind\":\"sample\",\"workload\":\"%s\",\"engine\":%u,"
"\"sample\":%u,\"repetitions\":%u,"
"\"ns\":%llu,\"compiled\":%llu,\"cache_hits\":%llu,"
"\"fallbacks\":%llu}\n",
names[work], engine, sample, repetitions,
(unsigned long long)result.ns,
(unsigned long long)result.compiled,
(unsigned long long)result.cache_hits,
(unsigned long long)result.fallbacks);
}
bx_memory_free(memory);
for (auto *bench : benches)
bx_bench_free(bench);
}
}
int main(int argc, char **argv) {
if (argc == 2 && std::strcmp(argv[1], "--benchmark") == 0) {
benchmark();
return 0;
}
if (argc == 2 && std::strcmp(argv[1], "--runaway") == 0) {
run(lifted_loop, 5, 0, 0x2000);
return 9;
}
if (argc == 2 && std::strcmp(argv[1], "--wrong-answer") == 0)
return integer_checks(argc, argv);
if (argc != 1)
return 64;
integer_checks(argc, argv);
require(std::fegetround() == FE_TONEAREST,
"probe requires host round-to-nearest");
floating_point();
vectors();
control_flow();
std::printf("{\"kind\":\"summary\",\"observations\":%u,\"mismatches\":%u}\n",
observations, mismatches);
return mismatches ? 1 : 0;
}
+219
View File
@@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original trusted harness. Remill headers remain external, under Apache-2.0.
#include "remill/Arch/X86/Runtime/State.h"
#include <csetjmp>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
struct ResultState {
uint64_t rax, rsp, rip, flags, data, data_hi, read_only, exit;
};
extern "C" {
Memory *bx_memory_new();
void bx_memory_free(Memory *);
uint8_t bx_read(const Memory *, uint64_t, uint64_t *);
uint8_t bx_write(Memory *, uint64_t, uint64_t);
uint8_t bx_run(uint32_t, const uint8_t *, size_t, uint64_t, uint64_t, uint64_t,
ResultState *);
Memory *lifted_add(State &, uint64_t, Memory *);
Memory *lifted_load(State &, uint64_t, Memory *);
Memory *lifted_store(State &, uint64_t, Memory *);
Memory *lifted_ud2(State &, uint64_t, Memory *);
Memory *lifted_jump(State &, uint64_t, Memory *);
}
static std::jmp_buf escape;
static bool returned;
[[noreturn]] static void stop(int reason) { std::longjmp(escape, reason); }
extern "C" uint64_t __remill_read_memory_64(Memory *m, uint64_t address) {
uint64_t result;
if (!bx_read(m, address, &result))
stop(1);
return result;
}
extern "C" Memory *__remill_write_memory_64(Memory *m, uint64_t address,
uint64_t value) {
if (!bx_write(m, address, value))
stop(1);
return m;
}
extern "C" Memory *__remill_function_return(State &, uint64_t address,
Memory *m) {
if (address != 0x4000)
stop(3);
returned = true;
return m;
}
// All other transfers fail explicitly; this harness has no guest dispatcher.
extern "C" Memory *__remill_jump(State &, uint64_t, Memory *) { stop(2); }
extern "C" Memory *__remill_error(State &, uint64_t, Memory *) { stop(2); }
extern "C" Memory *__remill_missing_block(State &, uint64_t, Memory *) {
stop(2);
}
extern "C" Memory *__remill_function_call(State &, uint64_t, Memory *) {
stop(2);
}
extern "C" Memory *__remill_async_hyper_call(State &, uint64_t, Memory *) {
stop(2);
}
extern "C" Memory *__remill_sync_hyper_call(State &, Memory *, uint32_t) {
stop(2);
}
// These intrinsics annotate an already-computed predicate; they do not compute
// flags.
extern "C" bool __remill_flag_computation_zero(bool value, ...) {
return value;
}
extern "C" bool __remill_flag_computation_sign(bool value, ...) {
return value;
}
extern "C" bool __remill_flag_computation_overflow(bool value, ...) {
return value;
}
extern "C" bool __remill_flag_computation_carry(bool value, ...) {
return value;
}
using Trace = Memory *(*)(State &, uint64_t, Memory *);
static State state;
static ResultState run(Trace trace, uint64_t a, uint64_t b, uint64_t address) {
std::memset(&state, 0, sizeof(state));
state.gpr.rax.qword = a;
state.gpr.rcx.qword = b;
state.gpr.rbx.qword = address;
state.gpr.rsp.qword = 0x3000;
Memory *memory = bx_memory_new();
returned = false;
int status = setjmp(escape);
if (!status) {
trace(state, 0x1000, memory);
if (!returned)
stop(3);
}
uint64_t data = 0, data_hi = 0, read_only = 0;
if (!bx_read(memory, 0x2000, &data) || !bx_read(memory, 0x2008, &data_hi) ||
!bx_read(memory, 0x6000, &read_only))
std::abort();
const auto &f = state.aflag;
ResultState result{state.gpr.rax.qword,
state.gpr.rsp.qword,
state.gpr.rip.qword,
uint64_t(f.cf) | uint64_t(f.pf) << 2 |
uint64_t(f.af) << 4 | uint64_t(f.zf) << 6 |
uint64_t(f.sf) << 7 | uint64_t(f.of) << 11,
data,
data_hi,
read_only,
uint64_t(status)};
bx_memory_free(memory);
return result;
}
static void require(bool condition, const char *message) {
if (!condition) {
std::fprintf(stderr, "FAIL: %s\n", message);
std::exit(1);
}
}
static const uint8_t add_code[] = {0x48, 0x01, 0xc8, 0x48, 0x89, 0x03, 0xc3};
static const uint8_t load_code[] = {0x48, 0x8b, 0x03, 0xc3};
static const uint8_t store_code[] = {0x48, 0x89, 0x03, 0xc3};
static int integer_checks(int argc, char **argv) {
// Hand-derived ADD results: CF/PF/AF/ZF/SF/OF occupy x86 RFLAGS positions.
struct Case {
uint64_t a, b, value, flags;
};
Case cases[] = {
{1, 2, 3, 0x4},
{~0ULL, 1, 0, 0x55},
{0x7fffffffffffffffULL, 1, 0x8000000000000000ULL, 0x894},
{0x8000000000000000ULL, 0x8000000000000000ULL, 0, 0x845},
{15, 1, 16, 0x10},
{0, 0, 0, 0x44},
};
if (argc == 2 && std::strcmp(argv[1], "--wrong-answer") == 0)
cases[0].value ^= 1;
else if (argc != 1)
return 64;
unsigned checks = 0;
for (const auto &c : cases) {
auto actual = run(lifted_add, c.a, c.b, 0x2000);
require(actual.exit == 0 && actual.rax == c.value &&
actual.data == c.value && actual.flags == c.flags &&
actual.rsp == 0x3008 && actual.data_hi == 0 &&
actual.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"Remill ADD known answer");
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState baseline{};
require(bx_run(engine, add_code, sizeof(add_code), c.a, c.b, 0x2000,
&baseline),
"baseline available");
require(baseline.exit == 0 && baseline.rax == c.value &&
baseline.data == c.value && baseline.flags == c.flags &&
baseline.rsp == 0x3008 && baseline.data_hi == 0 &&
baseline.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"BetterXen ADD known answer");
++checks;
}
++checks;
}
// Checked GuestMemory rejects unmapped reads/writes, read-only writes and
// split writes.
struct Fault {
Trace trace;
const uint8_t *code;
size_t size;
uint64_t address;
};
const Fault faults[] = {
{lifted_load, load_code, sizeof(load_code), 0x5000},
{lifted_store, store_code, sizeof(store_code), 0x5000},
{lifted_store, store_code, sizeof(store_code), 0x6000},
{lifted_store, store_code, sizeof(store_code), 0x200c},
};
for (const auto &c : faults) {
const auto actual = run(c.trace, 42, 0, c.address);
require(actual.exit == 1 && actual.rip == 0x1000 && actual.rax == 42 &&
actual.rsp == 0x3000 && actual.flags == 0 && actual.data == 0 &&
actual.data_hi == 0 &&
actual.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"Remill checked memory rejection");
for (unsigned engine = 0; engine < 2; ++engine) {
ResultState baseline{};
require(bx_run(engine, c.code, c.size, 42, 0, c.address, &baseline),
"fault baseline available");
require(baseline.exit == 1 && baseline.rip == 0x1000 &&
baseline.rax == 42 && baseline.rsp == 0x3000 &&
baseline.flags == 0 && baseline.data == 0 &&
baseline.data_hi == 0 &&
baseline.read_only == 0xa5a5a5a5a5a5a5a5ULL,
"BetterXen checked memory rejection");
std::printf("fault address=0x%llx engine=%u baseline_rip=0x%llx "
"remill_rip=0x%llx\n",
(unsigned long long)c.address, engine,
(unsigned long long)baseline.rip,
(unsigned long long)actual.rip);
++checks;
}
++checks;
}
require(run(lifted_ud2, 0, 0, 0x2000).exit == 2, "UD2 must stop");
++checks;
require(run(lifted_jump, 0x5000, 0, 0x2000).exit == 2,
"indirect jump must stop");
++checks;
std::printf(
"PASS %u checks: 6 arithmetic cases and 4 memory rejections across "
"Remill, interpreter and DBT; 2 Remill control rejections\n",
checks);
return 0;
}
#ifndef REMILL_EXTENDED_PROBES
int main(int argc, char **argv) { return integer_checks(argc, argv); }
#endif