blob: de5f27a98ca0a2685b841ea9bc321b5a19cbd054 [file]
// 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.
//! Dual-ISA (`x86-64` and `AArch64`) differential decoder and x86-64 execution
//! oracle comparing Anneal's Lean 4 instruction decoders (`Anneal.ElfX86` +
//! `WordSimd` and `Anneal.ElfAArch64`) against `llvm-objdump --disassemble`
//! and GNU `objdump -d --show-raw-insn`, plus three-band `ScalarEval`
//! execution replay (`exec`) against JSONL silicon/sandbox traces.
pub mod corpus;
pub mod exec;
pub mod lean;
pub mod objdump;
use serde::{Deserialize, Serialize};
/// Target instruction set architecture.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Arch {
X86_64,
AArch64,
}
/// Which x86-64 Lean decoder surface to query.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum X86DecoderLane {
/// `Anneal.ElfX86.PrefixDecode` only.
Base,
/// `Anneal.ElfX86.WordSimd` (composing `PrefixDecode` + word SIMD/scalar).
WordSimd,
}
/// External reference disassembler leg.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DisasmLeg {
LlvmObjdump,
GnuObjdump,
}
/// One disassembled instruction parsed from `llvm-objdump` or GNU `objdump`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DisasmInsn {
/// Byte offset relative to the start of the disassembled byte buffer.
pub offset: u64,
/// Normalized little-endian instruction bytes.
pub bytes: Vec<u8>,
/// Lowercased instruction mnemonic (with leading `lock` separated).
pub mnemonic: String,
/// Operand text following the mnemonic.
pub operands: String,
/// True iff a `LOCK` prefix was emitted on this instruction.
pub locked: bool,
/// True iff the disassembler emitted an invalid/unknown/data pseudo-op.
pub is_bad: bool,
}
impl DisasmInsn {
pub fn len(&self) -> usize {
self.bytes.len()
}
pub fn is_empty(&self) -> bool {
self.bytes.is_empty()
}
}
/// One decoded instruction returned by Anneal's Lean decoder driver.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LeanInsn {
pub offset: u64,
pub len: usize,
pub mnemonic: String,
pub detail: String,
}
/// Result of a single Lean decoder query.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "status", content = "entries", rename_all = "snake_case")]
pub enum LeanDecodeStatus {
DecodeNone,
Ok(Vec<LeanInsn>),
}
/// Expected outcome classification for a differential test case.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CaseExpectation {
/// Whole stream must decode cleanly in Lean and match every available
/// disassembler leg with zero gaps and zero mismatches.
FullMatch,
/// Whole stream must fail closed (`DecodeNone`) in Lean with zero
/// mismatches on any available disassembler leg.
ExpectedDecodeNone,
/// Arbitrary binary/hex probe: fail-closed `DECODE_NONE` gaps are allowed
/// and reported, while any mismatch or missing disassembler leg fails.
ReportGaps,
}
/// Input specification for one differential oracle case.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CaseSpec {
pub id: String,
pub description: String,
pub arch: Arch,
pub x86_lane: X86DecoderLane,
pub bytes: Vec<u8>,
pub expectation: CaseExpectation,
}
/// Verdict classification for a single instruction or stream comparison.
///
/// Compares instruction boundaries, byte lengths, canonical mnemonics, and
/// coarse semantic tags (`vex=128`/`vex=256`, `lock`, AArch64 `sp`/`zr`);
/// full operand syntax is not compared.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum InsnVerdictKind {
Match,
DisasmOnly,
FailClosedGap,
LengthMismatch,
MnemonicMismatch,
DetailMismatch,
BoundaryMismatch,
ExtraLeanAccept,
}
/// Detailed per-instruction verdict record.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InsnVerdict {
pub offset: u64,
pub bytes_hex: String,
pub kind: InsnVerdictKind,
pub disasm_len: usize,
pub disasm_mnemonic: String,
pub disasm_operands: String,
pub lean_len: Option<usize>,
pub lean_mnemonic: Option<String>,
pub lean_detail: Option<String>,
pub note: String,
}
/// Whole-stream comparison summary against one disassembler leg.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegComparison {
pub leg: DisasmLeg,
pub available: bool,
pub error: Option<String>,
pub disasm_insn_count: usize,
pub lean_stream_ok: bool,
pub stream_boundary_agree: bool,
pub stream_all_match: bool,
pub matched_insns: usize,
pub fail_closed_gaps: usize,
pub mismatches: usize,
pub verdicts: Vec<InsnVerdict>,
}
/// Cross-disassembler agreement between `llvm-objdump` and GNU `objdump`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DisasmAgreement {
pub compared: bool,
pub boundaries_agree: bool,
pub mnemonics_agree: bool,
pub differences: Vec<String>,
}
/// Complete JSON verdict report for one differential test case.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CaseReport {
pub id: String,
pub description: String,
pub arch: Arch,
pub x86_lane: X86DecoderLane,
pub byte_len: usize,
pub bytes_hex: String,
pub expectation: CaseExpectation,
pub expectation_ok: bool,
pub expectation_error: Option<String>,
pub lean_stream_status: Option<LeanDecodeStatus>,
pub disasm_agreement: DisasmAgreement,
pub legs: Vec<LegComparison>,
}
/// Policy flags controlling which oracle failures fail the batch verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OracleGatePolicy {
/// Require Lean evaluation results to be present for every case.
pub require_lean: bool,
/// Require GNU `objdump` to be available on `x86-64` cases.
pub require_gnu_x86: bool,
}
impl Default for OracleGatePolicy {
fn default() -> Self {
Self { require_lean: true, require_gnu_x86: true }
}
}
/// Aggregate JSON report across all evaluated cases.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BatchReport {
pub schema: String,
pub passed: bool,
pub total_cases: usize,
pub total_insns_checked: usize,
pub total_matched_insns: usize,
pub total_fail_closed_gaps: usize,
pub total_mismatches: usize,
pub total_expectation_failures: usize,
pub total_leg_errors: usize,
pub cases: Vec<CaseReport>,
}
/// Format bytes as space-separated lowercase hex (`"41 90 c3"`).
pub fn format_bytes_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(" ")
}
/// Parse a hex string (spaces, commas, `0x` prefixes, or contiguous hex pairs)
/// into raw bytes.
pub fn parse_hex_bytes(input: &str) -> Result<Vec<u8>, String> {
let mut cleaned = String::with_capacity(input.len());
for tok in input.split(|c: char| c.is_whitespace() || c == ',' || c == ';') {
if tok.is_empty() {
continue;
}
let hex = tok.strip_prefix("0x").or_else(|| tok.strip_prefix("0X")).unwrap_or(tok);
cleaned.push_str(hex);
}
if !cleaned.len().is_multiple_of(2) {
return Err(format!("hex byte string has odd length ({} digits)", cleaned.len()));
}
let mut out = Vec::with_capacity(cleaned.len() / 2);
let bytes = cleaned.as_bytes();
for i in (0..bytes.len()).step_by(2) {
let s = std::str::from_utf8(&bytes[i..i + 2]).map_err(|e| e.to_string())?;
let b = u8::from_str_radix(s, 16).map_err(|e| format!("invalid hex byte `{s}`: {e}"))?;
out.push(b);
}
Ok(out)
}
/// Canonicalize an x86-64 mnemonic alias to match `Anneal.IsaOracleDriver`.
pub fn canonicalize_x86_mnemonic(raw: &str) -> String {
let m = raw.trim().to_ascii_lowercase();
match m.as_str() {
// Conditional jump aliases.
"jz" => "je".to_string(),
"jnz" => "jne".to_string(),
"jc" | "jnae" => "jb".to_string(),
"jnb" | "jnc" => "jae".to_string(),
"jna" => "jbe".to_string(),
"jnbe" => "ja".to_string(),
"jnge" => "jl".to_string(),
"jnl" => "jge".to_string(),
"jng" => "jle".to_string(),
"jnle" => "jg".to_string(),
"jpe" => "jp".to_string(),
"jpo" => "jnp".to_string(),
// Conditional move aliases.
"cmovz" => "cmove".to_string(),
"cmovnz" => "cmovne".to_string(),
"cmovc" | "cmovnae" => "cmovb".to_string(),
"cmovnb" | "cmovnc" => "cmovae".to_string(),
"cmovna" => "cmovbe".to_string(),
"cmovnbe" => "cmova".to_string(),
"cmovnge" => "cmovl".to_string(),
"cmovnl" => "cmovge".to_string(),
"cmovng" => "cmovle".to_string(),
"cmovnle" => "cmovg".to_string(),
"cmovpe" => "cmovp".to_string(),
"cmovpo" => "cmovnp".to_string(),
// Other x86-64 Intel/AT&T canonical aliases.
"sal" => "shl".to_string(),
"retq" => "ret".to_string(),
"movslq" => "movsxd".to_string(),
"int3" => "int3".to_string(),
_ => m,
}
}
/// True iff raw x86-64 instruction `bytes` encode the single-byte `0x90`
/// opcode (with optional legacy/REX prefixes and `REX.B == 0`), distinguishing
/// architectural `nop` (`90` / `66 90` / `48 90`) from ModR/M `xchg` (`87 c0`
/// / `48 87 c0` / `66 87 c0`) and `REX.B + 0x90` (`41 90` / `49 90`).
pub fn is_x86_nop_90_encoding(bytes: &[u8]) -> bool {
let mut active_rex: Option<u8> = None;
let mut idx = 0usize;
while idx < bytes.len() {
let b = bytes[idx];
match b {
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3 => {
active_rex = None;
idx += 1;
}
0x40..=0x4F => {
active_rex = Some(b);
idx += 1;
}
_ => break,
}
}
idx + 1 == bytes.len() && bytes[idx] == 0x90 && active_rex.is_none_or(|r| (r & 0x01) == 0)
}
/// True iff an x86-64 disassembly line represents an architectural `0x90`
/// accumulator self-exchange (`xchg ax,ax`, `xchg eax,eax`, `xchg rax,rax`),
/// distinct from `41 90` (`xchg r8d, eax`) and ModR/M `87 c0` (`xchg eax,eax`,
/// which zero-extends `rax` in 64-bit mode and is NOT a `nop`).
pub fn is_x86_nop_self_xchg(mnemonic: &str, operands: &str, bytes: &[u8]) -> bool {
if !mnemonic.trim().eq_ignore_ascii_case("xchg") || !is_x86_nop_90_encoding(bytes) {
return false;
}
let compact: String =
operands.chars().filter(|c| !c.is_whitespace()).map(|c| c.to_ascii_lowercase()).collect();
matches!(compact.as_str(), "ax,ax" | "eax,eax" | "rax,rax")
}
fn a64_word_le(bytes: &[u8]) -> Option<u32> {
let arr: [u8; 4] = bytes.try_into().ok()?;
Some(u32::from_le_bytes(arr))
}
fn a64_is_imm_op(op: &str) -> bool {
op.starts_with('#')
}
/// Check whether a Lean canonical mnemonic agrees with an external
/// disassembler mnemonic, gating architectural aliases on both ISAs by their
/// exact instruction encoding (`disasm_bytes`) and operand shape.
pub fn mnemonics_equivalent(
arch: Arch,
lean_mnemonic: &str,
lean_detail: &str,
disasm_mnemonic: &str,
disasm_operands: &str,
disasm_bytes: &[u8],
) -> bool {
match arch {
Arch::X86_64 => {
let l = canonicalize_x86_mnemonic(lean_mnemonic);
let d = canonicalize_x86_mnemonic(disasm_mnemonic);
if l == d {
return true;
}
// `movabs` (64-bit immediate mov) vs `mov`.
if (l == "movabs" && d == "mov") || (l == "mov" && d == "movabs") {
return true;
}
// `int3` vs `int 3`.
if l == "int3" && d == "int" && disasm_operands.trim() == "3" {
return true;
}
// GNU `objdump` prints `66 90` / `90` / `48 90` as `xchg ax,ax`
// (self-exchange on accumulator), which is architecturally `nop`
// only for post-prefix opcode `0x90` with `REX.B == 0` (distinct
// from `41 90` `xchg r8d, eax` and ModR/M `87 c0`).
if l == "nop" && is_x86_nop_self_xchg(&d, disasm_operands, disasm_bytes) {
return true;
}
false
}
Arch::AArch64 => {
let l = lean_mnemonic.trim().to_ascii_lowercase();
let d = disasm_mnemonic.trim().to_ascii_lowercase();
if l == d {
return true;
}
let Some(w) = a64_word_le(disasm_bytes) else {
return false;
};
let ops = split_top_level_operands(disasm_operands);
let op0 = ops.first().map(String::as_str).unwrap_or("");
let op1 = ops.get(1).map(String::as_str).unwrap_or("");
match (l.as_str(), d.as_str()) {
("adds", "cmn") => {
lean_detail.contains("rd=zr")
&& ((w & 0x7F80_0000) == 0x3100_0000
|| (w & 0x7F20_0000) == 0x2B00_0000
|| (w & 0x7FE0_0000) == 0x2B20_0000)
}
("subs", "cmp") => {
lean_detail.contains("rd=zr")
&& ((w & 0x7F80_0000) == 0x7100_0000
|| (w & 0x7F20_0000) == 0x6B00_0000
|| (w & 0x7FE0_0000) == 0x6B20_0000)
}
("sub", "neg") => (w & 0x7F20_03E0) == 0x4B00_03E0,
("subs", "negs") => (w & 0x7F20_03E0) == 0x6B00_03E0,
("ands", "tst") => {
lean_detail.contains("rd=zr")
&& ((w & 0x7F80_0000) == 0x7200_0000 || (w & 0x7F20_0000) == 0x6A00_0000)
}
// `MOV` aliases disambiguated by ARMv8-A encoding class and
// operand shape (register, bitmask immediate, SP-to-SP/GPR
// `ADD #0`, `MOVZ`, or `MOVN`).
("orr", "mov") => {
let is_orr_reg = (w & 0x7FE0_FFE0) == 0x2A00_03E0
&& ops.len() == 2
&& !a64_is_imm_op(op1)
&& !is_a64_sp_reg(op0)
&& !is_a64_sp_reg(op1);
let is_orr_imm =
(w & 0x7F80_03E0) == 0x3200_03E0 && ops.len() == 2 && a64_is_imm_op(op1);
is_orr_reg || is_orr_imm
}
("add", "mov") => {
let rd_or_rn_sp = (w & 0x1F) == 31 || ((w >> 5) & 0x1F) == 31;
(w & 0x7FFF_FC00) == 0x1100_0000
&& rd_or_rn_sp
&& ops.len() == 2
&& !a64_is_imm_op(op1)
&& (is_a64_sp_reg(op0) || is_a64_sp_reg(op1))
}
("movz", "mov") => {
(w & 0x7F80_0000) == 0x5280_0000 && ops.len() == 2 && a64_is_imm_op(op1)
}
("movn", "mov") => {
(w & 0x7F80_0000) == 0x1280_0000 && ops.len() == 2 && a64_is_imm_op(op1)
}
("orn", "mvn") => (w & 0x7F20_03E0) == 0x2A20_03E0,
("ubfm", "lsl" | "lsr" | "ubfx" | "ubfiz" | "uxtb" | "uxth") => {
(w & 0x7F80_0000) == 0x5300_0000
}
("sbfm", "asr" | "sbfx" | "sbfiz" | "sxtb" | "sxth" | "sxtw") => {
(w & 0x7F80_0000) == 0x1300_0000
}
("bfm", "bfi" | "bfxil") => (w & 0x7F80_0000) == 0x3300_0000,
("madd", "mul") => (w & 0x7FE0_FC00) == 0x1B00_7C00,
("msub", "mneg") => (w & 0x7FE0_FC00) == 0x1B00_FC00,
("csinc", "cinc" | "cset") => (w & 0x7FE0_0C00) == 0x1A80_0400,
("csinv", "cinv" | "csetm") => (w & 0x7FE0_0C00) == 0x5A80_0000,
("csneg", "cneg") => (w & 0x7FE0_0C00) == 0x5A80_0400,
("b.cs", "b.hs") | ("b.cc", "b.lo") => (w & 0xFF00_0010) == 0x5400_0000,
("trap", "brk") => {
(w & 0xFFE0_001F) == 0xD420_0000 && ops.len() == 1 && a64_is_imm_op(op0)
}
("trap", "hlt") => {
(w & 0xFFE0_001F) == 0xD440_0000 && ops.len() == 1 && a64_is_imm_op(op0)
}
_ => false,
}
}
}
}
fn has_x86_vec_reg(ops_lower: &str, prefix: &str) -> bool {
let bytes = ops_lower.as_bytes();
let plen = prefix.len();
for (i, _) in ops_lower.match_indices(prefix) {
let prev_ok = i == 0 || !(bytes[i - 1].is_ascii_alphanumeric() || bytes[i - 1] == b'_');
let next_ok = bytes.get(i + plen).is_some_and(u8::is_ascii_digit);
if prev_ok && next_ok {
return true;
}
}
false
}
fn split_top_level_operands(operands: &str) -> Vec<String> {
let mut out = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
for (i, ch) in operands.char_indices() {
match ch {
'[' => depth += 1,
']' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
let tok = operands[start..i].trim().to_ascii_lowercase();
if !tok.is_empty() {
out.push(tok);
}
start = i + 1;
}
_ => {}
}
}
let tail = operands[start..].trim().to_ascii_lowercase();
if !tail.is_empty() {
out.push(tail);
}
out
}
fn is_a64_sp_reg(op: &str) -> bool {
matches!(op, "sp" | "wsp")
}
fn is_a64_zr_reg(op: &str) -> bool {
matches!(op, "xzr" | "wzr")
}
/// Cross-check semantic detail tags emitted by `Anneal.IsaOracleDriver`
/// bidirectionally against disassembler operands/prefixes (`vex=128` vs
/// `vex=256`, `lock`, and positional AArch64 `rd=sp`/`rn=sp`/`rd=zr`).
pub fn check_detail_consistency(
arch: Arch,
lean: &LeanInsn,
disasm: &DisasmInsn,
) -> Option<String> {
let has_tag = |needle: &str| lean.detail.split(',').any(|t| t == needle);
let ops_lower = disasm.operands.to_ascii_lowercase();
match arch {
Arch::X86_64 => {
// Bidirectional LOCK prefix parity.
let lean_has_lock = has_tag("lock");
if disasm.locked != lean_has_lock {
return Some(if disasm.locked {
"disassembler emitted LOCK prefix but Lean decoded unlocked".to_string()
} else {
"Lean decoded LOCK prefix but disassembler did not".to_string()
});
}
// Bidirectional VEX width (`vex=256` <-> `ymm*`, `vex=128` <->
// `xmm*` without `ymm*`).
let lean_has_vex256 = has_tag("vex=256");
let lean_has_vex128 = has_tag("vex=128");
if lean_has_vex256 && lean_has_vex128 {
return Some(
"Lean emitted contradictory VEX width tags (`vex=128,vex=256`)".into(),
);
}
let has_ymm = has_x86_vec_reg(&ops_lower, "ymm");
let has_xmm = has_x86_vec_reg(&ops_lower, "xmm");
if has_ymm {
if lean_has_vex128 {
return Some(format!(
"Lean decoded VEX.128 (`xmm`) but disassembler operands contain `ymm`: \
`{}`",
disasm.operands
));
}
if !lean_has_vex256 {
return Some(format!(
"disassembler operands contain `ymm` (VEX.256) but Lean omitted \
`vex=256`: `{}`",
disasm.operands
));
}
} else {
if lean_has_vex256 {
return Some(format!(
"Lean decoded VEX.256 (`ymm`) but disassembler operands are `{}`",
disasm.operands
));
}
if has_xmm && !lean_has_vex128 {
return Some(format!(
"disassembler operands contain `xmm` (VEX.128) without `ymm`, but Lean \
omitted `vex=128`: `{}`",
disasm.operands
));
}
if !has_xmm && lean_has_vex128 {
return Some(format!(
"Lean decoded VEX.128 (`xmm`) but disassembler operands have no `xmm` \
register: `{}`",
disasm.operands
));
}
}
}
Arch::AArch64 => {
// Bidirectional, positional SP (`rd=sp`, `rn=sp`) and ZR (`rd=zr`)
// parity for AArch64 ALU instructions that distinguish `x31`.
let lean_has_rd_sp = has_tag("rd=sp");
let lean_has_rn_sp = has_tag("rn=sp");
let lean_has_rd_zr = has_tag("rd=zr");
let d_mn = disasm.mnemonic.trim().to_ascii_lowercase();
let l_mn = lean.mnemonic.trim().to_ascii_lowercase();
let ops = split_top_level_operands(&disasm.operands);
let op0 = ops.first().map(String::as_str).unwrap_or("");
let op1 = ops.get(1).map(String::as_str).unwrap_or("");
let lean_emits_alu_x31_tags = matches!(
l_mn.as_str(),
"add"
| "adds"
| "sub"
| "subs"
| "and"
| "orr"
| "eor"
| "ands"
| "bic"
| "orn"
| "eon"
| "bics"
);
let (disasm_rd_is_sp, disasm_rn_is_sp, disasm_rd_is_zr) = match d_mn.as_str() {
// `cmp`/`cmn` are `subs`/`adds` with implicit `rd=zr`; op0 is
// `rn`.
"cmp" | "cmn" => (false, is_a64_sp_reg(op0), true),
// `tst` is `ands` with implicit `rd=zr`.
"tst" => (false, false, true),
// `neg`/`negs`/`mvn` have implicit `rn=zr`; op0 is `rd`.
"neg" | "negs" | "mvn" => (false, false, is_a64_zr_reg(op0)),
// `mov` can alias `add` (with `sp`), `orr`, `movz`, or `movn`.
"mov" => (
is_a64_sp_reg(op0),
is_a64_sp_reg(op1),
lean_emits_alu_x31_tags && is_a64_zr_reg(op0),
),
"add" | "adds" | "sub" | "subs" | "and" | "orr" | "eor" | "ands" | "bic"
| "orn" | "eon" | "bics" => {
(is_a64_sp_reg(op0), is_a64_sp_reg(op1), is_a64_zr_reg(op0))
}
_ => (false, false, false),
};
if lean_has_rd_sp != disasm_rd_is_sp {
return Some(if lean_has_rd_sp {
format!(
"Lean decoded `rd=sp` but disassembler `rd` operand is not SP: `{} {}`",
disasm.mnemonic, disasm.operands
)
} else {
format!(
"disassembler `rd` operand is SP (`{} {}`) but Lean omitted `rd=sp`",
disasm.mnemonic, disasm.operands
)
});
}
if lean_has_rn_sp != disasm_rn_is_sp {
return Some(if lean_has_rn_sp {
format!(
"Lean decoded `rn=sp` but disassembler `rn` operand is not SP: `{} {}`",
disasm.mnemonic, disasm.operands
)
} else {
format!(
"disassembler `rn` operand is SP (`{} {}`) but Lean omitted `rn=sp`",
disasm.mnemonic, disasm.operands
)
});
}
if lean_has_rd_zr != disasm_rd_is_zr {
return Some(if lean_has_rd_zr {
format!(
"Lean decoded XZR/WZR (`rd=zr`) but disassembler emitted `{} {}`",
disasm.mnemonic, disasm.operands
)
} else {
format!(
"disassembler `rd` is XZR/WZR (`{} {}`) but Lean omitted `rd=zr`",
disasm.mnemonic, disasm.operands
)
});
}
}
}
None
}
/// Compare two disassembler legs (`llvm-objdump` vs GNU `objdump`) for
/// instruction boundary and mnemonic agreement.
pub fn compare_disassemblers(
arch: Arch,
llvm: Option<&[DisasmInsn]>,
gnu: Option<&[DisasmInsn]>,
) -> DisasmAgreement {
let (Some(a), Some(b)) = (llvm, gnu) else {
return DisasmAgreement {
compared: false,
boundaries_agree: false,
mnemonics_agree: false,
differences: Vec::new(),
};
};
let mut differences = Vec::new();
let boundaries_agree = a.len() == b.len()
&& a.iter().zip(b.iter()).all(|(x, y)| x.offset == y.offset && x.bytes == y.bytes);
if !boundaries_agree {
differences.push(format!(
"boundary divergence: llvm-objdump decoded {} insns vs GNU objdump {} insns",
a.len(),
b.len()
));
}
let mut mnemonics_agree = boundaries_agree;
for (x, y) in a.iter().zip(b.iter()) {
if x.offset == y.offset && x.bytes == y.bytes {
if x.is_bad != y.is_bad {
mnemonics_agree = false;
differences.push(format!(
"offset 0x{:x}: validity divergence (llvm is_bad={} `{} {}` vs gnu \
is_bad={} `{} {}`)",
x.offset, x.is_bad, x.mnemonic, x.operands, y.is_bad, y.mnemonic, y.operands
));
}
if x.locked != y.locked {
mnemonics_agree = false;
differences.push(format!(
"offset 0x{:x}: LOCK prefix divergence (llvm locked={} vs gnu locked={})",
x.offset, x.locked, y.locked
));
}
let eq = match arch {
Arch::X86_64 => {
let mx = canonicalize_x86_mnemonic(&x.mnemonic);
let my = canonicalize_x86_mnemonic(&y.mnemonic);
mx == my
|| (mx == "nop" && is_x86_nop_self_xchg(&my, &y.operands, &y.bytes))
|| (my == "nop" && is_x86_nop_self_xchg(&mx, &x.operands, &x.bytes))
}
Arch::AArch64 => x.mnemonic.eq_ignore_ascii_case(&y.mnemonic),
};
if !eq {
mnemonics_agree = false;
differences.push(format!(
"offset 0x{:x}: llvm `{}` vs gnu `{}`",
x.offset, x.mnemonic, y.mnemonic
));
}
}
}
DisasmAgreement { compared: true, boundaries_agree, mnemonics_agree, differences }
}
/// Compare external disassembler instructions against Anneal's Lean decoder
/// (using both the whole-stream result and per-instruction probes at each
/// disassembled offset).
pub fn compare_against_lean(
arch: Arch,
leg: DisasmLeg,
disasm: &[DisasmInsn],
lean_stream: Option<&LeanDecodeStatus>,
lean_per_insn: &[Option<LeanDecodeStatus>],
) -> LegComparison {
let (lean_stream_ok, stream_entries) = match lean_stream {
Some(LeanDecodeStatus::Ok(es)) => (true, Some(es.as_slice())),
_ => (false, None),
};
let stream_boundary_agree = match stream_entries {
Some(es) => {
es.len() == disasm.len()
&& es
.iter()
.zip(disasm.iter())
.all(|(l, d)| l.offset == d.offset && l.len == d.len())
}
None => false,
};
let mut verdicts = Vec::with_capacity(disasm.len());
let mut matched_insns = 0usize;
let mut fail_closed_gaps = 0usize;
let mut mismatches = 0usize;
for (idx, d) in disasm.iter().enumerate() {
// When the whole-stream Lean decoder returned `Ok(es)`, compare
// strictly against `es` so omitted disassembler boundaries surface as
// `BoundaryMismatch` instead of being masked by per-instruction
// fallback. Use `lean_per_insn` only when the whole stream failed
// closed (`DecodeNone`) or was omitted.
let stream_missing_boundary =
stream_entries.is_some_and(|es| !es.iter().any(|e| e.offset == d.offset));
let (kind, lean_len, lean_mnemonic, lean_detail, note) = if stream_missing_boundary {
mismatches += 1;
(
InsnVerdictKind::BoundaryMismatch,
None,
None,
None,
format!(
"Lean stream returned Ok but omitted disassembler boundary at offset 0x{:x} \
(`{} {}`)",
d.offset, d.mnemonic, d.operands
),
)
} else {
let lean_entry: Option<&LeanInsn> = match stream_entries {
Some(es) => es.iter().find(|e| e.offset == d.offset),
None => match lean_per_insn.get(idx).and_then(|o| o.as_ref()) {
Some(LeanDecodeStatus::Ok(es)) => es.first(),
_ => None,
},
};
match lean_entry {
None => {
fail_closed_gaps += 1;
let note = if d.is_bad {
"fail-closed DECODE_NONE on invalid/pseudo encoding".to_string()
} else {
format!(
"fail-closed DECODE_NONE gap (disassembler decoded `{} {}`)",
d.mnemonic, d.operands
)
};
(InsnVerdictKind::FailClosedGap, None, None, None, note)
}
Some(l) => {
if d.is_bad {
mismatches += 1;
(
InsnVerdictKind::ExtraLeanAccept,
Some(l.len),
Some(l.mnemonic.clone()),
Some(l.detail.clone()),
format!(
"Lean accepted `{}` ({} B) where disassembler reported invalid \
`{} {}`",
l.mnemonic, l.len, d.mnemonic, d.operands
),
)
} else if l.len != d.len() {
mismatches += 1;
(
InsnVerdictKind::LengthMismatch,
Some(l.len),
Some(l.mnemonic.clone()),
Some(l.detail.clone()),
format!(
"byte length mismatch: Lean {} B vs disassembler {} B",
l.len,
d.len()
),
)
} else if !mnemonics_equivalent(
arch,
&l.mnemonic,
&l.detail,
&d.mnemonic,
&d.operands,
&d.bytes,
) {
mismatches += 1;
(
InsnVerdictKind::MnemonicMismatch,
Some(l.len),
Some(l.mnemonic.clone()),
Some(l.detail.clone()),
format!(
"mnemonic mismatch: Lean `{}` vs disassembler `{}`",
l.mnemonic, d.mnemonic
),
)
} else if let Some(det_err) = check_detail_consistency(arch, l, d) {
mismatches += 1;
(
InsnVerdictKind::DetailMismatch,
Some(l.len),
Some(l.mnemonic.clone()),
Some(l.detail.clone()),
det_err,
)
} else {
matched_insns += 1;
(
InsnVerdictKind::Match,
Some(l.len),
Some(l.mnemonic.clone()),
Some(l.detail.clone()),
"exact boundary, length, mnemonic, and detail match".to_string(),
)
}
}
}
};
verdicts.push(InsnVerdict {
offset: d.offset,
bytes_hex: format_bytes_hex(&d.bytes),
kind,
disasm_len: d.len(),
disasm_mnemonic: d.mnemonic.clone(),
disasm_operands: d.operands.clone(),
lean_len,
lean_mnemonic,
lean_detail,
note,
});
}
// Record any extra boundaries produced by a whole-stream Lean decode that
// do not correspond to any disassembler instruction offset.
if let Some(es) = stream_entries {
for e in es {
if !disasm.iter().any(|d| d.offset == e.offset) {
mismatches += 1;
verdicts.push(InsnVerdict {
offset: e.offset,
bytes_hex: String::new(),
kind: InsnVerdictKind::BoundaryMismatch,
disasm_len: 0,
disasm_mnemonic: String::new(),
disasm_operands: String::new(),
lean_len: Some(e.len),
lean_mnemonic: Some(e.mnemonic.clone()),
lean_detail: Some(e.detail.clone()),
note: "Lean stream decoded boundary absent from disassembler".to_string(),
});
}
}
}
let stream_all_match =
lean_stream_ok && stream_boundary_agree && fail_closed_gaps == 0 && mismatches == 0;
LegComparison {
leg,
available: true,
error: None,
disasm_insn_count: disasm.len(),
lean_stream_ok,
stream_boundary_agree,
stream_all_match,
matched_insns,
fail_closed_gaps,
mismatches,
verdicts,
}
}
/// Build a `LegComparison` for `--disasm-only` mode where Lean did not
/// execute, recording each disassembled instruction as `DisasmOnly` rather
/// than a fake Lean `DECODE_NONE` gap.
pub fn record_disasm_only_leg(leg: DisasmLeg, disasm: &[DisasmInsn]) -> LegComparison {
let verdicts = disasm
.iter()
.map(|d| InsnVerdict {
offset: d.offset,
bytes_hex: format_bytes_hex(&d.bytes),
kind: InsnVerdictKind::DisasmOnly,
disasm_len: d.len(),
disasm_mnemonic: d.mnemonic.clone(),
disasm_operands: d.operands.clone(),
lean_len: None,
lean_mnemonic: None,
lean_detail: None,
note: "Lean decoder not executed (--disasm-only)".to_string(),
})
.collect();
LegComparison {
leg,
available: true,
error: None,
disasm_insn_count: disasm.len(),
lean_stream_ok: false,
stream_boundary_agree: false,
stream_all_match: false,
matched_insns: 0,
fail_closed_gaps: 0,
mismatches: 0,
verdicts,
}
}
/// Evaluate whether a case met its configured `CaseExpectation` and gate
/// policy across all disassembler legs and Lean output.
pub fn evaluate_case_expectation(
case: &CaseSpec,
lean_stream: Option<&LeanDecodeStatus>,
disasm_agreement: &DisasmAgreement,
legs: &[LegComparison],
policy: OracleGatePolicy,
) -> (bool, Option<String>, usize) {
let mut leg_errors = 0usize;
let mut reasons: Vec<String> = Vec::new();
let llvm_leg = legs.iter().find(|l| l.leg == DisasmLeg::LlvmObjdump);
match llvm_leg {
Some(l) if l.available => {
if !case.bytes.is_empty() && l.disasm_insn_count == 0 {
leg_errors += 1;
reasons.push("llvm-objdump decoded 0 instructions on non-empty input".to_string());
}
}
Some(l) => {
leg_errors += 1;
reasons.push(format!(
"llvm-objdump unavailable: {}",
l.error.as_deref().unwrap_or("unknown error")
));
}
None => {
leg_errors += 1;
reasons.push("llvm-objdump leg missing".to_string());
}
}
let gnu_leg = legs.iter().find(|l| l.leg == DisasmLeg::GnuObjdump);
if case.arch == Arch::X86_64 && policy.require_gnu_x86 {
match gnu_leg {
Some(l) if l.available => {
if !case.bytes.is_empty() && l.disasm_insn_count == 0 {
leg_errors += 1;
reasons
.push("gnu-objdump decoded 0 instructions on non-empty input".to_string());
}
}
Some(l) => {
leg_errors += 1;
reasons.push(format!(
"gnu-objdump unavailable on x86-64: {}",
l.error.as_deref().unwrap_or("unknown error")
));
}
None => {
leg_errors += 1;
reasons.push("gnu-objdump leg missing on x86-64".to_string());
}
}
}
if policy.require_lean && lean_stream.is_none() {
reasons.push("Lean evaluation missing (pass --lean-bin)".to_string());
}
for leg in legs.iter().filter(|l| l.available) {
if leg.mismatches > 0 {
reasons.push(format!("{:?} reported {} mismatch(es)", leg.leg, leg.mismatches));
}
}
if policy.require_lean {
match case.expectation {
CaseExpectation::FullMatch => {
if !matches!(lean_stream, Some(LeanDecodeStatus::Ok(_))) {
reasons.push(
"expected FullMatch but Lean stream returned DECODE_NONE".to_string(),
);
}
for leg in legs.iter().filter(|l| l.available) {
if !leg.stream_all_match {
reasons.push(format!(
"expected FullMatch but {:?} had gaps={} mismatches={} boundary_agree={}",
leg.leg, leg.fail_closed_gaps, leg.mismatches, leg.stream_boundary_agree
));
}
}
if disasm_agreement.compared
&& (!disasm_agreement.boundaries_agree || !disasm_agreement.mnemonics_agree)
{
reasons.push(format!(
"disassembler divergence on FullMatch case: {}",
disasm_agreement.differences.join("; ")
));
}
}
CaseExpectation::ExpectedDecodeNone => {
if !matches!(lean_stream, Some(LeanDecodeStatus::DecodeNone)) {
reasons.push(
"expected ExpectedDecodeNone but Lean stream accepted input".to_string(),
);
}
}
CaseExpectation::ReportGaps => {}
}
} else if !disasm_agreement.compared {
reasons.push(
"no differential comparison ran in --disasm-only mode (requires both llvm-objdump \
and GNU objdump legs)"
.to_string(),
);
} else if !disasm_agreement.boundaries_agree || !disasm_agreement.mnemonics_agree {
reasons.push(format!(
"disassembler divergence in --disasm-only mode: {}",
disasm_agreement.differences.join("; ")
));
}
if reasons.is_empty() {
(true, None, leg_errors)
} else {
(false, Some(reasons.join("; ")), leg_errors)
}
}
/// Assemble a `BatchReport` aggregating instruction counts, mismatches across
/// **all** available disassembler legs, expectation failures, and leg errors.
pub fn assemble_batch_report(cases: Vec<CaseReport>, total_leg_errors: usize) -> BatchReport {
let mut total_insns_checked = 0usize;
let mut total_matched_insns = 0usize;
let mut total_fail_closed_gaps = 0usize;
let mut total_mismatches = 0usize;
let mut total_expectation_failures = 0usize;
for c in &cases {
if !c.expectation_ok {
total_expectation_failures += 1;
}
// Instruction/match/gap totals come from the primary `llvm-objdump`
// leg (when available, else GNU) so dual-leg cases are not
// double-counted, while `total_mismatches` sums across EVERY available
// disassembler leg so a GNU-only mismatch always fails the run.
if let Some(primary) = c
.legs
.iter()
.find(|l| l.leg == DisasmLeg::LlvmObjdump && l.available)
.or_else(|| c.legs.iter().find(|l| l.available))
{
total_insns_checked += primary.disasm_insn_count;
total_matched_insns += primary.matched_insns;
total_fail_closed_gaps += primary.fail_closed_gaps;
}
for leg in c.legs.iter().filter(|l| l.available) {
total_mismatches += leg.mismatches;
}
}
let passed = !cases.is_empty()
&& total_insns_checked > 0
&& total_mismatches == 0
&& total_expectation_failures == 0
&& total_leg_errors == 0;
BatchReport {
schema: "anneal-isa-oracle/v1".to_string(),
passed,
total_cases: cases.len(),
total_insns_checked,
total_matched_insns,
total_fail_closed_gaps,
total_mismatches,
total_expectation_failures,
total_leg_errors,
cases,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
lean::{
encode_lean_byte_list, parse_lean_batch_output, render_lean_batch_script,
LeanBatchQuery, LeanQueryLane,
},
objdump::{
build_minimal_elf64, create_exclusive_temp_file, extract_elf64_section,
parse_objdump_output, parse_raw_insn_bytes,
},
};
#[test]
fn aarch64_big_endian_word_normalizes_to_little_endian_bytes() {
let bytes = parse_raw_insn_bytes(Arch::AArch64, "d65f03c0").expect("parse ret word");
assert_eq!(bytes, vec![0xc0, 0x03, 0x5f, 0xd6]);
let nop = parse_raw_insn_bytes(Arch::AArch64, "d503201f").expect("parse nop word");
assert_eq!(nop, vec![0x1f, 0x20, 0x03, 0xd5]);
// Space-separated byte form is also accepted verbatim.
let raw = parse_raw_insn_bytes(Arch::AArch64, "c0 03 5f d6").expect("parse raw bytes");
assert_eq!(raw, vec![0xc0, 0x03, 0x5f, 0xd6]);
}
#[test]
fn parse_llvm_objdump_x86_and_aarch64_outputs() {
let llvm_x86 = "\
/tmp/test.o:\tfile format elf64-x86-64
Disassembly of section .text:
0000000000000000 <.text>:
0: 41 90 \txchg\teax, r8d
2: 48 63 06 \tmovsxd\trax, dword ptr [rsi]
5: 6b c0 02 \timul\teax, eax, 0x2
8: c5 e9 fd cb \tvpaddw\txmm1, xmm2, xmm3
c: c5 ed fd cb \tvpaddw\tymm1, ymm2, ymm3
10: c3 \tret
";
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::LlvmObjdump, llvm_x86)
.expect("parse llvm x86");
assert_eq!(insns.len(), 6);
assert_eq!(insns[0].offset, 0);
assert_eq!(insns[0].bytes, vec![0x41, 0x90]);
assert_eq!(insns[0].mnemonic, "xchg");
assert_eq!(insns[1].mnemonic, "movsxd");
assert_eq!(insns[2].mnemonic, "imul");
assert_eq!(insns[3].operands, "xmm1, xmm2, xmm3");
assert_eq!(insns[4].operands, "ymm1, ymm2, ymm3");
assert_eq!(insns[5].offset, 0x10);
assert_eq!(insns[5].mnemonic, "ret");
let llvm_a64 = "\
/tmp/a64.o:\tfile format elf64-littleaarch64
Disassembly of section .text:
0000000000000000 <.text>:
0: 910043ff \tadd\tsp, sp, #0x10
4: b100001f \tcmn\tx0, #0x0
8: ea01001f \ttst\tx0, x1
c: a9400000 \tldp\tx0, x0, [x0]
10: d65f03c0 \tret
";
let a64 = parse_objdump_output(Arch::AArch64, DisasmLeg::LlvmObjdump, llvm_a64)
.expect("parse llvm a64");
assert_eq!(a64.len(), 5);
assert_eq!(a64[0].bytes, vec![0xff, 0x43, 0x00, 0x91]);
assert_eq!(a64[0].mnemonic, "add");
assert_eq!(a64[0].operands, "sp, sp, #0x10");
assert_eq!(a64[1].bytes, vec![0x1f, 0x00, 0x00, 0xb1]);
assert_eq!(a64[1].mnemonic, "cmn");
assert_eq!(a64[2].bytes, vec![0x1f, 0x00, 0x01, 0xea]);
assert_eq!(a64[2].mnemonic, "tst");
assert_eq!(a64[3].bytes, vec![0x00, 0x00, 0x40, 0xa9]);
assert_eq!(a64[3].mnemonic, "ldp");
assert_eq!(a64[4].bytes, vec![0xc0, 0x03, 0x5f, 0xd6]);
assert_eq!(a64[4].mnemonic, "ret");
}
#[test]
fn parse_gnu_objdump_continuation_lines_lock_and_data16_nop() {
let gnu_x86 = concat!(
"/tmp/test.o: file format elf64-x86-64\n\n",
"Disassembly of section .text:\n\n",
"0000000000000000 <.text>:\n",
" 0:\t48 b8 11 22 33 44 55 \tmovabs rax,0x8877665544332211\n",
" 7:\t66 77 88 \n",
" a:\tf0 01 c0 \tlock add eax,eax\n",
" d:\t66 66 90 \tdata16 xchg ax,ax\n",
" 10:\t66 66 66 66 66 66 66 \tdata16 data16 data16\n",
" 17:\t66 66 66 66 66 66 66 \n",
" 1e:\t66 90 \txchg ax,ax\n",
);
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::GnuObjdump, gnu_x86)
.expect("parse gnu x86");
assert_eq!(insns.len(), 5);
assert_eq!(insns[0].offset, 0);
assert_eq!(insns[0].len(), 10);
assert_eq!(
insns[0].bytes,
vec![0x48, 0xb8, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]
);
assert_eq!(insns[0].mnemonic, "movabs");
assert_eq!(insns[1].offset, 0xa);
assert!(insns[1].locked);
assert_eq!(insns[1].mnemonic, "add");
assert_eq!(insns[1].operands, "eax,eax");
// Legal multi-0x66 NOP (`66 66 90` -> `data16 xchg ax,ax`) unwraps to
// `xchg ax,ax` with `is_bad = false` and matches Lean `.nop`.
assert_eq!(insns[2].offset, 0xd);
assert_eq!(insns[2].bytes, vec![0x66, 0x66, 0x90]);
assert_eq!(insns[2].mnemonic, "xchg");
assert_eq!(insns[2].operands, "ax,ax");
assert!(!insns[2].is_bad);
let nop_lean = LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0xd,
len: 3,
mnemonic: "nop".to_string(),
detail: String::new(),
}]);
let nop_cmp = compare_against_lean(
Arch::X86_64,
DisasmLeg::GnuObjdump,
&insns[2..3],
Some(&nop_lean),
&[Some(nop_lean.clone())],
);
assert_eq!(nop_cmp.matched_insns, 1);
assert_eq!(nop_cmp.mismatches, 0);
// Standalone `data16 data16 data16` continuation remains `is_bad`.
assert_eq!(insns[3].len(), 14);
assert!(insns[3].is_bad);
}
#[test]
fn adversarial_verdicts_x86_and_aarch64() {
// 1. `41 90` (`xchg`), VEX L=0/1 (`vpaddw`), `movsxd`, and VEX `0x3B`
// `vpminud` gap.
let disasm_x86 = vec![
DisasmInsn {
offset: 0,
bytes: vec![0x41, 0x90],
mnemonic: "xchg".to_string(),
operands: "eax, r8d".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 2,
bytes: vec![0xc5, 0xe9, 0xfd, 0xcb],
mnemonic: "vpaddw".to_string(),
operands: "xmm1, xmm2, xmm3".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 6,
bytes: vec![0xc5, 0xed, 0xfd, 0xcb],
mnemonic: "vpaddw".to_string(),
operands: "ymm1, ymm2, ymm3".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 10,
bytes: vec![0x48, 0x63, 0x06],
mnemonic: "movsxd".to_string(),
operands: "rax, dword ptr [rsi]".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 13,
bytes: vec![0xc4, 0xe2, 0x6d, 0x3b, 0xcb],
mnemonic: "vpminud".to_string(),
operands: "ymm1, ymm2, ymm3".to_string(),
locked: false,
is_bad: false,
},
];
let per_insn = vec![
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 2,
mnemonic: "xchg".to_string(),
detail: String::new(),
}])),
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 2,
len: 4,
mnemonic: "vpaddw".to_string(),
detail: "vex=128".to_string(),
}])),
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 6,
len: 4,
mnemonic: "vpaddw".to_string(),
detail: "vex=256".to_string(),
}])),
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 10,
len: 3,
mnemonic: "movsxd".to_string(),
detail: "sext32".to_string(),
}])),
Some(LeanDecodeStatus::DecodeNone),
];
let cmp = compare_against_lean(
Arch::X86_64,
DisasmLeg::LlvmObjdump,
&disasm_x86,
Some(&LeanDecodeStatus::DecodeNone),
&per_insn,
);
assert_eq!(cmp.matched_insns, 4);
assert_eq!(cmp.fail_closed_gaps, 1);
assert_eq!(cmp.mismatches, 0);
assert_eq!(cmp.verdicts[4].kind, InsnVerdictKind::FailClosedGap);
// 2. VEX L-bit width mismatch is caught as `DetailMismatch`.
let bad_vex = vec![Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 2,
len: 4,
mnemonic: "vpaddw".to_string(),
detail: "vex=256".to_string(),
}]))];
let vex_cmp = compare_against_lean(
Arch::X86_64,
DisasmLeg::LlvmObjdump,
&disasm_x86[1..2],
None,
&bad_vex,
);
assert_eq!(vex_cmp.mismatches, 1);
assert_eq!(vex_cmp.verdicts[0].kind, InsnVerdictKind::DetailMismatch);
// 3. AArch64 `ldp` overlap (fail-closed) + `x31` SP vs XZR (`cmn` and
// shifted-register `tst` aliases).
let disasm_a64 = vec![
DisasmInsn {
offset: 0,
bytes: vec![0xff, 0x43, 0x00, 0x91],
mnemonic: "add".to_string(),
operands: "sp, sp, #0x10".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 4,
bytes: vec![0x1f, 0x00, 0x00, 0xb1],
mnemonic: "cmn".to_string(),
operands: "x0, #0x0".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 8,
bytes: vec![0x1f, 0x00, 0x01, 0xea],
mnemonic: "tst".to_string(),
operands: "x0, x1".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 12,
bytes: vec![0x00, 0x00, 0x40, 0xa9],
mnemonic: "ldp".to_string(),
operands: "x0, x0, [x0]".to_string(),
locked: false,
is_bad: false,
},
];
let a64_per = vec![
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 4,
mnemonic: "add".to_string(),
detail: "rd=sp,rn=sp".to_string(),
}])),
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 4,
len: 4,
mnemonic: "adds".to_string(),
detail: "rd=zr".to_string(),
}])),
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 8,
len: 4,
mnemonic: "ands".to_string(),
detail: "rd=zr".to_string(),
}])),
Some(LeanDecodeStatus::DecodeNone),
];
let a64_cmp = compare_against_lean(
Arch::AArch64,
DisasmLeg::LlvmObjdump,
&disasm_a64,
Some(&LeanDecodeStatus::DecodeNone),
&a64_per,
);
assert_eq!(a64_cmp.matched_insns, 3);
assert_eq!(a64_cmp.fail_closed_gaps, 1);
assert_eq!(a64_cmp.mismatches, 0);
}
#[test]
fn batch_gate_enforces_gnu_mismatches_expectations_and_availability() {
let case = CaseSpec {
id: "test_case".to_string(),
description: "sample".to_string(),
arch: Arch::X86_64,
x86_lane: X86DecoderLane::WordSimd,
bytes: vec![0x41, 0x90],
expectation: CaseExpectation::FullMatch,
};
let lean_ok = LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 2,
mnemonic: "xchg".to_string(),
detail: String::new(),
}]);
let llvm_ok = LegComparison {
leg: DisasmLeg::LlvmObjdump,
available: true,
error: None,
disasm_insn_count: 1,
lean_stream_ok: true,
stream_boundary_agree: true,
stream_all_match: true,
matched_insns: 1,
fail_closed_gaps: 0,
mismatches: 0,
verdicts: Vec::new(),
};
let gnu_mismatch = LegComparison {
leg: DisasmLeg::GnuObjdump,
available: true,
error: None,
disasm_insn_count: 1,
lean_stream_ok: true,
stream_boundary_agree: true,
stream_all_match: false,
matched_insns: 0,
fail_closed_gaps: 0,
mismatches: 1,
verdicts: Vec::new(),
};
let agree_ok = DisasmAgreement {
compared: true,
boundaries_agree: true,
mnemonics_agree: true,
differences: Vec::new(),
};
// 1. GNU-only mismatch MUST fail the case and batch report.
let (ok, err, leg_errs) = evaluate_case_expectation(
&case,
Some(&lean_ok),
&agree_ok,
&[llvm_ok.clone(), gnu_mismatch.clone()],
OracleGatePolicy::default(),
);
assert!(!ok);
assert!(err.unwrap().contains("GnuObjdump"));
assert_eq!(leg_errs, 0);
let batch = assemble_batch_report(
vec![CaseReport {
id: case.id.clone(),
description: case.description.clone(),
arch: case.arch,
x86_lane: case.x86_lane,
byte_len: case.bytes.len(),
bytes_hex: format_bytes_hex(&case.bytes),
expectation: case.expectation,
expectation_ok: ok,
expectation_error: Some("gnu mismatch".to_string()),
lean_stream_status: Some(lean_ok.clone()),
disasm_agreement: agree_ok.clone(),
legs: vec![llvm_ok.clone(), gnu_mismatch],
}],
leg_errs,
);
assert!(!batch.passed);
assert_eq!(batch.total_mismatches, 1);
assert_eq!(batch.total_expectation_failures, 1);
// 2. Missing llvm-objdump MUST increment `leg_errors` and fail batch.
let llvm_missing = LegComparison {
leg: DisasmLeg::LlvmObjdump,
available: false,
error: Some("not found".to_string()),
disasm_insn_count: 0,
lean_stream_ok: true,
stream_boundary_agree: false,
stream_all_match: false,
matched_insns: 0,
fail_closed_gaps: 0,
mismatches: 0,
verdicts: Vec::new(),
};
let (ok2, _, leg_errs2) = evaluate_case_expectation(
&case,
Some(&lean_ok),
&DisasmAgreement {
compared: false,
boundaries_agree: false,
mnemonics_agree: false,
differences: Vec::new(),
},
&[llvm_missing],
OracleGatePolicy::default(),
);
assert!(!ok2);
assert!(leg_errs2 >= 1);
// 3. FullMatch regressing to DECODE_NONE MUST fail expectation.
let (ok3, err3, _) = evaluate_case_expectation(
&case,
Some(&LeanDecodeStatus::DecodeNone),
&agree_ok,
&[llvm_ok.clone(), llvm_ok.clone()],
OracleGatePolicy { require_lean: true, require_gnu_x86: false },
);
assert!(!ok3);
assert!(err3.unwrap().contains("DECODE_NONE"));
// 4. Omitting Lean evaluation when `require_lean = true` MUST fail.
let (ok4, err4, _) = evaluate_case_expectation(
&case,
None,
&agree_ok,
&[llvm_ok],
OracleGatePolicy { require_lean: true, require_gnu_x86: false },
);
assert!(!ok4);
assert!(err4.unwrap().contains("Lean evaluation missing"));
}
#[test]
fn malformed_elf64_shdr_offsets_fail_without_overflow_panic() {
let mut elf = build_minimal_elf64(Arch::X86_64, &[0xc3]);
// Set `e_shoff = u64::MAX - 10` and `e_shstrndx = 0` so naive
// `shstr_hdr + 24` would overflow.
elf[40..48].copy_from_slice(&(u64::MAX - 10).to_le_bytes());
elf[62..64].copy_from_slice(&0u16.to_le_bytes());
assert!(extract_elf64_section(&elf, ".text").is_err());
// Set `e_shoff` near `usize::MAX` with `e_shnum = 3` so loop index
// multiplication/addition would overflow.
elf[40..48].copy_from_slice(&(u64::MAX - 64).to_le_bytes());
elf[62..64].copy_from_slice(&1u16.to_le_bytes());
assert!(extract_elf64_section(&elf, ".text").is_err());
}
#[test]
fn exclusive_temp_file_creates_distinct_files_cleanly() {
let dir = std::env::temp_dir();
let p1 = create_exclusive_temp_file(&dir, "unit", b"abc").expect("create temp 1");
let p2 = create_exclusive_temp_file(&dir, "unit", b"def").expect("create temp 2");
assert_ne!(p1, p2);
assert_eq!(std::fs::read(&p1).expect("read p1"), b"abc");
assert_eq!(std::fs::read(&p2).expect("read p2"), b"def");
let _ = std::fs::remove_file(&p1);
let _ = std::fs::remove_file(&p2);
}
#[test]
fn minimal_elf64_roundtrips_for_both_architectures() {
let x86_bytes = vec![0x41, 0x90, 0x48, 0x63, 0x06, 0xc3];
let x86_elf = build_minimal_elf64(Arch::X86_64, &x86_bytes);
let (arch, extracted) = extract_elf64_section(&x86_elf, ".text").expect("extract x86");
assert_eq!(arch, Arch::X86_64);
assert_eq!(extracted, x86_bytes);
let a64_bytes = vec![0xc0, 0x03, 0x5f, 0xd6, 0x1f, 0x20, 0x03, 0xd5];
let a64_elf = build_minimal_elf64(Arch::AArch64, &a64_bytes);
let (arch2, extracted2) = extract_elf64_section(&a64_elf, ".text").expect("extract a64");
assert_eq!(arch2, Arch::AArch64);
assert_eq!(extracted2, a64_bytes);
}
#[test]
fn lean_batch_script_and_output_parser_roundtrip() {
let q = LeanBatchQuery {
id: "case0".to_string(),
lane: LeanQueryLane::X86WordSimdStream,
pos: 0,
require_reloc: false,
bmi1: false,
popcnt: false,
lzcnt: false,
bytes: vec![0x41, 0x90, 0xc3],
};
let script = render_lean_batch_script(&[q]).expect("render script");
assert!(script.contains("import Anneal.IsaOracleDriver"));
assert!(script.contains(".x86WordSimdStream"));
assert!(script.contains("[0x41, 0x90, 0xC3]"));
// Large byte vectors chunk into <= 32 byte sublists.
let big = vec![0x90u8; 40];
let encoded = encode_lean_byte_list(&big);
assert!(encoded.contains(" ++ "));
let out = "\
ORACLE|case0|OK 0:2:xchg;2:1:ret
ORACLE|case1|NONE
ORACLE|case2|OK 0:4:vpaddw/vex=256
";
let parsed = parse_lean_batch_output(out).expect("parse lean out");
assert_eq!(parsed.len(), 3);
assert_eq!(parsed["case1"], LeanDecodeStatus::DecodeNone);
match &parsed["case2"] {
LeanDecodeStatus::Ok(es) => {
assert_eq!(es.len(), 1);
assert_eq!(es[0].mnemonic, "vpaddw");
assert_eq!(es[0].detail, "vex=256");
}
other => panic!("unexpected status: {other:?}"),
}
}
#[test]
fn nop_self_xchg_alias_and_aarch64_mov_trap_aliases_require_matching_encoding() {
// x86-64 `nop` <-> `xchg` alias accepts only post-prefix opcode `0x90`
// with `REX.B == 0`, rejecting `41 90` and ModR/M `87 c0` / `48 87 c0`
// / `66 87 c0`.
assert!(mnemonics_equivalent(Arch::X86_64, "nop", "", "xchg", "ax,ax", &[0x66, 0x90]));
assert!(mnemonics_equivalent(Arch::X86_64, "nop", "", "xchg", "rax,rax", &[0x48, 0x90]));
assert!(!mnemonics_equivalent(Arch::X86_64, "nop", "", "xchg", "r8d,eax", &[0x41, 0x90]));
assert!(!mnemonics_equivalent(Arch::X86_64, "nop", "", "xchg", "eax,eax", &[0x87, 0xc0]));
assert!(!mnemonics_equivalent(
Arch::X86_64,
"nop",
"",
"xchg",
"rax,rax",
&[0x48, 0x87, 0xc0],
));
assert!(!mnemonics_equivalent(
Arch::X86_64,
"nop",
"",
"xchg",
"ax,ax",
&[0x66, 0x87, 0xc0],
));
// AArch64 `mov` aliases must match exact encoding class and operand
// shape: `d2800020` (`movz x0, #0x1`) accepts ONLY `movz`, never
// `add`/`orr`/`movn`.
let movz_bytes = 0xd280_0020u32.to_le_bytes();
assert!(mnemonics_equivalent(Arch::AArch64, "movz", "", "mov", "x0, #0x1", &movz_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "add", "", "mov", "x0, #0x1", &movz_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "orr", "", "mov", "x0, #0x1", &movz_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "movn", "", "mov", "x0, #0x1", &movz_bytes));
// `910003e0` (`mov x0, sp` = `add x0, sp, #0`) accepts ONLY `add`.
let add_sp_bytes = 0x9100_03e0u32.to_le_bytes();
assert!(mnemonics_equivalent(
Arch::AArch64,
"add",
"rn=sp",
"mov",
"x0, sp",
&add_sp_bytes
));
assert!(!mnemonics_equivalent(Arch::AArch64, "orr", "", "mov", "x0, sp", &add_sp_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "movz", "", "mov", "x0, sp", &add_sp_bytes));
// `aa0103e0` (`mov x0, x1` = `orr x0, xzr, x1`) accepts ONLY `orr`.
let orr_reg_bytes = 0xaa01_03e0u32.to_le_bytes();
assert!(mnemonics_equivalent(Arch::AArch64, "orr", "", "mov", "x0, x1", &orr_reg_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "add", "", "mov", "x0, x1", &orr_reg_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "movz", "", "mov", "x0, x1", &orr_reg_bytes));
// `92800000` (`mov x0, #-0x1` = `movn x0, #0`) accepts ONLY `movn`.
let movn_bytes = 0x9280_0000u32.to_le_bytes();
assert!(mnemonics_equivalent(Arch::AArch64, "movn", "", "mov", "x0, #-0x1", &movn_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "movz", "", "mov", "x0, #-0x1", &movn_bytes));
// `trap` <-> `brk`/`hlt` must match `BRK` (`0xd4200000`) / `HLT`
// (`0xd4400000`) encoding and immediate operand.
let brk_bytes = 0xd420_0000u32.to_le_bytes();
let hlt_bytes = 0xd440_0000u32.to_le_bytes();
assert!(mnemonics_equivalent(Arch::AArch64, "trap", "", "brk", "#0", &brk_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "trap", "", "hlt", "#0", &brk_bytes));
assert!(mnemonics_equivalent(Arch::AArch64, "trap", "", "hlt", "#0", &hlt_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "trap", "", "brk", "#0", &hlt_bytes));
assert!(!mnemonics_equivalent(Arch::AArch64, "trap", "", "brk", "#0", &movz_bytes));
}
#[test]
fn disasm_only_mode_gates_on_disassembler_divergence_without_fake_gaps() {
let case = CaseSpec {
id: "disasm_only_div".to_string(),
description: "LOCK on register diverges between llvm and GNU".to_string(),
arch: Arch::X86_64,
x86_lane: X86DecoderLane::WordSimd,
bytes: vec![0xf0, 0x01, 0xc0],
expectation: CaseExpectation::ReportGaps,
};
let llvm_insns = vec![
DisasmInsn {
offset: 0,
bytes: vec![0xf0],
mnemonic: "lock".to_string(),
operands: String::new(),
locked: true,
is_bad: false,
},
DisasmInsn {
offset: 1,
bytes: vec![0x01, 0xc0],
mnemonic: "add".to_string(),
operands: "eax, eax".to_string(),
locked: false,
is_bad: false,
},
];
let gnu_insns = vec![DisasmInsn {
offset: 0,
bytes: vec![0xf0, 0x01, 0xc0],
mnemonic: "add".to_string(),
operands: "eax,eax".to_string(),
locked: true,
is_bad: false,
}];
let llvm_leg = record_disasm_only_leg(DisasmLeg::LlvmObjdump, &llvm_insns);
let gnu_leg = record_disasm_only_leg(DisasmLeg::GnuObjdump, &gnu_insns);
assert_eq!(llvm_leg.fail_closed_gaps, 0);
assert!(llvm_leg.verdicts.iter().all(|v| v.kind == InsnVerdictKind::DisasmOnly));
let agreement = compare_disassemblers(Arch::X86_64, Some(&llvm_insns), Some(&gnu_insns));
assert!(!agreement.boundaries_agree);
let (ok, err, leg_errs) = evaluate_case_expectation(
&case,
None,
&agreement,
&[llvm_leg.clone(), gnu_leg.clone()],
OracleGatePolicy { require_lean: false, require_gnu_x86: true },
);
assert!(!ok);
assert!(err.unwrap().contains("disassembler divergence in --disasm-only"));
let batch = assemble_batch_report(
vec![CaseReport {
id: case.id,
description: case.description,
arch: case.arch,
x86_lane: case.x86_lane,
byte_len: case.bytes.len(),
bytes_hex: format_bytes_hex(&case.bytes),
expectation: case.expectation,
expectation_ok: ok,
expectation_error: Some("divergence".to_string()),
lean_stream_status: None,
disasm_agreement: agreement,
legs: vec![llvm_leg, gnu_leg],
}],
leg_errs,
);
assert!(!batch.passed);
assert_eq!(batch.total_fail_closed_gaps, 0);
}
#[test]
fn parse_gnu_objdump_strips_repz_ret_cs_and_rex_prefixes() {
let gnu_x86 = concat!(
"/tmp/p.o: file format elf64-x86-64\n\n",
"Disassembly of section .text:\n\n",
"0000000000000000 <.text>:\n",
" 0:\tf3 c3 \trepz ret\n",
" 2:\t66 2e 0f 1f 84 00 00 \tcs nop WORD PTR [rax+rax*1+0x0]\n",
" 9:\t00 00 00 \n",
" c:\t48 90 \trex.W nop\n",
" e:\t48 74 05 \trex.W je 0x16\n",
" 11:\t48 b4 12 \trex.W mov spl,0x12\n",
" 14:\t41 04 01 \trex.B add al,0x1\n",
);
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::GnuObjdump, gnu_x86)
.expect("parse gnu prefixed insns");
assert_eq!(insns.len(), 6);
assert_eq!(insns[0].mnemonic, "ret");
assert_eq!(insns[1].mnemonic, "nop");
assert_eq!(insns[1].len(), 10);
assert_eq!(insns[2].mnemonic, "nop");
assert_eq!(insns[3].mnemonic, "je");
assert_eq!(insns[4].mnemonic, "mov");
assert_eq!(insns[5].mnemonic, "add");
}
#[test]
fn check_detail_consistency_catches_lock_mismatch_with_nonempty_detail() {
let locked_disasm = DisasmInsn {
offset: 0,
bytes: vec![0xf0, 0x48, 0x63, 0x06],
mnemonic: "movsxd".to_string(),
operands: "rax, dword ptr [rsi]".to_string(),
locked: true,
is_bad: false,
};
let lean_sext = LeanInsn {
offset: 0,
len: 4,
mnemonic: "movsxd".to_string(),
detail: "sext32".to_string(),
};
assert!(check_detail_consistency(Arch::X86_64, &lean_sext, &locked_disasm).is_some());
let locked_vex_disasm = DisasmInsn {
offset: 0,
bytes: vec![0xf0, 0xc5, 0xe9, 0xfd, 0xcb],
mnemonic: "vpaddw".to_string(),
operands: "xmm1, xmm2, xmm3".to_string(),
locked: true,
is_bad: false,
};
let lean_vex = LeanInsn {
offset: 0,
len: 5,
mnemonic: "vpaddw".to_string(),
detail: "vex=128".to_string(),
};
assert!(check_detail_consistency(Arch::X86_64, &lean_vex, &locked_vex_disasm).is_some());
}
#[test]
fn stream_ok_with_missing_disasm_boundary_records_mismatch_even_with_per_insn_match() {
let disasm = vec![
DisasmInsn {
offset: 0,
bytes: vec![0x41, 0x90],
mnemonic: "xchg".to_string(),
operands: "eax, r8d".to_string(),
locked: false,
is_bad: false,
},
DisasmInsn {
offset: 2,
bytes: vec![0xc3],
mnemonic: "ret".to_string(),
operands: String::new(),
locked: false,
is_bad: false,
},
];
// Truncated whole-stream Ok omitting the trailing `ret` at offset 2.
let truncated_stream = LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 2,
mnemonic: "xchg".to_string(),
detail: String::new(),
}]);
// Even though per-instruction probes match both offsets, whole-stream
// Ok must NOT silently fall back to per-instruction probes.
let per_insn = vec![
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 2,
mnemonic: "xchg".to_string(),
detail: String::new(),
}])),
Some(LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 2,
len: 1,
mnemonic: "ret".to_string(),
detail: String::new(),
}])),
];
let cmp = compare_against_lean(
Arch::X86_64,
DisasmLeg::LlvmObjdump,
&disasm,
Some(&truncated_stream),
&per_insn,
);
assert!(!cmp.stream_boundary_agree);
assert_eq!(cmp.matched_insns, 1);
assert_eq!(cmp.mismatches, 1);
assert_eq!(cmp.verdicts[1].kind, InsnVerdictKind::BoundaryMismatch);
// Under `ReportGaps` (`--hex`/`--elf`), this mismatch MUST fail the
// gate.
let case = CaseSpec {
id: "truncated_stream".to_string(),
description: "stream omits trailing boundary".to_string(),
arch: Arch::X86_64,
x86_lane: X86DecoderLane::WordSimd,
bytes: vec![0x41, 0x90, 0xc3],
expectation: CaseExpectation::ReportGaps,
};
let (ok, err, _) = evaluate_case_expectation(
&case,
Some(&truncated_stream),
&DisasmAgreement {
compared: false,
boundaries_agree: false,
mnemonics_agree: false,
differences: Vec::new(),
},
&[cmp],
OracleGatePolicy { require_lean: true, require_gnu_x86: false },
);
assert!(!ok);
assert!(err.unwrap().contains("mismatch"));
}
#[test]
fn parse_gnu_objdump_marks_operand_bad_as_invalid_for_extra_lean_accept() {
let gnu_x86 = concat!(
"/tmp/bad.o: file format elf64-x86-64\n\n",
"Disassembly of section .text:\n\n",
"0000000000000000 <.text>:\n",
" 0:\t8d c0 \tlea eax,(bad)\n",
" 2:\tc5 f8 17 c0 \tvmovhps (bad),xmm0\n",
);
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::GnuObjdump, gnu_x86)
.expect("parse gnu operand (bad)");
assert_eq!(insns.len(), 2);
assert!(insns[0].is_bad);
assert!(insns[1].is_bad);
// Erroneous Lean acceptance of an operand-`(bad)` line MUST flag
// `ExtraLeanAccept`.
let bad_accept = LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 2,
mnemonic: "lea".to_string(),
detail: String::new(),
}]);
let cmp = compare_against_lean(
Arch::X86_64,
DisasmLeg::GnuObjdump,
&insns[0..1],
Some(&bad_accept),
&[Some(bad_accept.clone())],
);
assert_eq!(cmp.mismatches, 1);
assert_eq!(cmp.verdicts[0].kind, InsnVerdictKind::ExtraLeanAccept);
}
#[test]
fn check_detail_consistency_enforces_bidirectional_vex_and_positional_a64_x31() {
// Trigger 1: AArch64 `add sp, sp, #0x10` must fail if Lean omits tags.
let add_sp_sp = DisasmInsn {
offset: 0,
bytes: vec![0xff, 0x43, 0x00, 0x91],
mnemonic: "add".to_string(),
operands: "sp, sp, #0x10".to_string(),
locked: false,
is_bad: false,
};
let lean_add_empty =
LeanInsn { offset: 0, len: 4, mnemonic: "add".to_string(), detail: String::new() };
assert!(check_detail_consistency(Arch::AArch64, &lean_add_empty, &add_sp_sp).is_some());
let lean_add_sp_sp = LeanInsn {
offset: 0,
len: 4,
mnemonic: "add".to_string(),
detail: "rd=sp,rn=sp".to_string(),
};
assert!(check_detail_consistency(Arch::AArch64, &lean_add_sp_sp, &add_sp_sp).is_none());
// Trigger 2: x86-64 VEX width must match bidirectionally even when
// `lean.detail` is empty or holds another tag.
let vpaddw_ymm = DisasmInsn {
offset: 0,
bytes: vec![0xc5, 0xed, 0xfd, 0xcb],
mnemonic: "vpaddw".to_string(),
operands: "ymm1, ymm2, ymm3".to_string(),
locked: false,
is_bad: false,
};
let lean_no_vex =
LeanInsn { offset: 0, len: 4, mnemonic: "vpaddw".to_string(), detail: String::new() };
assert!(check_detail_consistency(Arch::X86_64, &lean_no_vex, &vpaddw_ymm).is_some());
let lean_other_tag = LeanInsn {
offset: 0,
len: 4,
mnemonic: "vpaddw".to_string(),
detail: "sext32".to_string(),
};
assert!(check_detail_consistency(Arch::X86_64, &lean_other_tag, &vpaddw_ymm).is_some());
let lean_vex256 = LeanInsn {
offset: 0,
len: 4,
mnemonic: "vpaddw".to_string(),
detail: "vex=256".to_string(),
};
assert!(check_detail_consistency(Arch::X86_64, &lean_vex256, &vpaddw_ymm).is_none());
let vpaddw_xmm = DisasmInsn {
offset: 0,
bytes: vec![0xc5, 0xe9, 0xfd, 0xcb],
mnemonic: "vpaddw".to_string(),
operands: "xmm1, xmm2, xmm3".to_string(),
locked: false,
is_bad: false,
};
assert!(check_detail_consistency(Arch::X86_64, &lean_no_vex, &vpaddw_xmm).is_some());
let lean_vex128 = LeanInsn {
offset: 0,
len: 4,
mnemonic: "vpaddw".to_string(),
detail: "vex=128".to_string(),
};
assert!(check_detail_consistency(Arch::X86_64, &lean_vex128, &vpaddw_xmm).is_none());
// Trigger 3: Positional `rd=sp` vs `rn=sp` on `add x0, sp, #0x10`.
let add_x0_sp = DisasmInsn {
offset: 0,
bytes: vec![0xe0, 0x43, 0x00, 0x91],
mnemonic: "add".to_string(),
operands: "x0, sp, #0x10".to_string(),
locked: false,
is_bad: false,
};
let lean_rd_sp = LeanInsn {
offset: 0,
len: 4,
mnemonic: "add".to_string(),
detail: "rd=sp".to_string(),
};
let lean_rn_sp = LeanInsn {
offset: 0,
len: 4,
mnemonic: "add".to_string(),
detail: "rn=sp".to_string(),
};
assert!(check_detail_consistency(Arch::AArch64, &lean_rd_sp, &add_x0_sp).is_some());
assert!(check_detail_consistency(Arch::AArch64, &lean_add_sp_sp, &add_x0_sp).is_some());
assert!(check_detail_consistency(Arch::AArch64, &lean_add_empty, &add_x0_sp).is_some());
assert!(check_detail_consistency(Arch::AArch64, &lean_rn_sp, &add_x0_sp).is_none());
// `cmp sp, #0x10` requires both `rd=zr` and `rn=sp`; `ldr x0, [sp,
// #16]` must not expect ALU `rn=sp`.
let cmp_sp = DisasmInsn {
offset: 0,
bytes: vec![0xff, 0x43, 0x00, 0xf1],
mnemonic: "cmp".to_string(),
operands: "sp, #0x10".to_string(),
locked: false,
is_bad: false,
};
let lean_cmp_missing_rn = LeanInsn {
offset: 0,
len: 4,
mnemonic: "subs".to_string(),
detail: "rd=zr".to_string(),
};
let lean_cmp_ok = LeanInsn {
offset: 0,
len: 4,
mnemonic: "subs".to_string(),
detail: "rd=zr,rn=sp".to_string(),
};
assert!(check_detail_consistency(Arch::AArch64, &lean_cmp_missing_rn, &cmp_sp).is_some());
assert!(check_detail_consistency(Arch::AArch64, &lean_cmp_ok, &cmp_sp).is_none());
let ldr_sp = DisasmInsn {
offset: 0,
bytes: vec![0xe0, 0x0b, 0x40, 0xf9],
mnemonic: "ldr".to_string(),
operands: "x0, [sp, #16]".to_string(),
locked: false,
is_bad: false,
};
let lean_ldr =
LeanInsn { offset: 0, len: 4, mnemonic: "ldr".to_string(), detail: "w=64".to_string() };
assert!(check_detail_consistency(Arch::AArch64, &lean_ldr, &ldr_sp).is_none());
}
#[test]
fn parse_gnu_objdump_strips_notrack_fs_gs_addr32_and_preserves_non_nop_data16() {
let gnu_x86 = concat!(
"/tmp/pfx2.o: file format elf64-x86-64\n\n",
"Disassembly of section .text:\n\n",
"0000000000000000 <.text>:\n",
" 0:\t3e ff e0 \tnotrack jmp rax\n",
" 3:\t3e ff d0 \tnotrack call rax\n",
" 6:\t64 89 c0 \tfs mov eax,eax\n",
" 9:\t65 89 c0 \tgs mov eax,eax\n",
" c:\t67 89 c0 \taddr32 mov eax,eax\n",
" f:\t64 c5 e9 fd cb \tfs vpaddw xmm1,xmm2,xmm3\n",
" 14:\t67 0f 44 c3 \taddr32 cmove eax,ebx\n",
" 18:\t66 66 2e 0f 1f 84 00 \tdata16 cs nop WORD PTR [rax+rax*1+0x0]\n",
" 1f:\t00 00 00 00\n",
" 23:\t66 74 02 \tdata16 je 0x28\n",
" 26:\t66 00 c0 \tdata16 add al,al\n",
);
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::GnuObjdump, gnu_x86)
.expect("parse gnu prefix forms");
assert_eq!(insns.len(), 10);
let expected = [
("jmp", false),
("call", false),
("mov", false),
("mov", false),
("mov", false),
("vpaddw", false),
("cmove", false),
("nop", false),
("data16", true),
("data16", true),
];
for (i, (mn, bad)) in expected.iter().enumerate() {
assert_eq!(insns[i].mnemonic, *mn, "idx {i}");
assert_eq!(insns[i].is_bad, *bad, "idx {i}");
}
}
#[test]
fn disasm_only_mode_fails_non_vacuously_when_only_one_leg_is_available() {
let a64_ret = DisasmInsn {
offset: 0,
bytes: vec![0xc0, 0x03, 0x5f, 0xd6],
mnemonic: "ret".to_string(),
operands: String::new(),
locked: false,
is_bad: false,
};
let llvm_leg =
record_disasm_only_leg(DisasmLeg::LlvmObjdump, std::slice::from_ref(&a64_ret));
let gnu_unavail = LegComparison {
leg: DisasmLeg::GnuObjdump,
available: false,
error: Some("GNU objdump lacks AArch64 target".to_string()),
disasm_insn_count: 0,
lean_stream_ok: false,
matched_insns: 0,
fail_closed_gaps: 0,
mismatches: 0,
stream_boundary_agree: false,
stream_all_match: false,
verdicts: Vec::new(),
};
let agree = compare_disassemblers(Arch::AArch64, Some(&[a64_ret]), None);
assert!(!agree.compared);
// AArch64 `--disasm-only` with only `llvm-objdump` MUST fail
// non-vacuously.
let a64_case = CaseSpec {
id: "a64_single_leg_disasm_only".to_string(),
description: "single-leg AArch64 --disasm-only".to_string(),
arch: Arch::AArch64,
x86_lane: X86DecoderLane::Base,
bytes: vec![0xc0, 0x03, 0x5f, 0xd6],
expectation: CaseExpectation::ReportGaps,
};
let (ok_a64, err_a64, leg_errs_a64) = evaluate_case_expectation(
&a64_case,
None,
&agree,
&[llvm_leg.clone(), gnu_unavail.clone()],
OracleGatePolicy { require_lean: false, require_gnu_x86: true },
);
assert!(!ok_a64);
assert!(err_a64.as_deref().unwrap_or("").contains("no differential comparison"));
let report = assemble_batch_report(
vec![CaseReport {
id: a64_case.id,
description: a64_case.description,
arch: Arch::AArch64,
x86_lane: X86DecoderLane::Base,
byte_len: 4,
bytes_hex: "c0035fd6".to_string(),
expectation: CaseExpectation::ReportGaps,
expectation_ok: ok_a64,
expectation_error: err_a64,
lean_stream_status: None,
disasm_agreement: agree.clone(),
legs: vec![llvm_leg.clone(), gnu_unavail.clone()],
}],
leg_errs_a64,
);
assert!(!report.passed);
// x86-64 `--disasm-only --allow-missing-gnu` with missing GNU MUST
// also fail non-vacuously.
let x86_case = CaseSpec {
id: "x86_single_leg_disasm_only".to_string(),
description: "single-leg x86-64 --disasm-only".to_string(),
arch: Arch::X86_64,
x86_lane: X86DecoderLane::WordSimd,
bytes: vec![0xc3],
expectation: CaseExpectation::ReportGaps,
};
let (ok_x86, err_x86, _) = evaluate_case_expectation(
&x86_case,
None,
&agree,
&[llvm_leg, gnu_unavail],
OracleGatePolicy { require_lean: false, require_gnu_x86: false },
);
assert!(!ok_x86);
assert!(err_x86.as_deref().unwrap_or("").contains("no differential comparison"));
}
#[test]
fn parse_gnu_objdump_strips_redundant_data16_on_rex_w_and_dup_66_but_keeps_unmodeled() {
let gnu_x86 = concat!(
"/tmp/d16.o: file format elf64-x86-64\n\n",
"Disassembly of section .text:\n\n",
"0000000000000000 <.text>:\n",
" 0:\t66 48 50 \tdata16 rex.W push rax\n",
" 3:\t66 48 89 c0 \tdata16 mov rax,rax\n",
" 7:\t66 48 0f 44 c3 \tdata16 cmove rax,rbx\n",
" c:\t66 48 0f b6 c3 \tdata16 movzx rax,bl\n",
" 11:\t66 66 50 \tdata16 push ax\n",
" 14:\t66 66 48 50 \tdata16 data16 rex.W push rax\n",
" 18:\t66 66 66 66 66 66 66 \tdata16 data16 data16 data16 data16 data16 data16 rex.W push rax\n",
" 1f:\t48 50\n",
" 21:\t66 74 02 \tdata16 je 0x26\n",
" 24:\t66 00 c0 \tdata16 add al,al\n",
);
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::GnuObjdump, gnu_x86)
.expect("parse gnu data16 forms");
assert_eq!(insns.len(), 9);
let expected = [
("push", false),
("mov", false),
("cmove", false),
("movzx", false),
("push", false),
("push", false),
("push", false),
("data16", true),
("data16", true),
];
for (i, (mn, bad)) in expected.iter().enumerate() {
assert_eq!(insns[i].mnemonic, *mn, "idx {i}");
assert_eq!(insns[i].is_bad, *bad, "idx {i}");
}
assert_eq!(insns[6].bytes.len(), 9);
}
#[test]
fn compare_disassemblers_detects_is_bad_and_locked_divergence() {
let lea_ok = DisasmInsn {
offset: 0,
bytes: vec![0x8d, 0xc0],
mnemonic: "lea".to_string(),
operands: "eax, eax".to_string(),
locked: false,
is_bad: false,
};
let lea_bad = DisasmInsn {
offset: 0,
bytes: vec![0x8d, 0xc0],
mnemonic: "lea".to_string(),
operands: "(bad)".to_string(),
locked: false,
is_bad: true,
};
let ag_bad = compare_disassemblers(
Arch::X86_64,
Some(std::slice::from_ref(&lea_ok)),
Some(std::slice::from_ref(&lea_bad)),
);
assert!(ag_bad.compared);
assert!(ag_bad.boundaries_agree);
assert!(!ag_bad.mnemonics_agree);
assert!(ag_bad.differences.iter().any(|d| d.contains("validity divergence")));
let add_unlocked = DisasmInsn {
offset: 0,
bytes: vec![0xf0, 0x01, 0x00],
mnemonic: "add".to_string(),
operands: "dword ptr [rax], eax".to_string(),
locked: false,
is_bad: false,
};
let add_locked = DisasmInsn { locked: true, ..add_unlocked.clone() };
let ag_lock = compare_disassemblers(
Arch::X86_64,
Some(std::slice::from_ref(&add_unlocked)),
Some(std::slice::from_ref(&add_locked)),
);
assert!(ag_lock.compared);
assert!(ag_lock.boundaries_agree);
assert!(!ag_lock.mnemonics_agree);
assert!(ag_lock.differences.iter().any(|d| d.contains("LOCK prefix divergence")));
}
#[test]
fn parse_gnu_objdump_preserves_ud_vex_prefixes_and_0x66_rexw_branch_or_byte() {
let gnu_x86 = concat!(
"/tmp/ud.o: file format elf64-x86-64\n\n",
"Disassembly of section .text:\n\n",
"0000000000000000 <.text>:\n",
" 0:\t40 c5 e9 fd cb \trex vpaddw xmm1,xmm2,xmm3\n",
" 5:\t66 48 c5 e9 fd cb \tdata16 rex.W vpaddw xmm1,xmm2,xmm3\n",
" b:\t64 c5 e9 fd cb \tfs vpaddw xmm1,xmm2,xmm3\n",
" 10:\t66 48 74 02 \tdata16 rex.W je 0x16\n",
" 14:\t66 48 00 c0 \tdata16 rex.W add al,al\n",
" 18:\t66 48 ff e0 \tdata16 rex.W jmp rax\n",
" 1c:\t66 48 ff c0 \tdata16 inc rax\n",
);
let insns = parse_objdump_output(Arch::X86_64, DisasmLeg::GnuObjdump, gnu_x86)
.expect("parse gnu ud forms");
assert_eq!(insns.len(), 7);
let expected = [
("rex", true),
("data16", true),
("vpaddw", false),
("data16", true),
("data16", true),
("data16", true),
("inc", false),
];
for (i, (mn, bad)) in expected.iter().enumerate() {
assert_eq!(insns[i].mnemonic, *mn, "idx {i}");
assert_eq!(insns[i].is_bad, *bad, "idx {i}");
}
// Erroneous Lean acceptance of `#UD` REX-prefixed VEX MUST report
// `ExtraLeanAccept`.
let bad_accept = LeanDecodeStatus::Ok(vec![LeanInsn {
offset: 0,
len: 5,
mnemonic: "vpaddw".to_string(),
detail: "vex=128".to_string(),
}]);
let cmp = compare_against_lean(
Arch::X86_64,
DisasmLeg::GnuObjdump,
&insns[0..1],
Some(&bad_accept),
&[Some(bad_accept.clone())],
);
assert_eq!(cmp.mismatches, 1);
assert_eq!(cmp.verdicts[0].kind, InsnVerdictKind::ExtraLeanAccept);
}
#[test]
fn hex_parser_and_adversarial_corpus_invariants() {
let parsed = parse_hex_bytes("0x41, 90 c3").expect("parse hex");
assert_eq!(parsed, vec![0x41, 0x90, 0xc3]);
assert!(parse_hex_bytes("abc").is_err());
let cases = corpus::default_adversarial_corpus();
assert!(cases.iter().any(|c| c.id == "x86_41_90_xchg"));
assert!(cases.iter().any(|c| c.id == "x86_redundant_66_nop"));
assert!(cases.iter().any(|c| c.id == "x86_prefix_ret_and_nops"));
assert!(cases.iter().any(|c| c.id == "x86_over_15b_gp0"));
assert!(cases.iter().any(|c| c.id == "x86_lock_on_reg_ud"));
assert!(cases.iter().any(|c| c.id == "x86_vex_l0_vpaddw"));
assert!(cases.iter().any(|c| c.id == "x86_vex_l1_vpaddw"));
assert!(cases.iter().any(|c| c.id == "x86_vpmaxuw_and_vpbroadcastd"));
assert!(cases.iter().any(|c| c.id == "x86_vpminud_0x3b_gap"));
assert!(cases.iter().any(|c| c.id == "x86_movsxd_and_mov32"));
assert!(cases.iter().any(|c| c.id == "x86_imul_imm8_0x6b"));
assert!(cases.iter().any(|c| c.id == "x86_lock_imul_6b"));
assert!(cases.iter().any(|c| c.id == "a64_ldp_overlap_unpred"));
assert!(cases.iter().any(|c| c.id == "a64_x31_sp_vs_xzr"));
}
}