blob: 08d48f0003aef1fd89be5c65323c5c155ad7f06b [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.
//! CLI entrypoint for `anneal-isa-oracle`: dual-ISA (`x86-64` + `AArch64`)
//! differential decoder oracle comparing Anneal's Lean decoders against
//! `llvm-objdump --disassemble` and GNU `objdump -d --show-raw-insn`, plus
//! the `exec` subcommand for three-band `Anneal.ElfX86.ScalarEval` execution
//! replay against JSONL silicon/sandbox traces.
use std::{collections::BTreeMap, fs, path::PathBuf, process::ExitCode};
use anneal_isa_oracle::{
assemble_batch_report, compare_against_lean, compare_disassemblers,
corpus::default_adversarial_corpus,
evaluate_case_expectation,
exec::{
assemble_exec_report, default_exec_corpus, parse_exec_jsonl, run_lean_exec_batch, ExecBand,
ExecBatchReport,
},
format_bytes_hex,
lean::{run_lean_batch, LeanBatchQuery, LeanQueryLane},
objdump::{extract_elf64_section, run_gnu_objdump_bytes, run_llvm_objdump_bytes},
parse_hex_bytes, record_disasm_only_leg, Arch, BatchReport, CaseExpectation, CaseReport,
CaseSpec, DisasmInsn, DisasmLeg, LeanDecodeStatus, LegComparison, OracleGatePolicy,
X86DecoderLane,
};
struct CliArgs {
arch: Option<Arch>,
x86_lane: X86DecoderLane,
hex: Option<String>,
elf: Option<PathBuf>,
section: String,
adversarial: bool,
lean_bin: Option<String>,
olean_dir: Option<PathBuf>,
disasm_only: bool,
allow_missing_gnu: bool,
llvm_objdump: String,
gnu_objdump: String,
require_reloc: bool,
pretty: bool,
}
fn usage() -> &'static str {
"Usage: anneal-isa-oracle [OPTIONS]\n\
\x20 anneal-isa-oracle exec [EXEC OPTIONS]\n\
\n\
Subcommands:\n\
exec Three-band x86-64 ScalarEval execution differential replay\n\
\n\
Input mode (choose one):\n\
--adversarial Run built-in dual-ISA adversarial corpus\n\
--hex <BYTES> --arch <ISA> Probe raw hex byte sequence (`x86-64` or `aarch64`)\n\
--elf <PATH> [--section .text] Probe section bytes from an ELF64 file\n\
\n\
Options:\n\
--lane <base|word-simd> x86-64 Lean decoder lane (default: word-simd)\n\
--lean-bin <PATH> Lean 4 binary for Anneal decoder evaluation\n\
--olean-dir <DIR> Prebuilt .olean directory for LEAN_PATH\n\
--disasm-only Allow running without --lean-bin (disassembler check only)\n\
--allow-missing-gnu Do not fail when GNU objdump is unavailable on x86-64\n\
--llvm-objdump <PATH> llvm-objdump binary (default: llvm-objdump)\n\
--gnu-objdump <PATH> GNU objdump binary (default: objdump)\n\
--require-reloc Enable relocatable-object strict mode in Lean\n\
--pretty Pretty-print JSON output\n\
-h, --help Show this help message"
}
struct ExecCliArgs {
corpora: Vec<PathBuf>,
self_test: bool,
bands: Vec<ExecBand>,
fuel: usize,
batch_size: usize,
lean_bin: String,
olean_dir: Option<PathBuf>,
strict_coverage: bool,
pretty: bool,
}
fn exec_usage() -> &'static str {
"Usage: anneal-isa-oracle exec [OPTIONS]\n\
\n\
Input mode (choose one or more):\n\
--corpus <PATH> Replay JSONL execution trace file (repeatable)\n\
--self-test Run built-in 3-band synthetic execution corpus\n\
\n\
Options:\n\
--band <scalar|rep|sandbox> Filter records to one semantic band (repeatable)\n\
--fuel <N> Max ScalarEval steps per record (default: 64)\n\
--batch-size <N> Records evaluated per Lean process (default: 64)\n\
--lean-bin <PATH> Lean 4 binary for Anneal.ElfX86.ScalarEval (required)\n\
--olean-dir <DIR> Prebuilt .olean directory for LEAN_PATH\n\
--strict-coverage Fail if any record hits decode/step backlog\n\
--pretty Pretty-print JSON output\n\
-h, --help Show this help message"
}
fn parse_exec_args(mut args: impl Iterator<Item = String>) -> Result<ExecCliArgs, String> {
let mut corpora = Vec::new();
let mut self_test = false;
let mut bands = Vec::new();
let mut fuel = 64usize;
let mut batch_size = 64usize;
let mut lean_bin: Option<String> = None;
let mut olean_dir: Option<PathBuf> = None;
let mut strict_coverage = false;
let mut pretty = false;
while let Some(arg) = args.next() {
match arg.as_str() {
"-h" | "--help" => {
println!("{}", exec_usage());
std::process::exit(0);
}
"--self-test" => self_test = true,
"--strict-coverage" => strict_coverage = true,
"--pretty" => pretty = true,
"--corpus" => {
let p = args.next().ok_or_else(|| "--corpus requires a path".to_owned())?;
corpora.push(PathBuf::from(p));
}
"--band" => {
let raw = args.next().ok_or_else(|| "--band requires a value".to_owned())?;
let b = ExecBand::parse_cli(&raw)?;
if !bands.contains(&b) {
bands.push(b);
}
}
"--fuel" => {
let raw =
args.next().ok_or_else(|| "--fuel requires a positive integer".to_owned())?;
fuel = raw.parse::<usize>().map_err(|e| format!("invalid --fuel `{raw}`: {e}"))?;
if fuel == 0 {
return Err("--fuel must be > 0".to_owned());
}
}
"--batch-size" => {
let raw = args
.next()
.ok_or_else(|| "--batch-size requires a positive integer".to_owned())?;
batch_size = raw
.parse::<usize>()
.map_err(|e| format!("invalid --batch-size `{raw}`: {e}"))?;
if batch_size == 0 {
return Err("--batch-size must be > 0".to_owned());
}
}
"--lean-bin" => {
lean_bin =
Some(args.next().ok_or_else(|| "--lean-bin requires a path".to_owned())?);
}
"--olean-dir" => {
let p = args.next().ok_or_else(|| "--olean-dir requires a directory".to_owned())?;
olean_dir = Some(PathBuf::from(p));
}
other => return Err(format!("unknown exec argument `{other}`\n\n{}", exec_usage())),
}
}
if !self_test && corpora.is_empty() {
return Err(format!(
"specify --self-test and/or at least one --corpus <PATH>\n\n{}",
exec_usage()
));
}
let lean_bin = lean_bin
.ok_or_else(|| "--lean-bin <PATH> is required for `anneal-isa-oracle exec`".to_owned())?;
Ok(ExecCliArgs {
corpora,
self_test,
bands,
fuel,
batch_size,
lean_bin,
olean_dir,
strict_coverage,
pretty,
})
}
fn run_exec(cli: ExecCliArgs) -> Result<ExecBatchReport, String> {
let mut records = Vec::new();
if cli.self_test {
records.extend(default_exec_corpus());
}
for path in &cli.corpora {
let text = fs::read_to_string(path)
.map_err(|e| format!("failed to read `{}`: {e}", path.display()))?;
let label = path
.file_stem()
.map_or_else(|| path.display().to_string(), |s| s.to_string_lossy().into_owned());
let parsed = parse_exec_jsonl(&label, &text)?;
records.extend(parsed.records);
}
if !cli.bands.is_empty() {
records.retain(|r| cli.bands.contains(&r.band));
}
if records.is_empty() {
return Err("no execution records matched the selected inputs/band filters".to_owned());
}
let outcomes = run_lean_exec_batch(
&cli.lean_bin,
cli.olean_dir.as_deref(),
&records,
cli.fuel,
cli.batch_size,
)?;
assemble_exec_report(&records, &outcomes, cli.strict_coverage)
}
fn parse_args() -> Result<CliArgs, String> {
let mut args = std::env::args().skip(1);
let mut cli = CliArgs {
arch: None,
x86_lane: X86DecoderLane::WordSimd,
hex: None,
elf: None,
section: ".text".to_string(),
adversarial: false,
lean_bin: None,
olean_dir: None,
disasm_only: false,
allow_missing_gnu: false,
llvm_objdump: "llvm-objdump".to_string(),
gnu_objdump: "objdump".to_string(),
require_reloc: false,
pretty: false,
};
while let Some(arg) = args.next() {
match arg.as_str() {
"-h" | "--help" => {
println!("{}", usage());
std::process::exit(0);
}
"--adversarial" => cli.adversarial = true,
"--disasm-only" => cli.disasm_only = true,
"--allow-missing-gnu" => cli.allow_missing_gnu = true,
"--require-reloc" => cli.require_reloc = true,
"--pretty" => cli.pretty = true,
"--arch" => {
let v = args.next().ok_or_else(|| "--arch requires a value".to_string())?;
cli.arch = Some(match v.as_str() {
"x86-64" | "x86_64" | "x64" => Arch::X86_64,
"aarch64" | "arm64" => Arch::AArch64,
other => return Err(format!("unsupported --arch `{other}`")),
});
}
"--lane" => {
let v = args.next().ok_or_else(|| "--lane requires a value".to_string())?;
cli.x86_lane = match v.as_str() {
"base" => X86DecoderLane::Base,
"word-simd" => X86DecoderLane::WordSimd,
other => return Err(format!("unsupported --lane `{other}`")),
};
}
"--hex" => {
cli.hex = Some(args.next().ok_or_else(|| "--hex requires a value".to_string())?);
}
"--elf" => {
let p = args.next().ok_or_else(|| "--elf requires a path".to_string())?;
cli.elf = Some(PathBuf::from(p));
}
"--section" => {
cli.section = args.next().ok_or_else(|| "--section requires a name".to_string())?;
}
"--lean-bin" => {
cli.lean_bin =
Some(args.next().ok_or_else(|| "--lean-bin requires a path".to_string())?);
}
"--olean-dir" => {
let p =
args.next().ok_or_else(|| "--olean-dir requires a directory".to_string())?;
cli.olean_dir = Some(PathBuf::from(p));
}
"--llvm-objdump" => {
cli.llvm_objdump =
args.next().ok_or_else(|| "--llvm-objdump requires a path".to_string())?;
}
"--gnu-objdump" => {
cli.gnu_objdump =
args.next().ok_or_else(|| "--gnu-objdump requires a path".to_string())?;
}
other => return Err(format!("unknown argument `{other}`\n\n{}", usage())),
}
}
if cli.lean_bin.is_none() && !cli.disasm_only {
return Err(
"--lean-bin <PATH> is required for differential checking (pass --disasm-only to \
compare external disassemblers without Lean)"
.to_string(),
);
}
Ok(cli)
}
fn build_cases(cli: &CliArgs) -> Result<Vec<CaseSpec>, String> {
if cli.adversarial {
return Ok(default_adversarial_corpus());
}
if let Some(elf_path) = &cli.elf {
let elf_bytes = fs::read(elf_path)
.map_err(|e| format!("failed to read `{}`: {e}", elf_path.display()))?;
let (detected_arch, sec_bytes) = extract_elf64_section(&elf_bytes, &cli.section)?;
let arch = cli.arch.unwrap_or(detected_arch);
return Ok(vec![CaseSpec {
id: format!("{}:{}", elf_path.display(), cli.section),
description: format!("ELF64 section `{}`", cli.section),
arch,
x86_lane: cli.x86_lane,
bytes: sec_bytes,
expectation: CaseExpectation::ReportGaps,
}]);
}
if let Some(hex) = &cli.hex {
let arch = cli.arch.ok_or_else(|| "--hex requires --arch <x86-64|aarch64>".to_string())?;
let bytes = parse_hex_bytes(hex)?;
return Ok(vec![CaseSpec {
id: "cli_hex".to_string(),
description: "CLI raw hex byte sequence".to_string(),
arch,
x86_lane: cli.x86_lane,
bytes,
expectation: CaseExpectation::ReportGaps,
}]);
}
Err(format!("specify one of --adversarial, --elf, or --hex\n\n{}", usage()))
}
fn run(cli: CliArgs) -> Result<BatchReport, String> {
let cases = build_cases(&cli)?;
// Run both external disassembler legs first so we know every instruction
// boundary to probe individually in Lean alongside whole-stream decoding.
struct DisasmPair {
llvm: Result<Vec<DisasmInsn>, String>,
gnu: Result<Vec<DisasmInsn>, String>,
}
let mut disasm_results: Vec<DisasmPair> = Vec::with_capacity(cases.len());
for case in &cases {
let llvm = run_llvm_objdump_bytes(&cli.llvm_objdump, case.arch, &case.bytes);
let gnu = run_gnu_objdump_bytes(&cli.gnu_objdump, case.arch, &case.bytes);
disasm_results.push(DisasmPair { llvm, gnu });
}
// Build one consolidated Lean batch covering whole-stream decode + every
// disassembled instruction window across all cases.
let mut lean_map: BTreeMap<String, LeanDecodeStatus> = BTreeMap::new();
if let Some(lean_bin) = &cli.lean_bin {
let mut queries: Vec<LeanBatchQuery> = Vec::new();
for (c_idx, (case, pair)) in cases.iter().zip(disasm_results.iter()).enumerate() {
queries.push(LeanBatchQuery {
id: format!("c{c_idx}_stream"),
lane: LeanQueryLane::stream_for(case.arch, case.x86_lane),
pos: 0,
require_reloc: cli.require_reloc,
bmi1: false,
popcnt: false,
lzcnt: false,
bytes: case.bytes.clone(),
});
// Collect unique offsets from both disassembler legs so each
// boundary is probed in Lean in a single batch call.
let mut offsets: Vec<u64> = Vec::new();
if let Ok(insns) = &pair.llvm {
for ins in insns {
if !offsets.contains(&ins.offset) {
offsets.push(ins.offset);
}
}
}
if let Ok(insns) = &pair.gnu {
for ins in insns {
if !offsets.contains(&ins.offset) {
offsets.push(ins.offset);
}
}
}
for off in offsets {
let start = off as usize;
let window_len = match case.arch {
Arch::X86_64 => 16,
Arch::AArch64 => 4,
};
let slice = case
.bytes
.get(start..case.bytes.len().min(start + window_len))
.unwrap_or(&[])
.to_vec();
queries.push(LeanBatchQuery {
id: format!("c{c_idx}_off_{off}"),
lane: LeanQueryLane::one_for(case.arch, case.x86_lane),
pos: off,
require_reloc: cli.require_reloc,
bmi1: false,
popcnt: false,
lzcnt: false,
bytes: slice,
});
}
}
lean_map = run_lean_batch(lean_bin, cli.olean_dir.as_deref(), &queries)?;
}
let policy = OracleGatePolicy {
require_lean: !cli.disasm_only,
require_gnu_x86: !cli.allow_missing_gnu,
};
let mut reports = Vec::with_capacity(cases.len());
let mut total_leg_errors = 0usize;
for (c_idx, (case, pair)) in cases.iter().zip(disasm_results.iter()).enumerate() {
let lean_stream = lean_map.get(&format!("c{c_idx}_stream")).cloned();
let disasm_agreement =
compare_disassemblers(case.arch, pair.llvm.as_deref().ok(), pair.gnu.as_deref().ok());
let mut legs = Vec::new();
for (leg, res) in [(DisasmLeg::LlvmObjdump, &pair.llvm), (DisasmLeg::GnuObjdump, &pair.gnu)]
{
match res {
Ok(insns) => {
if cli.disasm_only {
legs.push(record_disasm_only_leg(leg, insns));
} else {
let per_insn: Vec<Option<LeanDecodeStatus>> = insns
.iter()
.map(|d| lean_map.get(&format!("c{c_idx}_off_{}", d.offset)).cloned())
.collect();
legs.push(compare_against_lean(
case.arch,
leg,
insns,
lean_stream.as_ref(),
&per_insn,
));
}
}
Err(err) => {
legs.push(LegComparison {
leg,
available: false,
error: Some(err.clone()),
disasm_insn_count: 0,
lean_stream_ok: matches!(lean_stream, Some(LeanDecodeStatus::Ok(_))),
stream_boundary_agree: false,
stream_all_match: false,
matched_insns: 0,
fail_closed_gaps: 0,
mismatches: 0,
verdicts: Vec::new(),
});
}
}
}
let (expectation_ok, expectation_error, leg_errs) =
evaluate_case_expectation(case, lean_stream.as_ref(), &disasm_agreement, &legs, policy);
total_leg_errors += leg_errs;
reports.push(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,
expectation_error,
lean_stream_status: lean_stream,
disasm_agreement,
legs,
});
}
Ok(assemble_batch_report(reports, total_leg_errors))
}
fn main() -> ExitCode {
let mut raw_args = std::env::args().skip(1).peekable();
if raw_args.peek().map(String::as_str) == Some("exec") {
let _ = raw_args.next();
let cli = match parse_exec_args(raw_args) {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let pretty = cli.pretty;
return match run_exec(cli) {
Ok(report) => {
let json = if pretty {
serde_json::to_string_pretty(&report)
} else {
serde_json::to_string(&report)
};
match json {
Ok(s) => {
println!("{s}");
if report.passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
Err(e) => {
eprintln!("error: failed to serialize exec report: {e}");
ExitCode::from(2)
}
}
}
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
};
}
let cli = match parse_args() {
Ok(c) => c,
Err(e) => {
eprintln!("error: {e}");
return ExitCode::from(2);
}
};
let pretty = cli.pretty;
match run(cli) {
Ok(report) => {
let json = if pretty {
serde_json::to_string_pretty(&report)
} else {
serde_json::to_string(&report)
};
match json {
Ok(s) => {
println!("{s}");
if report.passed {
ExitCode::SUCCESS
} else {
ExitCode::from(1)
}
}
Err(e) => {
eprintln!("error: failed to serialize report: {e}");
ExitCode::from(2)
}
}
}
Err(e) => {
eprintln!("error: {e}");
ExitCode::from(2)
}
}
}