| // Copyright 2026 The Fuchsia Authors | |
| // | |
| // Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| // <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| // license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| // This file may not be copied, modified, or distributed except according to | |
| // those terms. | |
| //! Three-band x86-64 execution differential oracle (`anneal-isa-oracle exec`). | |
| //! | |
| //! Compares `Anneal.ElfX86.ScalarEval` (`decodeStreamScalar`, `stepScalar`, | |
| //! `readFootprint`, `writeFootprint`) against replayed JSONL silicon/sandbox | |
| //! execution traces across three explicit coverage bands: | |
| //! - **Band 1 (`ScalarGpr`)**: shared scalar GPR forms, | |
| //! - **Band 2 (`RepString`)**: `rep movsb` / `rep stosb` string operations | |
| //! under `DF = 0`, and | |
| //! - **Band 3 (`ExtendedSandbox`)**: extended forms collected from native | |
| //! sandbox harnesses (such as `vmovdqu` and 8/16-bit memory loads). | |
| //! | |
| //! Undefined architectural status flags tracked by `ScalarState.undefFlags` | |
| //! are masked out during flag comparison. Cross-vendor records sharing an | |
| //! identical input pre-state that `ScalarEval` stepped are audited so any | |
| //! defined divergence between hardware vendors fails closed as a model defect, | |
| //! while unstepped multi-vendor groups are tallied explicitly in | |
| //! `shared_cases_unaudited`. | |
| use std::{ | |
| collections::{BTreeMap, BTreeSet}, | |
| fmt::Write as _, | |
| io::Write as _, | |
| path::Path, | |
| process::{Command, Stdio}, | |
| }; | |
| use serde::{Deserialize, Serialize}; | |
| use crate::{lean::encode_lean_byte_list, parse_hex_bytes}; | |
| /// Schema identifier for `anneal-isa-oracle exec` JSON reports. | |
| pub const EXEC_REPORT_SCHEMA: &str = "anneal-isa-oracle-exec/v1"; | |
| /// Default byte size of the sandboxed memory arena in hardware replay records. | |
| pub const DEFAULT_ARENA_SIZE: usize = 8192; | |
| /// Bitmask of the six x86-64 arithmetic status flags tracked by `RFlags`: | |
| /// `CF` (bit 0), `PF` (bit 2), `AF` (bit 4), `ZF` (bit 6), `SF` (bit 7), | |
| /// and `OF` (bit 11). | |
| pub const ARITH_FLAGS_MASK: u64 = (1 << 0) | (1 << 2) | (1 << 4) | (1 << 6) | (1 << 7) | (1 << 11); | |
| const FLAG_BITS: [(&str, u32); 6] = | |
| [("CF", 0), ("PF", 2), ("AF", 4), ("ZF", 6), ("SF", 7), ("OF", 11)]; | |
| /// Semantic coverage band for a replayed x86-64 execution record. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] | |
| #[serde(rename_all = "snake_case")] | |
| pub enum ExecBand { | |
| /// Band 1: baseline scalar GPR instruction sequences. | |
| ScalarGpr, | |
| /// Band 2: `rep movsb` / `rep stosb` string operations (`DF = 0`). | |
| RepString, | |
| /// Band 3: extended sandbox-captured forms (vector `vmovdqu`, 8/16-bit | |
| /// loads, and other instructions outside the baseline scalar corpus). | |
| ExtendedSandbox, | |
| } | |
| impl ExecBand { | |
| /// Parse a CLI `--band` selector (`scalar`, `rep`, or `sandbox`). | |
| pub fn parse_cli(raw: &str) -> Result<Self, String> { | |
| match raw { | |
| "scalar" | "scalar_gpr" | "band1" => Ok(Self::ScalarGpr), | |
| "rep" | "rep_string" | "band2" => Ok(Self::RepString), | |
| "sandbox" | "extended_sandbox" | "band3" => Ok(Self::ExtendedSandbox), | |
| other => Err(format!( | |
| "unsupported --band `{other}` (expected `scalar`, `rep`, or `sandbox`)" | |
| )), | |
| } | |
| } | |
| /// All three bands in canonical reporting order. | |
| pub const ALL: [Self; 3] = [Self::ScalarGpr, Self::RepString, Self::ExtendedSandbox]; | |
| } | |
| /// Optional instruction metadata attached to a replay record's `program` array. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct ProgramInsnMeta { | |
| pub kind: String, | |
| } | |
| /// Single byte patch inside the replayed memory arena. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct MemPatch { | |
| pub offset: usize, | |
| pub value: u8, | |
| } | |
| /// Architectural state snapshot captured before or after executing a record. | |
| #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] | |
| pub struct ExecStateSnapshot { | |
| /// Sixteen 64-bit GPRs in canonical x86-64 encoding order (`rax..r15`). | |
| pub regs: [u64; 16], | |
| /// Instruction pointer (`RIP`) value. | |
| pub rip: u64, | |
| /// Masked arithmetic status flags (`CF`, `PF`, `AF`, `ZF`, `SF`, `OF`). | |
| pub arithmetic_flags: u64, | |
| /// Optional raw `RFLAGS` register value. | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub raw_rflags: Option<u64>, | |
| /// Optional low 128-bit vector register snapshot (`xmm0..xmm15`). | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub xmm: Option<Vec<[u64; 2]>>, | |
| /// Optional `MXCSR` control/status register value. | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub mxcsr: Option<u32>, | |
| } | |
| /// Corpus-level header metadata parsed from a JSONL `Header` line. | |
| #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct CorpusHeader { | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub vendor: Option<String>, | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub cpuid_vendor: Option<String>, | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub cpu_model: Option<String>, | |
| #[serde(default, skip_serializing_if = "Option::is_none")] | |
| pub arena_size: Option<usize>, | |
| } | |
| /// Kind of hardware replay record (`Normal` execution or `Trap` fault). | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| #[serde(rename_all = "snake_case")] | |
| pub enum ExecRecordKind { | |
| Normal, | |
| Trap, | |
| } | |
| /// Normalized execution record ready for Lean `ScalarEval` replay. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct ExecRecord { | |
| pub case_id: String, | |
| pub vendor: String, | |
| pub kind: ExecRecordKind, | |
| pub band: ExecBand, | |
| pub body_hex: String, | |
| pub bytes: Vec<u8>, | |
| pub base_address: u64, | |
| pub arena_address: u64, | |
| pub arena_size: usize, | |
| pub default_byte: u8, | |
| /// Optional interior RIP stop offset relative to `base_address` | |
| /// (`0` means run until halt or end of `bytes`). | |
| pub capture_boundary: u64, | |
| pub program_kinds: Vec<String>, | |
| pub initial: ExecStateSnapshot, | |
| #[serde(skip_serializing_if = "Option::is_none")] | |
| pub observed: Option<ExecStateSnapshot>, | |
| /// Initial non-default arena byte overrides relative to `default_byte`, | |
| /// normalized in ascending offset order with no duplicate offsets. | |
| pub initial_memory: Vec<MemPatch>, | |
| /// Complete final non-default arena byte snapshot relative to | |
| /// `default_byte` (matching hardware replay corpus convention), normalized | |
| /// in ascending offset order with no duplicate offsets. | |
| pub observed_memory_diffs: Vec<MemPatch>, | |
| #[serde(skip_serializing_if = "Option::is_none")] | |
| pub trap_signal: Option<String>, | |
| /// Optional absolute RIP of the faulting instruction on `Trap` records | |
| /// when a full `observed` fault-time register snapshot is not recorded. | |
| #[serde(skip_serializing_if = "Option::is_none")] | |
| pub fault_rip: Option<u64>, | |
| } | |
| /// Parsed JSONL corpus bundle with header metadata and normalized records. | |
| #[derive(Debug, Clone, PartialEq, Eq)] | |
| pub struct ParsedExecCorpus { | |
| pub source_label: String, | |
| pub header: CorpusHeader, | |
| pub records: Vec<ExecRecord>, | |
| } | |
| #[derive(Debug, Deserialize)] | |
| struct RawJsonlRecord { | |
| record_kind: String, | |
| #[serde(default)] | |
| vendor: Option<String>, | |
| #[serde(default)] | |
| cpuid_vendor: Option<String>, | |
| #[serde(default)] | |
| cpu_model: Option<String>, | |
| #[serde(default)] | |
| case_id: Option<String>, | |
| #[serde(default)] | |
| band: Option<ExecBand>, | |
| #[serde(default)] | |
| body_hex: Option<String>, | |
| #[serde(default)] | |
| base_address: Option<u64>, | |
| #[serde(default)] | |
| arena_address: Option<u64>, | |
| #[serde(default)] | |
| arena_size: Option<usize>, | |
| #[serde(default)] | |
| default_byte: Option<u8>, | |
| #[serde(default)] | |
| capture_boundary: Option<u64>, | |
| #[serde(default)] | |
| program: Vec<ProgramInsnMeta>, | |
| #[serde(default)] | |
| initial: Option<ExecStateSnapshot>, | |
| #[serde(default)] | |
| observed: Option<ExecStateSnapshot>, | |
| #[serde(default)] | |
| initial_memory: Vec<MemPatch>, | |
| #[serde(default)] | |
| observed_memory_diffs: Vec<MemPatch>, | |
| #[serde(default)] | |
| signal: Option<serde_json::Value>, | |
| #[serde(default)] | |
| trap_signal: Option<serde_json::Value>, | |
| #[serde(default)] | |
| trap_kind: Option<String>, | |
| #[serde(default)] | |
| fault_rip: Option<u64>, | |
| } | |
| /// Classify a record into one of the three semantic oracle bands using an | |
| /// explicit band override, program instruction metadata, or raw opcode bytes. | |
| pub fn classify_record_band( | |
| explicit: Option<ExecBand>, | |
| program_kinds: &[String], | |
| bytes: &[u8], | |
| ) -> ExecBand { | |
| if let Some(band) = explicit { | |
| return band; | |
| } | |
| for kind in program_kinds { | |
| let lower = kind.to_ascii_lowercase(); | |
| if lower.contains("repmovsb") | |
| || lower.contains("rep_movsb") | |
| || lower.contains("repstosb") | |
| || lower.contains("rep_stosb") | |
| { | |
| return ExecBand::RepString; | |
| } | |
| } | |
| for kind in program_kinds { | |
| let lower = kind.to_ascii_lowercase(); | |
| if lower.contains("vmovdqu") | |
| || lower.contains("vmovdqa") | |
| || lower.contains("mov8") | |
| || lower.contains("mov16") | |
| || lower.contains("xmm") | |
| || lower.contains("ymm") | |
| || lower.contains("vex") | |
| { | |
| return ExecBand::ExtendedSandbox; | |
| } | |
| } | |
| // Raw opcode fallback only when `program` metadata is omitted: | |
| // - `F3 A4` (`rep movsb`) and `F3 AA` (`rep stosb`) -> Band 2. | |
| // - 2-byte/3-byte VEX (`C4`/`C5`) or 8-bit/16-bit mem load (`8A`, `66 8B`) | |
| // -> Band 3. | |
| // When `program` metadata is present, do not scan raw bytes so scalar | |
| // immediates/displacements containing `F3 A4`/`F3 AA` are never | |
| // misclassified as `RepString`. | |
| if program_kinds.is_empty() { | |
| if bytes.windows(2).any(|w| w == [0xF3, 0xA4] || w == [0xF3, 0xAA]) { | |
| return ExecBand::RepString; | |
| } | |
| if bytes.first().is_some_and(|&b| b == 0xC4 || b == 0xC5 || b == 0x8A) | |
| || bytes.starts_with(&[0x66, 0x8B]) | |
| { | |
| return ExecBand::ExtendedSandbox; | |
| } | |
| } | |
| ExecBand::ScalarGpr | |
| } | |
| fn validate_arena_range(arena_address: u64, arena_size: usize, ctx: &str) -> Result<(), String> { | |
| if arena_size == 0 { | |
| return Err(format!("{ctx}: arena_size must be > 0")); | |
| } | |
| let last_off = u64::try_from(arena_size - 1) | |
| .map_err(|_| format!("{ctx}: arena_size {arena_size} overflows u64"))?; | |
| if arena_address.checked_add(last_off).is_none() { | |
| return Err(format!("{ctx}: arena [{arena_address:#x}, +{arena_size}) wraps past 2^64")); | |
| } | |
| Ok(()) | |
| } | |
| fn normalize_mem_patches( | |
| patches: &[MemPatch], | |
| arena_size: usize, | |
| field_name: &str, | |
| ctx: &str, | |
| ) -> Result<Vec<MemPatch>, String> { | |
| let mut map = BTreeMap::new(); | |
| for p in patches { | |
| if p.offset >= arena_size { | |
| return Err(format!( | |
| "{ctx}: {field_name} offset {} >= arena_size {arena_size}", | |
| p.offset | |
| )); | |
| } | |
| if map.insert(p.offset, p.value).is_some() { | |
| return Err(format!("{ctx}: duplicate {field_name} offset {}", p.offset)); | |
| } | |
| } | |
| Ok(map.into_iter().map(|(offset, value)| MemPatch { offset, value }).collect()) | |
| } | |
| fn canonical_arena_map(patches: &[MemPatch], default_byte: u8) -> BTreeMap<usize, u8> { | |
| let mut map = BTreeMap::new(); | |
| for p in patches { | |
| if p.value != default_byte { | |
| map.insert(p.offset, p.value); | |
| } | |
| } | |
| map | |
| } | |
| /// Parse a JSONL hardware/sandbox execution trace into normalized | |
| /// [`ExecRecord`]s. | |
| pub fn parse_exec_jsonl(source_label: &str, input: &str) -> Result<ParsedExecCorpus, String> { | |
| let mut header = CorpusHeader::default(); | |
| let mut vendor = source_label.to_owned(); | |
| let mut default_arena_size = DEFAULT_ARENA_SIZE; | |
| let mut records = Vec::new(); | |
| for (line_idx, raw_line) in input.lines().enumerate() { | |
| let trimmed = raw_line.trim(); | |
| if trimmed.is_empty() { | |
| continue; | |
| } | |
| let line_no = line_idx + 1; | |
| let ctx = format!("{source_label}:{line_no}"); | |
| let raw: RawJsonlRecord = serde_json::from_str(trimmed) | |
| .map_err(|e| format!("{ctx}: invalid JSON record: {e}"))?; | |
| match raw.record_kind.as_str() { | |
| "Header" => { | |
| if let Some(v) = raw.vendor.or(raw.cpuid_vendor.clone()) { | |
| if !v.trim().is_empty() { | |
| vendor = v.trim().to_owned(); | |
| } | |
| } | |
| if let Some(sz) = raw.arena_size { | |
| if sz == 0 { | |
| return Err(format!("{ctx}: arena_size must be > 0")); | |
| } | |
| default_arena_size = sz; | |
| } | |
| header = CorpusHeader { | |
| vendor: Some(vendor.clone()), | |
| cpuid_vendor: raw.cpuid_vendor, | |
| cpu_model: raw.cpu_model, | |
| arena_size: Some(default_arena_size), | |
| }; | |
| } | |
| "Normal" | "Trap" => { | |
| let kind = if raw.record_kind == "Normal" { | |
| ExecRecordKind::Normal | |
| } else { | |
| ExecRecordKind::Trap | |
| }; | |
| let case_id = raw | |
| .case_id | |
| .filter(|s| !s.trim().is_empty()) | |
| .ok_or_else(|| format!("{ctx}: missing case_id"))?; | |
| let body_hex = raw.body_hex.ok_or_else(|| format!("{ctx}: missing body_hex"))?; | |
| let bytes = parse_hex_bytes(&body_hex) | |
| .map_err(|e| format!("{ctx}: invalid body_hex: {e}"))?; | |
| if bytes.is_empty() { | |
| return Err(format!("{ctx}: body_hex must not be empty")); | |
| } | |
| let initial = raw.initial.ok_or_else(|| format!("{ctx}: missing initial state"))?; | |
| let base_address = raw.base_address.unwrap_or(0); | |
| if initial.rip < base_address { | |
| return Err(format!( | |
| "{ctx}: initial.rip ({}) < base_address ({base_address})", | |
| initial.rip | |
| )); | |
| } | |
| let init_rip_rel = initial.rip - base_address; | |
| if init_rip_rel >= bytes.len() as u64 { | |
| return Err(format!( | |
| "{ctx}: initial RIP offset {init_rip_rel} must be < body length {}", | |
| bytes.len() | |
| )); | |
| } | |
| let capture_boundary = raw.capture_boundary.unwrap_or(0); | |
| if capture_boundary > 0 { | |
| if capture_boundary > bytes.len() as u64 { | |
| return Err(format!( | |
| "{ctx}: capture_boundary {capture_boundary} exceeds body length {}", | |
| bytes.len() | |
| )); | |
| } | |
| if init_rip_rel >= capture_boundary { | |
| return Err(format!( | |
| "{ctx}: initial RIP offset {init_rip_rel} must be < capture_boundary \ | |
| {capture_boundary}" | |
| )); | |
| } | |
| } | |
| let arena_size = raw.arena_size.unwrap_or(default_arena_size); | |
| let arena_address = raw | |
| .arena_address | |
| .ok_or_else(|| format!("{ctx}: missing required arena_address"))?; | |
| validate_arena_range(arena_address, arena_size, &ctx)?; | |
| if kind == ExecRecordKind::Trap && arena_address == 0 { | |
| return Err(format!( | |
| "{ctx}: Trap record must specify a non-zero arena_address" | |
| )); | |
| } | |
| let initial_memory = | |
| normalize_mem_patches(&raw.initial_memory, arena_size, "initial_memory", &ctx)?; | |
| let observed_memory_diffs = normalize_mem_patches( | |
| &raw.observed_memory_diffs, | |
| arena_size, | |
| "observed_memory_diffs", | |
| &ctx, | |
| )?; | |
| let observed = | |
| match kind { | |
| ExecRecordKind::Normal => Some(raw.observed.ok_or_else(|| { | |
| format!("{ctx}: Normal record missing observed state") | |
| })?), | |
| ExecRecordKind::Trap => raw.observed, | |
| }; | |
| let program_kinds: Vec<String> = raw.program.into_iter().map(|p| p.kind).collect(); | |
| let band = classify_record_band(raw.band, &program_kinds, &bytes); | |
| let rec_vendor = | |
| raw.vendor.filter(|v| !v.trim().is_empty()).unwrap_or_else(|| vendor.clone()); | |
| let parse_sig_val = |v: serde_json::Value| match v { | |
| serde_json::Value::String(s) => s, | |
| other => other.to_string(), | |
| }; | |
| let raw_sigs: Vec<String> = [ | |
| raw.trap_signal.map(parse_sig_val), | |
| raw.trap_kind, | |
| raw.signal.map(parse_sig_val), | |
| ] | |
| .into_iter() | |
| .flatten() | |
| .map(|s| s.trim().to_owned()) | |
| .filter(|s| !s.is_empty()) | |
| .collect(); | |
| if raw_sigs.windows(2).any(|w| !w[0].eq_ignore_ascii_case(&w[1])) { | |
| return Err(format!("{ctx}: conflicting trap signal fields ({raw_sigs:?})")); | |
| } | |
| let trap_signal = raw_sigs.into_iter().next(); | |
| if let (Some(fr), Some(obs)) = (raw.fault_rip, observed.as_ref()) { | |
| if fr != obs.rip { | |
| return Err(format!( | |
| "{ctx}: conflicting fault_rip ({fr:#x}) and observed.rip ({:#x})", | |
| obs.rip | |
| )); | |
| } | |
| } | |
| records.push(ExecRecord { | |
| case_id, | |
| vendor: rec_vendor, | |
| kind, | |
| band, | |
| body_hex, | |
| bytes, | |
| base_address, | |
| arena_address, | |
| arena_size, | |
| default_byte: raw.default_byte.unwrap_or(0), | |
| capture_boundary, | |
| program_kinds, | |
| initial, | |
| observed, | |
| initial_memory, | |
| observed_memory_diffs, | |
| trap_signal, | |
| fault_rip: raw.fault_rip, | |
| }); | |
| } | |
| other => { | |
| return Err(format!("{ctx}: unsupported record_kind `{other}`")); | |
| } | |
| } | |
| } | |
| Ok(ParsedExecCorpus { source_label: source_label.to_owned(), header, records }) | |
| } | |
| /// Raw execution outcome emitted by the Lean `Anneal.ElfX86.ScalarEval` batch | |
| /// driver for one record. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| #[serde(tag = "status", rename_all = "snake_case")] | |
| pub enum LeanExecOutcome { | |
| /// `decodeStreamScalar` returned `none` (fail-closed decode backlog). | |
| DecodeFail, | |
| /// `stepScalar` returned `none` (unmodeled op or poisoned undefined flag). | |
| StepFail, | |
| /// Fuel exhausted before reaching a halt or stream boundary. | |
| OutOfFuel { fuel: usize }, | |
| /// Execution reached the end of the decoded stream or a halting `ret`. | |
| Stepped { | |
| rip_rel: u64, | |
| halted: bool, | |
| flags: u64, | |
| undef_flags: u64, | |
| regs: [u64; 16], | |
| mem: Vec<MemPatch>, | |
| oob_access: bool, | |
| }, | |
| } | |
| /// Verdict for one differential execution record. | |
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] | |
| #[serde(rename_all = "SCREAMING_SNAKE_CASE")] | |
| pub enum ExecVerdictKind { | |
| /// `Normal` record decoded, stepped, and agreed on all GPRs, defined | |
| /// status flags, non-halted `RIP`, checked arena memory bytes, and | |
| /// unchanged XMM/MXCSR vector/FP state (since `ScalarEval` models scalar | |
| /// state only). | |
| Pass, | |
| /// `Trap` record carrying an explicit symbolic memory-fault signal | |
| /// (`SIGSEGV`/`SIGBUS`/memory-fault class) and a fault-time RIP | |
| /// (`observed.rip` or `fault_rip`) whose out-of-arena memory access | |
| /// (`oob_access == true`), faulting RIP, fault-time GPRs (when present), | |
| /// and pre-fault arena memory all match `ScalarEval`. | |
| TrapPredicted, | |
| /// Fail-closed decode gap (`decodeStreamScalar = none`); reported in the | |
| /// coverage backlog rather than hidden. | |
| DecodeFail, | |
| /// Fail-closed step gap (`stepScalar = none`); reported in the coverage | |
| /// backlog rather than hidden. | |
| StepFail, | |
| /// Fuel exhausted before terminating; always fails the batch gate. | |
| OutOfFuel, | |
| /// Semantic discrepancy between `ScalarEval` and observed hardware state | |
| /// on a defined output; always fails the batch gate. | |
| Mismatch, | |
| /// Hardware trapped while `ScalarEval` stepped cleanly inside the arena | |
| /// with no out-of-arena access; always fails the batch gate. | |
| TrapMismatch, | |
| } | |
| impl ExecVerdictKind { | |
| /// Returns `true` iff this verdict is a semantic or infrastructure failure | |
| /// (independent of `--strict-coverage`). | |
| pub const fn is_hard_failure(self) -> bool { | |
| matches!(self, Self::Mismatch | Self::TrapMismatch | Self::OutOfFuel) | |
| } | |
| /// Returns `true` iff this verdict is a fail-closed coverage backlog item. | |
| pub const fn is_coverage_gap(self) -> bool { | |
| matches!(self, Self::DecodeFail | Self::StepFail) | |
| } | |
| } | |
| /// Per-record differential execution report. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct ExecCaseReport { | |
| pub case_id: String, | |
| pub vendor: String, | |
| pub kind: ExecRecordKind, | |
| pub band: ExecBand, | |
| pub body_hex: String, | |
| pub program_kinds: Vec<String>, | |
| pub verdict: ExecVerdictKind, | |
| pub undef_flags_mask: u64, | |
| pub halted: bool, | |
| pub memory_checked: bool, | |
| pub memory_mutated: bool, | |
| pub differences: Vec<String>, | |
| } | |
| /// Per-band summary tally. | |
| #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct BandSummary { | |
| pub total: usize, | |
| pub passed: usize, | |
| pub trap_predicted: usize, | |
| pub decode_fail: usize, | |
| pub step_fail: usize, | |
| pub out_of_fuel: usize, | |
| pub mismatch: usize, | |
| pub trap_mismatch: usize, | |
| pub undef_flags_masked: usize, | |
| pub memory_checked: usize, | |
| pub memory_mutated: usize, | |
| } | |
| /// Cross-vendor defined-output disagreement defect (a soundness alarm when | |
| /// two hardware vendors disagree on an output that `ScalarEval` marked | |
| /// defined). | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct CrossVendorDefect { | |
| pub case_id: String, | |
| pub vendor_a: String, | |
| pub vendor_b: String, | |
| pub detail: String, | |
| } | |
| /// Summary of cross-vendor consistency across multi-vendor corpora. | |
| #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct CrossVendorSummary { | |
| /// Identical-input multi-vendor groups stepped by `ScalarEval` and audited | |
| /// against its defined/undefined flag metadata. | |
| pub shared_cases: usize, | |
| /// Identical-input multi-vendor groups skipped because `ScalarEval` did | |
| /// not step them (e.g. `DecodeFail`, `StepFail`, or `OutOfFuel`). | |
| pub shared_cases_unaudited: usize, | |
| pub undefined_flag_diffs: usize, | |
| pub defined_defects: Vec<CrossVendorDefect>, | |
| } | |
| /// Complete JSON report emitted by `anneal-isa-oracle exec`. | |
| #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | |
| pub struct ExecBatchReport { | |
| pub schema: String, | |
| pub passed: bool, | |
| pub strict_coverage: bool, | |
| pub total_records: usize, | |
| pub total_passed: usize, | |
| pub total_trap_predicted: usize, | |
| pub total_decode_fail: usize, | |
| pub total_step_fail: usize, | |
| pub total_out_of_fuel: usize, | |
| pub total_mismatch: usize, | |
| pub total_trap_mismatch: usize, | |
| pub bands: BTreeMap<ExecBand, BandSummary>, | |
| pub cross_vendor: CrossVendorSummary, | |
| pub cases: Vec<ExecCaseReport>, | |
| } | |
| /// Returns `true` iff `trap_signal` is present and names a symbolic | |
| /// memory-fault signal class (`SIGSEGV`/`SIGBUS` or memory/page fault label) | |
| /// that an out-of-arena memory access predicts. Missing signals and raw | |
| /// numeric signal codes (such as `7` or `10`, which differ across Linux and | |
| /// macOS) fail closed and return `false`. | |
| fn is_memory_fault_signal(sig: Option<&str>) -> bool { | |
| let Some(raw) = sig.map(str::trim).filter(|s| !s.is_empty()) else { | |
| return false; | |
| }; | |
| let lower = raw.to_ascii_lowercase(); | |
| matches!( | |
| lower.as_str(), | |
| "sigsegv" | "segv" | "sigbus" | "bus" | "mem_fault" | "memory_fault" | "page_fault" | "oob" | |
| ) | |
| } | |
| fn compare_defined_flags( | |
| calc_flags_raw: u64, | |
| undef_flags_raw: u64, | |
| exp_flags_raw: u64, | |
| prefix: &str, | |
| diffs: &mut Vec<String>, | |
| ) { | |
| let calc_flags = calc_flags_raw & ARITH_FLAGS_MASK; | |
| let exp_flags = exp_flags_raw & ARITH_FLAGS_MASK; | |
| let undef = undef_flags_raw & ARITH_FLAGS_MASK; | |
| for &(name, bit) in &FLAG_BITS { | |
| let mask = 1u64 << bit; | |
| if (undef & mask) == 0 && ((calc_flags & mask) != (exp_flags & mask)) { | |
| diffs.push(format!( | |
| "{prefix}{name}(calc={},exp={})", | |
| (calc_flags & mask) != 0, | |
| (exp_flags & mask) != 0 | |
| )); | |
| } | |
| } | |
| } | |
| fn compare_arena_memory(record: &ExecRecord, mem: &[MemPatch], diffs: &mut Vec<String>) { | |
| let mut obs_map = BTreeMap::new(); | |
| for p in &record.observed_memory_diffs { | |
| obs_map.insert(p.offset, p.value); | |
| } | |
| let mut calc_map = BTreeMap::new(); | |
| for p in mem { | |
| calc_map.insert(p.offset, p.value); | |
| } | |
| let mut offsets = BTreeSet::new(); | |
| for p in &record.initial_memory { | |
| offsets.insert(p.offset); | |
| } | |
| for p in &record.observed_memory_diffs { | |
| offsets.insert(p.offset); | |
| } | |
| for p in mem { | |
| offsets.insert(p.offset); | |
| } | |
| for off in offsets { | |
| let calc_b = calc_map.get(&off).copied().unwrap_or(record.default_byte); | |
| let exp_b = obs_map.get(&off).copied().unwrap_or(record.default_byte); | |
| if calc_b != exp_b { | |
| diffs.push(format!("mem@{off}(calc={calc_b:#04x},exp={exp_b:#04x})")); | |
| } | |
| } | |
| } | |
| /// Compare one [`ExecRecord`] against its [`LeanExecOutcome`]. | |
| pub fn evaluate_exec_record(record: &ExecRecord, outcome: &LeanExecOutcome) -> ExecCaseReport { | |
| let init_map = canonical_arena_map(&record.initial_memory, record.default_byte); | |
| let obs_map_norm = canonical_arena_map(&record.observed_memory_diffs, record.default_byte); | |
| let memory_checked = | |
| !record.initial_memory.is_empty() || !record.observed_memory_diffs.is_empty(); | |
| let memory_mutated = init_map != obs_map_norm; | |
| let mut report = ExecCaseReport { | |
| case_id: record.case_id.clone(), | |
| vendor: record.vendor.clone(), | |
| kind: record.kind, | |
| band: record.band, | |
| body_hex: record.body_hex.clone(), | |
| program_kinds: record.program_kinds.clone(), | |
| verdict: ExecVerdictKind::DecodeFail, | |
| undef_flags_mask: 0, | |
| halted: false, | |
| memory_checked, | |
| memory_mutated, | |
| differences: Vec::new(), | |
| }; | |
| match outcome { | |
| LeanExecOutcome::DecodeFail => { | |
| report.verdict = ExecVerdictKind::DecodeFail; | |
| } | |
| LeanExecOutcome::StepFail => { | |
| // Unmodeled ops or poisoned undefined-flag reads do not predict a | |
| // hardware fault; report them honestly as coverage backlog on both | |
| // Normal and Trap records so --strict-coverage catches them. | |
| report.verdict = ExecVerdictKind::StepFail; | |
| } | |
| LeanExecOutcome::OutOfFuel { fuel } => { | |
| report.verdict = ExecVerdictKind::OutOfFuel; | |
| report.differences.push(format!("ScalarEval exhausted fuel ({fuel} steps)")); | |
| } | |
| LeanExecOutcome::Stepped { rip_rel, halted, flags, undef_flags, regs, mem, oob_access } => { | |
| report.undef_flags_mask = *undef_flags & ARITH_FLAGS_MASK; | |
| report.halted = *halted; | |
| match record.kind { | |
| ExecRecordKind::Trap => { | |
| if *oob_access && is_memory_fault_signal(record.trap_signal.as_deref()) { | |
| let mut fault_diffs = Vec::new(); | |
| match record.observed.as_ref().map(|o| o.rip).or(record.fault_rip) { | |
| None => { | |
| fault_diffs.push( | |
| "Trap record missing observed.rip and fault_rip; cannot verify \ | |
| hardware fault location" | |
| .to_owned(), | |
| ); | |
| } | |
| Some(expected_rip) => match record.base_address.checked_add(*rip_rel) { | |
| Some(calc_abs) if calc_abs == expected_rip => {} | |
| Some(calc_abs) => { | |
| fault_diffs.push(format!( | |
| "fault_rip(calc={calc_abs:#x},exp={expected_rip:#x})" | |
| )); | |
| } | |
| None => { | |
| fault_diffs.push(format!( | |
| "fault_rip_overflow(base={:#x},rel={rip_rel:#x})", | |
| record.base_address | |
| )); | |
| } | |
| }, | |
| } | |
| if let Some(obs) = &record.observed { | |
| for (idx, (&calc, &exp)) in regs.iter().zip(obs.regs.iter()).enumerate() | |
| { | |
| if calc != exp { | |
| fault_diffs | |
| .push(format!("fault_r{idx}(calc={calc:#x},exp={exp:#x})")); | |
| } | |
| } | |
| compare_defined_flags( | |
| *flags, | |
| *undef_flags, | |
| obs.arithmetic_flags, | |
| "fault_", | |
| &mut fault_diffs, | |
| ); | |
| if record.initial.xmm != obs.xmm { | |
| fault_diffs.push( | |
| "xmm(observed XMM state differs from initial; ScalarEval does \ | |
| not model vector registers)" | |
| .to_owned(), | |
| ); | |
| } | |
| if record.initial.mxcsr != obs.mxcsr { | |
| fault_diffs.push(format!( | |
| "mxcsr(calc={:?},exp={:?}; ScalarEval does not model MXCSR)", | |
| record.initial.mxcsr, obs.mxcsr | |
| )); | |
| } | |
| } | |
| compare_arena_memory(record, mem, &mut fault_diffs); | |
| if fault_diffs.is_empty() { | |
| report.verdict = ExecVerdictKind::TrapPredicted; | |
| } else { | |
| report.verdict = ExecVerdictKind::TrapMismatch; | |
| report.differences = fault_diffs; | |
| } | |
| } else if *oob_access { | |
| report.verdict = ExecVerdictKind::TrapMismatch; | |
| let sig = record.trap_signal.as_deref().unwrap_or("<missing>"); | |
| report.differences.push(format!( | |
| "hardware trapped with missing or non-memory signal ({sig}) which an \ | |
| out-of-arena memory access does not predict" | |
| )); | |
| } else { | |
| report.verdict = ExecVerdictKind::TrapMismatch; | |
| let sig = record.trap_signal.as_deref().unwrap_or("trap"); | |
| report.differences.push(format!( | |
| "hardware trapped ({sig}) while ScalarEval completed in-arena \ | |
| at rip_rel={rip_rel}" | |
| )); | |
| } | |
| } | |
| ExecRecordKind::Normal => { | |
| let Some(obs) = &record.observed else { | |
| report.verdict = ExecVerdictKind::Mismatch; | |
| report.differences.push("Normal record missing observed state".to_owned()); | |
| return report; | |
| }; | |
| let mut diffs = Vec::new(); | |
| for (idx, (&calc, &exp)) in regs.iter().zip(obs.regs.iter()).enumerate() { | |
| if calc != exp { | |
| diffs.push(format!("r{idx}(calc={calc:#x},exp={exp:#x})")); | |
| } | |
| } | |
| compare_defined_flags( | |
| *flags, | |
| *undef_flags, | |
| obs.arithmetic_flags, | |
| "", | |
| &mut diffs, | |
| ); | |
| if !halted { | |
| match record.base_address.checked_add(*rip_rel) { | |
| Some(calc_abs) if calc_abs == obs.rip => {} | |
| Some(calc_abs) => { | |
| diffs.push(format!("rip(calc={calc_abs:#x},exp={:#x})", obs.rip)); | |
| } | |
| None => { | |
| diffs.push(format!( | |
| "rip_overflow(base={:#x},rel={rip_rel:#x})", | |
| record.base_address | |
| )); | |
| } | |
| } | |
| } | |
| if *oob_access { | |
| diffs.push("mem_oob(access outside replayed arena)".to_owned()); | |
| } | |
| compare_arena_memory(record, mem, &mut diffs); | |
| // ScalarEval models scalar GPR/flags/memory state only and | |
| // leaves vector/FP state unmodified. Fail closed if the | |
| // observed trace reports any XMM or MXCSR change rather | |
| // than emitting a false Pass on misdecoded vector ops. | |
| if record.initial.xmm != obs.xmm { | |
| diffs.push( | |
| "xmm(observed XMM state differs from initial; ScalarEval does not \ | |
| model vector registers)" | |
| .to_owned(), | |
| ); | |
| } | |
| if record.initial.mxcsr != obs.mxcsr { | |
| diffs.push(format!( | |
| "mxcsr(calc={:?},exp={:?}; ScalarEval does not model MXCSR)", | |
| record.initial.mxcsr, obs.mxcsr | |
| )); | |
| } | |
| if diffs.is_empty() { | |
| report.verdict = ExecVerdictKind::Pass; | |
| } else { | |
| report.verdict = ExecVerdictKind::Mismatch; | |
| report.differences = diffs; | |
| } | |
| } | |
| } | |
| } | |
| } | |
| report | |
| } | |
| #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] | |
| struct CrossVendorInputKey { | |
| case_id: String, | |
| bytes: Vec<u8>, | |
| base_address: u64, | |
| arena_address: u64, | |
| arena_size: usize, | |
| default_byte: u8, | |
| capture_boundary: u64, | |
| initial: ExecStateSnapshot, | |
| initial_memory: BTreeMap<usize, u8>, | |
| } | |
| /// Audit cross-vendor consistency across all replayed `Normal` records sharing | |
| /// the exact same input pre-state (`case_id`, `bytes`, addresses, `initial`, | |
| /// and canonical `initial_memory`). | |
| /// | |
| /// Fails closed if `records.len() != outcomes.len()`. | |
| pub fn audit_cross_vendor( | |
| records: &[ExecRecord], | |
| outcomes: &[LeanExecOutcome], | |
| ) -> Result<CrossVendorSummary, String> { | |
| if records.len() != outcomes.len() { | |
| return Err(format!( | |
| "record/outcome length mismatch in audit_cross_vendor: {} records vs {} outcomes", | |
| records.len(), | |
| outcomes.len() | |
| )); | |
| } | |
| let mut by_input: BTreeMap<CrossVendorInputKey, Vec<(&ExecRecord, &LeanExecOutcome)>> = | |
| BTreeMap::new(); | |
| for (rec, out) in records.iter().zip(outcomes.iter()) { | |
| if rec.kind != ExecRecordKind::Normal || rec.observed.is_none() { | |
| continue; | |
| } | |
| let key = CrossVendorInputKey { | |
| case_id: rec.case_id.clone(), | |
| bytes: rec.bytes.clone(), | |
| base_address: rec.base_address, | |
| arena_address: rec.arena_address, | |
| arena_size: rec.arena_size, | |
| default_byte: rec.default_byte, | |
| capture_boundary: rec.capture_boundary, | |
| initial: rec.initial.clone(), | |
| initial_memory: canonical_arena_map(&rec.initial_memory, rec.default_byte), | |
| }; | |
| by_input.entry(key).or_default().push((rec, out)); | |
| } | |
| let mut summary = CrossVendorSummary::default(); | |
| for (key, group) in by_input { | |
| // Pick one canonical representative per distinct vendor name first so | |
| // multi-vendor groups that the model did not step are explicitly | |
| // counted in `shared_cases_unaudited` rather than silently dropped. | |
| let mut by_vendor: BTreeMap<&str, &ExecRecord> = BTreeMap::new(); | |
| for &(rec, _) in &group { | |
| by_vendor.entry(rec.vendor.as_str()).or_insert(rec); | |
| } | |
| if by_vendor.len() < 2 { | |
| continue; | |
| } | |
| // Take the model's undefined-flag mask and halt bit from any Stepped | |
| // outcome in this identical-input group. | |
| let Some((undef_mask, halted)) = group.iter().find_map(|(_, out)| match out { | |
| LeanExecOutcome::Stepped { undef_flags, halted, .. } => { | |
| Some((*undef_flags & ARITH_FLAGS_MASK, *halted)) | |
| } | |
| _ => None, | |
| }) else { | |
| summary.shared_cases_unaudited += 1; | |
| continue; | |
| }; | |
| summary.shared_cases += 1; | |
| let vendors: Vec<(&str, &ExecRecord)> = by_vendor.into_iter().collect(); | |
| let mut counted_undef_diff = false; | |
| for i in 0..vendors.len() { | |
| let (vendor_a, rec_a) = vendors[i]; | |
| let Some(obs_a) = &rec_a.observed else { | |
| continue; | |
| }; | |
| let mem_a = canonical_arena_map(&rec_a.observed_memory_diffs, rec_a.default_byte); | |
| for &(vendor_b, rec_b) in &vendors[i + 1..] { | |
| let Some(obs_b) = &rec_b.observed else { | |
| continue; | |
| }; | |
| let mem_b = canonical_arena_map(&rec_b.observed_memory_diffs, rec_b.default_byte); | |
| let flags_a = obs_a.arithmetic_flags & ARITH_FLAGS_MASK; | |
| let flags_b = obs_b.arithmetic_flags & ARITH_FLAGS_MASK; | |
| let flag_xor = flags_a ^ flags_b; | |
| let defined_flag_xor = flag_xor & !undef_mask; | |
| let undef_flag_xor = flag_xor & undef_mask; | |
| if undef_flag_xor != 0 && !counted_undef_diff { | |
| summary.undefined_flag_diffs += 1; | |
| counted_undef_diff = true; | |
| } | |
| let mut defects = Vec::new(); | |
| if obs_a.regs != obs_b.regs { | |
| defects.push("GPR post-state differs across vendors".to_owned()); | |
| } | |
| if defined_flag_xor != 0 { | |
| defects.push(format!( | |
| "defined arithmetic flags differ across vendors \ | |
| (xor={defined_flag_xor:#x})" | |
| )); | |
| } | |
| if !halted && obs_a.rip != obs_b.rip { | |
| defects.push(format!( | |
| "RIP differs across vendors ({:#x} vs {:#x})", | |
| obs_a.rip, obs_b.rip | |
| )); | |
| } | |
| if mem_a != mem_b { | |
| defects.push("observed memory diffs differ across vendors".to_owned()); | |
| } | |
| if obs_a.xmm != obs_b.xmm { | |
| defects.push("observed XMM state differs across vendors".to_owned()); | |
| } | |
| if obs_a.mxcsr != obs_b.mxcsr { | |
| defects.push("observed MXCSR differs across vendors".to_owned()); | |
| } | |
| if !defects.is_empty() { | |
| summary.defined_defects.push(CrossVendorDefect { | |
| case_id: key.case_id.clone(), | |
| vendor_a: vendor_a.to_owned(), | |
| vendor_b: vendor_b.to_owned(), | |
| detail: defects.join("; "), | |
| }); | |
| } | |
| } | |
| } | |
| } | |
| Ok(summary) | |
| } | |
| /// Assemble an [`ExecBatchReport`] from records, Lean outcomes, and policy. | |
| /// | |
| /// Fails closed if `records.len() != outcomes.len()`. | |
| pub fn assemble_exec_report( | |
| records: &[ExecRecord], | |
| outcomes: &[LeanExecOutcome], | |
| strict_coverage: bool, | |
| ) -> Result<ExecBatchReport, String> { | |
| if records.len() != outcomes.len() { | |
| return Err(format!( | |
| "record/outcome length mismatch in assemble_exec_report: {} records vs {} outcomes", | |
| records.len(), | |
| outcomes.len() | |
| )); | |
| } | |
| let mut bands = BTreeMap::new(); | |
| for band in ExecBand::ALL { | |
| bands.insert(band, BandSummary::default()); | |
| } | |
| let mut cases = Vec::with_capacity(records.len()); | |
| let mut total_passed = 0usize; | |
| let mut total_trap_predicted = 0usize; | |
| let mut total_decode_fail = 0usize; | |
| let mut total_step_fail = 0usize; | |
| let mut total_out_of_fuel = 0usize; | |
| let mut total_mismatch = 0usize; | |
| let mut total_trap_mismatch = 0usize; | |
| for (rec, out) in records.iter().zip(outcomes.iter()) { | |
| let rep = evaluate_exec_record(rec, out); | |
| let b = bands.entry(rep.band).or_default(); | |
| b.total += 1; | |
| if rep.undef_flags_mask != 0 { | |
| b.undef_flags_masked += 1; | |
| } | |
| if rep.memory_checked { | |
| b.memory_checked += 1; | |
| } | |
| if rep.memory_mutated { | |
| b.memory_mutated += 1; | |
| } | |
| match rep.verdict { | |
| ExecVerdictKind::Pass => { | |
| total_passed += 1; | |
| b.passed += 1; | |
| } | |
| ExecVerdictKind::TrapPredicted => { | |
| total_trap_predicted += 1; | |
| b.trap_predicted += 1; | |
| } | |
| ExecVerdictKind::DecodeFail => { | |
| total_decode_fail += 1; | |
| b.decode_fail += 1; | |
| } | |
| ExecVerdictKind::StepFail => { | |
| total_step_fail += 1; | |
| b.step_fail += 1; | |
| } | |
| ExecVerdictKind::OutOfFuel => { | |
| total_out_of_fuel += 1; | |
| b.out_of_fuel += 1; | |
| } | |
| ExecVerdictKind::Mismatch => { | |
| total_mismatch += 1; | |
| b.mismatch += 1; | |
| } | |
| ExecVerdictKind::TrapMismatch => { | |
| total_trap_mismatch += 1; | |
| b.trap_mismatch += 1; | |
| } | |
| } | |
| cases.push(rep); | |
| } | |
| let cross_vendor = audit_cross_vendor(records, outcomes)?; | |
| let hard_failures = total_mismatch | |
| + total_trap_mismatch | |
| + total_out_of_fuel | |
| + cross_vendor.defined_defects.len(); | |
| let coverage_gaps = total_decode_fail + total_step_fail; | |
| let verified = total_passed + total_trap_predicted; | |
| let passed = verified > 0 && hard_failures == 0 && (!strict_coverage || coverage_gaps == 0); | |
| Ok(ExecBatchReport { | |
| schema: EXEC_REPORT_SCHEMA.to_owned(), | |
| passed, | |
| strict_coverage, | |
| total_records: records.len(), | |
| total_passed, | |
| total_trap_predicted, | |
| total_decode_fail, | |
| total_step_fail, | |
| total_out_of_fuel, | |
| total_mismatch, | |
| total_trap_mismatch, | |
| bands, | |
| cross_vendor, | |
| cases, | |
| }) | |
| } | |
| /// Encode a Lean list literal as balanced 32-element chunks joined with `++`, | |
| /// keeping elaborator AST depth `O(log N)` so dense arena snapshots never | |
| /// overflow Lean's default `maxRecDepth` (512). | |
| fn encode_lean_list_balanced(items: &[String]) -> String { | |
| fn join_tree(leaves: &[String]) -> String { | |
| match leaves { | |
| [] => "[]".to_owned(), | |
| [only] => only.clone(), | |
| _ => { | |
| let mid = leaves.len() / 2; | |
| format!("({} ++ {})", join_tree(&leaves[..mid]), join_tree(&leaves[mid..])) | |
| } | |
| } | |
| } | |
| if items.is_empty() { | |
| return "[]".to_owned(); | |
| } | |
| let leaves: Vec<String> = | |
| items.chunks(32).map(|chunk| format!("[{}]", chunk.join(", "))).collect(); | |
| join_tree(&leaves) | |
| } | |
| /// Render a deterministic Lean 4 `--stdin` batch script that runs | |
| /// `Anneal.ElfX86.ScalarEval` over `records` and emits `EXEC|<idx>|...` lines. | |
| pub fn render_lean_exec_script(records: &[ExecRecord], fuel: usize) -> Result<String, String> { | |
| if fuel == 0 { | |
| return Err("fuel must be > 0".to_owned()); | |
| } | |
| let mut script = String::new(); | |
| script.push_str("import Init\n"); | |
| script.push_str("import Anneal.ElfX86.ScalarEval\n"); | |
| script.push_str("open Anneal.ElfX86\n\n"); | |
| script.push_str(LEAN_EXEC_PRELUDE); | |
| script.push('\n'); | |
| script.push_str("private def execQueries : List ExecQuery := [\n"); | |
| for (idx, rec) in records.iter().enumerate() { | |
| let rec_ctx = format!("record `{}`", rec.case_id); | |
| validate_arena_range(rec.arena_address, rec.arena_size, &rec_ctx)?; | |
| if rec.bytes.is_empty() { | |
| return Err(format!("{rec_ctx}: bytes must not be empty")); | |
| } | |
| let init_rip_rel = rec | |
| .initial | |
| .rip | |
| .checked_sub(rec.base_address) | |
| .ok_or_else(|| format!("{rec_ctx} has initial.rip < base_address"))?; | |
| if init_rip_rel >= rec.bytes.len() as u64 { | |
| return Err(format!( | |
| "{rec_ctx} has initial RIP offset {init_rip_rel} >= body length {}", | |
| rec.bytes.len() | |
| )); | |
| } | |
| let active_bytes: &[u8] = if rec.capture_boundary > 0 { | |
| let bound = usize::try_from(rec.capture_boundary).map_err(|_| { | |
| format!("{rec_ctx} capture_boundary {} overflows usize", rec.capture_boundary) | |
| })?; | |
| if bound > rec.bytes.len() { | |
| return Err(format!( | |
| "{rec_ctx} capture_boundary {bound} exceeds body length {}", | |
| rec.bytes.len() | |
| )); | |
| } | |
| if init_rip_rel >= rec.capture_boundary { | |
| return Err(format!( | |
| "{rec_ctx} initial RIP offset {init_rip_rel} >= capture_boundary {}", | |
| rec.capture_boundary | |
| )); | |
| } | |
| &rec.bytes[..bound] | |
| } else { | |
| &rec.bytes | |
| }; | |
| let regs_lean: Vec<String> = rec.initial.regs.iter().map(|r| r.to_string()).collect(); | |
| let init_mem_lean: Vec<String> = rec | |
| .initial_memory | |
| .iter() | |
| .map(|p| format!("({}, 0x{:02X})", p.offset, p.value)) | |
| .collect(); | |
| let mut watch_set = BTreeSet::new(); | |
| for p in &rec.initial_memory { | |
| watch_set.insert(p.offset); | |
| } | |
| for p in &rec.observed_memory_diffs { | |
| watch_set.insert(p.offset); | |
| } | |
| let watch_lean: Vec<String> = watch_set.iter().map(|o| o.to_string()).collect(); | |
| let comma = if idx + 1 == records.len() { "" } else { "," }; | |
| let _ = writeln!( | |
| script, | |
| " {{ idx := {idx}, bytes := {}, arenaAddr := {}, arenaSize := {}, \ | |
| defaultByte := 0x{:02X}, initRipRel := {init_rip_rel}, \ | |
| captureBoundary := {}, initRegs := [{}], initFlags := {}, \ | |
| initMem := {}, watchOffsets := {}, fuel := {fuel} }}{comma}", | |
| encode_lean_byte_list(active_bytes), | |
| rec.arena_address, | |
| rec.arena_size, | |
| rec.default_byte, | |
| rec.capture_boundary, | |
| regs_lean.join(", "), | |
| rec.initial.arithmetic_flags & ARITH_FLAGS_MASK, | |
| encode_lean_list_balanced(&init_mem_lean), | |
| encode_lean_list_balanced(&watch_lean), | |
| ); | |
| } | |
| script.push_str("]\n\n"); | |
| script.push_str("#eval do\n for q in execQueries do\n IO.println (evalExecQuery q)\n"); | |
| Ok(script) | |
| } | |
| /// Parse `EXEC|<idx>|...` wire lines emitted by [`render_lean_exec_script`]. | |
| pub fn parse_lean_exec_output( | |
| stdout: &str, | |
| expected_count: usize, | |
| ) -> Result<Vec<LeanExecOutcome>, String> { | |
| let mut parsed: BTreeMap<usize, LeanExecOutcome> = BTreeMap::new(); | |
| for raw_line in stdout.lines() { | |
| let trimmed = raw_line.trim(); | |
| let Some(rest) = trimmed.strip_prefix("EXEC|") else { | |
| continue; | |
| }; | |
| let Some((idx_str, payload)) = rest.split_once('|') else { | |
| return Err(format!("malformed EXEC line: `{trimmed}`")); | |
| }; | |
| let idx = | |
| idx_str.parse::<usize>().map_err(|e| format!("invalid EXEC index `{idx_str}`: {e}"))?; | |
| let outcome = if payload == "DECODE_FAIL" { | |
| LeanExecOutcome::DecodeFail | |
| } else if payload == "STEP_FAIL" { | |
| LeanExecOutcome::StepFail | |
| } else if let Some(f_str) = payload.strip_prefix("OUT_OF_FUEL|") { | |
| let fuel = f_str | |
| .parse::<usize>() | |
| .map_err(|e| format!("invalid OUT_OF_FUEL value `{f_str}`: {e}"))?; | |
| LeanExecOutcome::OutOfFuel { fuel } | |
| } else if let Some(body) = payload.strip_prefix("OK|") { | |
| parse_stepped_payload(body)? | |
| } else { | |
| return Err(format!("unknown EXEC payload `{payload}` for index {idx}")); | |
| }; | |
| if parsed.insert(idx, outcome).is_some() { | |
| return Err(format!("duplicate EXEC result for index {idx}")); | |
| } | |
| } | |
| let mut out = Vec::with_capacity(expected_count); | |
| for idx in 0..expected_count { | |
| let outcome = parsed | |
| .remove(&idx) | |
| .ok_or_else(|| format!("Lean exec output missing result for index {idx}"))?; | |
| out.push(outcome); | |
| } | |
| if !parsed.is_empty() { | |
| return Err(format!( | |
| "Lean exec output contained unexpected extra indices: {:?}", | |
| parsed.keys().collect::<Vec<_>>() | |
| )); | |
| } | |
| Ok(out) | |
| } | |
| fn parse_stepped_payload(body: &str) -> Result<LeanExecOutcome, String> { | |
| // Format: | |
| // rip=<n>|halted=<0|1>|flags=<n>|undef=<n>|oob=<0|1>|regs=<csv>|mem=<csv> | |
| let mut fields = BTreeMap::new(); | |
| for part in body.split('|') { | |
| let Some((k, v)) = part.split_once('=') else { | |
| return Err(format!("malformed EXEC OK field `{part}`")); | |
| }; | |
| fields.insert(k, v); | |
| } | |
| let get = |k: &str| { | |
| fields.get(k).copied().ok_or_else(|| format!("missing `{k}` field in EXEC OK payload")) | |
| }; | |
| let rip_rel = | |
| get("rip")?.parse::<u64>().map_err(|e| format!("invalid rip in EXEC OK payload: {e}"))?; | |
| let halted = match get("halted")? { | |
| "1" | "true" => true, | |
| "0" | "false" => false, | |
| other => return Err(format!("invalid halted value `{other}`")), | |
| }; | |
| let flags = get("flags")? | |
| .parse::<u64>() | |
| .map_err(|e| format!("invalid flags in EXEC OK payload: {e}"))?; | |
| let undef_flags = get("undef")? | |
| .parse::<u64>() | |
| .map_err(|e| format!("invalid undef in EXEC OK payload: {e}"))?; | |
| let oob_access = match get("oob")? { | |
| "1" | "true" => true, | |
| "0" | "false" => false, | |
| other => return Err(format!("invalid oob value `{other}`")), | |
| }; | |
| let regs_raw: Vec<&str> = get("regs")?.split(',').collect(); | |
| if regs_raw.len() != 16 { | |
| return Err(format!("expected 16 GPRs in EXEC OK payload, got {}", regs_raw.len())); | |
| } | |
| let mut regs = [0u64; 16]; | |
| for (slot, tok) in regs.iter_mut().zip(regs_raw.iter()) { | |
| *slot = tok.parse::<u64>().map_err(|e| format!("invalid GPR value `{tok}`: {e}"))?; | |
| } | |
| let mem_str = get("mem")?; | |
| let mut mem = Vec::new(); | |
| if !mem_str.is_empty() && mem_str != "-" { | |
| for item in mem_str.split(',') { | |
| let Some((off_s, val_s)) = item.split_once(':') else { | |
| return Err(format!("malformed mem entry `{item}`")); | |
| }; | |
| let offset = | |
| off_s.parse::<usize>().map_err(|e| format!("invalid mem offset `{off_s}`: {e}"))?; | |
| let value = | |
| val_s.parse::<u8>().map_err(|e| format!("invalid mem byte `{val_s}`: {e}"))?; | |
| mem.push(MemPatch { offset, value }); | |
| } | |
| } | |
| Ok(LeanExecOutcome::Stepped { rip_rel, halted, flags, undef_flags, regs, mem, oob_access }) | |
| } | |
| /// Run `Anneal.ElfX86.ScalarEval` in batches against `records` via | |
| /// `lean --stdin`. | |
| pub fn run_lean_exec_batch( | |
| lean_bin: &str, | |
| olean_dir: Option<&Path>, | |
| records: &[ExecRecord], | |
| fuel: usize, | |
| batch_size: usize, | |
| ) -> Result<Vec<LeanExecOutcome>, String> { | |
| if records.is_empty() { | |
| return Ok(Vec::new()); | |
| } | |
| if batch_size == 0 { | |
| return Err("batch_size must be > 0".to_owned()); | |
| } | |
| let mut all_outcomes = Vec::with_capacity(records.len()); | |
| for chunk in records.chunks(batch_size) { | |
| let script = render_lean_exec_script(chunk, fuel)?; | |
| let mut cmd = Command::new(lean_bin); | |
| cmd.arg("--stdin").stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); | |
| if let Some(dir) = olean_dir { | |
| let mut lean_path = dir.as_os_str().to_os_string(); | |
| if let Some(existing) = std::env::var_os("LEAN_PATH") { | |
| if !existing.is_empty() { | |
| lean_path.push(":"); | |
| lean_path.push(existing); | |
| } | |
| } | |
| cmd.env("LEAN_PATH", lean_path); | |
| } | |
| let mut child = cmd.spawn().map_err(|e| format!("failed to spawn `{lean_bin}`: {e}"))?; | |
| { | |
| let mut stdin = | |
| child.stdin.take().ok_or_else(|| "failed to open lean stdin".to_owned())?; | |
| stdin | |
| .write_all(script.as_bytes()) | |
| .map_err(|e| format!("failed to write lean stdin: {e}"))?; | |
| } | |
| let out = child | |
| .wait_with_output() | |
| .map_err(|e| format!("failed waiting for `{lean_bin}`: {e}"))?; | |
| if !out.status.success() { | |
| let stdout = String::from_utf8_lossy(&out.stdout); | |
| let stderr = String::from_utf8_lossy(&out.stderr); | |
| return Err(format!( | |
| "`{lean_bin}` exec batch failed (status {}):\nstdout: {}\nstderr: {}", | |
| out.status, | |
| stdout.trim(), | |
| stderr.trim() | |
| )); | |
| } | |
| let stdout = String::from_utf8_lossy(&out.stdout); | |
| let chunk_outcomes = parse_lean_exec_output(&stdout, chunk.len())?; | |
| all_outcomes.extend(chunk_outcomes); | |
| } | |
| Ok(all_outcomes) | |
| } | |
| /// Built-in clean-room 3-band synthetic execution corpus for offline | |
| /// `--self-test` verification of `anneal-isa-oracle exec`. | |
| pub fn default_exec_corpus() -> Vec<ExecRecord> { | |
| let base = 0x40_0000u64; | |
| let arena = 0x70_0000u64; | |
| let empty_regs = [0u64; 16]; | |
| // Band 1 (ScalarGpr): `add rax, rbx` (48 01 D8): 19 + 23 = 42. | |
| let mut r_add_in = empty_regs; | |
| r_add_in[0] = 19; | |
| r_add_in[3] = 23; | |
| let mut r_add_out = r_add_in; | |
| r_add_out[0] = 42; | |
| // 0x13 + 0x17 = 0x2a (popcount 3 -> PF=0; 3+7=10 < 16 -> AF=0; | |
| // CF/ZF/SF/OF=0). | |
| let add_rec = ExecRecord { | |
| case_id: "self_b1_add_rax_rbx".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Normal, | |
| band: ExecBand::ScalarGpr, | |
| body_hex: "4801d8".to_owned(), | |
| bytes: vec![0x48, 0x01, 0xD8], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0, | |
| capture_boundary: 3, | |
| program_kinds: vec!["Add".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_add_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_add_out, | |
| rip: base + 3, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }), | |
| initial_memory: Vec::new(), | |
| observed_memory_diffs: Vec::new(), | |
| trap_signal: None, | |
| fault_rip: None, | |
| }; | |
| // Band 1 (ScalarGpr): `shl eax, 2` (C1 E0 02) on 1 -> 4; OF & AF are | |
| // architecturally undefined and must be masked out (set OF=1 in observed | |
| // to prove undefined-flag masking works). | |
| let mut r_shl_in = empty_regs; | |
| r_shl_in[0] = 1; | |
| let mut r_shl_out = empty_regs; | |
| r_shl_out[0] = 4; | |
| let shl_rec = ExecRecord { | |
| case_id: "self_b1_shl_eax_2_undef_of".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Normal, | |
| band: ExecBand::ScalarGpr, | |
| body_hex: "c1e002".to_owned(), | |
| bytes: vec![0xC1, 0xE0, 0x02], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0, | |
| capture_boundary: 3, | |
| program_kinds: vec!["Shl".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_shl_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_shl_out, | |
| rip: base + 3, | |
| // 4 = 0b100 -> PF=0, ZF=0, SF=0, CF=0; intentionally flip OF (2048) | |
| // and AF (16) which ScalarEval marks undefined for shift count 2. | |
| arithmetic_flags: (1 << 11) | (1 << 4), | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }), | |
| initial_memory: Vec::new(), | |
| observed_memory_diffs: Vec::new(), | |
| trap_signal: None, | |
| fault_rip: None, | |
| }; | |
| // Band 1 (ScalarGpr): `mov [rdi], eax` (89 07) writing 0x11223344 into | |
| // arena offset 16. | |
| let mut r_st_in = empty_regs; | |
| r_st_in[0] = 0x1122_3344; | |
| r_st_in[7] = arena + 16; // rdi | |
| let store_rec = ExecRecord { | |
| case_id: "self_b1_mov_store_u32".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Normal, | |
| band: ExecBand::ScalarGpr, | |
| body_hex: "8907".to_owned(), | |
| bytes: vec![0x89, 0x07], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0xAA, | |
| capture_boundary: 2, | |
| program_kinds: vec!["MovStore".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_st_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_st_in, | |
| rip: base + 2, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }), | |
| initial_memory: Vec::new(), | |
| observed_memory_diffs: vec![ | |
| MemPatch { offset: 16, value: 0x44 }, | |
| MemPatch { offset: 17, value: 0x33 }, | |
| MemPatch { offset: 18, value: 0x22 }, | |
| MemPatch { offset: 19, value: 0x11 }, | |
| ], | |
| trap_signal: None, | |
| fault_rip: None, | |
| }; | |
| // Band 1 (ScalarGpr): out-of-arena store trap (`mov [rdi], eax` at | |
| // `arena + 8192`) predicted by `writeFootprint` OOB check at `rip = base`. | |
| let mut r_trap_in = empty_regs; | |
| r_trap_in[0] = 1; | |
| r_trap_in[7] = arena + DEFAULT_ARENA_SIZE as u64; | |
| let trap_rec = ExecRecord { | |
| case_id: "self_b1_oob_store_trap".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Trap, | |
| band: ExecBand::ScalarGpr, | |
| body_hex: "8907".to_owned(), | |
| bytes: vec![0x89, 0x07], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0, | |
| capture_boundary: 2, | |
| program_kinds: vec!["MovStore".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_trap_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_trap_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }), | |
| initial_memory: Vec::new(), | |
| observed_memory_diffs: Vec::new(), | |
| trap_signal: Some("SIGSEGV".to_owned()), | |
| fault_rip: Some(base), | |
| }; | |
| // Band 2 (RepString): `rep movsb` (`F3 A4`), reported honestly in the | |
| // Band-2 coverage backlog until `ScalarEval` models `rep` string ops. | |
| let mut r_rep_in = empty_regs; | |
| r_rep_in[1] = 2; // rcx | |
| r_rep_in[6] = arena; // rsi | |
| r_rep_in[7] = arena + 64; // rdi | |
| let mut r_rep_out = r_rep_in; | |
| r_rep_out[1] = 0; | |
| r_rep_out[6] = arena + 2; | |
| r_rep_out[7] = arena + 66; | |
| let rep_rec = ExecRecord { | |
| case_id: "self_b2_rep_movsb".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Normal, | |
| band: ExecBand::RepString, | |
| body_hex: "f3a4".to_owned(), | |
| bytes: vec![0xF3, 0xA4], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0, | |
| capture_boundary: 2, | |
| program_kinds: vec!["RepMovsb".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_rep_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_rep_out, | |
| rip: base + 2, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }), | |
| initial_memory: vec![ | |
| MemPatch { offset: 0, value: 0xDE }, | |
| MemPatch { offset: 1, value: 0xAD }, | |
| ], | |
| observed_memory_diffs: vec![ | |
| MemPatch { offset: 0, value: 0xDE }, | |
| MemPatch { offset: 1, value: 0xAD }, | |
| MemPatch { offset: 64, value: 0xDE }, | |
| MemPatch { offset: 65, value: 0xAD }, | |
| ], | |
| trap_signal: None, | |
| fault_rip: None, | |
| }; | |
| // Band 3 (ExtendedSandbox): 8-bit `mov al, [rdi]` (`8A 07`) which | |
| // `ScalarEval` already executes bit-for-bit against sandbox records. | |
| let mut r_b3_in = empty_regs; | |
| r_b3_in[0] = 0xAABB_CC00; | |
| r_b3_in[7] = arena + 8; | |
| let mut r_b3_out = r_b3_in; | |
| r_b3_out[0] = 0xAABB_CC5A; | |
| let sandbox_mov8_rec = ExecRecord { | |
| case_id: "self_b3_mov8_load_al".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Normal, | |
| band: ExecBand::ExtendedSandbox, | |
| body_hex: "8a07".to_owned(), | |
| bytes: vec![0x8A, 0x07], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0, | |
| capture_boundary: 2, | |
| program_kinds: vec!["Mov8Load".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_b3_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_b3_out, | |
| rip: base + 2, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: None, | |
| mxcsr: None, | |
| }), | |
| initial_memory: vec![MemPatch { offset: 8, value: 0x5A }], | |
| observed_memory_diffs: vec![MemPatch { offset: 8, value: 0x5A }], | |
| trap_signal: None, | |
| fault_rip: None, | |
| }; | |
| // Band 3 (ExtendedSandbox): `vmovdqu xmm0, [rdi]` (`C5 FA 6F 07`), | |
| // honestly reported in the Band-3 coverage backlog until vector value | |
| // steps land in `ScalarEval`. | |
| let mut vmovdqu_obs_xmm = vec![[0, 0]; 16]; | |
| vmovdqu_obs_xmm[0] = [0x5A, 0]; | |
| let sandbox_vmovdqu_rec = ExecRecord { | |
| case_id: "self_b3_vmovdqu_xmm0".to_owned(), | |
| vendor: "synthetic".to_owned(), | |
| kind: ExecRecordKind::Normal, | |
| band: ExecBand::ExtendedSandbox, | |
| body_hex: "c5fa6f07".to_owned(), | |
| bytes: vec![0xC5, 0xFA, 0x6F, 0x07], | |
| base_address: base, | |
| arena_address: arena, | |
| arena_size: DEFAULT_ARENA_SIZE, | |
| default_byte: 0, | |
| capture_boundary: 4, | |
| program_kinds: vec!["VmovdquLoad".to_owned()], | |
| initial: ExecStateSnapshot { | |
| regs: r_b3_in, | |
| rip: base, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: Some(vec![[0, 0]; 16]), | |
| mxcsr: Some(0x1F80), | |
| }, | |
| observed: Some(ExecStateSnapshot { | |
| regs: r_b3_in, | |
| rip: base + 4, | |
| arithmetic_flags: 0, | |
| raw_rflags: None, | |
| xmm: Some(vmovdqu_obs_xmm), | |
| mxcsr: Some(0x1F80), | |
| }), | |
| initial_memory: vec![MemPatch { offset: 8, value: 0x5A }], | |
| observed_memory_diffs: vec![MemPatch { offset: 8, value: 0x5A }], | |
| trap_signal: None, | |
| fault_rip: None, | |
| }; | |
| vec![add_rec, shl_rec, store_rec, trap_rec, rep_rec, sandbox_mov8_rec, sandbox_vmovdqu_rec] | |
| } | |
| const LEAN_EXEC_PRELUDE: &str = r#"private structure ExecQuery where | |
| idx : Nat | |
| bytes : List UInt8 | |
| arenaAddr : Nat | |
| arenaSize : Nat | |
| defaultByte : UInt8 | |
| initRipRel : Nat | |
| captureBoundary : Nat | |
| initRegs : List Nat | |
| initFlags : Nat | |
| initMem : List (Nat × UInt8) | |
| watchOffsets : List Nat | |
| fuel : Nat | |
| private def parseFlagsBits (n : Nat) : RFlags := | |
| let bit (k : Nat) : Bool := (n >>> k) &&& 1 == 1 | |
| ⟨bit 0, bit 2, bit 4, bit 6, bit 7, bit 11⟩ | |
| private def packFlagsBits (f : RFlags) : Nat := | |
| (if f.cf then 1 else 0) + (if f.pf then 4 else 0) + (if f.af then 16 else 0) + | |
| (if f.zf then 64 else 0) + (if f.sf then 128 else 0) + (if f.of then 2048 else 0) | |
| private def packUndefBits (u : FlagMask) : Nat := | |
| (if u.cf then 1 else 0) + (if u.pf then 4 else 0) + (if u.af then 16 else 0) + | |
| (if u.zf then 64 else 0) + (if u.sf then 128 else 0) + (if u.of then 2048 else 0) | |
| private def allGprs : List Gpr := | |
| [.rax, .rcx, .rdx, .rbx, .rsp, .rbp, .rsi, .rdi, | |
| .r8, .r9, .r10, .r11, .r12, .r13, .r14, .r15] | |
| private def mkRegFile (xs : List Nat) : RegFile := | |
| fun g => UInt64.ofNat (xs.getD (gprToNat g) 0) | |
| private def mkArenaMem (arena : UInt64) (arenaSize : Nat) (defB : UInt8) | |
| (patches : List (Nat × UInt8)) : ByteMem := | |
| fun addr => | |
| if addr.toNat >= arena.toNat && addr.toNat < arena.toNat + arenaSize then | |
| let off := addr.toNat - arena.toNat | |
| match patches.find? (fun p => p.1 == off) with | |
| | some (_, v) => v | |
| | none => defB | |
| else defB | |
| private def regionAddrs (r : Option MemRegion) : List UInt64 := | |
| match r with | |
| | none => [] | |
| | some reg => (List.range reg.width).map (fun k => addrAdd reg.base k) | |
| private def inArena (arena arenaSize : Nat) (a : UInt64) : Bool := | |
| a.toNat >= arena && a.toNat < arena + arenaSize | |
| private inductive RunRes where | |
| | done (st : ScalarState) (touched : List UInt64) (oob : Bool) | |
| | stepFail | |
| | outOfFuel | |
| private def runExecProg (prog : List (Nat × Nat × ScalarInsn)) | |
| (bytesLen arena arenaSize captureBoundary : Nat) | |
| (fuel : Nat) (st : ScalarState) (touched : List UInt64) : RunRes := | |
| if st.halted || (captureBoundary > 0 && st.rip == captureBoundary) then | |
| .done st touched false | |
| else match fetchInsn prog st.rip with | |
| | none => | |
| if st.rip == bytesLen then | |
| .done st touched false | |
| else | |
| .stepFail | |
| | some (len, ins) => | |
| match fuel with | |
| | 0 => .outOfFuel | |
| | fuel' + 1 => | |
| let rAddrs := regionAddrs (readFootprint st ins) | |
| let wAddrs := regionAddrs (writeFootprint st ins) | |
| let stepOob := (rAddrs ++ wAddrs).any (fun a => !inArena arena arenaSize a) | |
| if stepOob then | |
| -- Halt immediately on the first out-of-arena memory access without | |
| -- committing the faulting instruction, matching hardware trap behavior | |
| -- even inside loops. | |
| .done st touched true | |
| else | |
| match stepScalar st ins len with | |
| | none => .stepFail | |
| | some st' => | |
| runExecProg prog bytesLen arena arenaSize captureBoundary fuel' st' (touched ++ wAddrs) | |
| private def evalExecQuery (q : ExecQuery) : String := | |
| let cfg : DecodeConfig := { requireRelocForRip := false } | |
| match decodeStreamScalar cfg [] q.bytes with | |
| | none => s!"EXEC|{q.idx}|DECODE_FAIL" | |
| | some prog => | |
| let arenaU64 := UInt64.ofNat q.arenaAddr | |
| let st0 : ScalarState := { | |
| regs := mkRegFile q.initRegs | |
| flags := parseFlagsBits q.initFlags | |
| undefFlags := FlagMask.dead | |
| rip := q.initRipRel | |
| mem := mkArenaMem arenaU64 q.arenaSize q.defaultByte q.initMem | |
| halted := false | |
| } | |
| match runExecProg prog q.bytes.length q.arenaAddr q.arenaSize q.captureBoundary q.fuel st0 [] with | |
| | .stepFail => s!"EXEC|{q.idx}|STEP_FAIL" | |
| | .outOfFuel => s!"EXEC|{q.idx}|OUT_OF_FUEL|{q.fuel}" | |
| | .done st' touched oob => | |
| let regsStr := String.intercalate "," (allGprs.map (fun g => toString (st'.regs g).toNat)) | |
| let touchedOffs := touched.filterMap (fun a => | |
| if inArena q.arenaAddr q.arenaSize a then some (a.toNat - q.arenaAddr) else none) | |
| let allOffs := (q.watchOffsets ++ touchedOffs).eraseDups | |
| let memEntries := allOffs.map (fun off => | |
| let v := (st'.mem (UInt64.ofNat (q.arenaAddr + off))).toNat | |
| s!"{off}:{v}") | |
| let memStr := if memEntries.isEmpty then "-" else String.intercalate "," memEntries | |
| let haltedBit := if st'.halted then 1 else 0 | |
| let oobBit := if oob then 1 else 0 | |
| let flBits := packFlagsBits st'.flags | |
| let uBits := packUndefBits st'.undefFlags | |
| s!"EXEC|{q.idx}|OK|rip={st'.rip}|halted={haltedBit}|flags={flBits}|undef={uBits}|oob={oobBit}|regs={regsStr}|mem={memStr}" | |
| "#; |